echarts.js 2.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. function find(obj, cb, context) {
  575. if (!(obj && cb)) {
  576. return;
  577. }
  578. for (var i = 0, len = obj.length; i < len; i++) {
  579. if (cb.call(context, obj[i], i, obj)) {
  580. return obj[i];
  581. }
  582. }
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @param {*} context
  588. * @return {Function}
  589. */
  590. function bind(func, context) {
  591. var args = nativeSlice.call(arguments, 2);
  592. return function () {
  593. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  594. };
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {Function} func
  599. * @return {Function}
  600. */
  601. function curry(func) {
  602. var args = nativeSlice.call(arguments, 1);
  603. return function () {
  604. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  605. };
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isArray(value) {
  613. return objToString.call(value) === '[object Array]';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isFunction$1(value) {
  621. return typeof value === 'function';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isString(value) {
  629. return objToString.call(value) === '[object String]';
  630. }
  631. /**
  632. * @memberOf module:zrender/core/util
  633. * @param {*} value
  634. * @return {boolean}
  635. */
  636. function isObject$1(value) {
  637. // Avoid a V8 JIT bug in Chrome 19-20.
  638. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  639. var type = typeof value;
  640. return type === 'function' || (!!value && type === 'object');
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isBuiltInObject(value) {
  648. return !!BUILTIN_OBJECT[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isTypedArray(value) {
  656. return !!TYPED_ARRAY[objToString.call(value)];
  657. }
  658. /**
  659. * @memberOf module:zrender/core/util
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function isDom(value) {
  664. return typeof value === 'object'
  665. && typeof value.nodeType === 'number'
  666. && typeof value.ownerDocument === 'object';
  667. }
  668. /**
  669. * Whether is exactly NaN. Notice isNaN('a') returns true.
  670. * @param {*} value
  671. * @return {boolean}
  672. */
  673. function eqNaN(value) {
  674. /* eslint-disable-next-line no-self-compare */
  675. return value !== value;
  676. }
  677. /**
  678. * If value1 is not null, then return value1, otherwise judget rest of values.
  679. * Low performance.
  680. * @memberOf module:zrender/core/util
  681. * @return {*} Final value
  682. */
  683. function retrieve(values) {
  684. for (var i = 0, len = arguments.length; i < len; i++) {
  685. if (arguments[i] != null) {
  686. return arguments[i];
  687. }
  688. }
  689. }
  690. function retrieve2(value0, value1) {
  691. return value0 != null
  692. ? value0
  693. : value1;
  694. }
  695. function retrieve3(value0, value1, value2) {
  696. return value0 != null
  697. ? value0
  698. : value1 != null
  699. ? value1
  700. : value2;
  701. }
  702. /**
  703. * @memberOf module:zrender/core/util
  704. * @param {Array} arr
  705. * @param {number} startIndex
  706. * @param {number} endIndex
  707. * @return {Array}
  708. */
  709. function slice() {
  710. return Function.call.apply(nativeSlice, arguments);
  711. }
  712. /**
  713. * Normalize css liked array configuration
  714. * e.g.
  715. * 3 => [3, 3, 3, 3]
  716. * [4, 2] => [4, 2, 4, 2]
  717. * [4, 3, 2] => [4, 3, 2, 3]
  718. * @param {number|Array.<number>} val
  719. * @return {Array.<number>}
  720. */
  721. function normalizeCssArray(val) {
  722. if (typeof (val) === 'number') {
  723. return [val, val, val, val];
  724. }
  725. var len = val.length;
  726. if (len === 2) {
  727. // vertical | horizontal
  728. return [val[0], val[1], val[0], val[1]];
  729. }
  730. else if (len === 3) {
  731. // top | horizontal | bottom
  732. return [val[0], val[1], val[2], val[1]];
  733. }
  734. return val;
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {boolean} condition
  739. * @param {string} message
  740. */
  741. function assert$1(condition, message) {
  742. if (!condition) {
  743. throw new Error(message);
  744. }
  745. }
  746. /**
  747. * @memberOf module:zrender/core/util
  748. * @param {string} str string to be trimed
  749. * @return {string} trimed string
  750. */
  751. function trim(str) {
  752. if (str == null) {
  753. return null;
  754. }
  755. else if (typeof str.trim === 'function') {
  756. return str.trim();
  757. }
  758. else {
  759. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  760. }
  761. }
  762. var primitiveKey = '__ec_primitive__';
  763. /**
  764. * Set an object as primitive to be ignored traversing children in clone or merge
  765. */
  766. function setAsPrimitive(obj) {
  767. obj[primitiveKey] = true;
  768. }
  769. function isPrimitive(obj) {
  770. return obj[primitiveKey];
  771. }
  772. /**
  773. * @constructor
  774. * @param {Object} obj Only apply `ownProperty`.
  775. */
  776. function HashMap(obj) {
  777. var isArr = isArray(obj);
  778. // Key should not be set on this, otherwise
  779. // methods get/set/... may be overrided.
  780. this.data = {};
  781. var thisMap = this;
  782. (obj instanceof HashMap)
  783. ? obj.each(visit)
  784. : (obj && each$1(obj, visit));
  785. function visit(value, key) {
  786. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  787. }
  788. }
  789. HashMap.prototype = {
  790. constructor: HashMap,
  791. // Do not provide `has` method to avoid defining what is `has`.
  792. // (We usually treat `null` and `undefined` as the same, different
  793. // from ES6 Map).
  794. get: function (key) {
  795. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  796. },
  797. set: function (key, value) {
  798. // Comparing with invocation chaining, `return value` is more commonly
  799. // used in this case: `var someVal = map.set('a', genVal());`
  800. return (this.data[key] = value);
  801. },
  802. // Although util.each can be performed on this hashMap directly, user
  803. // should not use the exposed keys, who are prefixed.
  804. each: function (cb, context) {
  805. context !== void 0 && (cb = bind(cb, context));
  806. /* eslint-disable guard-for-in */
  807. for (var key in this.data) {
  808. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  809. }
  810. /* eslint-enable guard-for-in */
  811. },
  812. // Do not use this method if performance sensitive.
  813. removeKey: function (key) {
  814. delete this.data[key];
  815. }
  816. };
  817. function createHashMap(obj) {
  818. return new HashMap(obj);
  819. }
  820. function concatArray(a, b) {
  821. var newArray = new a.constructor(a.length + b.length);
  822. for (var i = 0; i < a.length; i++) {
  823. newArray[i] = a[i];
  824. }
  825. var offset = a.length;
  826. for (i = 0; i < b.length; i++) {
  827. newArray[i + offset] = b[i];
  828. }
  829. return newArray;
  830. }
  831. function noop() {}
  832. var zrUtil = (Object.freeze || Object)({
  833. $override: $override,
  834. clone: clone,
  835. merge: merge,
  836. mergeAll: mergeAll,
  837. extend: extend,
  838. defaults: defaults,
  839. createCanvas: createCanvas,
  840. getContext: getContext,
  841. indexOf: indexOf,
  842. inherits: inherits,
  843. mixin: mixin,
  844. isArrayLike: isArrayLike,
  845. each: each$1,
  846. map: map,
  847. reduce: reduce,
  848. filter: filter,
  849. find: find,
  850. bind: bind,
  851. curry: curry,
  852. isArray: isArray,
  853. isFunction: isFunction$1,
  854. isString: isString,
  855. isObject: isObject$1,
  856. isBuiltInObject: isBuiltInObject,
  857. isTypedArray: isTypedArray,
  858. isDom: isDom,
  859. eqNaN: eqNaN,
  860. retrieve: retrieve,
  861. retrieve2: retrieve2,
  862. retrieve3: retrieve3,
  863. slice: slice,
  864. normalizeCssArray: normalizeCssArray,
  865. assert: assert$1,
  866. trim: trim,
  867. setAsPrimitive: setAsPrimitive,
  868. isPrimitive: isPrimitive,
  869. createHashMap: createHashMap,
  870. concatArray: concatArray,
  871. noop: noop
  872. });
  873. /* global Float32Array */
  874. var ArrayCtor = typeof Float32Array === 'undefined'
  875. ? Array
  876. : Float32Array;
  877. /**
  878. * 创建一个向量
  879. * @param {number} [x=0]
  880. * @param {number} [y=0]
  881. * @return {Vector2}
  882. */
  883. function create(x, y) {
  884. var out = new ArrayCtor(2);
  885. if (x == null) {
  886. x = 0;
  887. }
  888. if (y == null) {
  889. y = 0;
  890. }
  891. out[0] = x;
  892. out[1] = y;
  893. return out;
  894. }
  895. /**
  896. * 复制向量数据
  897. * @param {Vector2} out
  898. * @param {Vector2} v
  899. * @return {Vector2}
  900. */
  901. function copy(out, v) {
  902. out[0] = v[0];
  903. out[1] = v[1];
  904. return out;
  905. }
  906. /**
  907. * 克隆一个向量
  908. * @param {Vector2} v
  909. * @return {Vector2}
  910. */
  911. function clone$1(v) {
  912. var out = new ArrayCtor(2);
  913. out[0] = v[0];
  914. out[1] = v[1];
  915. return out;
  916. }
  917. /**
  918. * 设置向量的两个项
  919. * @param {Vector2} out
  920. * @param {number} a
  921. * @param {number} b
  922. * @return {Vector2} 结果
  923. */
  924. function set(out, a, b) {
  925. out[0] = a;
  926. out[1] = b;
  927. return out;
  928. }
  929. /**
  930. * 向量相加
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function add(out, v1, v2) {
  936. out[0] = v1[0] + v2[0];
  937. out[1] = v1[1] + v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量缩放后相加
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. * @param {number} a
  946. */
  947. function scaleAndAdd(out, v1, v2, a) {
  948. out[0] = v1[0] + v2[0] * a;
  949. out[1] = v1[1] + v2[1] * a;
  950. return out;
  951. }
  952. /**
  953. * 向量相减
  954. * @param {Vector2} out
  955. * @param {Vector2} v1
  956. * @param {Vector2} v2
  957. */
  958. function sub(out, v1, v2) {
  959. out[0] = v1[0] - v2[0];
  960. out[1] = v1[1] - v2[1];
  961. return out;
  962. }
  963. /**
  964. * 向量长度
  965. * @param {Vector2} v
  966. * @return {number}
  967. */
  968. function len(v) {
  969. return Math.sqrt(lenSquare(v));
  970. }
  971. var length = len; // jshint ignore:line
  972. /**
  973. * 向量长度平方
  974. * @param {Vector2} v
  975. * @return {number}
  976. */
  977. function lenSquare(v) {
  978. return v[0] * v[0] + v[1] * v[1];
  979. }
  980. var lengthSquare = lenSquare;
  981. /**
  982. * 向量乘法
  983. * @param {Vector2} out
  984. * @param {Vector2} v1
  985. * @param {Vector2} v2
  986. */
  987. function mul(out, v1, v2) {
  988. out[0] = v1[0] * v2[0];
  989. out[1] = v1[1] * v2[1];
  990. return out;
  991. }
  992. /**
  993. * 向量除法
  994. * @param {Vector2} out
  995. * @param {Vector2} v1
  996. * @param {Vector2} v2
  997. */
  998. function div(out, v1, v2) {
  999. out[0] = v1[0] / v2[0];
  1000. out[1] = v1[1] / v2[1];
  1001. return out;
  1002. }
  1003. /**
  1004. * 向量点乘
  1005. * @param {Vector2} v1
  1006. * @param {Vector2} v2
  1007. * @return {number}
  1008. */
  1009. function dot(v1, v2) {
  1010. return v1[0] * v2[0] + v1[1] * v2[1];
  1011. }
  1012. /**
  1013. * 向量缩放
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. * @param {number} s
  1017. */
  1018. function scale(out, v, s) {
  1019. out[0] = v[0] * s;
  1020. out[1] = v[1] * s;
  1021. return out;
  1022. }
  1023. /**
  1024. * 向量归一化
  1025. * @param {Vector2} out
  1026. * @param {Vector2} v
  1027. */
  1028. function normalize(out, v) {
  1029. var d = len(v);
  1030. if (d === 0) {
  1031. out[0] = 0;
  1032. out[1] = 0;
  1033. }
  1034. else {
  1035. out[0] = v[0] / d;
  1036. out[1] = v[1] / d;
  1037. }
  1038. return out;
  1039. }
  1040. /**
  1041. * 计算向量间距离
  1042. * @param {Vector2} v1
  1043. * @param {Vector2} v2
  1044. * @return {number}
  1045. */
  1046. function distance(v1, v2) {
  1047. return Math.sqrt(
  1048. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1050. );
  1051. }
  1052. var dist = distance;
  1053. /**
  1054. * 向量距离平方
  1055. * @param {Vector2} v1
  1056. * @param {Vector2} v2
  1057. * @return {number}
  1058. */
  1059. function distanceSquare(v1, v2) {
  1060. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1061. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1062. }
  1063. var distSquare = distanceSquare;
  1064. /**
  1065. * 求负向量
  1066. * @param {Vector2} out
  1067. * @param {Vector2} v
  1068. */
  1069. function negate(out, v) {
  1070. out[0] = -v[0];
  1071. out[1] = -v[1];
  1072. return out;
  1073. }
  1074. /**
  1075. * 插值两个点
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. * @param {number} t
  1080. */
  1081. function lerp(out, v1, v2, t) {
  1082. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1083. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1084. return out;
  1085. }
  1086. /**
  1087. * 矩阵左乘向量
  1088. * @param {Vector2} out
  1089. * @param {Vector2} v
  1090. * @param {Vector2} m
  1091. */
  1092. function applyTransform(out, v, m) {
  1093. var x = v[0];
  1094. var y = v[1];
  1095. out[0] = m[0] * x + m[2] * y + m[4];
  1096. out[1] = m[1] * x + m[3] * y + m[5];
  1097. return out;
  1098. }
  1099. /**
  1100. * 求两个向量最小值
  1101. * @param {Vector2} out
  1102. * @param {Vector2} v1
  1103. * @param {Vector2} v2
  1104. */
  1105. function min(out, v1, v2) {
  1106. out[0] = Math.min(v1[0], v2[0]);
  1107. out[1] = Math.min(v1[1], v2[1]);
  1108. return out;
  1109. }
  1110. /**
  1111. * 求两个向量最大值
  1112. * @param {Vector2} out
  1113. * @param {Vector2} v1
  1114. * @param {Vector2} v2
  1115. */
  1116. function max(out, v1, v2) {
  1117. out[0] = Math.max(v1[0], v2[0]);
  1118. out[1] = Math.max(v1[1], v2[1]);
  1119. return out;
  1120. }
  1121. var vector = (Object.freeze || Object)({
  1122. create: create,
  1123. copy: copy,
  1124. clone: clone$1,
  1125. set: set,
  1126. add: add,
  1127. scaleAndAdd: scaleAndAdd,
  1128. sub: sub,
  1129. len: len,
  1130. length: length,
  1131. lenSquare: lenSquare,
  1132. lengthSquare: lengthSquare,
  1133. mul: mul,
  1134. div: div,
  1135. dot: dot,
  1136. scale: scale,
  1137. normalize: normalize,
  1138. distance: distance,
  1139. dist: dist,
  1140. distanceSquare: distanceSquare,
  1141. distSquare: distSquare,
  1142. negate: negate,
  1143. lerp: lerp,
  1144. applyTransform: applyTransform,
  1145. min: min,
  1146. max: max
  1147. });
  1148. // TODO Draggable for group
  1149. // FIXME Draggable on element which has parent rotation or scale
  1150. function Draggable() {
  1151. this.on('mousedown', this._dragStart, this);
  1152. this.on('mousemove', this._drag, this);
  1153. this.on('mouseup', this._dragEnd, this);
  1154. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1155. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1156. // `_dragEnd` when globalout. That would brings better user experience.
  1157. // this.on('globalout', this._dragEnd, this);
  1158. // this._dropTarget = null;
  1159. // this._draggingTarget = null;
  1160. // this._x = 0;
  1161. // this._y = 0;
  1162. }
  1163. Draggable.prototype = {
  1164. constructor: Draggable,
  1165. _dragStart: function (e) {
  1166. var draggingTarget = e.target;
  1167. if (draggingTarget && draggingTarget.draggable) {
  1168. this._draggingTarget = draggingTarget;
  1169. draggingTarget.dragging = true;
  1170. this._x = e.offsetX;
  1171. this._y = e.offsetY;
  1172. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1173. }
  1174. },
  1175. _drag: function (e) {
  1176. var draggingTarget = this._draggingTarget;
  1177. if (draggingTarget) {
  1178. var x = e.offsetX;
  1179. var y = e.offsetY;
  1180. var dx = x - this._x;
  1181. var dy = y - this._y;
  1182. this._x = x;
  1183. this._y = y;
  1184. draggingTarget.drift(dx, dy, e);
  1185. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1186. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1187. var lastDropTarget = this._dropTarget;
  1188. this._dropTarget = dropTarget;
  1189. if (draggingTarget !== dropTarget) {
  1190. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1191. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1192. }
  1193. if (dropTarget && dropTarget !== lastDropTarget) {
  1194. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1195. }
  1196. }
  1197. }
  1198. },
  1199. _dragEnd: function (e) {
  1200. var draggingTarget = this._draggingTarget;
  1201. if (draggingTarget) {
  1202. draggingTarget.dragging = false;
  1203. }
  1204. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1205. if (this._dropTarget) {
  1206. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1207. }
  1208. this._draggingTarget = null;
  1209. this._dropTarget = null;
  1210. }
  1211. };
  1212. function param(target, e) {
  1213. return {target: target, topTarget: e && e.topTarget};
  1214. }
  1215. /**
  1216. * Event Mixin
  1217. * @module zrender/mixin/Eventful
  1218. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1219. * pissang (https://www.github.com/pissang)
  1220. */
  1221. var arrySlice = Array.prototype.slice;
  1222. /**
  1223. * Event dispatcher.
  1224. *
  1225. * @alias module:zrender/mixin/Eventful
  1226. * @constructor
  1227. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1228. * `eventProcessor.xxx` called.
  1229. * @param {Function} [eventProcessor.normalizeQuery]
  1230. * param: {string|Object} Raw query.
  1231. * return: {string|Object} Normalized query.
  1232. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1233. * if it returns `true`.
  1234. * param: {string} eventType
  1235. * param: {string|Object} query
  1236. * return: {boolean}
  1237. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1238. * param: {string} eventType
  1239. */
  1240. var Eventful = function (eventProcessor) {
  1241. this._$handlers = {};
  1242. this._$eventProcessor = eventProcessor;
  1243. };
  1244. Eventful.prototype = {
  1245. constructor: Eventful,
  1246. /**
  1247. * The handler can only be triggered once, then removed.
  1248. *
  1249. * @param {string} event The event name.
  1250. * @param {string|Object} [query] Condition used on event filter.
  1251. * @param {Function} handler The event handler.
  1252. * @param {Object} context
  1253. */
  1254. one: function (event, query, handler, context) {
  1255. return on(this, event, query, handler, context, true);
  1256. },
  1257. /**
  1258. * Bind a handler.
  1259. *
  1260. * @param {string} event The event name.
  1261. * @param {string|Object} [query] Condition used on event filter.
  1262. * @param {Function} handler The event handler.
  1263. * @param {Object} [context]
  1264. */
  1265. on: function (event, query, handler, context) {
  1266. return on(this, event, query, handler, context, false);
  1267. },
  1268. /**
  1269. * Whether any handler has bound.
  1270. *
  1271. * @param {string} event
  1272. * @return {boolean}
  1273. */
  1274. isSilent: function (event) {
  1275. var _h = this._$handlers;
  1276. return !_h[event] || !_h[event].length;
  1277. },
  1278. /**
  1279. * Unbind a event.
  1280. *
  1281. * @param {string} [event] The event name.
  1282. * If no `event` input, "off" all listeners.
  1283. * @param {Function} [handler] The event handler.
  1284. * If no `handler` input, "off" all listeners of the `event`.
  1285. */
  1286. off: function (event, handler) {
  1287. var _h = this._$handlers;
  1288. if (!event) {
  1289. this._$handlers = {};
  1290. return this;
  1291. }
  1292. if (handler) {
  1293. if (_h[event]) {
  1294. var newList = [];
  1295. for (var i = 0, l = _h[event].length; i < l; i++) {
  1296. if (_h[event][i].h !== handler) {
  1297. newList.push(_h[event][i]);
  1298. }
  1299. }
  1300. _h[event] = newList;
  1301. }
  1302. if (_h[event] && _h[event].length === 0) {
  1303. delete _h[event];
  1304. }
  1305. }
  1306. else {
  1307. delete _h[event];
  1308. }
  1309. return this;
  1310. },
  1311. /**
  1312. * Dispatch a event.
  1313. *
  1314. * @param {string} type The event name.
  1315. */
  1316. trigger: function (type) {
  1317. var _h = this._$handlers[type];
  1318. var eventProcessor = this._$eventProcessor;
  1319. if (_h) {
  1320. var args = arguments;
  1321. var argLen = args.length;
  1322. if (argLen > 3) {
  1323. args = arrySlice.call(args, 1);
  1324. }
  1325. var len = _h.length;
  1326. for (var i = 0; i < len;) {
  1327. var hItem = _h[i];
  1328. if (eventProcessor
  1329. && eventProcessor.filter
  1330. && hItem.query != null
  1331. && !eventProcessor.filter(type, hItem.query)
  1332. ) {
  1333. i++;
  1334. continue;
  1335. }
  1336. // Optimize advise from backbone
  1337. switch (argLen) {
  1338. case 1:
  1339. hItem.h.call(hItem.ctx);
  1340. break;
  1341. case 2:
  1342. hItem.h.call(hItem.ctx, args[1]);
  1343. break;
  1344. case 3:
  1345. hItem.h.call(hItem.ctx, args[1], args[2]);
  1346. break;
  1347. default:
  1348. // have more than 2 given arguments
  1349. hItem.h.apply(hItem.ctx, args);
  1350. break;
  1351. }
  1352. if (hItem.one) {
  1353. _h.splice(i, 1);
  1354. len--;
  1355. }
  1356. else {
  1357. i++;
  1358. }
  1359. }
  1360. }
  1361. eventProcessor && eventProcessor.afterTrigger
  1362. && eventProcessor.afterTrigger(type);
  1363. return this;
  1364. },
  1365. /**
  1366. * Dispatch a event with context, which is specified at the last parameter.
  1367. *
  1368. * @param {string} type The event name.
  1369. */
  1370. triggerWithContext: function (type) {
  1371. var _h = this._$handlers[type];
  1372. var eventProcessor = this._$eventProcessor;
  1373. if (_h) {
  1374. var args = arguments;
  1375. var argLen = args.length;
  1376. if (argLen > 4) {
  1377. args = arrySlice.call(args, 1, args.length - 1);
  1378. }
  1379. var ctx = args[args.length - 1];
  1380. var len = _h.length;
  1381. for (var i = 0; i < len;) {
  1382. var hItem = _h[i];
  1383. if (eventProcessor
  1384. && eventProcessor.filter
  1385. && hItem.query != null
  1386. && !eventProcessor.filter(type, hItem.query)
  1387. ) {
  1388. i++;
  1389. continue;
  1390. }
  1391. // Optimize advise from backbone
  1392. switch (argLen) {
  1393. case 1:
  1394. hItem.h.call(ctx);
  1395. break;
  1396. case 2:
  1397. hItem.h.call(ctx, args[1]);
  1398. break;
  1399. case 3:
  1400. hItem.h.call(ctx, args[1], args[2]);
  1401. break;
  1402. default:
  1403. // have more than 2 given arguments
  1404. hItem.h.apply(ctx, args);
  1405. break;
  1406. }
  1407. if (hItem.one) {
  1408. _h.splice(i, 1);
  1409. len--;
  1410. }
  1411. else {
  1412. i++;
  1413. }
  1414. }
  1415. }
  1416. eventProcessor && eventProcessor.afterTrigger
  1417. && eventProcessor.afterTrigger(type);
  1418. return this;
  1419. }
  1420. };
  1421. function normalizeQuery(host, query) {
  1422. var eventProcessor = host._$eventProcessor;
  1423. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1424. query = eventProcessor.normalizeQuery(query);
  1425. }
  1426. return query;
  1427. }
  1428. function on(eventful, event, query, handler, context, isOnce) {
  1429. var _h = eventful._$handlers;
  1430. if (typeof query === 'function') {
  1431. context = handler;
  1432. handler = query;
  1433. query = null;
  1434. }
  1435. if (!handler || !event) {
  1436. return eventful;
  1437. }
  1438. query = normalizeQuery(eventful, query);
  1439. if (!_h[event]) {
  1440. _h[event] = [];
  1441. }
  1442. for (var i = 0; i < _h[event].length; i++) {
  1443. if (_h[event][i].h === handler) {
  1444. return eventful;
  1445. }
  1446. }
  1447. var wrap = {
  1448. h: handler,
  1449. one: isOnce,
  1450. query: query,
  1451. ctx: context || eventful,
  1452. // FIXME
  1453. // Do not publish this feature util it is proved that it makes sense.
  1454. callAtLast: handler.zrEventfulCallAtLast
  1455. };
  1456. var lastIndex = _h[event].length - 1;
  1457. var lastWrap = _h[event][lastIndex];
  1458. (lastWrap && lastWrap.callAtLast)
  1459. ? _h[event].splice(lastIndex, 0, wrap)
  1460. : _h[event].push(wrap);
  1461. return eventful;
  1462. }
  1463. /**
  1464. * The algoritm is learnt from
  1465. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1466. * And we made some optimization for matrix inversion.
  1467. * Other similar approaches:
  1468. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1469. */
  1470. var LN2 = Math.log(2);
  1471. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1472. var cacheKey = rowMask + '-' + colMask;
  1473. var fullRank = rows.length;
  1474. if (detCache.hasOwnProperty(cacheKey)) {
  1475. return detCache[cacheKey];
  1476. }
  1477. if (rank === 1) {
  1478. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1479. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1480. return rows[rowStart][colStart];
  1481. }
  1482. var subRowMask = rowMask | (1 << rowStart);
  1483. var subRowStart = rowStart + 1;
  1484. while (rowMask & (1 << subRowStart)) {
  1485. subRowStart++;
  1486. }
  1487. var sum = 0;
  1488. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1489. var colTag = 1 << j;
  1490. if (!(colTag & colMask)) {
  1491. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1492. // det(subMatrix(0, j))
  1493. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1494. colLocalIdx++;
  1495. }
  1496. }
  1497. detCache[cacheKey] = sum;
  1498. return sum;
  1499. }
  1500. /**
  1501. * Usage:
  1502. * ```js
  1503. * var transformer = buildTransformer(
  1504. * [10, 44, 100, 44, 100, 300, 10, 300],
  1505. * [50, 54, 130, 14, 140, 330, 14, 220]
  1506. * );
  1507. * var out = [];
  1508. * transformer && transformer([11, 33], out);
  1509. * ```
  1510. *
  1511. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1512. *
  1513. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1514. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1515. * @return {Function} transformer If fail, return null/undefined.
  1516. */
  1517. function buildTransformer(src, dest) {
  1518. var mA = [
  1519. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1520. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1521. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1522. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1523. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1524. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1525. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1526. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1527. ];
  1528. var detCache = {};
  1529. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1530. if (det === 0) {
  1531. return;
  1532. }
  1533. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1534. var vh = [];
  1535. for (var i = 0; i < 8; i++) {
  1536. for (var j = 0; j < 8; j++) {
  1537. vh[j] == null && (vh[j] = 0);
  1538. vh[j] += ((i + j) % 2 ? -1 : 1)
  1539. // det(subMatrix(i, j))
  1540. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1541. / det * dest[i];
  1542. }
  1543. }
  1544. return function (out, srcPointX, srcPointY) {
  1545. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1546. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1547. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1548. };
  1549. }
  1550. /**
  1551. * Utilities for mouse or touch events.
  1552. */
  1553. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1554. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1555. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1556. var _calcOut = [];
  1557. /**
  1558. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1559. * the input `el`.
  1560. * CSS transform (2D & 3D) is supported.
  1561. *
  1562. * The strategy to fetch the coords:
  1563. * + If `calculate` is not set as `true`, users of this method should
  1564. * ensure that `el` is the same or the same size & location as `e.target`.
  1565. * Otherwise the result coords are probably not expected. Because we
  1566. * firstly try to get coords from e.offsetX/e.offsetY.
  1567. * + If `calculate` is set as `true`, the input `el` can be any element
  1568. * and we force to calculate the coords based on `el`.
  1569. * + The input `el` should be positionable (not position:static).
  1570. *
  1571. * The force `calculate` can be used in case like:
  1572. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1573. *
  1574. * @param {HTMLElement} el DOM element.
  1575. * @param {Event} e Mouse event or touch event.
  1576. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1577. * @param {boolean} [calculate=false] Whether to force calculate
  1578. * the coordinates but not use ones provided by browser.
  1579. */
  1580. function clientToLocal(el, e, out, calculate) {
  1581. out = out || {};
  1582. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1583. // to the padding edge of the target element. The only browser using this convention
  1584. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1585. // not support the properties.
  1586. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1587. // In zr painter.dom, padding edge equals to border edge.
  1588. if (calculate || !env$1.canvasSupported) {
  1589. calculateZrXY(el, e, out);
  1590. }
  1591. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1592. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1593. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1594. // zoom-factor, overflow / opacity layers, transforms ...)
  1595. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1596. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1597. // BTW3, In ff, offsetX/offsetY is always 0.
  1598. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1599. out.zrX = e.layerX;
  1600. out.zrY = e.layerY;
  1601. }
  1602. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1603. else if (e.offsetX != null) {
  1604. out.zrX = e.offsetX;
  1605. out.zrY = e.offsetY;
  1606. }
  1607. // For some other device, e.g., IOS safari.
  1608. else {
  1609. calculateZrXY(el, e, out);
  1610. }
  1611. return out;
  1612. }
  1613. function calculateZrXY(el, e, out) {
  1614. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1615. if (el.getBoundingClientRect && env$1.domSupported) {
  1616. var ex = e.clientX;
  1617. var ey = e.clientY;
  1618. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1619. // Original approach, which do not support CSS transform.
  1620. // marker can not be locationed in a canvas container
  1621. // (getBoundingClientRect is always 0). We do not support
  1622. // that input a pre-created canvas to zr while using css
  1623. // transform in iOS.
  1624. var box = el.getBoundingClientRect();
  1625. out.zrX = ex - box.left;
  1626. out.zrY = ey - box.top;
  1627. return;
  1628. }
  1629. else {
  1630. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1631. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1632. if (transformer) {
  1633. transformer(_calcOut, ex, ey);
  1634. out.zrX = _calcOut[0];
  1635. out.zrY = _calcOut[1];
  1636. return;
  1637. }
  1638. }
  1639. }
  1640. out.zrX = out.zrY = 0;
  1641. }
  1642. function prepareCoordMarkers(el, saved) {
  1643. var markers = saved.markers;
  1644. if (markers) {
  1645. return markers;
  1646. }
  1647. markers = saved.markers = [];
  1648. var propLR = ['left', 'right'];
  1649. var propTB = ['top', 'bottom'];
  1650. for (var i = 0; i < 4; i++) {
  1651. var marker = document.createElement('div');
  1652. var stl = marker.style;
  1653. var idxLR = i % 2;
  1654. var idxTB = (i >> 1) % 2;
  1655. stl.cssText = [
  1656. 'position:absolute',
  1657. 'visibility: hidden',
  1658. 'padding: 0',
  1659. 'margin: 0',
  1660. 'border-width: 0',
  1661. 'width:0',
  1662. 'height:0',
  1663. // 'width: 5px',
  1664. // 'height: 5px',
  1665. propLR[idxLR] + ':0',
  1666. propTB[idxTB] + ':0',
  1667. propLR[1 - idxLR] + ':auto',
  1668. propTB[1 - idxTB] + ':auto',
  1669. ''
  1670. ].join('!important;');
  1671. el.appendChild(marker);
  1672. markers.push(marker);
  1673. }
  1674. return markers;
  1675. }
  1676. function preparePointerTransformer(markers, saved) {
  1677. var transformer = saved.transformer;
  1678. var oldSrcCoords = saved.srcCoords;
  1679. var useOld = true;
  1680. var srcCoords = [];
  1681. var destCoords = [];
  1682. for (var i = 0; i < 4; i++) {
  1683. var rect = markers[i].getBoundingClientRect();
  1684. var ii = 2 * i;
  1685. var x = rect.left;
  1686. var y = rect.top;
  1687. srcCoords.push(x, y);
  1688. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1689. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1690. }
  1691. // Cache to avoid time consuming of `buildTransformer`.
  1692. return useOld
  1693. ? transformer
  1694. : (
  1695. saved.srcCoords = srcCoords,
  1696. saved.transformer = buildTransformer(srcCoords, destCoords)
  1697. );
  1698. }
  1699. /**
  1700. * Find native event compat for legency IE.
  1701. * Should be called at the begining of a native event listener.
  1702. *
  1703. * @param {Event} [e] Mouse event or touch event or pointer event.
  1704. * For lagency IE, we use `window.event` is used.
  1705. * @return {Event} The native event.
  1706. */
  1707. function getNativeEvent(e) {
  1708. return e || window.event;
  1709. }
  1710. /**
  1711. * Normalize the coordinates of the input event.
  1712. *
  1713. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1714. * the input `el`.
  1715. * Get `e.zrDelta` if using mouse wheel.
  1716. * Get `e.which`, see the comment inside this function.
  1717. *
  1718. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1719. *
  1720. * Notice: see comments in `clientToLocal`. check the relationship
  1721. * between the result coords and the parameters `el` and `calculate`.
  1722. *
  1723. * @param {HTMLElement} el DOM element.
  1724. * @param {Event} [e] See `getNativeEvent`.
  1725. * @param {boolean} [calculate=false] Whether to force calculate
  1726. * the coordinates but not use ones provided by browser.
  1727. * @return {UIEvent} The normalized native UIEvent.
  1728. */
  1729. function normalizeEvent(el, e, calculate) {
  1730. e = getNativeEvent(e);
  1731. if (e.zrX != null) {
  1732. return e;
  1733. }
  1734. var eventType = e.type;
  1735. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1736. if (!isTouch) {
  1737. clientToLocal(el, e, e, calculate);
  1738. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1739. }
  1740. else {
  1741. var touch = eventType !== 'touchend'
  1742. ? e.targetTouches[0]
  1743. : e.changedTouches[0];
  1744. touch && clientToLocal(el, touch, e, calculate);
  1745. }
  1746. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1747. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1748. // If e.which has been defined, it may be readonly,
  1749. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1750. var button = e.button;
  1751. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1752. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1753. }
  1754. // [Caution]: `e.which` from browser is not always reliable. For example,
  1755. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1756. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1757. // `mousedown (pointerdown)` is the same as Chrome does.
  1758. return e;
  1759. }
  1760. /**
  1761. * @param {HTMLElement} el
  1762. * @param {string} name
  1763. * @param {Function} handler
  1764. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1765. * @param {boolean} [opt.capture=false]
  1766. * @param {boolean} [opt.passive=false]
  1767. */
  1768. function addEventListener(el, name, handler, opt) {
  1769. if (isDomLevel2) {
  1770. // Reproduct the console warning:
  1771. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1772. // Consider marking event handler as 'passive' to make the page more responsive.
  1773. // Just set console log level: verbose in chrome dev tool.
  1774. // then the warning log will be printed when addEventListener called.
  1775. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1776. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1777. // listener delegate all of the upper events of element. Some of those events need
  1778. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1779. // Before passive can be adopted, these issues should be considered:
  1780. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1781. // passive or not.
  1782. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1783. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1784. // compatibility should be handled.
  1785. // var opts = (env.passiveSupported && name === 'mousewheel')
  1786. // ? {passive: true}
  1787. // // By default, the third param of el.addEventListener is `capture: false`.
  1788. // : void 0;
  1789. // el.addEventListener(name, handler /* , opts */);
  1790. el.addEventListener(name, handler, opt);
  1791. }
  1792. else {
  1793. // For simplicity, do not implement `setCapture` for IE9-.
  1794. el.attachEvent('on' + name, handler);
  1795. }
  1796. }
  1797. /**
  1798. * Parameter are the same as `addEventListener`.
  1799. *
  1800. * Notice that if a listener is registered twice, one with capture and one without,
  1801. * remove each one separately. Removal of a capturing listener does not affect a
  1802. * non-capturing version of the same listener, and vice versa.
  1803. */
  1804. function removeEventListener(el, name, handler, opt) {
  1805. if (isDomLevel2) {
  1806. el.removeEventListener(name, handler, opt);
  1807. }
  1808. else {
  1809. el.detachEvent('on' + name, handler);
  1810. }
  1811. }
  1812. /**
  1813. * preventDefault and stopPropagation.
  1814. * Notice: do not use this method in zrender. It can only be
  1815. * used by upper applications if necessary.
  1816. *
  1817. * @param {Event} e A mouse or touch event.
  1818. */
  1819. var stop = isDomLevel2
  1820. ? function (e) {
  1821. e.preventDefault();
  1822. e.stopPropagation();
  1823. e.cancelBubble = true;
  1824. }
  1825. : function (e) {
  1826. e.returnValue = false;
  1827. e.cancelBubble = true;
  1828. };
  1829. /**
  1830. * This method only works for mouseup and mousedown. The functionality is restricted
  1831. * for fault tolerance, See the `e.which` compatibility above.
  1832. *
  1833. * @param {MouseEvent} e
  1834. * @return {boolean}
  1835. */
  1836. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1837. return e.which === 2 || e.which === 3;
  1838. }
  1839. /**
  1840. * To be removed.
  1841. * @deprecated
  1842. */
  1843. /**
  1844. * Only implements needed gestures for mobile.
  1845. */
  1846. var GestureMgr = function () {
  1847. /**
  1848. * @private
  1849. * @type {Array.<Object>}
  1850. */
  1851. this._track = [];
  1852. };
  1853. GestureMgr.prototype = {
  1854. constructor: GestureMgr,
  1855. recognize: function (event, target, root) {
  1856. this._doTrack(event, target, root);
  1857. return this._recognize(event);
  1858. },
  1859. clear: function () {
  1860. this._track.length = 0;
  1861. return this;
  1862. },
  1863. _doTrack: function (event, target, root) {
  1864. var touches = event.touches;
  1865. if (!touches) {
  1866. return;
  1867. }
  1868. var trackItem = {
  1869. points: [],
  1870. touches: [],
  1871. target: target,
  1872. event: event
  1873. };
  1874. for (var i = 0, len = touches.length; i < len; i++) {
  1875. var touch = touches[i];
  1876. var pos = clientToLocal(root, touch, {});
  1877. trackItem.points.push([pos.zrX, pos.zrY]);
  1878. trackItem.touches.push(touch);
  1879. }
  1880. this._track.push(trackItem);
  1881. },
  1882. _recognize: function (event) {
  1883. for (var eventName in recognizers) {
  1884. if (recognizers.hasOwnProperty(eventName)) {
  1885. var gestureInfo = recognizers[eventName](this._track, event);
  1886. if (gestureInfo) {
  1887. return gestureInfo;
  1888. }
  1889. }
  1890. }
  1891. }
  1892. };
  1893. function dist$1(pointPair) {
  1894. var dx = pointPair[1][0] - pointPair[0][0];
  1895. var dy = pointPair[1][1] - pointPair[0][1];
  1896. return Math.sqrt(dx * dx + dy * dy);
  1897. }
  1898. function center(pointPair) {
  1899. return [
  1900. (pointPair[0][0] + pointPair[1][0]) / 2,
  1901. (pointPair[0][1] + pointPair[1][1]) / 2
  1902. ];
  1903. }
  1904. var recognizers = {
  1905. pinch: function (track, event) {
  1906. var trackLen = track.length;
  1907. if (!trackLen) {
  1908. return;
  1909. }
  1910. var pinchEnd = (track[trackLen - 1] || {}).points;
  1911. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1912. if (pinchPre
  1913. && pinchPre.length > 1
  1914. && pinchEnd
  1915. && pinchEnd.length > 1
  1916. ) {
  1917. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1918. !isFinite(pinchScale) && (pinchScale = 1);
  1919. event.pinchScale = pinchScale;
  1920. var pinchCenter = center(pinchEnd);
  1921. event.pinchX = pinchCenter[0];
  1922. event.pinchY = pinchCenter[1];
  1923. return {
  1924. type: 'pinch',
  1925. target: track[0].target,
  1926. event: event
  1927. };
  1928. }
  1929. }
  1930. // Only pinch currently.
  1931. };
  1932. /**
  1933. * [The interface between `Handler` and `HandlerProxy`]:
  1934. *
  1935. * The default `HandlerProxy` only support the common standard web environment
  1936. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1937. * But `HandlerProxy` can be replaced to support more non-standard environment
  1938. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1939. * not provided (like echarts-gl did).
  1940. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1941. * make break changes util inevitable. The interface include the public methods
  1942. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1943. * drives `Handler`.
  1944. */
  1945. /**
  1946. * [Drag outside]:
  1947. *
  1948. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1949. * zrender area when dragging. That is important for the improvement of the user experience
  1950. * when dragging something near the boundary without being terminated unexpectedly.
  1951. *
  1952. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1953. * to resolve this issue. But some drawbacks of it is described in
  1954. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1955. *
  1956. * Instead, we referenced the specifications:
  1957. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1958. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1959. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1960. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1961. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1962. *
  1963. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1964. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1965. * to fire until release the pointer. That is implemented by listen to those event on
  1966. * `document`.
  1967. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1968. * The touch event support this feature by default.
  1969. *
  1970. * Note:
  1971. * There might be some cases that the mouse event can not be
  1972. * received on `document`. For example,
  1973. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1974. * of zr dom throw Error .
  1975. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1976. * zr dom call `stopPropagation`.
  1977. * In these cases, the `mousemove` event might be keep triggered event
  1978. * if the mouse is released. We try to reduce the side-effect in those cases.
  1979. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1980. *
  1981. * Note:
  1982. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1983. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1984. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1985. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1986. * But they are needed to work when the pointer inside the zrender dom.
  1987. */
  1988. var SILENT = 'silent';
  1989. function makeEventPacket(eveType, targetInfo, event) {
  1990. return {
  1991. type: eveType,
  1992. event: event,
  1993. // target can only be an element that is not silent.
  1994. target: targetInfo.target,
  1995. // topTarget can be a silent element.
  1996. topTarget: targetInfo.topTarget,
  1997. cancelBubble: false,
  1998. offsetX: event.zrX,
  1999. offsetY: event.zrY,
  2000. gestureEvent: event.gestureEvent,
  2001. pinchX: event.pinchX,
  2002. pinchY: event.pinchY,
  2003. pinchScale: event.pinchScale,
  2004. wheelDelta: event.zrDelta,
  2005. zrByTouch: event.zrByTouch,
  2006. which: event.which,
  2007. stop: stopEvent
  2008. };
  2009. }
  2010. function stopEvent() {
  2011. stop(this.event);
  2012. }
  2013. function EmptyProxy() {}
  2014. EmptyProxy.prototype.dispose = function () {};
  2015. var handlerNames = [
  2016. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2017. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2018. ];
  2019. /**
  2020. * @alias module:zrender/Handler
  2021. * @constructor
  2022. * @extends module:zrender/mixin/Eventful
  2023. * @param {module:zrender/Storage} storage Storage instance.
  2024. * @param {module:zrender/Painter} painter Painter instance.
  2025. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2026. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2027. */
  2028. var Handler = function (storage, painter, proxy, painterRoot) {
  2029. Eventful.call(this);
  2030. this.storage = storage;
  2031. this.painter = painter;
  2032. this.painterRoot = painterRoot;
  2033. proxy = proxy || new EmptyProxy();
  2034. /**
  2035. * Proxy of event. can be Dom, WebGLSurface, etc.
  2036. */
  2037. this.proxy = null;
  2038. /**
  2039. * {target, topTarget, x, y}
  2040. * @private
  2041. * @type {Object}
  2042. */
  2043. this._hovered = {};
  2044. /**
  2045. * @private
  2046. * @type {Date}
  2047. */
  2048. this._lastTouchMoment;
  2049. /**
  2050. * @private
  2051. * @type {number}
  2052. */
  2053. this._lastX;
  2054. /**
  2055. * @private
  2056. * @type {number}
  2057. */
  2058. this._lastY;
  2059. /**
  2060. * @private
  2061. * @type {module:zrender/core/GestureMgr}
  2062. */
  2063. this._gestureMgr;
  2064. Draggable.call(this);
  2065. this.setHandlerProxy(proxy);
  2066. };
  2067. Handler.prototype = {
  2068. constructor: Handler,
  2069. setHandlerProxy: function (proxy) {
  2070. if (this.proxy) {
  2071. this.proxy.dispose();
  2072. }
  2073. if (proxy) {
  2074. each$1(handlerNames, function (name) {
  2075. proxy.on && proxy.on(name, this[name], this);
  2076. }, this);
  2077. // Attach handler
  2078. proxy.handler = this;
  2079. }
  2080. this.proxy = proxy;
  2081. },
  2082. mousemove: function (event) {
  2083. var x = event.zrX;
  2084. var y = event.zrY;
  2085. var isOutside = isOutsideBoundary(this, x, y);
  2086. var lastHovered = this._hovered;
  2087. var lastHoveredTarget = lastHovered.target;
  2088. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2089. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2090. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2091. // See #6198.
  2092. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2093. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2094. lastHoveredTarget = lastHovered.target;
  2095. }
  2096. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2097. var hoveredTarget = hovered.target;
  2098. var proxy = this.proxy;
  2099. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2100. // Mouse out on previous hovered element
  2101. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2102. this.dispatchToElement(lastHovered, 'mouseout', event);
  2103. }
  2104. // Mouse moving on one element
  2105. this.dispatchToElement(hovered, 'mousemove', event);
  2106. // Mouse over on a new element
  2107. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2108. this.dispatchToElement(hovered, 'mouseover', event);
  2109. }
  2110. },
  2111. mouseout: function (event) {
  2112. var eventControl = event.zrEventControl;
  2113. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2114. if (eventControl !== 'only_globalout') {
  2115. this.dispatchToElement(this._hovered, 'mouseout', event);
  2116. }
  2117. if (eventControl !== 'no_globalout') {
  2118. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2119. // the `globalout` should have been triggered. But currently not.
  2120. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2121. }
  2122. },
  2123. /**
  2124. * Resize
  2125. */
  2126. resize: function (event) {
  2127. this._hovered = {};
  2128. },
  2129. /**
  2130. * Dispatch event
  2131. * @param {string} eventName
  2132. * @param {event=} eventArgs
  2133. */
  2134. dispatch: function (eventName, eventArgs) {
  2135. var handler = this[eventName];
  2136. handler && handler.call(this, eventArgs);
  2137. },
  2138. /**
  2139. * Dispose
  2140. */
  2141. dispose: function () {
  2142. this.proxy.dispose();
  2143. this.storage =
  2144. this.proxy =
  2145. this.painter = null;
  2146. },
  2147. /**
  2148. * 设置默认的cursor style
  2149. * @param {string} [cursorStyle='default'] 例如 crosshair
  2150. */
  2151. setCursorStyle: function (cursorStyle) {
  2152. var proxy = this.proxy;
  2153. proxy.setCursor && proxy.setCursor(cursorStyle);
  2154. },
  2155. /**
  2156. * 事件分发代理
  2157. *
  2158. * @private
  2159. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2160. * @param {string} eventName 事件名称
  2161. * @param {Object} event 事件对象
  2162. */
  2163. dispatchToElement: function (targetInfo, eventName, event) {
  2164. targetInfo = targetInfo || {};
  2165. var el = targetInfo.target;
  2166. if (el && el.silent) {
  2167. return;
  2168. }
  2169. var eventHandler = 'on' + eventName;
  2170. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2171. while (el) {
  2172. el[eventHandler]
  2173. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2174. el.trigger(eventName, eventPacket);
  2175. el = el.parent;
  2176. if (eventPacket.cancelBubble) {
  2177. break;
  2178. }
  2179. }
  2180. if (!eventPacket.cancelBubble) {
  2181. // 冒泡到顶级 zrender 对象
  2182. this.trigger(eventName, eventPacket);
  2183. // 分发事件到用户自定义层
  2184. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2185. this.painter && this.painter.eachOtherLayer(function (layer) {
  2186. if (typeof (layer[eventHandler]) === 'function') {
  2187. layer[eventHandler].call(layer, eventPacket);
  2188. }
  2189. if (layer.trigger) {
  2190. layer.trigger(eventName, eventPacket);
  2191. }
  2192. });
  2193. }
  2194. },
  2195. /**
  2196. * @private
  2197. * @param {number} x
  2198. * @param {number} y
  2199. * @param {module:zrender/graphic/Displayable} exclude
  2200. * @return {model:zrender/Element}
  2201. * @method
  2202. */
  2203. findHover: function (x, y, exclude) {
  2204. var list = this.storage.getDisplayList();
  2205. var out = {x: x, y: y};
  2206. for (var i = list.length - 1; i >= 0; i--) {
  2207. var hoverCheckResult;
  2208. if (list[i] !== exclude
  2209. // getDisplayList may include ignored item in VML mode
  2210. && !list[i].ignore
  2211. && (hoverCheckResult = isHover(list[i], x, y))
  2212. ) {
  2213. !out.topTarget && (out.topTarget = list[i]);
  2214. if (hoverCheckResult !== SILENT) {
  2215. out.target = list[i];
  2216. break;
  2217. }
  2218. }
  2219. }
  2220. return out;
  2221. },
  2222. processGesture: function (event, stage) {
  2223. if (!this._gestureMgr) {
  2224. this._gestureMgr = new GestureMgr();
  2225. }
  2226. var gestureMgr = this._gestureMgr;
  2227. stage === 'start' && gestureMgr.clear();
  2228. var gestureInfo = gestureMgr.recognize(
  2229. event,
  2230. this.findHover(event.zrX, event.zrY, null).target,
  2231. this.proxy.dom
  2232. );
  2233. stage === 'end' && gestureMgr.clear();
  2234. // Do not do any preventDefault here. Upper application do that if necessary.
  2235. if (gestureInfo) {
  2236. var type = gestureInfo.type;
  2237. event.gestureEvent = type;
  2238. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2239. }
  2240. }
  2241. };
  2242. // Common handlers
  2243. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2244. Handler.prototype[name] = function (event) {
  2245. var x = event.zrX;
  2246. var y = event.zrY;
  2247. var isOutside = isOutsideBoundary(this, x, y);
  2248. var hovered;
  2249. var hoveredTarget;
  2250. if (name !== 'mouseup' || !isOutside) {
  2251. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2252. hovered = this.findHover(x, y);
  2253. hoveredTarget = hovered.target;
  2254. }
  2255. if (name === 'mousedown') {
  2256. this._downEl = hoveredTarget;
  2257. this._downPoint = [event.zrX, event.zrY];
  2258. // In case click triggered before mouseup
  2259. this._upEl = hoveredTarget;
  2260. }
  2261. else if (name === 'mouseup') {
  2262. this._upEl = hoveredTarget;
  2263. }
  2264. else if (name === 'click') {
  2265. if (this._downEl !== this._upEl
  2266. // Original click event is triggered on the whole canvas element,
  2267. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2268. // which should be filtered, otherwise it will bring trouble to
  2269. // pan and zoom.
  2270. || !this._downPoint
  2271. // Arbitrary value
  2272. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2273. ) {
  2274. return;
  2275. }
  2276. this._downPoint = null;
  2277. }
  2278. this.dispatchToElement(hovered, name, event);
  2279. };
  2280. });
  2281. function isHover(displayable, x, y) {
  2282. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2283. var el = displayable;
  2284. var isSilent;
  2285. while (el) {
  2286. // If clipped by ancestor.
  2287. // FIXME: If clipPath has neither stroke nor fill,
  2288. // el.clipPath.contain(x, y) will always return false.
  2289. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2290. return false;
  2291. }
  2292. if (el.silent) {
  2293. isSilent = true;
  2294. }
  2295. el = el.parent;
  2296. }
  2297. return isSilent ? SILENT : true;
  2298. }
  2299. return false;
  2300. }
  2301. /**
  2302. * See [Drag outside].
  2303. */
  2304. function isOutsideBoundary(handlerInstance, x, y) {
  2305. var painter = handlerInstance.painter;
  2306. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2307. }
  2308. mixin(Handler, Eventful);
  2309. mixin(Handler, Draggable);
  2310. /**
  2311. * 3x2矩阵操作类
  2312. * @exports zrender/tool/matrix
  2313. */
  2314. /* global Float32Array */
  2315. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2316. ? Array
  2317. : Float32Array;
  2318. /**
  2319. * Create a identity matrix.
  2320. * @return {Float32Array|Array.<number>}
  2321. */
  2322. function create$1() {
  2323. var out = new ArrayCtor$1(6);
  2324. identity(out);
  2325. return out;
  2326. }
  2327. /**
  2328. * 设置矩阵为单位矩阵
  2329. * @param {Float32Array|Array.<number>} out
  2330. */
  2331. function identity(out) {
  2332. out[0] = 1;
  2333. out[1] = 0;
  2334. out[2] = 0;
  2335. out[3] = 1;
  2336. out[4] = 0;
  2337. out[5] = 0;
  2338. return out;
  2339. }
  2340. /**
  2341. * 复制矩阵
  2342. * @param {Float32Array|Array.<number>} out
  2343. * @param {Float32Array|Array.<number>} m
  2344. */
  2345. function copy$1(out, m) {
  2346. out[0] = m[0];
  2347. out[1] = m[1];
  2348. out[2] = m[2];
  2349. out[3] = m[3];
  2350. out[4] = m[4];
  2351. out[5] = m[5];
  2352. return out;
  2353. }
  2354. /**
  2355. * 矩阵相乘
  2356. * @param {Float32Array|Array.<number>} out
  2357. * @param {Float32Array|Array.<number>} m1
  2358. * @param {Float32Array|Array.<number>} m2
  2359. */
  2360. function mul$1(out, m1, m2) {
  2361. // Consider matrix.mul(m, m2, m);
  2362. // where out is the same as m2.
  2363. // So use temp variable to escape error.
  2364. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2365. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2366. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2367. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2368. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2369. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2370. out[0] = out0;
  2371. out[1] = out1;
  2372. out[2] = out2;
  2373. out[3] = out3;
  2374. out[4] = out4;
  2375. out[5] = out5;
  2376. return out;
  2377. }
  2378. /**
  2379. * 平移变换
  2380. * @param {Float32Array|Array.<number>} out
  2381. * @param {Float32Array|Array.<number>} a
  2382. * @param {Float32Array|Array.<number>} v
  2383. */
  2384. function translate(out, a, v) {
  2385. out[0] = a[0];
  2386. out[1] = a[1];
  2387. out[2] = a[2];
  2388. out[3] = a[3];
  2389. out[4] = a[4] + v[0];
  2390. out[5] = a[5] + v[1];
  2391. return out;
  2392. }
  2393. /**
  2394. * 旋转变换
  2395. * @param {Float32Array|Array.<number>} out
  2396. * @param {Float32Array|Array.<number>} a
  2397. * @param {number} rad
  2398. */
  2399. function rotate(out, a, rad) {
  2400. var aa = a[0];
  2401. var ac = a[2];
  2402. var atx = a[4];
  2403. var ab = a[1];
  2404. var ad = a[3];
  2405. var aty = a[5];
  2406. var st = Math.sin(rad);
  2407. var ct = Math.cos(rad);
  2408. out[0] = aa * ct + ab * st;
  2409. out[1] = -aa * st + ab * ct;
  2410. out[2] = ac * ct + ad * st;
  2411. out[3] = -ac * st + ct * ad;
  2412. out[4] = ct * atx + st * aty;
  2413. out[5] = ct * aty - st * atx;
  2414. return out;
  2415. }
  2416. /**
  2417. * 缩放变换
  2418. * @param {Float32Array|Array.<number>} out
  2419. * @param {Float32Array|Array.<number>} a
  2420. * @param {Float32Array|Array.<number>} v
  2421. */
  2422. function scale$1(out, a, v) {
  2423. var vx = v[0];
  2424. var vy = v[1];
  2425. out[0] = a[0] * vx;
  2426. out[1] = a[1] * vy;
  2427. out[2] = a[2] * vx;
  2428. out[3] = a[3] * vy;
  2429. out[4] = a[4] * vx;
  2430. out[5] = a[5] * vy;
  2431. return out;
  2432. }
  2433. /**
  2434. * 求逆矩阵
  2435. * @param {Float32Array|Array.<number>} out
  2436. * @param {Float32Array|Array.<number>} a
  2437. */
  2438. function invert(out, a) {
  2439. var aa = a[0];
  2440. var ac = a[2];
  2441. var atx = a[4];
  2442. var ab = a[1];
  2443. var ad = a[3];
  2444. var aty = a[5];
  2445. var det = aa * ad - ab * ac;
  2446. if (!det) {
  2447. return null;
  2448. }
  2449. det = 1.0 / det;
  2450. out[0] = ad * det;
  2451. out[1] = -ab * det;
  2452. out[2] = -ac * det;
  2453. out[3] = aa * det;
  2454. out[4] = (ac * aty - ad * atx) * det;
  2455. out[5] = (ab * atx - aa * aty) * det;
  2456. return out;
  2457. }
  2458. /**
  2459. * Clone a new matrix.
  2460. * @param {Float32Array|Array.<number>} a
  2461. */
  2462. function clone$2(a) {
  2463. var b = create$1();
  2464. copy$1(b, a);
  2465. return b;
  2466. }
  2467. var matrix = (Object.freeze || Object)({
  2468. create: create$1,
  2469. identity: identity,
  2470. copy: copy$1,
  2471. mul: mul$1,
  2472. translate: translate,
  2473. rotate: rotate,
  2474. scale: scale$1,
  2475. invert: invert,
  2476. clone: clone$2
  2477. });
  2478. /**
  2479. * 提供变换扩展
  2480. * @module zrender/mixin/Transformable
  2481. * @author pissang (https://www.github.com/pissang)
  2482. */
  2483. var mIdentity = identity;
  2484. var EPSILON = 5e-5;
  2485. function isNotAroundZero(val) {
  2486. return val > EPSILON || val < -EPSILON;
  2487. }
  2488. /**
  2489. * @alias module:zrender/mixin/Transformable
  2490. * @constructor
  2491. */
  2492. var Transformable = function (opts) {
  2493. opts = opts || {};
  2494. // If there are no given position, rotation, scale
  2495. if (!opts.position) {
  2496. /**
  2497. * 平移
  2498. * @type {Array.<number>}
  2499. * @default [0, 0]
  2500. */
  2501. this.position = [0, 0];
  2502. }
  2503. if (opts.rotation == null) {
  2504. /**
  2505. * 旋转
  2506. * @type {Array.<number>}
  2507. * @default 0
  2508. */
  2509. this.rotation = 0;
  2510. }
  2511. if (!opts.scale) {
  2512. /**
  2513. * 缩放
  2514. * @type {Array.<number>}
  2515. * @default [1, 1]
  2516. */
  2517. this.scale = [1, 1];
  2518. }
  2519. /**
  2520. * 旋转和缩放的原点
  2521. * @type {Array.<number>}
  2522. * @default null
  2523. */
  2524. this.origin = this.origin || null;
  2525. };
  2526. var transformableProto = Transformable.prototype;
  2527. transformableProto.transform = null;
  2528. /**
  2529. * 判断是否需要有坐标变换
  2530. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2531. */
  2532. transformableProto.needLocalTransform = function () {
  2533. return isNotAroundZero(this.rotation)
  2534. || isNotAroundZero(this.position[0])
  2535. || isNotAroundZero(this.position[1])
  2536. || isNotAroundZero(this.scale[0] - 1)
  2537. || isNotAroundZero(this.scale[1] - 1);
  2538. };
  2539. var scaleTmp = [];
  2540. transformableProto.updateTransform = function () {
  2541. var parent = this.parent;
  2542. var parentHasTransform = parent && parent.transform;
  2543. var needLocalTransform = this.needLocalTransform();
  2544. var m = this.transform;
  2545. if (!(needLocalTransform || parentHasTransform)) {
  2546. m && mIdentity(m);
  2547. return;
  2548. }
  2549. m = m || create$1();
  2550. if (needLocalTransform) {
  2551. this.getLocalTransform(m);
  2552. }
  2553. else {
  2554. mIdentity(m);
  2555. }
  2556. // 应用父节点变换
  2557. if (parentHasTransform) {
  2558. if (needLocalTransform) {
  2559. mul$1(m, parent.transform, m);
  2560. }
  2561. else {
  2562. copy$1(m, parent.transform);
  2563. }
  2564. }
  2565. // 保存这个变换矩阵
  2566. this.transform = m;
  2567. var globalScaleRatio = this.globalScaleRatio;
  2568. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2569. this.getGlobalScale(scaleTmp);
  2570. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2571. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2572. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2573. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2574. m[0] *= sx;
  2575. m[1] *= sx;
  2576. m[2] *= sy;
  2577. m[3] *= sy;
  2578. }
  2579. this.invTransform = this.invTransform || create$1();
  2580. invert(this.invTransform, m);
  2581. };
  2582. transformableProto.getLocalTransform = function (m) {
  2583. return Transformable.getLocalTransform(this, m);
  2584. };
  2585. /**
  2586. * 将自己的transform应用到context上
  2587. * @param {CanvasRenderingContext2D} ctx
  2588. */
  2589. transformableProto.setTransform = function (ctx) {
  2590. var m = this.transform;
  2591. var dpr = ctx.dpr || 1;
  2592. if (m) {
  2593. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2594. }
  2595. else {
  2596. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2597. }
  2598. };
  2599. transformableProto.restoreTransform = function (ctx) {
  2600. var dpr = ctx.dpr || 1;
  2601. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2602. };
  2603. var tmpTransform = [];
  2604. var originTransform = create$1();
  2605. transformableProto.setLocalTransform = function (m) {
  2606. if (!m) {
  2607. // TODO return or set identity?
  2608. return;
  2609. }
  2610. var sx = m[0] * m[0] + m[1] * m[1];
  2611. var sy = m[2] * m[2] + m[3] * m[3];
  2612. var position = this.position;
  2613. var scale$$1 = this.scale;
  2614. if (isNotAroundZero(sx - 1)) {
  2615. sx = Math.sqrt(sx);
  2616. }
  2617. if (isNotAroundZero(sy - 1)) {
  2618. sy = Math.sqrt(sy);
  2619. }
  2620. if (m[0] < 0) {
  2621. sx = -sx;
  2622. }
  2623. if (m[3] < 0) {
  2624. sy = -sy;
  2625. }
  2626. position[0] = m[4];
  2627. position[1] = m[5];
  2628. scale$$1[0] = sx;
  2629. scale$$1[1] = sy;
  2630. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2631. };
  2632. /**
  2633. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2634. */
  2635. transformableProto.decomposeTransform = function () {
  2636. if (!this.transform) {
  2637. return;
  2638. }
  2639. var parent = this.parent;
  2640. var m = this.transform;
  2641. if (parent && parent.transform) {
  2642. // Get local transform and decompose them to position, scale, rotation
  2643. mul$1(tmpTransform, parent.invTransform, m);
  2644. m = tmpTransform;
  2645. }
  2646. var origin = this.origin;
  2647. if (origin && (origin[0] || origin[1])) {
  2648. originTransform[4] = origin[0];
  2649. originTransform[5] = origin[1];
  2650. mul$1(tmpTransform, m, originTransform);
  2651. tmpTransform[4] -= origin[0];
  2652. tmpTransform[5] -= origin[1];
  2653. m = tmpTransform;
  2654. }
  2655. this.setLocalTransform(m);
  2656. };
  2657. /**
  2658. * Get global scale
  2659. * @return {Array.<number>}
  2660. */
  2661. transformableProto.getGlobalScale = function (out) {
  2662. var m = this.transform;
  2663. out = out || [];
  2664. if (!m) {
  2665. out[0] = 1;
  2666. out[1] = 1;
  2667. return out;
  2668. }
  2669. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2670. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2671. if (m[0] < 0) {
  2672. out[0] = -out[0];
  2673. }
  2674. if (m[3] < 0) {
  2675. out[1] = -out[1];
  2676. }
  2677. return out;
  2678. };
  2679. /**
  2680. * 变换坐标位置到 shape 的局部坐标空间
  2681. * @method
  2682. * @param {number} x
  2683. * @param {number} y
  2684. * @return {Array.<number>}
  2685. */
  2686. transformableProto.transformCoordToLocal = function (x, y) {
  2687. var v2 = [x, y];
  2688. var invTransform = this.invTransform;
  2689. if (invTransform) {
  2690. applyTransform(v2, v2, invTransform);
  2691. }
  2692. return v2;
  2693. };
  2694. /**
  2695. * 变换局部坐标位置到全局坐标空间
  2696. * @method
  2697. * @param {number} x
  2698. * @param {number} y
  2699. * @return {Array.<number>}
  2700. */
  2701. transformableProto.transformCoordToGlobal = function (x, y) {
  2702. var v2 = [x, y];
  2703. var transform = this.transform;
  2704. if (transform) {
  2705. applyTransform(v2, v2, transform);
  2706. }
  2707. return v2;
  2708. };
  2709. /**
  2710. * @static
  2711. * @param {Object} target
  2712. * @param {Array.<number>} target.origin
  2713. * @param {number} target.rotation
  2714. * @param {Array.<number>} target.position
  2715. * @param {Array.<number>} [m]
  2716. */
  2717. Transformable.getLocalTransform = function (target, m) {
  2718. m = m || [];
  2719. mIdentity(m);
  2720. var origin = target.origin;
  2721. var scale$$1 = target.scale || [1, 1];
  2722. var rotation = target.rotation || 0;
  2723. var position = target.position || [0, 0];
  2724. if (origin) {
  2725. // Translate to origin
  2726. m[4] -= origin[0];
  2727. m[5] -= origin[1];
  2728. }
  2729. scale$1(m, m, scale$$1);
  2730. if (rotation) {
  2731. rotate(m, m, rotation);
  2732. }
  2733. if (origin) {
  2734. // Translate back from origin
  2735. m[4] += origin[0];
  2736. m[5] += origin[1];
  2737. }
  2738. m[4] += position[0];
  2739. m[5] += position[1];
  2740. return m;
  2741. };
  2742. /**
  2743. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2744. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2745. * @exports zrender/animation/easing
  2746. */
  2747. var easing = {
  2748. /**
  2749. * @param {number} k
  2750. * @return {number}
  2751. */
  2752. linear: function (k) {
  2753. return k;
  2754. },
  2755. /**
  2756. * @param {number} k
  2757. * @return {number}
  2758. */
  2759. quadraticIn: function (k) {
  2760. return k * k;
  2761. },
  2762. /**
  2763. * @param {number} k
  2764. * @return {number}
  2765. */
  2766. quadraticOut: function (k) {
  2767. return k * (2 - k);
  2768. },
  2769. /**
  2770. * @param {number} k
  2771. * @return {number}
  2772. */
  2773. quadraticInOut: function (k) {
  2774. if ((k *= 2) < 1) {
  2775. return 0.5 * k * k;
  2776. }
  2777. return -0.5 * (--k * (k - 2) - 1);
  2778. },
  2779. // 三次方的缓动(t^3)
  2780. /**
  2781. * @param {number} k
  2782. * @return {number}
  2783. */
  2784. cubicIn: function (k) {
  2785. return k * k * k;
  2786. },
  2787. /**
  2788. * @param {number} k
  2789. * @return {number}
  2790. */
  2791. cubicOut: function (k) {
  2792. return --k * k * k + 1;
  2793. },
  2794. /**
  2795. * @param {number} k
  2796. * @return {number}
  2797. */
  2798. cubicInOut: function (k) {
  2799. if ((k *= 2) < 1) {
  2800. return 0.5 * k * k * k;
  2801. }
  2802. return 0.5 * ((k -= 2) * k * k + 2);
  2803. },
  2804. // 四次方的缓动(t^4)
  2805. /**
  2806. * @param {number} k
  2807. * @return {number}
  2808. */
  2809. quarticIn: function (k) {
  2810. return k * k * k * k;
  2811. },
  2812. /**
  2813. * @param {number} k
  2814. * @return {number}
  2815. */
  2816. quarticOut: function (k) {
  2817. return 1 - (--k * k * k * k);
  2818. },
  2819. /**
  2820. * @param {number} k
  2821. * @return {number}
  2822. */
  2823. quarticInOut: function (k) {
  2824. if ((k *= 2) < 1) {
  2825. return 0.5 * k * k * k * k;
  2826. }
  2827. return -0.5 * ((k -= 2) * k * k * k - 2);
  2828. },
  2829. // 五次方的缓动(t^5)
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. quinticIn: function (k) {
  2835. return k * k * k * k * k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quinticOut: function (k) {
  2842. return --k * k * k * k * k + 1;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quinticInOut: function (k) {
  2849. if ((k *= 2) < 1) {
  2850. return 0.5 * k * k * k * k * k;
  2851. }
  2852. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2853. },
  2854. // 正弦曲线的缓动(sin(t))
  2855. /**
  2856. * @param {number} k
  2857. * @return {number}
  2858. */
  2859. sinusoidalIn: function (k) {
  2860. return 1 - Math.cos(k * Math.PI / 2);
  2861. },
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. sinusoidalOut: function (k) {
  2867. return Math.sin(k * Math.PI / 2);
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. sinusoidalInOut: function (k) {
  2874. return 0.5 * (1 - Math.cos(Math.PI * k));
  2875. },
  2876. // 指数曲线的缓动(2^t)
  2877. /**
  2878. * @param {number} k
  2879. * @return {number}
  2880. */
  2881. exponentialIn: function (k) {
  2882. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2883. },
  2884. /**
  2885. * @param {number} k
  2886. * @return {number}
  2887. */
  2888. exponentialOut: function (k) {
  2889. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2890. },
  2891. /**
  2892. * @param {number} k
  2893. * @return {number}
  2894. */
  2895. exponentialInOut: function (k) {
  2896. if (k === 0) {
  2897. return 0;
  2898. }
  2899. if (k === 1) {
  2900. return 1;
  2901. }
  2902. if ((k *= 2) < 1) {
  2903. return 0.5 * Math.pow(1024, k - 1);
  2904. }
  2905. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2906. },
  2907. // 圆形曲线的缓动(sqrt(1-t^2))
  2908. /**
  2909. * @param {number} k
  2910. * @return {number}
  2911. */
  2912. circularIn: function (k) {
  2913. return 1 - Math.sqrt(1 - k * k);
  2914. },
  2915. /**
  2916. * @param {number} k
  2917. * @return {number}
  2918. */
  2919. circularOut: function (k) {
  2920. return Math.sqrt(1 - (--k * k));
  2921. },
  2922. /**
  2923. * @param {number} k
  2924. * @return {number}
  2925. */
  2926. circularInOut: function (k) {
  2927. if ((k *= 2) < 1) {
  2928. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2929. }
  2930. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2931. },
  2932. // 创建类似于弹簧在停止前来回振荡的动画
  2933. /**
  2934. * @param {number} k
  2935. * @return {number}
  2936. */
  2937. elasticIn: function (k) {
  2938. var s;
  2939. var a = 0.1;
  2940. var p = 0.4;
  2941. if (k === 0) {
  2942. return 0;
  2943. }
  2944. if (k === 1) {
  2945. return 1;
  2946. }
  2947. if (!a || a < 1) {
  2948. a = 1;
  2949. s = p / 4;
  2950. }
  2951. else {
  2952. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2953. }
  2954. return -(a * Math.pow(2, 10 * (k -= 1))
  2955. * Math.sin((k - s) * (2 * Math.PI) / p));
  2956. },
  2957. /**
  2958. * @param {number} k
  2959. * @return {number}
  2960. */
  2961. elasticOut: function (k) {
  2962. var s;
  2963. var a = 0.1;
  2964. var p = 0.4;
  2965. if (k === 0) {
  2966. return 0;
  2967. }
  2968. if (k === 1) {
  2969. return 1;
  2970. }
  2971. if (!a || a < 1) {
  2972. a = 1;
  2973. s = p / 4;
  2974. }
  2975. else {
  2976. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2977. }
  2978. return (a * Math.pow(2, -10 * k)
  2979. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2980. },
  2981. /**
  2982. * @param {number} k
  2983. * @return {number}
  2984. */
  2985. elasticInOut: function (k) {
  2986. var s;
  2987. var a = 0.1;
  2988. var p = 0.4;
  2989. if (k === 0) {
  2990. return 0;
  2991. }
  2992. if (k === 1) {
  2993. return 1;
  2994. }
  2995. if (!a || a < 1) {
  2996. a = 1;
  2997. s = p / 4;
  2998. }
  2999. else {
  3000. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3001. }
  3002. if ((k *= 2) < 1) {
  3003. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3004. * Math.sin((k - s) * (2 * Math.PI) / p));
  3005. }
  3006. return a * Math.pow(2, -10 * (k -= 1))
  3007. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3008. },
  3009. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3010. /**
  3011. * @param {number} k
  3012. * @return {number}
  3013. */
  3014. backIn: function (k) {
  3015. var s = 1.70158;
  3016. return k * k * ((s + 1) * k - s);
  3017. },
  3018. /**
  3019. * @param {number} k
  3020. * @return {number}
  3021. */
  3022. backOut: function (k) {
  3023. var s = 1.70158;
  3024. return --k * k * ((s + 1) * k + s) + 1;
  3025. },
  3026. /**
  3027. * @param {number} k
  3028. * @return {number}
  3029. */
  3030. backInOut: function (k) {
  3031. var s = 1.70158 * 1.525;
  3032. if ((k *= 2) < 1) {
  3033. return 0.5 * (k * k * ((s + 1) * k - s));
  3034. }
  3035. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3036. },
  3037. // 创建弹跳效果
  3038. /**
  3039. * @param {number} k
  3040. * @return {number}
  3041. */
  3042. bounceIn: function (k) {
  3043. return 1 - easing.bounceOut(1 - k);
  3044. },
  3045. /**
  3046. * @param {number} k
  3047. * @return {number}
  3048. */
  3049. bounceOut: function (k) {
  3050. if (k < (1 / 2.75)) {
  3051. return 7.5625 * k * k;
  3052. }
  3053. else if (k < (2 / 2.75)) {
  3054. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3055. }
  3056. else if (k < (2.5 / 2.75)) {
  3057. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3058. }
  3059. else {
  3060. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3061. }
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. bounceInOut: function (k) {
  3068. if (k < 0.5) {
  3069. return easing.bounceIn(k * 2) * 0.5;
  3070. }
  3071. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3072. }
  3073. };
  3074. /**
  3075. * 动画主控制器
  3076. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3077. * @config life(1000) 动画时长
  3078. * @config delay(0) 动画延迟时间
  3079. * @config loop(true)
  3080. * @config gap(0) 循环的间隔时间
  3081. * @config onframe
  3082. * @config easing(optional)
  3083. * @config ondestroy(optional)
  3084. * @config onrestart(optional)
  3085. *
  3086. * TODO pause
  3087. */
  3088. function Clip(options) {
  3089. this._target = options.target;
  3090. // 生命周期
  3091. this._life = options.life || 1000;
  3092. // 延时
  3093. this._delay = options.delay || 0;
  3094. // 开始时间
  3095. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3096. this._initialized = false;
  3097. // 是否循环
  3098. this.loop = options.loop == null ? false : options.loop;
  3099. this.gap = options.gap || 0;
  3100. this.easing = options.easing || 'Linear';
  3101. this.onframe = options.onframe;
  3102. this.ondestroy = options.ondestroy;
  3103. this.onrestart = options.onrestart;
  3104. this._pausedTime = 0;
  3105. this._paused = false;
  3106. }
  3107. Clip.prototype = {
  3108. constructor: Clip,
  3109. step: function (globalTime, deltaTime) {
  3110. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3111. // PENDING
  3112. if (!this._initialized) {
  3113. this._startTime = globalTime + this._delay;
  3114. this._initialized = true;
  3115. }
  3116. if (this._paused) {
  3117. this._pausedTime += deltaTime;
  3118. return;
  3119. }
  3120. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3121. // 还没开始
  3122. if (percent < 0) {
  3123. return;
  3124. }
  3125. percent = Math.min(percent, 1);
  3126. var easing$$1 = this.easing;
  3127. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3128. var schedule = typeof easingFunc === 'function'
  3129. ? easingFunc(percent)
  3130. : percent;
  3131. this.fire('frame', schedule);
  3132. // 结束
  3133. if (percent === 1) {
  3134. if (this.loop) {
  3135. this.restart(globalTime);
  3136. // 重新开始周期
  3137. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3138. return 'restart';
  3139. }
  3140. // 动画完成将这个控制器标识为待删除
  3141. // 在Animation.update中进行批量删除
  3142. this._needsRemove = true;
  3143. return 'destroy';
  3144. }
  3145. return null;
  3146. },
  3147. restart: function (globalTime) {
  3148. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3149. this._startTime = globalTime - remainder + this.gap;
  3150. this._pausedTime = 0;
  3151. this._needsRemove = false;
  3152. },
  3153. fire: function (eventType, arg) {
  3154. eventType = 'on' + eventType;
  3155. if (this[eventType]) {
  3156. this[eventType](this._target, arg);
  3157. }
  3158. },
  3159. pause: function () {
  3160. this._paused = true;
  3161. },
  3162. resume: function () {
  3163. this._paused = false;
  3164. }
  3165. };
  3166. // Simple LRU cache use doubly linked list
  3167. // @module zrender/core/LRU
  3168. /**
  3169. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3170. * @constructor
  3171. */
  3172. var LinkedList = function () {
  3173. /**
  3174. * @type {module:zrender/core/LRU~Entry}
  3175. */
  3176. this.head = null;
  3177. /**
  3178. * @type {module:zrender/core/LRU~Entry}
  3179. */
  3180. this.tail = null;
  3181. this._len = 0;
  3182. };
  3183. var linkedListProto = LinkedList.prototype;
  3184. /**
  3185. * Insert a new value at the tail
  3186. * @param {} val
  3187. * @return {module:zrender/core/LRU~Entry}
  3188. */
  3189. linkedListProto.insert = function (val) {
  3190. var entry = new Entry(val);
  3191. this.insertEntry(entry);
  3192. return entry;
  3193. };
  3194. /**
  3195. * Insert an entry at the tail
  3196. * @param {module:zrender/core/LRU~Entry} entry
  3197. */
  3198. linkedListProto.insertEntry = function (entry) {
  3199. if (!this.head) {
  3200. this.head = this.tail = entry;
  3201. }
  3202. else {
  3203. this.tail.next = entry;
  3204. entry.prev = this.tail;
  3205. entry.next = null;
  3206. this.tail = entry;
  3207. }
  3208. this._len++;
  3209. };
  3210. /**
  3211. * Remove entry.
  3212. * @param {module:zrender/core/LRU~Entry} entry
  3213. */
  3214. linkedListProto.remove = function (entry) {
  3215. var prev = entry.prev;
  3216. var next = entry.next;
  3217. if (prev) {
  3218. prev.next = next;
  3219. }
  3220. else {
  3221. // Is head
  3222. this.head = next;
  3223. }
  3224. if (next) {
  3225. next.prev = prev;
  3226. }
  3227. else {
  3228. // Is tail
  3229. this.tail = prev;
  3230. }
  3231. entry.next = entry.prev = null;
  3232. this._len--;
  3233. };
  3234. /**
  3235. * @return {number}
  3236. */
  3237. linkedListProto.len = function () {
  3238. return this._len;
  3239. };
  3240. /**
  3241. * Clear list
  3242. */
  3243. linkedListProto.clear = function () {
  3244. this.head = this.tail = null;
  3245. this._len = 0;
  3246. };
  3247. /**
  3248. * @constructor
  3249. * @param {} val
  3250. */
  3251. var Entry = function (val) {
  3252. /**
  3253. * @type {}
  3254. */
  3255. this.value = val;
  3256. /**
  3257. * @type {module:zrender/core/LRU~Entry}
  3258. */
  3259. this.next;
  3260. /**
  3261. * @type {module:zrender/core/LRU~Entry}
  3262. */
  3263. this.prev;
  3264. };
  3265. /**
  3266. * LRU Cache
  3267. * @constructor
  3268. * @alias module:zrender/core/LRU
  3269. */
  3270. var LRU = function (maxSize) {
  3271. this._list = new LinkedList();
  3272. this._map = {};
  3273. this._maxSize = maxSize || 10;
  3274. this._lastRemovedEntry = null;
  3275. };
  3276. var LRUProto = LRU.prototype;
  3277. /**
  3278. * @param {string} key
  3279. * @param {} value
  3280. * @return {} Removed value
  3281. */
  3282. LRUProto.put = function (key, value) {
  3283. var list = this._list;
  3284. var map = this._map;
  3285. var removed = null;
  3286. if (map[key] == null) {
  3287. var len = list.len();
  3288. // Reuse last removed entry
  3289. var entry = this._lastRemovedEntry;
  3290. if (len >= this._maxSize && len > 0) {
  3291. // Remove the least recently used
  3292. var leastUsedEntry = list.head;
  3293. list.remove(leastUsedEntry);
  3294. delete map[leastUsedEntry.key];
  3295. removed = leastUsedEntry.value;
  3296. this._lastRemovedEntry = leastUsedEntry;
  3297. }
  3298. if (entry) {
  3299. entry.value = value;
  3300. }
  3301. else {
  3302. entry = new Entry(value);
  3303. }
  3304. entry.key = key;
  3305. list.insertEntry(entry);
  3306. map[key] = entry;
  3307. }
  3308. return removed;
  3309. };
  3310. /**
  3311. * @param {string} key
  3312. * @return {}
  3313. */
  3314. LRUProto.get = function (key) {
  3315. var entry = this._map[key];
  3316. var list = this._list;
  3317. if (entry != null) {
  3318. // Put the latest used entry in the tail
  3319. if (entry !== list.tail) {
  3320. list.remove(entry);
  3321. list.insertEntry(entry);
  3322. }
  3323. return entry.value;
  3324. }
  3325. };
  3326. /**
  3327. * Clear the cache
  3328. */
  3329. LRUProto.clear = function () {
  3330. this._list.clear();
  3331. this._map = {};
  3332. };
  3333. var kCSSColorTable = {
  3334. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3335. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3336. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3337. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3338. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3339. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3340. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3341. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3342. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3343. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3344. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3345. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3346. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3347. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3348. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3349. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3350. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3351. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3352. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3353. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3354. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3355. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3356. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3357. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3358. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3359. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3360. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3361. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3362. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3363. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3364. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3365. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3366. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3367. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3368. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3369. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3370. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3371. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3372. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3373. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3374. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3375. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3376. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3377. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3378. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3379. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3380. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3381. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3382. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3383. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3384. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3385. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3386. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3387. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3388. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3389. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3390. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3391. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3392. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3393. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3394. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3395. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3396. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3397. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3398. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3399. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3400. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3401. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3402. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3403. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3404. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3405. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3406. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3407. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3408. };
  3409. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3410. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3411. return i < 0 ? 0 : i > 255 ? 255 : i;
  3412. }
  3413. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3414. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3415. return i < 0 ? 0 : i > 360 ? 360 : i;
  3416. }
  3417. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3418. return f < 0 ? 0 : f > 1 ? 1 : f;
  3419. }
  3420. function parseCssInt(str) { // int or percentage.
  3421. if (str.length && str.charAt(str.length - 1) === '%') {
  3422. return clampCssByte(parseFloat(str) / 100 * 255);
  3423. }
  3424. return clampCssByte(parseInt(str, 10));
  3425. }
  3426. function parseCssFloat(str) { // float or percentage.
  3427. if (str.length && str.charAt(str.length - 1) === '%') {
  3428. return clampCssFloat(parseFloat(str) / 100);
  3429. }
  3430. return clampCssFloat(parseFloat(str));
  3431. }
  3432. function cssHueToRgb(m1, m2, h) {
  3433. if (h < 0) {
  3434. h += 1;
  3435. }
  3436. else if (h > 1) {
  3437. h -= 1;
  3438. }
  3439. if (h * 6 < 1) {
  3440. return m1 + (m2 - m1) * h * 6;
  3441. }
  3442. if (h * 2 < 1) {
  3443. return m2;
  3444. }
  3445. if (h * 3 < 2) {
  3446. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3447. }
  3448. return m1;
  3449. }
  3450. function lerpNumber(a, b, p) {
  3451. return a + (b - a) * p;
  3452. }
  3453. function setRgba(out, r, g, b, a) {
  3454. out[0] = r;
  3455. out[1] = g;
  3456. out[2] = b;
  3457. out[3] = a;
  3458. return out;
  3459. }
  3460. function copyRgba(out, a) {
  3461. out[0] = a[0];
  3462. out[1] = a[1];
  3463. out[2] = a[2];
  3464. out[3] = a[3];
  3465. return out;
  3466. }
  3467. var colorCache = new LRU(20);
  3468. var lastRemovedArr = null;
  3469. function putToCache(colorStr, rgbaArr) {
  3470. // Reuse removed array
  3471. if (lastRemovedArr) {
  3472. copyRgba(lastRemovedArr, rgbaArr);
  3473. }
  3474. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3475. }
  3476. /**
  3477. * @param {string} colorStr
  3478. * @param {Array.<number>} out
  3479. * @return {Array.<number>}
  3480. * @memberOf module:zrender/util/color
  3481. */
  3482. function parse(colorStr, rgbaArr) {
  3483. if (!colorStr) {
  3484. return;
  3485. }
  3486. rgbaArr = rgbaArr || [];
  3487. var cached = colorCache.get(colorStr);
  3488. if (cached) {
  3489. return copyRgba(rgbaArr, cached);
  3490. }
  3491. // colorStr may be not string
  3492. colorStr = colorStr + '';
  3493. // Remove all whitespace, not compliant, but should just be more accepting.
  3494. var str = colorStr.replace(/ /g, '').toLowerCase();
  3495. // Color keywords (and transparent) lookup.
  3496. if (str in kCSSColorTable) {
  3497. copyRgba(rgbaArr, kCSSColorTable[str]);
  3498. putToCache(colorStr, rgbaArr);
  3499. return rgbaArr;
  3500. }
  3501. // #abc and #abc123 syntax.
  3502. if (str.charAt(0) === '#') {
  3503. if (str.length === 4) {
  3504. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3505. if (!(iv >= 0 && iv <= 0xfff)) {
  3506. setRgba(rgbaArr, 0, 0, 0, 1);
  3507. return; // Covers NaN.
  3508. }
  3509. setRgba(rgbaArr,
  3510. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3511. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3512. (iv & 0xf) | ((iv & 0xf) << 4),
  3513. 1
  3514. );
  3515. putToCache(colorStr, rgbaArr);
  3516. return rgbaArr;
  3517. }
  3518. else if (str.length === 7) {
  3519. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3520. if (!(iv >= 0 && iv <= 0xffffff)) {
  3521. setRgba(rgbaArr, 0, 0, 0, 1);
  3522. return; // Covers NaN.
  3523. }
  3524. setRgba(rgbaArr,
  3525. (iv & 0xff0000) >> 16,
  3526. (iv & 0xff00) >> 8,
  3527. iv & 0xff,
  3528. 1
  3529. );
  3530. putToCache(colorStr, rgbaArr);
  3531. return rgbaArr;
  3532. }
  3533. return;
  3534. }
  3535. var op = str.indexOf('(');
  3536. var ep = str.indexOf(')');
  3537. if (op !== -1 && ep + 1 === str.length) {
  3538. var fname = str.substr(0, op);
  3539. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3540. var alpha = 1; // To allow case fallthrough.
  3541. switch (fname) {
  3542. case 'rgba':
  3543. if (params.length !== 4) {
  3544. setRgba(rgbaArr, 0, 0, 0, 1);
  3545. return;
  3546. }
  3547. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3548. // Fall through.
  3549. case 'rgb':
  3550. if (params.length !== 3) {
  3551. setRgba(rgbaArr, 0, 0, 0, 1);
  3552. return;
  3553. }
  3554. setRgba(rgbaArr,
  3555. parseCssInt(params[0]),
  3556. parseCssInt(params[1]),
  3557. parseCssInt(params[2]),
  3558. alpha
  3559. );
  3560. putToCache(colorStr, rgbaArr);
  3561. return rgbaArr;
  3562. case 'hsla':
  3563. if (params.length !== 4) {
  3564. setRgba(rgbaArr, 0, 0, 0, 1);
  3565. return;
  3566. }
  3567. params[3] = parseCssFloat(params[3]);
  3568. hsla2rgba(params, rgbaArr);
  3569. putToCache(colorStr, rgbaArr);
  3570. return rgbaArr;
  3571. case 'hsl':
  3572. if (params.length !== 3) {
  3573. setRgba(rgbaArr, 0, 0, 0, 1);
  3574. return;
  3575. }
  3576. hsla2rgba(params, rgbaArr);
  3577. putToCache(colorStr, rgbaArr);
  3578. return rgbaArr;
  3579. default:
  3580. return;
  3581. }
  3582. }
  3583. setRgba(rgbaArr, 0, 0, 0, 1);
  3584. return;
  3585. }
  3586. /**
  3587. * @param {Array.<number>} hsla
  3588. * @param {Array.<number>} rgba
  3589. * @return {Array.<number>} rgba
  3590. */
  3591. function hsla2rgba(hsla, rgba) {
  3592. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3593. // NOTE(deanm): According to the CSS spec s/l should only be
  3594. // percentages, but we don't bother and let float or percentage.
  3595. var s = parseCssFloat(hsla[1]);
  3596. var l = parseCssFloat(hsla[2]);
  3597. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3598. var m1 = l * 2 - m2;
  3599. rgba = rgba || [];
  3600. setRgba(rgba,
  3601. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3602. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3603. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3604. 1
  3605. );
  3606. if (hsla.length === 4) {
  3607. rgba[3] = hsla[3];
  3608. }
  3609. return rgba;
  3610. }
  3611. /**
  3612. * @param {Array.<number>} rgba
  3613. * @return {Array.<number>} hsla
  3614. */
  3615. function rgba2hsla(rgba) {
  3616. if (!rgba) {
  3617. return;
  3618. }
  3619. // RGB from 0 to 255
  3620. var R = rgba[0] / 255;
  3621. var G = rgba[1] / 255;
  3622. var B = rgba[2] / 255;
  3623. var vMin = Math.min(R, G, B); // Min. value of RGB
  3624. var vMax = Math.max(R, G, B); // Max. value of RGB
  3625. var delta = vMax - vMin; // Delta RGB value
  3626. var L = (vMax + vMin) / 2;
  3627. var H;
  3628. var S;
  3629. // HSL results from 0 to 1
  3630. if (delta === 0) {
  3631. H = 0;
  3632. S = 0;
  3633. }
  3634. else {
  3635. if (L < 0.5) {
  3636. S = delta / (vMax + vMin);
  3637. }
  3638. else {
  3639. S = delta / (2 - vMax - vMin);
  3640. }
  3641. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3642. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3643. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3644. if (R === vMax) {
  3645. H = deltaB - deltaG;
  3646. }
  3647. else if (G === vMax) {
  3648. H = (1 / 3) + deltaR - deltaB;
  3649. }
  3650. else if (B === vMax) {
  3651. H = (2 / 3) + deltaG - deltaR;
  3652. }
  3653. if (H < 0) {
  3654. H += 1;
  3655. }
  3656. if (H > 1) {
  3657. H -= 1;
  3658. }
  3659. }
  3660. var hsla = [H * 360, S, L];
  3661. if (rgba[3] != null) {
  3662. hsla.push(rgba[3]);
  3663. }
  3664. return hsla;
  3665. }
  3666. /**
  3667. * @param {string} color
  3668. * @param {number} level
  3669. * @return {string}
  3670. * @memberOf module:zrender/util/color
  3671. */
  3672. function lift(color, level) {
  3673. var colorArr = parse(color);
  3674. if (colorArr) {
  3675. for (var i = 0; i < 3; i++) {
  3676. if (level < 0) {
  3677. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3678. }
  3679. else {
  3680. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3681. }
  3682. if (colorArr[i] > 255) {
  3683. colorArr[i] = 255;
  3684. }
  3685. else if (color[i] < 0) {
  3686. colorArr[i] = 0;
  3687. }
  3688. }
  3689. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3690. }
  3691. }
  3692. /**
  3693. * @param {string} color
  3694. * @return {string}
  3695. * @memberOf module:zrender/util/color
  3696. */
  3697. function toHex(color) {
  3698. var colorArr = parse(color);
  3699. if (colorArr) {
  3700. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3701. }
  3702. }
  3703. /**
  3704. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3705. * @param {number} normalizedValue A float between 0 and 1.
  3706. * @param {Array.<Array.<number>>} colors List of rgba color array
  3707. * @param {Array.<number>} [out] Mapped gba color array
  3708. * @return {Array.<number>} will be null/undefined if input illegal.
  3709. */
  3710. function fastLerp(normalizedValue, colors, out) {
  3711. if (!(colors && colors.length)
  3712. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3713. ) {
  3714. return;
  3715. }
  3716. out = out || [];
  3717. var value = normalizedValue * (colors.length - 1);
  3718. var leftIndex = Math.floor(value);
  3719. var rightIndex = Math.ceil(value);
  3720. var leftColor = colors[leftIndex];
  3721. var rightColor = colors[rightIndex];
  3722. var dv = value - leftIndex;
  3723. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3724. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3725. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3726. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3727. return out;
  3728. }
  3729. /**
  3730. * @deprecated
  3731. */
  3732. var fastMapToColor = fastLerp;
  3733. /**
  3734. * @param {number} normalizedValue A float between 0 and 1.
  3735. * @param {Array.<string>} colors Color list.
  3736. * @param {boolean=} fullOutput Default false.
  3737. * @return {(string|Object)} Result color. If fullOutput,
  3738. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3739. * @memberOf module:zrender/util/color
  3740. */
  3741. function lerp$1(normalizedValue, colors, fullOutput) {
  3742. if (!(colors && colors.length)
  3743. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3744. ) {
  3745. return;
  3746. }
  3747. var value = normalizedValue * (colors.length - 1);
  3748. var leftIndex = Math.floor(value);
  3749. var rightIndex = Math.ceil(value);
  3750. var leftColor = parse(colors[leftIndex]);
  3751. var rightColor = parse(colors[rightIndex]);
  3752. var dv = value - leftIndex;
  3753. var color = stringify(
  3754. [
  3755. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3756. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3757. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3758. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3759. ],
  3760. 'rgba'
  3761. );
  3762. return fullOutput
  3763. ? {
  3764. color: color,
  3765. leftIndex: leftIndex,
  3766. rightIndex: rightIndex,
  3767. value: value
  3768. }
  3769. : color;
  3770. }
  3771. /**
  3772. * @deprecated
  3773. */
  3774. var mapToColor = lerp$1;
  3775. /**
  3776. * @param {string} color
  3777. * @param {number=} h 0 ~ 360, ignore when null.
  3778. * @param {number=} s 0 ~ 1, ignore when null.
  3779. * @param {number=} l 0 ~ 1, ignore when null.
  3780. * @return {string} Color string in rgba format.
  3781. * @memberOf module:zrender/util/color
  3782. */
  3783. function modifyHSL(color, h, s, l) {
  3784. color = parse(color);
  3785. if (color) {
  3786. color = rgba2hsla(color);
  3787. h != null && (color[0] = clampCssAngle(h));
  3788. s != null && (color[1] = parseCssFloat(s));
  3789. l != null && (color[2] = parseCssFloat(l));
  3790. return stringify(hsla2rgba(color), 'rgba');
  3791. }
  3792. }
  3793. /**
  3794. * @param {string} color
  3795. * @param {number=} alpha 0 ~ 1
  3796. * @return {string} Color string in rgba format.
  3797. * @memberOf module:zrender/util/color
  3798. */
  3799. function modifyAlpha(color, alpha) {
  3800. color = parse(color);
  3801. if (color && alpha != null) {
  3802. color[3] = clampCssFloat(alpha);
  3803. return stringify(color, 'rgba');
  3804. }
  3805. }
  3806. /**
  3807. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3808. * @param {string} type 'rgba', 'hsva', ...
  3809. * @return {string} Result color. (If input illegal, return undefined).
  3810. */
  3811. function stringify(arrColor, type) {
  3812. if (!arrColor || !arrColor.length) {
  3813. return;
  3814. }
  3815. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3816. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3817. colorStr += ',' + arrColor[3];
  3818. }
  3819. return type + '(' + colorStr + ')';
  3820. }
  3821. var color = (Object.freeze || Object)({
  3822. parse: parse,
  3823. lift: lift,
  3824. toHex: toHex,
  3825. fastLerp: fastLerp,
  3826. fastMapToColor: fastMapToColor,
  3827. lerp: lerp$1,
  3828. mapToColor: mapToColor,
  3829. modifyHSL: modifyHSL,
  3830. modifyAlpha: modifyAlpha,
  3831. stringify: stringify
  3832. });
  3833. /**
  3834. * @module echarts/animation/Animator
  3835. */
  3836. var arraySlice = Array.prototype.slice;
  3837. function defaultGetter(target, key) {
  3838. return target[key];
  3839. }
  3840. function defaultSetter(target, key, value) {
  3841. target[key] = value;
  3842. }
  3843. /**
  3844. * @param {number} p0
  3845. * @param {number} p1
  3846. * @param {number} percent
  3847. * @return {number}
  3848. */
  3849. function interpolateNumber(p0, p1, percent) {
  3850. return (p1 - p0) * percent + p0;
  3851. }
  3852. /**
  3853. * @param {string} p0
  3854. * @param {string} p1
  3855. * @param {number} percent
  3856. * @return {string}
  3857. */
  3858. function interpolateString(p0, p1, percent) {
  3859. return percent > 0.5 ? p1 : p0;
  3860. }
  3861. /**
  3862. * @param {Array} p0
  3863. * @param {Array} p1
  3864. * @param {number} percent
  3865. * @param {Array} out
  3866. * @param {number} arrDim
  3867. */
  3868. function interpolateArray(p0, p1, percent, out, arrDim) {
  3869. var len = p0.length;
  3870. if (arrDim === 1) {
  3871. for (var i = 0; i < len; i++) {
  3872. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3873. }
  3874. }
  3875. else {
  3876. var len2 = len && p0[0].length;
  3877. for (var i = 0; i < len; i++) {
  3878. for (var j = 0; j < len2; j++) {
  3879. out[i][j] = interpolateNumber(
  3880. p0[i][j], p1[i][j], percent
  3881. );
  3882. }
  3883. }
  3884. }
  3885. }
  3886. // arr0 is source array, arr1 is target array.
  3887. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3888. function fillArr(arr0, arr1, arrDim) {
  3889. var arr0Len = arr0.length;
  3890. var arr1Len = arr1.length;
  3891. if (arr0Len !== arr1Len) {
  3892. // FIXME Not work for TypedArray
  3893. var isPreviousLarger = arr0Len > arr1Len;
  3894. if (isPreviousLarger) {
  3895. // Cut the previous
  3896. arr0.length = arr1Len;
  3897. }
  3898. else {
  3899. // Fill the previous
  3900. for (var i = arr0Len; i < arr1Len; i++) {
  3901. arr0.push(
  3902. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3903. );
  3904. }
  3905. }
  3906. }
  3907. // Handling NaN value
  3908. var len2 = arr0[0] && arr0[0].length;
  3909. for (var i = 0; i < arr0.length; i++) {
  3910. if (arrDim === 1) {
  3911. if (isNaN(arr0[i])) {
  3912. arr0[i] = arr1[i];
  3913. }
  3914. }
  3915. else {
  3916. for (var j = 0; j < len2; j++) {
  3917. if (isNaN(arr0[i][j])) {
  3918. arr0[i][j] = arr1[i][j];
  3919. }
  3920. }
  3921. }
  3922. }
  3923. }
  3924. /**
  3925. * @param {Array} arr0
  3926. * @param {Array} arr1
  3927. * @param {number} arrDim
  3928. * @return {boolean}
  3929. */
  3930. function isArraySame(arr0, arr1, arrDim) {
  3931. if (arr0 === arr1) {
  3932. return true;
  3933. }
  3934. var len = arr0.length;
  3935. if (len !== arr1.length) {
  3936. return false;
  3937. }
  3938. if (arrDim === 1) {
  3939. for (var i = 0; i < len; i++) {
  3940. if (arr0[i] !== arr1[i]) {
  3941. return false;
  3942. }
  3943. }
  3944. }
  3945. else {
  3946. var len2 = arr0[0].length;
  3947. for (var i = 0; i < len; i++) {
  3948. for (var j = 0; j < len2; j++) {
  3949. if (arr0[i][j] !== arr1[i][j]) {
  3950. return false;
  3951. }
  3952. }
  3953. }
  3954. }
  3955. return true;
  3956. }
  3957. /**
  3958. * Catmull Rom interpolate array
  3959. * @param {Array} p0
  3960. * @param {Array} p1
  3961. * @param {Array} p2
  3962. * @param {Array} p3
  3963. * @param {number} t
  3964. * @param {number} t2
  3965. * @param {number} t3
  3966. * @param {Array} out
  3967. * @param {number} arrDim
  3968. */
  3969. function catmullRomInterpolateArray(
  3970. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3971. ) {
  3972. var len = p0.length;
  3973. if (arrDim === 1) {
  3974. for (var i = 0; i < len; i++) {
  3975. out[i] = catmullRomInterpolate(
  3976. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3977. );
  3978. }
  3979. }
  3980. else {
  3981. var len2 = p0[0].length;
  3982. for (var i = 0; i < len; i++) {
  3983. for (var j = 0; j < len2; j++) {
  3984. out[i][j] = catmullRomInterpolate(
  3985. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3986. t, t2, t3
  3987. );
  3988. }
  3989. }
  3990. }
  3991. }
  3992. /**
  3993. * Catmull Rom interpolate number
  3994. * @param {number} p0
  3995. * @param {number} p1
  3996. * @param {number} p2
  3997. * @param {number} p3
  3998. * @param {number} t
  3999. * @param {number} t2
  4000. * @param {number} t3
  4001. * @return {number}
  4002. */
  4003. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4004. var v0 = (p2 - p0) * 0.5;
  4005. var v1 = (p3 - p1) * 0.5;
  4006. return (2 * (p1 - p2) + v0 + v1) * t3
  4007. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4008. + v0 * t + p1;
  4009. }
  4010. function cloneValue(value) {
  4011. if (isArrayLike(value)) {
  4012. var len = value.length;
  4013. if (isArrayLike(value[0])) {
  4014. var ret = [];
  4015. for (var i = 0; i < len; i++) {
  4016. ret.push(arraySlice.call(value[i]));
  4017. }
  4018. return ret;
  4019. }
  4020. return arraySlice.call(value);
  4021. }
  4022. return value;
  4023. }
  4024. function rgba2String(rgba) {
  4025. rgba[0] = Math.floor(rgba[0]);
  4026. rgba[1] = Math.floor(rgba[1]);
  4027. rgba[2] = Math.floor(rgba[2]);
  4028. return 'rgba(' + rgba.join(',') + ')';
  4029. }
  4030. function getArrayDim(keyframes) {
  4031. var lastValue = keyframes[keyframes.length - 1].value;
  4032. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4033. }
  4034. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4035. var getter = animator._getter;
  4036. var setter = animator._setter;
  4037. var useSpline = easing === 'spline';
  4038. var trackLen = keyframes.length;
  4039. if (!trackLen) {
  4040. return;
  4041. }
  4042. // Guess data type
  4043. var firstVal = keyframes[0].value;
  4044. var isValueArray = isArrayLike(firstVal);
  4045. var isValueColor = false;
  4046. var isValueString = false;
  4047. // For vertices morphing
  4048. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4049. var trackMaxTime;
  4050. // Sort keyframe as ascending
  4051. keyframes.sort(function (a, b) {
  4052. return a.time - b.time;
  4053. });
  4054. trackMaxTime = keyframes[trackLen - 1].time;
  4055. // Percents of each keyframe
  4056. var kfPercents = [];
  4057. // Value of each keyframe
  4058. var kfValues = [];
  4059. var prevValue = keyframes[0].value;
  4060. var isAllValueEqual = true;
  4061. for (var i = 0; i < trackLen; i++) {
  4062. kfPercents.push(keyframes[i].time / trackMaxTime);
  4063. // Assume value is a color when it is a string
  4064. var value = keyframes[i].value;
  4065. // Check if value is equal, deep check if value is array
  4066. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4067. || (!isValueArray && value === prevValue))) {
  4068. isAllValueEqual = false;
  4069. }
  4070. prevValue = value;
  4071. // Try converting a string to a color array
  4072. if (typeof value === 'string') {
  4073. var colorArray = parse(value);
  4074. if (colorArray) {
  4075. value = colorArray;
  4076. isValueColor = true;
  4077. }
  4078. else {
  4079. isValueString = true;
  4080. }
  4081. }
  4082. kfValues.push(value);
  4083. }
  4084. if (!forceAnimate && isAllValueEqual) {
  4085. return;
  4086. }
  4087. var lastValue = kfValues[trackLen - 1];
  4088. // Polyfill array and NaN value
  4089. for (var i = 0; i < trackLen - 1; i++) {
  4090. if (isValueArray) {
  4091. fillArr(kfValues[i], lastValue, arrDim);
  4092. }
  4093. else {
  4094. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4095. kfValues[i] = lastValue;
  4096. }
  4097. }
  4098. }
  4099. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4100. // Cache the key of last frame to speed up when
  4101. // animation playback is sequency
  4102. var lastFrame = 0;
  4103. var lastFramePercent = 0;
  4104. var start;
  4105. var w;
  4106. var p0;
  4107. var p1;
  4108. var p2;
  4109. var p3;
  4110. if (isValueColor) {
  4111. var rgba = [0, 0, 0, 0];
  4112. }
  4113. var onframe = function (target, percent) {
  4114. // Find the range keyframes
  4115. // kf1-----kf2---------current--------kf3
  4116. // find kf2 and kf3 and do interpolation
  4117. var frame;
  4118. // In the easing function like elasticOut, percent may less than 0
  4119. if (percent < 0) {
  4120. frame = 0;
  4121. }
  4122. else if (percent < lastFramePercent) {
  4123. // Start from next key
  4124. // PENDING start from lastFrame ?
  4125. start = Math.min(lastFrame + 1, trackLen - 1);
  4126. for (frame = start; frame >= 0; frame--) {
  4127. if (kfPercents[frame] <= percent) {
  4128. break;
  4129. }
  4130. }
  4131. // PENDING really need to do this ?
  4132. frame = Math.min(frame, trackLen - 2);
  4133. }
  4134. else {
  4135. for (frame = lastFrame; frame < trackLen; frame++) {
  4136. if (kfPercents[frame] > percent) {
  4137. break;
  4138. }
  4139. }
  4140. frame = Math.min(frame - 1, trackLen - 2);
  4141. }
  4142. lastFrame = frame;
  4143. lastFramePercent = percent;
  4144. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4145. if (range === 0) {
  4146. return;
  4147. }
  4148. else {
  4149. w = (percent - kfPercents[frame]) / range;
  4150. }
  4151. if (useSpline) {
  4152. p1 = kfValues[frame];
  4153. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4154. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4155. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4156. if (isValueArray) {
  4157. catmullRomInterpolateArray(
  4158. p0, p1, p2, p3, w, w * w, w * w * w,
  4159. getter(target, propName),
  4160. arrDim
  4161. );
  4162. }
  4163. else {
  4164. var value;
  4165. if (isValueColor) {
  4166. value = catmullRomInterpolateArray(
  4167. p0, p1, p2, p3, w, w * w, w * w * w,
  4168. rgba, 1
  4169. );
  4170. value = rgba2String(rgba);
  4171. }
  4172. else if (isValueString) {
  4173. // String is step(0.5)
  4174. return interpolateString(p1, p2, w);
  4175. }
  4176. else {
  4177. value = catmullRomInterpolate(
  4178. p0, p1, p2, p3, w, w * w, w * w * w
  4179. );
  4180. }
  4181. setter(
  4182. target,
  4183. propName,
  4184. value
  4185. );
  4186. }
  4187. }
  4188. else {
  4189. if (isValueArray) {
  4190. interpolateArray(
  4191. kfValues[frame], kfValues[frame + 1], w,
  4192. getter(target, propName),
  4193. arrDim
  4194. );
  4195. }
  4196. else {
  4197. var value;
  4198. if (isValueColor) {
  4199. interpolateArray(
  4200. kfValues[frame], kfValues[frame + 1], w,
  4201. rgba, 1
  4202. );
  4203. value = rgba2String(rgba);
  4204. }
  4205. else if (isValueString) {
  4206. // String is step(0.5)
  4207. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4208. }
  4209. else {
  4210. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4211. }
  4212. setter(
  4213. target,
  4214. propName,
  4215. value
  4216. );
  4217. }
  4218. }
  4219. };
  4220. var clip = new Clip({
  4221. target: animator._target,
  4222. life: trackMaxTime,
  4223. loop: animator._loop,
  4224. delay: animator._delay,
  4225. onframe: onframe,
  4226. ondestroy: oneTrackDone
  4227. });
  4228. if (easing && easing !== 'spline') {
  4229. clip.easing = easing;
  4230. }
  4231. return clip;
  4232. }
  4233. /**
  4234. * @alias module:zrender/animation/Animator
  4235. * @constructor
  4236. * @param {Object} target
  4237. * @param {boolean} loop
  4238. * @param {Function} getter
  4239. * @param {Function} setter
  4240. */
  4241. var Animator = function (target, loop, getter, setter) {
  4242. this._tracks = {};
  4243. this._target = target;
  4244. this._loop = loop || false;
  4245. this._getter = getter || defaultGetter;
  4246. this._setter = setter || defaultSetter;
  4247. this._clipCount = 0;
  4248. this._delay = 0;
  4249. this._doneList = [];
  4250. this._onframeList = [];
  4251. this._clipList = [];
  4252. };
  4253. Animator.prototype = {
  4254. /**
  4255. * 设置动画关键帧
  4256. * @param {number} time 关键帧时间,单位是ms
  4257. * @param {Object} props 关键帧的属性值,key-value表示
  4258. * @return {module:zrender/animation/Animator}
  4259. */
  4260. when: function (time /* ms */, props) {
  4261. var tracks = this._tracks;
  4262. for (var propName in props) {
  4263. if (!props.hasOwnProperty(propName)) {
  4264. continue;
  4265. }
  4266. if (!tracks[propName]) {
  4267. tracks[propName] = [];
  4268. // Invalid value
  4269. var value = this._getter(this._target, propName);
  4270. if (value == null) {
  4271. // zrLog('Invalid property ' + propName);
  4272. continue;
  4273. }
  4274. // If time is 0
  4275. // Then props is given initialize value
  4276. // Else
  4277. // Initialize value from current prop value
  4278. if (time !== 0) {
  4279. tracks[propName].push({
  4280. time: 0,
  4281. value: cloneValue(value)
  4282. });
  4283. }
  4284. }
  4285. tracks[propName].push({
  4286. time: time,
  4287. value: props[propName]
  4288. });
  4289. }
  4290. return this;
  4291. },
  4292. /**
  4293. * 添加动画每一帧的回调函数
  4294. * @param {Function} callback
  4295. * @return {module:zrender/animation/Animator}
  4296. */
  4297. during: function (callback) {
  4298. this._onframeList.push(callback);
  4299. return this;
  4300. },
  4301. pause: function () {
  4302. for (var i = 0; i < this._clipList.length; i++) {
  4303. this._clipList[i].pause();
  4304. }
  4305. this._paused = true;
  4306. },
  4307. resume: function () {
  4308. for (var i = 0; i < this._clipList.length; i++) {
  4309. this._clipList[i].resume();
  4310. }
  4311. this._paused = false;
  4312. },
  4313. isPaused: function () {
  4314. return !!this._paused;
  4315. },
  4316. _doneCallback: function () {
  4317. // Clear all tracks
  4318. this._tracks = {};
  4319. // Clear all clips
  4320. this._clipList.length = 0;
  4321. var doneList = this._doneList;
  4322. var len = doneList.length;
  4323. for (var i = 0; i < len; i++) {
  4324. doneList[i].call(this);
  4325. }
  4326. },
  4327. /**
  4328. * 开始执行动画
  4329. * @param {string|Function} [easing]
  4330. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4331. * @param {boolean} forceAnimate
  4332. * @return {module:zrender/animation/Animator}
  4333. */
  4334. start: function (easing, forceAnimate) {
  4335. var self = this;
  4336. var clipCount = 0;
  4337. var oneTrackDone = function () {
  4338. clipCount--;
  4339. if (!clipCount) {
  4340. self._doneCallback();
  4341. }
  4342. };
  4343. var lastClip;
  4344. for (var propName in this._tracks) {
  4345. if (!this._tracks.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. var clip = createTrackClip(
  4349. this, easing, oneTrackDone,
  4350. this._tracks[propName], propName, forceAnimate
  4351. );
  4352. if (clip) {
  4353. this._clipList.push(clip);
  4354. clipCount++;
  4355. // If start after added to animation
  4356. if (this.animation) {
  4357. this.animation.addClip(clip);
  4358. }
  4359. lastClip = clip;
  4360. }
  4361. }
  4362. // Add during callback on the last clip
  4363. if (lastClip) {
  4364. var oldOnFrame = lastClip.onframe;
  4365. lastClip.onframe = function (target, percent) {
  4366. oldOnFrame(target, percent);
  4367. for (var i = 0; i < self._onframeList.length; i++) {
  4368. self._onframeList[i](target, percent);
  4369. }
  4370. };
  4371. }
  4372. // This optimization will help the case that in the upper application
  4373. // the view may be refreshed frequently, where animation will be
  4374. // called repeatly but nothing changed.
  4375. if (!clipCount) {
  4376. this._doneCallback();
  4377. }
  4378. return this;
  4379. },
  4380. /**
  4381. * 停止动画
  4382. * @param {boolean} forwardToLast If move to last frame before stop
  4383. */
  4384. stop: function (forwardToLast) {
  4385. var clipList = this._clipList;
  4386. var animation = this.animation;
  4387. for (var i = 0; i < clipList.length; i++) {
  4388. var clip = clipList[i];
  4389. if (forwardToLast) {
  4390. // Move to last frame before stop
  4391. clip.onframe(this._target, 1);
  4392. }
  4393. animation && animation.removeClip(clip);
  4394. }
  4395. clipList.length = 0;
  4396. },
  4397. /**
  4398. * 设置动画延迟开始的时间
  4399. * @param {number} time 单位ms
  4400. * @return {module:zrender/animation/Animator}
  4401. */
  4402. delay: function (time) {
  4403. this._delay = time;
  4404. return this;
  4405. },
  4406. /**
  4407. * 添加动画结束的回调
  4408. * @param {Function} cb
  4409. * @return {module:zrender/animation/Animator}
  4410. */
  4411. done: function (cb) {
  4412. if (cb) {
  4413. this._doneList.push(cb);
  4414. }
  4415. return this;
  4416. },
  4417. /**
  4418. * @return {Array.<module:zrender/animation/Clip>}
  4419. */
  4420. getClips: function () {
  4421. return this._clipList;
  4422. }
  4423. };
  4424. var dpr = 1;
  4425. // If in browser environment
  4426. if (typeof window !== 'undefined') {
  4427. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4428. }
  4429. /**
  4430. * config默认配置项
  4431. * @exports zrender/config
  4432. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4433. */
  4434. /**
  4435. * Debug log mode:
  4436. * 0: Do nothing, for release.
  4437. * 1: console.error, for debug.
  4438. */
  4439. var debugMode = 0;
  4440. // retina 屏幕优化
  4441. var devicePixelRatio = dpr;
  4442. var logError = function () {
  4443. };
  4444. if (debugMode === 1) {
  4445. logError = console.error;
  4446. }
  4447. var logError$1 = logError;
  4448. /**
  4449. * @alias modue:zrender/mixin/Animatable
  4450. * @constructor
  4451. */
  4452. var Animatable = function () {
  4453. /**
  4454. * @type {Array.<module:zrender/animation/Animator>}
  4455. * @readOnly
  4456. */
  4457. this.animators = [];
  4458. };
  4459. Animatable.prototype = {
  4460. constructor: Animatable,
  4461. /**
  4462. * 动画
  4463. *
  4464. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4465. * @param {boolean} [loop] Whether to loop animation.
  4466. * @return {module:zrender/animation/Animator}
  4467. * @example:
  4468. * el.animate('style', false)
  4469. * .when(1000, {x: 10} )
  4470. * .done(function(){ // Animation done })
  4471. * .start()
  4472. */
  4473. animate: function (path, loop) {
  4474. var target;
  4475. var animatingShape = false;
  4476. var el = this;
  4477. var zr = this.__zr;
  4478. if (path) {
  4479. var pathSplitted = path.split('.');
  4480. var prop = el;
  4481. // If animating shape
  4482. animatingShape = pathSplitted[0] === 'shape';
  4483. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4484. if (!prop) {
  4485. continue;
  4486. }
  4487. prop = prop[pathSplitted[i]];
  4488. }
  4489. if (prop) {
  4490. target = prop;
  4491. }
  4492. }
  4493. else {
  4494. target = el;
  4495. }
  4496. if (!target) {
  4497. logError$1(
  4498. 'Property "'
  4499. + path
  4500. + '" is not existed in element '
  4501. + el.id
  4502. );
  4503. return;
  4504. }
  4505. var animators = el.animators;
  4506. var animator = new Animator(target, loop);
  4507. animator.during(function (target) {
  4508. el.dirty(animatingShape);
  4509. })
  4510. .done(function () {
  4511. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4512. animators.splice(indexOf(animators, animator), 1);
  4513. });
  4514. animators.push(animator);
  4515. // If animate after added to the zrender
  4516. if (zr) {
  4517. zr.animation.addAnimator(animator);
  4518. }
  4519. return animator;
  4520. },
  4521. /**
  4522. * 停止动画
  4523. * @param {boolean} forwardToLast If move to last frame before stop
  4524. */
  4525. stopAnimation: function (forwardToLast) {
  4526. var animators = this.animators;
  4527. var len = animators.length;
  4528. for (var i = 0; i < len; i++) {
  4529. animators[i].stop(forwardToLast);
  4530. }
  4531. animators.length = 0;
  4532. return this;
  4533. },
  4534. /**
  4535. * Caution: this method will stop previous animation.
  4536. * So do not use this method to one element twice before
  4537. * animation starts, unless you know what you are doing.
  4538. * @param {Object} target
  4539. * @param {number} [time=500] Time in ms
  4540. * @param {string} [easing='linear']
  4541. * @param {number} [delay=0]
  4542. * @param {Function} [callback]
  4543. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4544. * immediently when target values are the same as current values.
  4545. *
  4546. * @example
  4547. * // Animate position
  4548. * el.animateTo({
  4549. * position: [10, 10]
  4550. * }, function () { // done })
  4551. *
  4552. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4553. * el.animateTo({
  4554. * shape: {
  4555. * width: 500
  4556. * },
  4557. * style: {
  4558. * fill: 'red'
  4559. * }
  4560. * position: [10, 10]
  4561. * }, 100, 100, 'cubicOut', function () { // done })
  4562. */
  4563. // TODO Return animation key
  4564. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4565. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4566. },
  4567. /**
  4568. * Animate from the target state to current state.
  4569. * The params and the return value are the same as `this.animateTo`.
  4570. */
  4571. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4572. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4573. }
  4574. };
  4575. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4576. // animateTo(target, time, easing, callback);
  4577. if (isString(delay)) {
  4578. callback = easing;
  4579. easing = delay;
  4580. delay = 0;
  4581. }
  4582. // animateTo(target, time, delay, callback);
  4583. else if (isFunction$1(easing)) {
  4584. callback = easing;
  4585. easing = 'linear';
  4586. delay = 0;
  4587. }
  4588. // animateTo(target, time, callback);
  4589. else if (isFunction$1(delay)) {
  4590. callback = delay;
  4591. delay = 0;
  4592. }
  4593. // animateTo(target, callback)
  4594. else if (isFunction$1(time)) {
  4595. callback = time;
  4596. time = 500;
  4597. }
  4598. // animateTo(target)
  4599. else if (!time) {
  4600. time = 500;
  4601. }
  4602. // Stop all previous animations
  4603. animatable.stopAnimation();
  4604. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4605. // Animators may be removed immediately after start
  4606. // if there is nothing to animate
  4607. var animators = animatable.animators.slice();
  4608. var count = animators.length;
  4609. function done() {
  4610. count--;
  4611. if (!count) {
  4612. callback && callback();
  4613. }
  4614. }
  4615. // No animators. This should be checked before animators[i].start(),
  4616. // because 'done' may be executed immediately if no need to animate.
  4617. if (!count) {
  4618. callback && callback();
  4619. }
  4620. // Start after all animators created
  4621. // Incase any animator is done immediately when all animation properties are not changed
  4622. for (var i = 0; i < animators.length; i++) {
  4623. animators[i]
  4624. .done(done)
  4625. .start(easing, forceAnimate);
  4626. }
  4627. }
  4628. /**
  4629. * @param {string} path=''
  4630. * @param {Object} source=animatable
  4631. * @param {Object} target
  4632. * @param {number} [time=500]
  4633. * @param {number} [delay=0]
  4634. * @param {boolean} [reverse] If `true`, animate
  4635. * from the `target` to current state.
  4636. *
  4637. * @example
  4638. * // Animate position
  4639. * el._animateToShallow({
  4640. * position: [10, 10]
  4641. * })
  4642. *
  4643. * // Animate shape, style and position in 100ms, delayed 100ms
  4644. * el._animateToShallow({
  4645. * shape: {
  4646. * width: 500
  4647. * },
  4648. * style: {
  4649. * fill: 'red'
  4650. * }
  4651. * position: [10, 10]
  4652. * }, 100, 100)
  4653. */
  4654. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4655. var objShallow = {};
  4656. var propertyCount = 0;
  4657. for (var name in target) {
  4658. if (!target.hasOwnProperty(name)) {
  4659. continue;
  4660. }
  4661. if (source[name] != null) {
  4662. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4663. animateToShallow(
  4664. animatable,
  4665. path ? path + '.' + name : name,
  4666. source[name],
  4667. target[name],
  4668. time,
  4669. delay,
  4670. reverse
  4671. );
  4672. }
  4673. else {
  4674. if (reverse) {
  4675. objShallow[name] = source[name];
  4676. setAttrByPath(animatable, path, name, target[name]);
  4677. }
  4678. else {
  4679. objShallow[name] = target[name];
  4680. }
  4681. propertyCount++;
  4682. }
  4683. }
  4684. else if (target[name] != null && !reverse) {
  4685. setAttrByPath(animatable, path, name, target[name]);
  4686. }
  4687. }
  4688. if (propertyCount > 0) {
  4689. animatable.animate(path, false)
  4690. .when(time == null ? 500 : time, objShallow)
  4691. .delay(delay || 0);
  4692. }
  4693. }
  4694. function setAttrByPath(el, path, name, value) {
  4695. // Attr directly if not has property
  4696. // FIXME, if some property not needed for element ?
  4697. if (!path) {
  4698. el.attr(name, value);
  4699. }
  4700. else {
  4701. // Only support set shape or style
  4702. var props = {};
  4703. props[path] = {};
  4704. props[path][name] = value;
  4705. el.attr(props);
  4706. }
  4707. }
  4708. /**
  4709. * @alias module:zrender/Element
  4710. * @constructor
  4711. * @extends {module:zrender/mixin/Animatable}
  4712. * @extends {module:zrender/mixin/Transformable}
  4713. * @extends {module:zrender/mixin/Eventful}
  4714. */
  4715. var Element = function (opts) { // jshint ignore:line
  4716. Transformable.call(this, opts);
  4717. Eventful.call(this, opts);
  4718. Animatable.call(this, opts);
  4719. /**
  4720. * 画布元素ID
  4721. * @type {string}
  4722. */
  4723. this.id = opts.id || guid();
  4724. };
  4725. Element.prototype = {
  4726. /**
  4727. * 元素类型
  4728. * Element type
  4729. * @type {string}
  4730. */
  4731. type: 'element',
  4732. /**
  4733. * 元素名字
  4734. * Element name
  4735. * @type {string}
  4736. */
  4737. name: '',
  4738. /**
  4739. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4740. * ZRender instance will be assigned when element is associated with zrender
  4741. * @name module:/zrender/Element#__zr
  4742. * @type {module:zrender/ZRender}
  4743. */
  4744. __zr: null,
  4745. /**
  4746. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4747. * If ignore drawing and events of the element object
  4748. * @name module:/zrender/Element#ignore
  4749. * @type {boolean}
  4750. * @default false
  4751. */
  4752. ignore: false,
  4753. /**
  4754. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4755. * 该路径会继承被裁减对象的变换
  4756. * @type {module:zrender/graphic/Path}
  4757. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4758. * @readOnly
  4759. */
  4760. clipPath: null,
  4761. /**
  4762. * 是否是 Group
  4763. * @type {boolean}
  4764. */
  4765. isGroup: false,
  4766. /**
  4767. * Drift element
  4768. * @param {number} dx dx on the global space
  4769. * @param {number} dy dy on the global space
  4770. */
  4771. drift: function (dx, dy) {
  4772. switch (this.draggable) {
  4773. case 'horizontal':
  4774. dy = 0;
  4775. break;
  4776. case 'vertical':
  4777. dx = 0;
  4778. break;
  4779. }
  4780. var m = this.transform;
  4781. if (!m) {
  4782. m = this.transform = [1, 0, 0, 1, 0, 0];
  4783. }
  4784. m[4] += dx;
  4785. m[5] += dy;
  4786. this.decomposeTransform();
  4787. this.dirty(false);
  4788. },
  4789. /**
  4790. * Hook before update
  4791. */
  4792. beforeUpdate: function () {},
  4793. /**
  4794. * Hook after update
  4795. */
  4796. afterUpdate: function () {},
  4797. /**
  4798. * Update each frame
  4799. */
  4800. update: function () {
  4801. this.updateTransform();
  4802. },
  4803. /**
  4804. * @param {Function} cb
  4805. * @param {} context
  4806. */
  4807. traverse: function (cb, context) {},
  4808. /**
  4809. * @protected
  4810. */
  4811. attrKV: function (key, value) {
  4812. if (key === 'position' || key === 'scale' || key === 'origin') {
  4813. // Copy the array
  4814. if (value) {
  4815. var target = this[key];
  4816. if (!target) {
  4817. target = this[key] = [];
  4818. }
  4819. target[0] = value[0];
  4820. target[1] = value[1];
  4821. }
  4822. }
  4823. else {
  4824. this[key] = value;
  4825. }
  4826. },
  4827. /**
  4828. * Hide the element
  4829. */
  4830. hide: function () {
  4831. this.ignore = true;
  4832. this.__zr && this.__zr.refresh();
  4833. },
  4834. /**
  4835. * Show the element
  4836. */
  4837. show: function () {
  4838. this.ignore = false;
  4839. this.__zr && this.__zr.refresh();
  4840. },
  4841. /**
  4842. * @param {string|Object} key
  4843. * @param {*} value
  4844. */
  4845. attr: function (key, value) {
  4846. if (typeof key === 'string') {
  4847. this.attrKV(key, value);
  4848. }
  4849. else if (isObject$1(key)) {
  4850. for (var name in key) {
  4851. if (key.hasOwnProperty(name)) {
  4852. this.attrKV(name, key[name]);
  4853. }
  4854. }
  4855. }
  4856. this.dirty(false);
  4857. return this;
  4858. },
  4859. /**
  4860. * @param {module:zrender/graphic/Path} clipPath
  4861. */
  4862. setClipPath: function (clipPath) {
  4863. var zr = this.__zr;
  4864. if (zr) {
  4865. clipPath.addSelfToZr(zr);
  4866. }
  4867. // Remove previous clip path
  4868. if (this.clipPath && this.clipPath !== clipPath) {
  4869. this.removeClipPath();
  4870. }
  4871. this.clipPath = clipPath;
  4872. clipPath.__zr = zr;
  4873. clipPath.__clipTarget = this;
  4874. this.dirty(false);
  4875. },
  4876. /**
  4877. */
  4878. removeClipPath: function () {
  4879. var clipPath = this.clipPath;
  4880. if (clipPath) {
  4881. if (clipPath.__zr) {
  4882. clipPath.removeSelfFromZr(clipPath.__zr);
  4883. }
  4884. clipPath.__zr = null;
  4885. clipPath.__clipTarget = null;
  4886. this.clipPath = null;
  4887. this.dirty(false);
  4888. }
  4889. },
  4890. /**
  4891. * Add self from zrender instance.
  4892. * Not recursively because it will be invoked when element added to storage.
  4893. * @param {module:zrender/ZRender} zr
  4894. */
  4895. addSelfToZr: function (zr) {
  4896. this.__zr = zr;
  4897. // 添加动画
  4898. var animators = this.animators;
  4899. if (animators) {
  4900. for (var i = 0; i < animators.length; i++) {
  4901. zr.animation.addAnimator(animators[i]);
  4902. }
  4903. }
  4904. if (this.clipPath) {
  4905. this.clipPath.addSelfToZr(zr);
  4906. }
  4907. },
  4908. /**
  4909. * Remove self from zrender instance.
  4910. * Not recursively because it will be invoked when element added to storage.
  4911. * @param {module:zrender/ZRender} zr
  4912. */
  4913. removeSelfFromZr: function (zr) {
  4914. this.__zr = null;
  4915. // 移除动画
  4916. var animators = this.animators;
  4917. if (animators) {
  4918. for (var i = 0; i < animators.length; i++) {
  4919. zr.animation.removeAnimator(animators[i]);
  4920. }
  4921. }
  4922. if (this.clipPath) {
  4923. this.clipPath.removeSelfFromZr(zr);
  4924. }
  4925. }
  4926. };
  4927. mixin(Element, Animatable);
  4928. mixin(Element, Transformable);
  4929. mixin(Element, Eventful);
  4930. /**
  4931. * @module echarts/core/BoundingRect
  4932. */
  4933. var v2ApplyTransform = applyTransform;
  4934. var mathMin = Math.min;
  4935. var mathMax = Math.max;
  4936. /**
  4937. * @alias module:echarts/core/BoundingRect
  4938. */
  4939. function BoundingRect(x, y, width, height) {
  4940. if (width < 0) {
  4941. x = x + width;
  4942. width = -width;
  4943. }
  4944. if (height < 0) {
  4945. y = y + height;
  4946. height = -height;
  4947. }
  4948. /**
  4949. * @type {number}
  4950. */
  4951. this.x = x;
  4952. /**
  4953. * @type {number}
  4954. */
  4955. this.y = y;
  4956. /**
  4957. * @type {number}
  4958. */
  4959. this.width = width;
  4960. /**
  4961. * @type {number}
  4962. */
  4963. this.height = height;
  4964. }
  4965. BoundingRect.prototype = {
  4966. constructor: BoundingRect,
  4967. /**
  4968. * @param {module:echarts/core/BoundingRect} other
  4969. */
  4970. union: function (other) {
  4971. var x = mathMin(other.x, this.x);
  4972. var y = mathMin(other.y, this.y);
  4973. this.width = mathMax(
  4974. other.x + other.width,
  4975. this.x + this.width
  4976. ) - x;
  4977. this.height = mathMax(
  4978. other.y + other.height,
  4979. this.y + this.height
  4980. ) - y;
  4981. this.x = x;
  4982. this.y = y;
  4983. },
  4984. /**
  4985. * @param {Array.<number>} m
  4986. * @methods
  4987. */
  4988. applyTransform: (function () {
  4989. var lt = [];
  4990. var rb = [];
  4991. var lb = [];
  4992. var rt = [];
  4993. return function (m) {
  4994. // In case usage like this
  4995. // el.getBoundingRect().applyTransform(el.transform)
  4996. // And element has no transform
  4997. if (!m) {
  4998. return;
  4999. }
  5000. lt[0] = lb[0] = this.x;
  5001. lt[1] = rt[1] = this.y;
  5002. rb[0] = rt[0] = this.x + this.width;
  5003. rb[1] = lb[1] = this.y + this.height;
  5004. v2ApplyTransform(lt, lt, m);
  5005. v2ApplyTransform(rb, rb, m);
  5006. v2ApplyTransform(lb, lb, m);
  5007. v2ApplyTransform(rt, rt, m);
  5008. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5009. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5010. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5011. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5012. this.width = maxX - this.x;
  5013. this.height = maxY - this.y;
  5014. };
  5015. })(),
  5016. /**
  5017. * Calculate matrix of transforming from self to target rect
  5018. * @param {module:zrender/core/BoundingRect} b
  5019. * @return {Array.<number>}
  5020. */
  5021. calculateTransform: function (b) {
  5022. var a = this;
  5023. var sx = b.width / a.width;
  5024. var sy = b.height / a.height;
  5025. var m = create$1();
  5026. // 矩阵右乘
  5027. translate(m, m, [-a.x, -a.y]);
  5028. scale$1(m, m, [sx, sy]);
  5029. translate(m, m, [b.x, b.y]);
  5030. return m;
  5031. },
  5032. /**
  5033. * @param {(module:echarts/core/BoundingRect|Object)} b
  5034. * @return {boolean}
  5035. */
  5036. intersect: function (b) {
  5037. if (!b) {
  5038. return false;
  5039. }
  5040. if (!(b instanceof BoundingRect)) {
  5041. // Normalize negative width/height.
  5042. b = BoundingRect.create(b);
  5043. }
  5044. var a = this;
  5045. var ax0 = a.x;
  5046. var ax1 = a.x + a.width;
  5047. var ay0 = a.y;
  5048. var ay1 = a.y + a.height;
  5049. var bx0 = b.x;
  5050. var bx1 = b.x + b.width;
  5051. var by0 = b.y;
  5052. var by1 = b.y + b.height;
  5053. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5054. },
  5055. contain: function (x, y) {
  5056. var rect = this;
  5057. return x >= rect.x
  5058. && x <= (rect.x + rect.width)
  5059. && y >= rect.y
  5060. && y <= (rect.y + rect.height);
  5061. },
  5062. /**
  5063. * @return {module:echarts/core/BoundingRect}
  5064. */
  5065. clone: function () {
  5066. return new BoundingRect(this.x, this.y, this.width, this.height);
  5067. },
  5068. /**
  5069. * Copy from another rect
  5070. */
  5071. copy: function (other) {
  5072. this.x = other.x;
  5073. this.y = other.y;
  5074. this.width = other.width;
  5075. this.height = other.height;
  5076. },
  5077. plain: function () {
  5078. return {
  5079. x: this.x,
  5080. y: this.y,
  5081. width: this.width,
  5082. height: this.height
  5083. };
  5084. }
  5085. };
  5086. /**
  5087. * @param {Object|module:zrender/core/BoundingRect} rect
  5088. * @param {number} rect.x
  5089. * @param {number} rect.y
  5090. * @param {number} rect.width
  5091. * @param {number} rect.height
  5092. * @return {module:zrender/core/BoundingRect}
  5093. */
  5094. BoundingRect.create = function (rect) {
  5095. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5096. };
  5097. /**
  5098. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5099. * @module zrender/graphic/Group
  5100. * @example
  5101. * var Group = require('zrender/container/Group');
  5102. * var Circle = require('zrender/graphic/shape/Circle');
  5103. * var g = new Group();
  5104. * g.position[0] = 100;
  5105. * g.position[1] = 100;
  5106. * g.add(new Circle({
  5107. * style: {
  5108. * x: 100,
  5109. * y: 100,
  5110. * r: 20,
  5111. * }
  5112. * }));
  5113. * zr.add(g);
  5114. */
  5115. /**
  5116. * @alias module:zrender/graphic/Group
  5117. * @constructor
  5118. * @extends module:zrender/mixin/Transformable
  5119. * @extends module:zrender/mixin/Eventful
  5120. */
  5121. var Group = function (opts) {
  5122. opts = opts || {};
  5123. Element.call(this, opts);
  5124. for (var key in opts) {
  5125. if (opts.hasOwnProperty(key)) {
  5126. this[key] = opts[key];
  5127. }
  5128. }
  5129. this._children = [];
  5130. this.__storage = null;
  5131. this.__dirty = true;
  5132. };
  5133. Group.prototype = {
  5134. constructor: Group,
  5135. isGroup: true,
  5136. /**
  5137. * @type {string}
  5138. */
  5139. type: 'group',
  5140. /**
  5141. * 所有子孙元素是否响应鼠标事件
  5142. * @name module:/zrender/container/Group#silent
  5143. * @type {boolean}
  5144. * @default false
  5145. */
  5146. silent: false,
  5147. /**
  5148. * @return {Array.<module:zrender/Element>}
  5149. */
  5150. children: function () {
  5151. return this._children.slice();
  5152. },
  5153. /**
  5154. * 获取指定 index 的儿子节点
  5155. * @param {number} idx
  5156. * @return {module:zrender/Element}
  5157. */
  5158. childAt: function (idx) {
  5159. return this._children[idx];
  5160. },
  5161. /**
  5162. * 获取指定名字的儿子节点
  5163. * @param {string} name
  5164. * @return {module:zrender/Element}
  5165. */
  5166. childOfName: function (name) {
  5167. var children = this._children;
  5168. for (var i = 0; i < children.length; i++) {
  5169. if (children[i].name === name) {
  5170. return children[i];
  5171. }
  5172. }
  5173. },
  5174. /**
  5175. * @return {number}
  5176. */
  5177. childCount: function () {
  5178. return this._children.length;
  5179. },
  5180. /**
  5181. * 添加子节点到最后
  5182. * @param {module:zrender/Element} child
  5183. */
  5184. add: function (child) {
  5185. if (child && child !== this && child.parent !== this) {
  5186. this._children.push(child);
  5187. this._doAdd(child);
  5188. }
  5189. return this;
  5190. },
  5191. /**
  5192. * 添加子节点在 nextSibling 之前
  5193. * @param {module:zrender/Element} child
  5194. * @param {module:zrender/Element} nextSibling
  5195. */
  5196. addBefore: function (child, nextSibling) {
  5197. if (child && child !== this && child.parent !== this
  5198. && nextSibling && nextSibling.parent === this) {
  5199. var children = this._children;
  5200. var idx = children.indexOf(nextSibling);
  5201. if (idx >= 0) {
  5202. children.splice(idx, 0, child);
  5203. this._doAdd(child);
  5204. }
  5205. }
  5206. return this;
  5207. },
  5208. _doAdd: function (child) {
  5209. if (child.parent) {
  5210. child.parent.remove(child);
  5211. }
  5212. child.parent = this;
  5213. var storage = this.__storage;
  5214. var zr = this.__zr;
  5215. if (storage && storage !== child.__storage) {
  5216. storage.addToStorage(child);
  5217. if (child instanceof Group) {
  5218. child.addChildrenToStorage(storage);
  5219. }
  5220. }
  5221. zr && zr.refresh();
  5222. },
  5223. /**
  5224. * 移除子节点
  5225. * @param {module:zrender/Element} child
  5226. */
  5227. remove: function (child) {
  5228. var zr = this.__zr;
  5229. var storage = this.__storage;
  5230. var children = this._children;
  5231. var idx = indexOf(children, child);
  5232. if (idx < 0) {
  5233. return this;
  5234. }
  5235. children.splice(idx, 1);
  5236. child.parent = null;
  5237. if (storage) {
  5238. storage.delFromStorage(child);
  5239. if (child instanceof Group) {
  5240. child.delChildrenFromStorage(storage);
  5241. }
  5242. }
  5243. zr && zr.refresh();
  5244. return this;
  5245. },
  5246. /**
  5247. * 移除所有子节点
  5248. */
  5249. removeAll: function () {
  5250. var children = this._children;
  5251. var storage = this.__storage;
  5252. var child;
  5253. var i;
  5254. for (i = 0; i < children.length; i++) {
  5255. child = children[i];
  5256. if (storage) {
  5257. storage.delFromStorage(child);
  5258. if (child instanceof Group) {
  5259. child.delChildrenFromStorage(storage);
  5260. }
  5261. }
  5262. child.parent = null;
  5263. }
  5264. children.length = 0;
  5265. return this;
  5266. },
  5267. /**
  5268. * 遍历所有子节点
  5269. * @param {Function} cb
  5270. * @param {} context
  5271. */
  5272. eachChild: function (cb, context) {
  5273. var children = this._children;
  5274. for (var i = 0; i < children.length; i++) {
  5275. var child = children[i];
  5276. cb.call(context, child, i);
  5277. }
  5278. return this;
  5279. },
  5280. /**
  5281. * 深度优先遍历所有子孙节点
  5282. * @param {Function} cb
  5283. * @param {} context
  5284. */
  5285. traverse: function (cb, context) {
  5286. for (var i = 0; i < this._children.length; i++) {
  5287. var child = this._children[i];
  5288. cb.call(context, child);
  5289. if (child.type === 'group') {
  5290. child.traverse(cb, context);
  5291. }
  5292. }
  5293. return this;
  5294. },
  5295. addChildrenToStorage: function (storage) {
  5296. for (var i = 0; i < this._children.length; i++) {
  5297. var child = this._children[i];
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. },
  5304. delChildrenFromStorage: function (storage) {
  5305. for (var i = 0; i < this._children.length; i++) {
  5306. var child = this._children[i];
  5307. storage.delFromStorage(child);
  5308. if (child instanceof Group) {
  5309. child.delChildrenFromStorage(storage);
  5310. }
  5311. }
  5312. },
  5313. dirty: function () {
  5314. this.__dirty = true;
  5315. this.__zr && this.__zr.refresh();
  5316. return this;
  5317. },
  5318. /**
  5319. * @return {module:zrender/core/BoundingRect}
  5320. */
  5321. getBoundingRect: function (includeChildren) {
  5322. // TODO Caching
  5323. var rect = null;
  5324. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5325. var children = includeChildren || this._children;
  5326. var tmpMat = [];
  5327. for (var i = 0; i < children.length; i++) {
  5328. var child = children[i];
  5329. if (child.ignore || child.invisible) {
  5330. continue;
  5331. }
  5332. var childRect = child.getBoundingRect();
  5333. var transform = child.getLocalTransform(tmpMat);
  5334. // TODO
  5335. // The boundingRect cacluated by transforming original
  5336. // rect may be bigger than the actual bundingRect when rotation
  5337. // is used. (Consider a circle rotated aginst its center, where
  5338. // the actual boundingRect should be the same as that not be
  5339. // rotated.) But we can not find better approach to calculate
  5340. // actual boundingRect yet, considering performance.
  5341. if (transform) {
  5342. tmpRect.copy(childRect);
  5343. tmpRect.applyTransform(transform);
  5344. rect = rect || tmpRect.clone();
  5345. rect.union(tmpRect);
  5346. }
  5347. else {
  5348. rect = rect || childRect.clone();
  5349. rect.union(childRect);
  5350. }
  5351. }
  5352. return rect || tmpRect;
  5353. }
  5354. };
  5355. inherits(Group, Element);
  5356. // https://github.com/mziccard/node-timsort
  5357. var DEFAULT_MIN_MERGE = 32;
  5358. var DEFAULT_MIN_GALLOPING = 7;
  5359. function minRunLength(n) {
  5360. var r = 0;
  5361. while (n >= DEFAULT_MIN_MERGE) {
  5362. r |= n & 1;
  5363. n >>= 1;
  5364. }
  5365. return n + r;
  5366. }
  5367. function makeAscendingRun(array, lo, hi, compare) {
  5368. var runHi = lo + 1;
  5369. if (runHi === hi) {
  5370. return 1;
  5371. }
  5372. if (compare(array[runHi++], array[lo]) < 0) {
  5373. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5374. runHi++;
  5375. }
  5376. reverseRun(array, lo, runHi);
  5377. }
  5378. else {
  5379. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5380. runHi++;
  5381. }
  5382. }
  5383. return runHi - lo;
  5384. }
  5385. function reverseRun(array, lo, hi) {
  5386. hi--;
  5387. while (lo < hi) {
  5388. var t = array[lo];
  5389. array[lo++] = array[hi];
  5390. array[hi--] = t;
  5391. }
  5392. }
  5393. function binaryInsertionSort(array, lo, hi, start, compare) {
  5394. if (start === lo) {
  5395. start++;
  5396. }
  5397. for (; start < hi; start++) {
  5398. var pivot = array[start];
  5399. var left = lo;
  5400. var right = start;
  5401. var mid;
  5402. while (left < right) {
  5403. mid = left + right >>> 1;
  5404. if (compare(pivot, array[mid]) < 0) {
  5405. right = mid;
  5406. }
  5407. else {
  5408. left = mid + 1;
  5409. }
  5410. }
  5411. var n = start - left;
  5412. switch (n) {
  5413. case 3:
  5414. array[left + 3] = array[left + 2];
  5415. case 2:
  5416. array[left + 2] = array[left + 1];
  5417. case 1:
  5418. array[left + 1] = array[left];
  5419. break;
  5420. default:
  5421. while (n > 0) {
  5422. array[left + n] = array[left + n - 1];
  5423. n--;
  5424. }
  5425. }
  5426. array[left] = pivot;
  5427. }
  5428. }
  5429. function gallopLeft(value, array, start, length, hint, compare) {
  5430. var lastOffset = 0;
  5431. var maxOffset = 0;
  5432. var offset = 1;
  5433. if (compare(value, array[start + hint]) > 0) {
  5434. maxOffset = length - hint;
  5435. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5436. lastOffset = offset;
  5437. offset = (offset << 1) + 1;
  5438. if (offset <= 0) {
  5439. offset = maxOffset;
  5440. }
  5441. }
  5442. if (offset > maxOffset) {
  5443. offset = maxOffset;
  5444. }
  5445. lastOffset += hint;
  5446. offset += hint;
  5447. }
  5448. else {
  5449. maxOffset = hint + 1;
  5450. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5451. lastOffset = offset;
  5452. offset = (offset << 1) + 1;
  5453. if (offset <= 0) {
  5454. offset = maxOffset;
  5455. }
  5456. }
  5457. if (offset > maxOffset) {
  5458. offset = maxOffset;
  5459. }
  5460. var tmp = lastOffset;
  5461. lastOffset = hint - offset;
  5462. offset = hint - tmp;
  5463. }
  5464. lastOffset++;
  5465. while (lastOffset < offset) {
  5466. var m = lastOffset + (offset - lastOffset >>> 1);
  5467. if (compare(value, array[start + m]) > 0) {
  5468. lastOffset = m + 1;
  5469. }
  5470. else {
  5471. offset = m;
  5472. }
  5473. }
  5474. return offset;
  5475. }
  5476. function gallopRight(value, array, start, length, hint, compare) {
  5477. var lastOffset = 0;
  5478. var maxOffset = 0;
  5479. var offset = 1;
  5480. if (compare(value, array[start + hint]) < 0) {
  5481. maxOffset = hint + 1;
  5482. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5483. lastOffset = offset;
  5484. offset = (offset << 1) + 1;
  5485. if (offset <= 0) {
  5486. offset = maxOffset;
  5487. }
  5488. }
  5489. if (offset > maxOffset) {
  5490. offset = maxOffset;
  5491. }
  5492. var tmp = lastOffset;
  5493. lastOffset = hint - offset;
  5494. offset = hint - tmp;
  5495. }
  5496. else {
  5497. maxOffset = length - hint;
  5498. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5499. lastOffset = offset;
  5500. offset = (offset << 1) + 1;
  5501. if (offset <= 0) {
  5502. offset = maxOffset;
  5503. }
  5504. }
  5505. if (offset > maxOffset) {
  5506. offset = maxOffset;
  5507. }
  5508. lastOffset += hint;
  5509. offset += hint;
  5510. }
  5511. lastOffset++;
  5512. while (lastOffset < offset) {
  5513. var m = lastOffset + (offset - lastOffset >>> 1);
  5514. if (compare(value, array[start + m]) < 0) {
  5515. offset = m;
  5516. }
  5517. else {
  5518. lastOffset = m + 1;
  5519. }
  5520. }
  5521. return offset;
  5522. }
  5523. function TimSort(array, compare) {
  5524. var minGallop = DEFAULT_MIN_GALLOPING;
  5525. var runStart;
  5526. var runLength;
  5527. var stackSize = 0;
  5528. var tmp = [];
  5529. runStart = [];
  5530. runLength = [];
  5531. function pushRun(_runStart, _runLength) {
  5532. runStart[stackSize] = _runStart;
  5533. runLength[stackSize] = _runLength;
  5534. stackSize += 1;
  5535. }
  5536. function mergeRuns() {
  5537. while (stackSize > 1) {
  5538. var n = stackSize - 2;
  5539. if (
  5540. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5541. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5542. ) {
  5543. if (runLength[n - 1] < runLength[n + 1]) {
  5544. n--;
  5545. }
  5546. }
  5547. else if (runLength[n] > runLength[n + 1]) {
  5548. break;
  5549. }
  5550. mergeAt(n);
  5551. }
  5552. }
  5553. function forceMergeRuns() {
  5554. while (stackSize > 1) {
  5555. var n = stackSize - 2;
  5556. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5557. n--;
  5558. }
  5559. mergeAt(n);
  5560. }
  5561. }
  5562. function mergeAt(i) {
  5563. var start1 = runStart[i];
  5564. var length1 = runLength[i];
  5565. var start2 = runStart[i + 1];
  5566. var length2 = runLength[i + 1];
  5567. runLength[i] = length1 + length2;
  5568. if (i === stackSize - 3) {
  5569. runStart[i + 1] = runStart[i + 2];
  5570. runLength[i + 1] = runLength[i + 2];
  5571. }
  5572. stackSize--;
  5573. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5574. start1 += k;
  5575. length1 -= k;
  5576. if (length1 === 0) {
  5577. return;
  5578. }
  5579. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5580. if (length2 === 0) {
  5581. return;
  5582. }
  5583. if (length1 <= length2) {
  5584. mergeLow(start1, length1, start2, length2);
  5585. }
  5586. else {
  5587. mergeHigh(start1, length1, start2, length2);
  5588. }
  5589. }
  5590. function mergeLow(start1, length1, start2, length2) {
  5591. var i = 0;
  5592. for (i = 0; i < length1; i++) {
  5593. tmp[i] = array[start1 + i];
  5594. }
  5595. var cursor1 = 0;
  5596. var cursor2 = start2;
  5597. var dest = start1;
  5598. array[dest++] = array[cursor2++];
  5599. if (--length2 === 0) {
  5600. for (i = 0; i < length1; i++) {
  5601. array[dest + i] = tmp[cursor1 + i];
  5602. }
  5603. return;
  5604. }
  5605. if (length1 === 1) {
  5606. for (i = 0; i < length2; i++) {
  5607. array[dest + i] = array[cursor2 + i];
  5608. }
  5609. array[dest + length2] = tmp[cursor1];
  5610. return;
  5611. }
  5612. var _minGallop = minGallop;
  5613. var count1;
  5614. var count2;
  5615. var exit;
  5616. while (1) {
  5617. count1 = 0;
  5618. count2 = 0;
  5619. exit = false;
  5620. do {
  5621. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5622. array[dest++] = array[cursor2++];
  5623. count2++;
  5624. count1 = 0;
  5625. if (--length2 === 0) {
  5626. exit = true;
  5627. break;
  5628. }
  5629. }
  5630. else {
  5631. array[dest++] = tmp[cursor1++];
  5632. count1++;
  5633. count2 = 0;
  5634. if (--length1 === 1) {
  5635. exit = true;
  5636. break;
  5637. }
  5638. }
  5639. } while ((count1 | count2) < _minGallop);
  5640. if (exit) {
  5641. break;
  5642. }
  5643. do {
  5644. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5645. if (count1 !== 0) {
  5646. for (i = 0; i < count1; i++) {
  5647. array[dest + i] = tmp[cursor1 + i];
  5648. }
  5649. dest += count1;
  5650. cursor1 += count1;
  5651. length1 -= count1;
  5652. if (length1 <= 1) {
  5653. exit = true;
  5654. break;
  5655. }
  5656. }
  5657. array[dest++] = array[cursor2++];
  5658. if (--length2 === 0) {
  5659. exit = true;
  5660. break;
  5661. }
  5662. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5663. if (count2 !== 0) {
  5664. for (i = 0; i < count2; i++) {
  5665. array[dest + i] = array[cursor2 + i];
  5666. }
  5667. dest += count2;
  5668. cursor2 += count2;
  5669. length2 -= count2;
  5670. if (length2 === 0) {
  5671. exit = true;
  5672. break;
  5673. }
  5674. }
  5675. array[dest++] = tmp[cursor1++];
  5676. if (--length1 === 1) {
  5677. exit = true;
  5678. break;
  5679. }
  5680. _minGallop--;
  5681. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5682. if (exit) {
  5683. break;
  5684. }
  5685. if (_minGallop < 0) {
  5686. _minGallop = 0;
  5687. }
  5688. _minGallop += 2;
  5689. }
  5690. minGallop = _minGallop;
  5691. minGallop < 1 && (minGallop = 1);
  5692. if (length1 === 1) {
  5693. for (i = 0; i < length2; i++) {
  5694. array[dest + i] = array[cursor2 + i];
  5695. }
  5696. array[dest + length2] = tmp[cursor1];
  5697. }
  5698. else if (length1 === 0) {
  5699. throw new Error();
  5700. // throw new Error('mergeLow preconditions were not respected');
  5701. }
  5702. else {
  5703. for (i = 0; i < length1; i++) {
  5704. array[dest + i] = tmp[cursor1 + i];
  5705. }
  5706. }
  5707. }
  5708. function mergeHigh(start1, length1, start2, length2) {
  5709. var i = 0;
  5710. for (i = 0; i < length2; i++) {
  5711. tmp[i] = array[start2 + i];
  5712. }
  5713. var cursor1 = start1 + length1 - 1;
  5714. var cursor2 = length2 - 1;
  5715. var dest = start2 + length2 - 1;
  5716. var customCursor = 0;
  5717. var customDest = 0;
  5718. array[dest--] = array[cursor1--];
  5719. if (--length1 === 0) {
  5720. customCursor = dest - (length2 - 1);
  5721. for (i = 0; i < length2; i++) {
  5722. array[customCursor + i] = tmp[i];
  5723. }
  5724. return;
  5725. }
  5726. if (length2 === 1) {
  5727. dest -= length1;
  5728. cursor1 -= length1;
  5729. customDest = dest + 1;
  5730. customCursor = cursor1 + 1;
  5731. for (i = length1 - 1; i >= 0; i--) {
  5732. array[customDest + i] = array[customCursor + i];
  5733. }
  5734. array[dest] = tmp[cursor2];
  5735. return;
  5736. }
  5737. var _minGallop = minGallop;
  5738. while (true) {
  5739. var count1 = 0;
  5740. var count2 = 0;
  5741. var exit = false;
  5742. do {
  5743. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5744. array[dest--] = array[cursor1--];
  5745. count1++;
  5746. count2 = 0;
  5747. if (--length1 === 0) {
  5748. exit = true;
  5749. break;
  5750. }
  5751. }
  5752. else {
  5753. array[dest--] = tmp[cursor2--];
  5754. count2++;
  5755. count1 = 0;
  5756. if (--length2 === 1) {
  5757. exit = true;
  5758. break;
  5759. }
  5760. }
  5761. } while ((count1 | count2) < _minGallop);
  5762. if (exit) {
  5763. break;
  5764. }
  5765. do {
  5766. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5767. if (count1 !== 0) {
  5768. dest -= count1;
  5769. cursor1 -= count1;
  5770. length1 -= count1;
  5771. customDest = dest + 1;
  5772. customCursor = cursor1 + 1;
  5773. for (i = count1 - 1; i >= 0; i--) {
  5774. array[customDest + i] = array[customCursor + i];
  5775. }
  5776. if (length1 === 0) {
  5777. exit = true;
  5778. break;
  5779. }
  5780. }
  5781. array[dest--] = tmp[cursor2--];
  5782. if (--length2 === 1) {
  5783. exit = true;
  5784. break;
  5785. }
  5786. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5787. if (count2 !== 0) {
  5788. dest -= count2;
  5789. cursor2 -= count2;
  5790. length2 -= count2;
  5791. customDest = dest + 1;
  5792. customCursor = cursor2 + 1;
  5793. for (i = 0; i < count2; i++) {
  5794. array[customDest + i] = tmp[customCursor + i];
  5795. }
  5796. if (length2 <= 1) {
  5797. exit = true;
  5798. break;
  5799. }
  5800. }
  5801. array[dest--] = array[cursor1--];
  5802. if (--length1 === 0) {
  5803. exit = true;
  5804. break;
  5805. }
  5806. _minGallop--;
  5807. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5808. if (exit) {
  5809. break;
  5810. }
  5811. if (_minGallop < 0) {
  5812. _minGallop = 0;
  5813. }
  5814. _minGallop += 2;
  5815. }
  5816. minGallop = _minGallop;
  5817. if (minGallop < 1) {
  5818. minGallop = 1;
  5819. }
  5820. if (length2 === 1) {
  5821. dest -= length1;
  5822. cursor1 -= length1;
  5823. customDest = dest + 1;
  5824. customCursor = cursor1 + 1;
  5825. for (i = length1 - 1; i >= 0; i--) {
  5826. array[customDest + i] = array[customCursor + i];
  5827. }
  5828. array[dest] = tmp[cursor2];
  5829. }
  5830. else if (length2 === 0) {
  5831. throw new Error();
  5832. // throw new Error('mergeHigh preconditions were not respected');
  5833. }
  5834. else {
  5835. customCursor = dest - (length2 - 1);
  5836. for (i = 0; i < length2; i++) {
  5837. array[customCursor + i] = tmp[i];
  5838. }
  5839. }
  5840. }
  5841. this.mergeRuns = mergeRuns;
  5842. this.forceMergeRuns = forceMergeRuns;
  5843. this.pushRun = pushRun;
  5844. }
  5845. function sort(array, compare, lo, hi) {
  5846. if (!lo) {
  5847. lo = 0;
  5848. }
  5849. if (!hi) {
  5850. hi = array.length;
  5851. }
  5852. var remaining = hi - lo;
  5853. if (remaining < 2) {
  5854. return;
  5855. }
  5856. var runLength = 0;
  5857. if (remaining < DEFAULT_MIN_MERGE) {
  5858. runLength = makeAscendingRun(array, lo, hi, compare);
  5859. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5860. return;
  5861. }
  5862. var ts = new TimSort(array, compare);
  5863. var minRun = minRunLength(remaining);
  5864. do {
  5865. runLength = makeAscendingRun(array, lo, hi, compare);
  5866. if (runLength < minRun) {
  5867. var force = remaining;
  5868. if (force > minRun) {
  5869. force = minRun;
  5870. }
  5871. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5872. runLength = force;
  5873. }
  5874. ts.pushRun(lo, runLength);
  5875. ts.mergeRuns();
  5876. remaining -= runLength;
  5877. lo += runLength;
  5878. } while (remaining !== 0);
  5879. ts.forceMergeRuns();
  5880. }
  5881. // Use timsort because in most case elements are partially sorted
  5882. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5883. function shapeCompareFunc(a, b) {
  5884. if (a.zlevel === b.zlevel) {
  5885. if (a.z === b.z) {
  5886. // if (a.z2 === b.z2) {
  5887. // // FIXME Slow has renderidx compare
  5888. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5889. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5890. // return a.__renderidx - b.__renderidx;
  5891. // }
  5892. return a.z2 - b.z2;
  5893. }
  5894. return a.z - b.z;
  5895. }
  5896. return a.zlevel - b.zlevel;
  5897. }
  5898. /**
  5899. * 内容仓库 (M)
  5900. * @alias module:zrender/Storage
  5901. * @constructor
  5902. */
  5903. var Storage = function () { // jshint ignore:line
  5904. this._roots = [];
  5905. this._displayList = [];
  5906. this._displayListLen = 0;
  5907. };
  5908. Storage.prototype = {
  5909. constructor: Storage,
  5910. /**
  5911. * @param {Function} cb
  5912. *
  5913. */
  5914. traverse: function (cb, context) {
  5915. for (var i = 0; i < this._roots.length; i++) {
  5916. this._roots[i].traverse(cb, context);
  5917. }
  5918. },
  5919. /**
  5920. * 返回所有图形的绘制队列
  5921. * @param {boolean} [update=false] 是否在返回前更新该数组
  5922. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5923. *
  5924. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5925. * @return {Array.<module:zrender/graphic/Displayable>}
  5926. */
  5927. getDisplayList: function (update, includeIgnore) {
  5928. includeIgnore = includeIgnore || false;
  5929. if (update) {
  5930. this.updateDisplayList(includeIgnore);
  5931. }
  5932. return this._displayList;
  5933. },
  5934. /**
  5935. * 更新图形的绘制队列。
  5936. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5937. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5938. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5939. */
  5940. updateDisplayList: function (includeIgnore) {
  5941. this._displayListLen = 0;
  5942. var roots = this._roots;
  5943. var displayList = this._displayList;
  5944. for (var i = 0, len = roots.length; i < len; i++) {
  5945. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5946. }
  5947. displayList.length = this._displayListLen;
  5948. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5949. },
  5950. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5951. if (el.ignore && !includeIgnore) {
  5952. return;
  5953. }
  5954. el.beforeUpdate();
  5955. if (el.__dirty) {
  5956. el.update();
  5957. }
  5958. el.afterUpdate();
  5959. var userSetClipPath = el.clipPath;
  5960. if (userSetClipPath) {
  5961. // FIXME 效率影响
  5962. if (clipPaths) {
  5963. clipPaths = clipPaths.slice();
  5964. }
  5965. else {
  5966. clipPaths = [];
  5967. }
  5968. var currentClipPath = userSetClipPath;
  5969. var parentClipPath = el;
  5970. // Recursively add clip path
  5971. while (currentClipPath) {
  5972. // clipPath 的变换是基于使用这个 clipPath 的元素
  5973. currentClipPath.parent = parentClipPath;
  5974. currentClipPath.updateTransform();
  5975. clipPaths.push(currentClipPath);
  5976. parentClipPath = currentClipPath;
  5977. currentClipPath = currentClipPath.clipPath;
  5978. }
  5979. }
  5980. if (el.isGroup) {
  5981. var children = el._children;
  5982. for (var i = 0; i < children.length; i++) {
  5983. var child = children[i];
  5984. // Force to mark as dirty if group is dirty
  5985. // FIXME __dirtyPath ?
  5986. if (el.__dirty) {
  5987. child.__dirty = true;
  5988. }
  5989. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5990. }
  5991. // Mark group clean here
  5992. el.__dirty = false;
  5993. }
  5994. else {
  5995. el.__clipPaths = clipPaths;
  5996. this._displayList[this._displayListLen++] = el;
  5997. }
  5998. },
  5999. /**
  6000. * 添加图形(Shape)或者组(Group)到根节点
  6001. * @param {module:zrender/Element} el
  6002. */
  6003. addRoot: function (el) {
  6004. if (el.__storage === this) {
  6005. return;
  6006. }
  6007. if (el instanceof Group) {
  6008. el.addChildrenToStorage(this);
  6009. }
  6010. this.addToStorage(el);
  6011. this._roots.push(el);
  6012. },
  6013. /**
  6014. * 删除指定的图形(Shape)或者组(Group)
  6015. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6016. */
  6017. delRoot: function (el) {
  6018. if (el == null) {
  6019. // 不指定el清空
  6020. for (var i = 0; i < this._roots.length; i++) {
  6021. var root = this._roots[i];
  6022. if (root instanceof Group) {
  6023. root.delChildrenFromStorage(this);
  6024. }
  6025. }
  6026. this._roots = [];
  6027. this._displayList = [];
  6028. this._displayListLen = 0;
  6029. return;
  6030. }
  6031. if (el instanceof Array) {
  6032. for (var i = 0, l = el.length; i < l; i++) {
  6033. this.delRoot(el[i]);
  6034. }
  6035. return;
  6036. }
  6037. var idx = indexOf(this._roots, el);
  6038. if (idx >= 0) {
  6039. this.delFromStorage(el);
  6040. this._roots.splice(idx, 1);
  6041. if (el instanceof Group) {
  6042. el.delChildrenFromStorage(this);
  6043. }
  6044. }
  6045. },
  6046. addToStorage: function (el) {
  6047. if (el) {
  6048. el.__storage = this;
  6049. el.dirty(false);
  6050. }
  6051. return this;
  6052. },
  6053. delFromStorage: function (el) {
  6054. if (el) {
  6055. el.__storage = null;
  6056. }
  6057. return this;
  6058. },
  6059. /**
  6060. * 清空并且释放Storage
  6061. */
  6062. dispose: function () {
  6063. this._renderList =
  6064. this._roots = null;
  6065. },
  6066. displayableSortFunc: shapeCompareFunc
  6067. };
  6068. var SHADOW_PROPS = {
  6069. 'shadowBlur': 1,
  6070. 'shadowOffsetX': 1,
  6071. 'shadowOffsetY': 1,
  6072. 'textShadowBlur': 1,
  6073. 'textShadowOffsetX': 1,
  6074. 'textShadowOffsetY': 1,
  6075. 'textBoxShadowBlur': 1,
  6076. 'textBoxShadowOffsetX': 1,
  6077. 'textBoxShadowOffsetY': 1
  6078. };
  6079. var fixShadow = function (ctx, propName, value) {
  6080. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6081. return value *= ctx.dpr;
  6082. }
  6083. return value;
  6084. };
  6085. var ContextCachedBy = {
  6086. NONE: 0,
  6087. STYLE_BIND: 1,
  6088. PLAIN_TEXT: 2
  6089. };
  6090. // Avoid confused with 0/false.
  6091. var WILL_BE_RESTORED = 9;
  6092. var STYLE_COMMON_PROPS = [
  6093. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6094. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6095. ];
  6096. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6097. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6098. var Style = function (opts) {
  6099. this.extendFrom(opts, false);
  6100. };
  6101. function createLinearGradient(ctx, obj, rect) {
  6102. var x = obj.x == null ? 0 : obj.x;
  6103. var x2 = obj.x2 == null ? 1 : obj.x2;
  6104. var y = obj.y == null ? 0 : obj.y;
  6105. var y2 = obj.y2 == null ? 0 : obj.y2;
  6106. if (!obj.global) {
  6107. x = x * rect.width + rect.x;
  6108. x2 = x2 * rect.width + rect.x;
  6109. y = y * rect.height + rect.y;
  6110. y2 = y2 * rect.height + rect.y;
  6111. }
  6112. // Fix NaN when rect is Infinity
  6113. x = isNaN(x) ? 0 : x;
  6114. x2 = isNaN(x2) ? 1 : x2;
  6115. y = isNaN(y) ? 0 : y;
  6116. y2 = isNaN(y2) ? 0 : y2;
  6117. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6118. return canvasGradient;
  6119. }
  6120. function createRadialGradient(ctx, obj, rect) {
  6121. var width = rect.width;
  6122. var height = rect.height;
  6123. var min = Math.min(width, height);
  6124. var x = obj.x == null ? 0.5 : obj.x;
  6125. var y = obj.y == null ? 0.5 : obj.y;
  6126. var r = obj.r == null ? 0.5 : obj.r;
  6127. if (!obj.global) {
  6128. x = x * width + rect.x;
  6129. y = y * height + rect.y;
  6130. r = r * min;
  6131. }
  6132. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6133. return canvasGradient;
  6134. }
  6135. Style.prototype = {
  6136. constructor: Style,
  6137. /**
  6138. * @type {string}
  6139. */
  6140. fill: '#000',
  6141. /**
  6142. * @type {string}
  6143. */
  6144. stroke: null,
  6145. /**
  6146. * @type {number}
  6147. */
  6148. opacity: 1,
  6149. /**
  6150. * @type {number}
  6151. */
  6152. fillOpacity: null,
  6153. /**
  6154. * @type {number}
  6155. */
  6156. strokeOpacity: null,
  6157. /**
  6158. * `true` is not supported.
  6159. * `false`/`null`/`undefined` are the same.
  6160. * `false` is used to remove lineDash in some
  6161. * case that `null`/`undefined` can not be set.
  6162. * (e.g., emphasis.lineStyle in echarts)
  6163. * @type {Array.<number>|boolean}
  6164. */
  6165. lineDash: null,
  6166. /**
  6167. * @type {number}
  6168. */
  6169. lineDashOffset: 0,
  6170. /**
  6171. * @type {number}
  6172. */
  6173. shadowBlur: 0,
  6174. /**
  6175. * @type {number}
  6176. */
  6177. shadowOffsetX: 0,
  6178. /**
  6179. * @type {number}
  6180. */
  6181. shadowOffsetY: 0,
  6182. /**
  6183. * @type {number}
  6184. */
  6185. lineWidth: 1,
  6186. /**
  6187. * If stroke ignore scale
  6188. * @type {Boolean}
  6189. */
  6190. strokeNoScale: false,
  6191. // Bounding rect text configuration
  6192. // Not affected by element transform
  6193. /**
  6194. * @type {string}
  6195. */
  6196. text: null,
  6197. /**
  6198. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6199. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6200. * So do not visit it directly in upper application (like echarts),
  6201. * but use `contain/text#makeFont` instead.
  6202. * @type {string}
  6203. */
  6204. font: null,
  6205. /**
  6206. * The same as font. Use font please.
  6207. * @deprecated
  6208. * @type {string}
  6209. */
  6210. textFont: null,
  6211. /**
  6212. * It helps merging respectively, rather than parsing an entire font string.
  6213. * @type {string}
  6214. */
  6215. fontStyle: null,
  6216. /**
  6217. * It helps merging respectively, rather than parsing an entire font string.
  6218. * @type {string}
  6219. */
  6220. fontWeight: null,
  6221. /**
  6222. * It helps merging respectively, rather than parsing an entire font string.
  6223. * Should be 12 but not '12px'.
  6224. * @type {number}
  6225. */
  6226. fontSize: null,
  6227. /**
  6228. * It helps merging respectively, rather than parsing an entire font string.
  6229. * @type {string}
  6230. */
  6231. fontFamily: null,
  6232. /**
  6233. * Reserved for special functinality, like 'hr'.
  6234. * @type {string}
  6235. */
  6236. textTag: null,
  6237. /**
  6238. * @type {string}
  6239. */
  6240. textFill: '#000',
  6241. /**
  6242. * @type {string}
  6243. */
  6244. textStroke: null,
  6245. /**
  6246. * @type {number}
  6247. */
  6248. textWidth: null,
  6249. /**
  6250. * Only for textBackground.
  6251. * @type {number}
  6252. */
  6253. textHeight: null,
  6254. /**
  6255. * textStroke may be set as some color as a default
  6256. * value in upper applicaion, where the default value
  6257. * of textStrokeWidth should be 0 to make sure that
  6258. * user can choose to do not use text stroke.
  6259. * @type {number}
  6260. */
  6261. textStrokeWidth: 0,
  6262. /**
  6263. * @type {number}
  6264. */
  6265. textLineHeight: null,
  6266. /**
  6267. * 'inside', 'left', 'right', 'top', 'bottom'
  6268. * [x, y]
  6269. * Based on x, y of rect.
  6270. * @type {string|Array.<number>}
  6271. * @default 'inside'
  6272. */
  6273. textPosition: 'inside',
  6274. /**
  6275. * If not specified, use the boundingRect of a `displayable`.
  6276. * @type {Object}
  6277. */
  6278. textRect: null,
  6279. /**
  6280. * [x, y]
  6281. * @type {Array.<number>}
  6282. */
  6283. textOffset: null,
  6284. /**
  6285. * @type {string}
  6286. */
  6287. textAlign: null,
  6288. /**
  6289. * @type {string}
  6290. */
  6291. textVerticalAlign: null,
  6292. /**
  6293. * @type {number}
  6294. */
  6295. textDistance: 5,
  6296. /**
  6297. * @type {string}
  6298. */
  6299. textShadowColor: 'transparent',
  6300. /**
  6301. * @type {number}
  6302. */
  6303. textShadowBlur: 0,
  6304. /**
  6305. * @type {number}
  6306. */
  6307. textShadowOffsetX: 0,
  6308. /**
  6309. * @type {number}
  6310. */
  6311. textShadowOffsetY: 0,
  6312. /**
  6313. * @type {string}
  6314. */
  6315. textBoxShadowColor: 'transparent',
  6316. /**
  6317. * @type {number}
  6318. */
  6319. textBoxShadowBlur: 0,
  6320. /**
  6321. * @type {number}
  6322. */
  6323. textBoxShadowOffsetX: 0,
  6324. /**
  6325. * @type {number}
  6326. */
  6327. textBoxShadowOffsetY: 0,
  6328. /**
  6329. * Whether transform text.
  6330. * Only available in Path and Image element,
  6331. * where the text is called as `RectText`.
  6332. * @type {boolean}
  6333. */
  6334. transformText: false,
  6335. /**
  6336. * Text rotate around position of Path or Image.
  6337. * The origin of the rotation can be specified by `textOrigin`.
  6338. * Only available in Path and Image element,
  6339. * where the text is called as `RectText`.
  6340. */
  6341. textRotation: 0,
  6342. /**
  6343. * Text origin of text rotation.
  6344. * Useful in the case like label rotation of circular symbol.
  6345. * Only available in Path and Image element, where the text is called
  6346. * as `RectText` and the element is called as "host element".
  6347. * The value can be:
  6348. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6349. * base on the left-top corner of the rect of its host element.
  6350. * + If specified as a string `center`, it is the center of the rect of
  6351. * its host element.
  6352. * + By default, this origin is the `textPosition`.
  6353. * @type {string|Array.<number>}
  6354. */
  6355. textOrigin: null,
  6356. /**
  6357. * @type {string}
  6358. */
  6359. textBackgroundColor: null,
  6360. /**
  6361. * @type {string}
  6362. */
  6363. textBorderColor: null,
  6364. /**
  6365. * @type {number}
  6366. */
  6367. textBorderWidth: 0,
  6368. /**
  6369. * @type {number}
  6370. */
  6371. textBorderRadius: 0,
  6372. /**
  6373. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6374. * @type {number|Array.<number>}
  6375. */
  6376. textPadding: null,
  6377. /**
  6378. * Text styles for rich text.
  6379. * @type {Object}
  6380. */
  6381. rich: null,
  6382. /**
  6383. * {outerWidth, outerHeight, ellipsis, placeholder}
  6384. * @type {Object}
  6385. */
  6386. truncate: null,
  6387. /**
  6388. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6389. * @type {string}
  6390. */
  6391. blend: null,
  6392. /**
  6393. * @param {CanvasRenderingContext2D} ctx
  6394. */
  6395. bind: function (ctx, el, prevEl) {
  6396. var style = this;
  6397. var prevStyle = prevEl && prevEl.style;
  6398. // If no prevStyle, it means first draw.
  6399. // Only apply cache if the last time cachced by this function.
  6400. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6401. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6402. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6403. var prop = STYLE_COMMON_PROPS[i];
  6404. var styleName = prop[0];
  6405. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6406. // FIXME Invalid property value will cause style leak from previous element.
  6407. ctx[styleName] =
  6408. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6409. }
  6410. }
  6411. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6412. ctx.fillStyle = style.fill;
  6413. }
  6414. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6415. ctx.strokeStyle = style.stroke;
  6416. }
  6417. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6418. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6419. }
  6420. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6421. ctx.globalCompositeOperation = style.blend || 'source-over';
  6422. }
  6423. if (this.hasStroke()) {
  6424. var lineWidth = style.lineWidth;
  6425. ctx.lineWidth = lineWidth / (
  6426. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6427. );
  6428. }
  6429. },
  6430. hasFill: function () {
  6431. var fill = this.fill;
  6432. return fill != null && fill !== 'none';
  6433. },
  6434. hasStroke: function () {
  6435. var stroke = this.stroke;
  6436. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6437. },
  6438. /**
  6439. * Extend from other style
  6440. * @param {zrender/graphic/Style} otherStyle
  6441. * @param {boolean} overwrite true: overwrirte any way.
  6442. * false: overwrite only when !target.hasOwnProperty
  6443. * others: overwrite when property is not null/undefined.
  6444. */
  6445. extendFrom: function (otherStyle, overwrite) {
  6446. if (otherStyle) {
  6447. for (var name in otherStyle) {
  6448. if (otherStyle.hasOwnProperty(name)
  6449. && (overwrite === true
  6450. || (
  6451. overwrite === false
  6452. ? !this.hasOwnProperty(name)
  6453. : otherStyle[name] != null
  6454. )
  6455. )
  6456. ) {
  6457. this[name] = otherStyle[name];
  6458. }
  6459. }
  6460. }
  6461. },
  6462. /**
  6463. * Batch setting style with a given object
  6464. * @param {Object|string} obj
  6465. * @param {*} [obj]
  6466. */
  6467. set: function (obj, value) {
  6468. if (typeof obj === 'string') {
  6469. this[obj] = value;
  6470. }
  6471. else {
  6472. this.extendFrom(obj, true);
  6473. }
  6474. },
  6475. /**
  6476. * Clone
  6477. * @return {zrender/graphic/Style} [description]
  6478. */
  6479. clone: function () {
  6480. var newStyle = new this.constructor();
  6481. newStyle.extendFrom(this, true);
  6482. return newStyle;
  6483. },
  6484. getGradient: function (ctx, obj, rect) {
  6485. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6486. var canvasGradient = method(ctx, obj, rect);
  6487. var colorStops = obj.colorStops;
  6488. for (var i = 0; i < colorStops.length; i++) {
  6489. canvasGradient.addColorStop(
  6490. colorStops[i].offset, colorStops[i].color
  6491. );
  6492. }
  6493. return canvasGradient;
  6494. }
  6495. };
  6496. var styleProto = Style.prototype;
  6497. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6498. var prop = STYLE_COMMON_PROPS[i];
  6499. if (!(prop[0] in styleProto)) {
  6500. styleProto[prop[0]] = prop[1];
  6501. }
  6502. }
  6503. // Provide for others
  6504. Style.getGradient = styleProto.getGradient;
  6505. var Pattern = function (image, repeat) {
  6506. // Should do nothing more in this constructor. Because gradient can be
  6507. // declard by `color: {image: ...}`, where this constructor will not be called.
  6508. this.image = image;
  6509. this.repeat = repeat;
  6510. // Can be cloned
  6511. this.type = 'pattern';
  6512. };
  6513. Pattern.prototype.getCanvasPattern = function (ctx) {
  6514. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6515. };
  6516. /**
  6517. * @module zrender/Layer
  6518. * @author pissang(https://www.github.com/pissang)
  6519. */
  6520. function returnFalse() {
  6521. return false;
  6522. }
  6523. /**
  6524. * 创建dom
  6525. *
  6526. * @inner
  6527. * @param {string} id dom id 待用
  6528. * @param {Painter} painter painter instance
  6529. * @param {number} number
  6530. */
  6531. function createDom(id, painter, dpr) {
  6532. var newDom = createCanvas();
  6533. var width = painter.getWidth();
  6534. var height = painter.getHeight();
  6535. var newDomStyle = newDom.style;
  6536. if (newDomStyle) { // In node or some other non-browser environment
  6537. newDomStyle.position = 'absolute';
  6538. newDomStyle.left = 0;
  6539. newDomStyle.top = 0;
  6540. newDomStyle.width = width + 'px';
  6541. newDomStyle.height = height + 'px';
  6542. newDom.setAttribute('data-zr-dom-id', id);
  6543. }
  6544. newDom.width = width * dpr;
  6545. newDom.height = height * dpr;
  6546. return newDom;
  6547. }
  6548. /**
  6549. * @alias module:zrender/Layer
  6550. * @constructor
  6551. * @extends module:zrender/mixin/Transformable
  6552. * @param {string} id
  6553. * @param {module:zrender/Painter} painter
  6554. * @param {number} [dpr]
  6555. */
  6556. var Layer = function (id, painter, dpr) {
  6557. var dom;
  6558. dpr = dpr || devicePixelRatio;
  6559. if (typeof id === 'string') {
  6560. dom = createDom(id, painter, dpr);
  6561. }
  6562. // Not using isDom because in node it will return false
  6563. else if (isObject$1(id)) {
  6564. dom = id;
  6565. id = dom.id;
  6566. }
  6567. this.id = id;
  6568. this.dom = dom;
  6569. var domStyle = dom.style;
  6570. if (domStyle) { // Not in node
  6571. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6572. domStyle['-webkit-user-select'] = 'none';
  6573. domStyle['user-select'] = 'none';
  6574. domStyle['-webkit-touch-callout'] = 'none';
  6575. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6576. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6577. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6578. domStyle['border-width'] = 0;
  6579. }
  6580. this.domBack = null;
  6581. this.ctxBack = null;
  6582. this.painter = painter;
  6583. this.config = null;
  6584. // Configs
  6585. /**
  6586. * 每次清空画布的颜色
  6587. * @type {string}
  6588. * @default 0
  6589. */
  6590. this.clearColor = 0;
  6591. /**
  6592. * 是否开启动态模糊
  6593. * @type {boolean}
  6594. * @default false
  6595. */
  6596. this.motionBlur = false;
  6597. /**
  6598. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6599. * @type {number}
  6600. * @default 0.7
  6601. */
  6602. this.lastFrameAlpha = 0.7;
  6603. /**
  6604. * Layer dpr
  6605. * @type {number}
  6606. */
  6607. this.dpr = dpr;
  6608. };
  6609. Layer.prototype = {
  6610. constructor: Layer,
  6611. __dirty: true,
  6612. __used: false,
  6613. __drawIndex: 0,
  6614. __startIndex: 0,
  6615. __endIndex: 0,
  6616. incremental: false,
  6617. getElementCount: function () {
  6618. return this.__endIndex - this.__startIndex;
  6619. },
  6620. initContext: function () {
  6621. this.ctx = this.dom.getContext('2d');
  6622. this.ctx.dpr = this.dpr;
  6623. },
  6624. createBackBuffer: function () {
  6625. var dpr = this.dpr;
  6626. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6627. this.ctxBack = this.domBack.getContext('2d');
  6628. if (dpr !== 1) {
  6629. this.ctxBack.scale(dpr, dpr);
  6630. }
  6631. },
  6632. /**
  6633. * @param {number} width
  6634. * @param {number} height
  6635. */
  6636. resize: function (width, height) {
  6637. var dpr = this.dpr;
  6638. var dom = this.dom;
  6639. var domStyle = dom.style;
  6640. var domBack = this.domBack;
  6641. if (domStyle) {
  6642. domStyle.width = width + 'px';
  6643. domStyle.height = height + 'px';
  6644. }
  6645. dom.width = width * dpr;
  6646. dom.height = height * dpr;
  6647. if (domBack) {
  6648. domBack.width = width * dpr;
  6649. domBack.height = height * dpr;
  6650. if (dpr !== 1) {
  6651. this.ctxBack.scale(dpr, dpr);
  6652. }
  6653. }
  6654. },
  6655. /**
  6656. * 清空该层画布
  6657. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6658. * @param {Color} [clearColor]
  6659. */
  6660. clear: function (clearAll, clearColor) {
  6661. var dom = this.dom;
  6662. var ctx = this.ctx;
  6663. var width = dom.width;
  6664. var height = dom.height;
  6665. var clearColor = clearColor || this.clearColor;
  6666. var haveMotionBLur = this.motionBlur && !clearAll;
  6667. var lastFrameAlpha = this.lastFrameAlpha;
  6668. var dpr = this.dpr;
  6669. if (haveMotionBLur) {
  6670. if (!this.domBack) {
  6671. this.createBackBuffer();
  6672. }
  6673. this.ctxBack.globalCompositeOperation = 'copy';
  6674. this.ctxBack.drawImage(
  6675. dom, 0, 0,
  6676. width / dpr,
  6677. height / dpr
  6678. );
  6679. }
  6680. ctx.clearRect(0, 0, width, height);
  6681. if (clearColor && clearColor !== 'transparent') {
  6682. var clearColorGradientOrPattern;
  6683. // Gradient
  6684. if (clearColor.colorStops) {
  6685. // Cache canvas gradient
  6686. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6687. x: 0,
  6688. y: 0,
  6689. width: width,
  6690. height: height
  6691. });
  6692. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6693. }
  6694. // Pattern
  6695. else if (clearColor.image) {
  6696. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6697. }
  6698. ctx.save();
  6699. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6700. ctx.fillRect(0, 0, width, height);
  6701. ctx.restore();
  6702. }
  6703. if (haveMotionBLur) {
  6704. var domBack = this.domBack;
  6705. ctx.save();
  6706. ctx.globalAlpha = lastFrameAlpha;
  6707. ctx.drawImage(domBack, 0, 0, width, height);
  6708. ctx.restore();
  6709. }
  6710. }
  6711. };
  6712. var requestAnimationFrame = (
  6713. typeof window !== 'undefined'
  6714. && (
  6715. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6716. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6717. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6718. || window.mozRequestAnimationFrame
  6719. || window.webkitRequestAnimationFrame
  6720. )
  6721. ) || function (func) {
  6722. setTimeout(func, 16);
  6723. };
  6724. var globalImageCache = new LRU(50);
  6725. /**
  6726. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6727. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6728. */
  6729. function findExistImage(newImageOrSrc) {
  6730. if (typeof newImageOrSrc === 'string') {
  6731. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6732. return cachedImgObj && cachedImgObj.image;
  6733. }
  6734. else {
  6735. return newImageOrSrc;
  6736. }
  6737. }
  6738. /**
  6739. * Caution: User should cache loaded images, but not just count on LRU.
  6740. * Consider if required images more than LRU size, will dead loop occur?
  6741. *
  6742. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6743. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6744. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6745. * @param {Function} [cb] params: (image, cbPayload)
  6746. * @param {Object} [cbPayload] Payload on cb calling.
  6747. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6748. */
  6749. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6750. if (!newImageOrSrc) {
  6751. return image;
  6752. }
  6753. else if (typeof newImageOrSrc === 'string') {
  6754. // Image should not be loaded repeatly.
  6755. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6756. return image;
  6757. }
  6758. // Only when there is no existent image or existent image src
  6759. // is different, this method is responsible for load.
  6760. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6761. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6762. if (cachedImgObj) {
  6763. image = cachedImgObj.image;
  6764. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6765. }
  6766. else {
  6767. image = new Image();
  6768. image.onload = image.onerror = imageOnLoad;
  6769. globalImageCache.put(
  6770. newImageOrSrc,
  6771. image.__cachedImgObj = {
  6772. image: image,
  6773. pending: [pendingWrap]
  6774. }
  6775. );
  6776. image.src = image.__zrImageSrc = newImageOrSrc;
  6777. }
  6778. return image;
  6779. }
  6780. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6781. else {
  6782. return newImageOrSrc;
  6783. }
  6784. }
  6785. function imageOnLoad() {
  6786. var cachedImgObj = this.__cachedImgObj;
  6787. this.onload = this.onerror = this.__cachedImgObj = null;
  6788. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6789. var pendingWrap = cachedImgObj.pending[i];
  6790. var cb = pendingWrap.cb;
  6791. cb && cb(this, pendingWrap.cbPayload);
  6792. pendingWrap.hostEl.dirty();
  6793. }
  6794. cachedImgObj.pending.length = 0;
  6795. }
  6796. function isImageReady(image) {
  6797. return image && image.width && image.height;
  6798. }
  6799. var textWidthCache = {};
  6800. var textWidthCacheCounter = 0;
  6801. var TEXT_CACHE_MAX = 5000;
  6802. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6803. var DEFAULT_FONT$1 = '12px sans-serif';
  6804. // Avoid assign to an exported variable, for transforming to cjs.
  6805. var methods$1 = {};
  6806. function $override$1(name, fn) {
  6807. methods$1[name] = fn;
  6808. }
  6809. /**
  6810. * @public
  6811. * @param {string} text
  6812. * @param {string} font
  6813. * @return {number} width
  6814. */
  6815. function getWidth(text, font) {
  6816. font = font || DEFAULT_FONT$1;
  6817. var key = text + ':' + font;
  6818. if (textWidthCache[key]) {
  6819. return textWidthCache[key];
  6820. }
  6821. var textLines = (text + '').split('\n');
  6822. var width = 0;
  6823. for (var i = 0, l = textLines.length; i < l; i++) {
  6824. // textContain.measureText may be overrided in SVG or VML
  6825. width = Math.max(measureText(textLines[i], font).width, width);
  6826. }
  6827. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6828. textWidthCacheCounter = 0;
  6829. textWidthCache = {};
  6830. }
  6831. textWidthCacheCounter++;
  6832. textWidthCache[key] = width;
  6833. return width;
  6834. }
  6835. /**
  6836. * @public
  6837. * @param {string} text
  6838. * @param {string} font
  6839. * @param {string} [textAlign='left']
  6840. * @param {string} [textVerticalAlign='top']
  6841. * @param {Array.<number>} [textPadding]
  6842. * @param {Object} [rich]
  6843. * @param {Object} [truncate]
  6844. * @return {Object} {x, y, width, height, lineHeight}
  6845. */
  6846. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6847. return rich
  6848. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6849. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6850. }
  6851. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6852. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6853. var outerWidth = getWidth(text, font);
  6854. if (textPadding) {
  6855. outerWidth += textPadding[1] + textPadding[3];
  6856. }
  6857. var outerHeight = contentBlock.outerHeight;
  6858. var x = adjustTextX(0, outerWidth, textAlign);
  6859. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6860. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6861. rect.lineHeight = contentBlock.lineHeight;
  6862. return rect;
  6863. }
  6864. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6865. var contentBlock = parseRichText(text, {
  6866. rich: rich,
  6867. truncate: truncate,
  6868. font: font,
  6869. textAlign: textAlign,
  6870. textPadding: textPadding,
  6871. textLineHeight: textLineHeight
  6872. });
  6873. var outerWidth = contentBlock.outerWidth;
  6874. var outerHeight = contentBlock.outerHeight;
  6875. var x = adjustTextX(0, outerWidth, textAlign);
  6876. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6877. return new BoundingRect(x, y, outerWidth, outerHeight);
  6878. }
  6879. /**
  6880. * @public
  6881. * @param {number} x
  6882. * @param {number} width
  6883. * @param {string} [textAlign='left']
  6884. * @return {number} Adjusted x.
  6885. */
  6886. function adjustTextX(x, width, textAlign) {
  6887. // FIXME Right to left language
  6888. if (textAlign === 'right') {
  6889. x -= width;
  6890. }
  6891. else if (textAlign === 'center') {
  6892. x -= width / 2;
  6893. }
  6894. return x;
  6895. }
  6896. /**
  6897. * @public
  6898. * @param {number} y
  6899. * @param {number} height
  6900. * @param {string} [textVerticalAlign='top']
  6901. * @return {number} Adjusted y.
  6902. */
  6903. function adjustTextY(y, height, textVerticalAlign) {
  6904. if (textVerticalAlign === 'middle') {
  6905. y -= height / 2;
  6906. }
  6907. else if (textVerticalAlign === 'bottom') {
  6908. y -= height;
  6909. }
  6910. return y;
  6911. }
  6912. /**
  6913. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6914. * @public
  6915. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6916. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6917. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6918. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6919. */
  6920. function calculateTextPosition(out, style, rect) {
  6921. var textPosition = style.textPosition;
  6922. var distance = style.textDistance;
  6923. var x = rect.x;
  6924. var y = rect.y;
  6925. distance = distance || 0;
  6926. var height = rect.height;
  6927. var width = rect.width;
  6928. var halfHeight = height / 2;
  6929. var textAlign = 'left';
  6930. var textVerticalAlign = 'top';
  6931. switch (textPosition) {
  6932. case 'left':
  6933. x -= distance;
  6934. y += halfHeight;
  6935. textAlign = 'right';
  6936. textVerticalAlign = 'middle';
  6937. break;
  6938. case 'right':
  6939. x += distance + width;
  6940. y += halfHeight;
  6941. textVerticalAlign = 'middle';
  6942. break;
  6943. case 'top':
  6944. x += width / 2;
  6945. y -= distance;
  6946. textAlign = 'center';
  6947. textVerticalAlign = 'bottom';
  6948. break;
  6949. case 'bottom':
  6950. x += width / 2;
  6951. y += height + distance;
  6952. textAlign = 'center';
  6953. break;
  6954. case 'inside':
  6955. x += width / 2;
  6956. y += halfHeight;
  6957. textAlign = 'center';
  6958. textVerticalAlign = 'middle';
  6959. break;
  6960. case 'insideLeft':
  6961. x += distance;
  6962. y += halfHeight;
  6963. textVerticalAlign = 'middle';
  6964. break;
  6965. case 'insideRight':
  6966. x += width - distance;
  6967. y += halfHeight;
  6968. textAlign = 'right';
  6969. textVerticalAlign = 'middle';
  6970. break;
  6971. case 'insideTop':
  6972. x += width / 2;
  6973. y += distance;
  6974. textAlign = 'center';
  6975. break;
  6976. case 'insideBottom':
  6977. x += width / 2;
  6978. y += height - distance;
  6979. textAlign = 'center';
  6980. textVerticalAlign = 'bottom';
  6981. break;
  6982. case 'insideTopLeft':
  6983. x += distance;
  6984. y += distance;
  6985. break;
  6986. case 'insideTopRight':
  6987. x += width - distance;
  6988. y += distance;
  6989. textAlign = 'right';
  6990. break;
  6991. case 'insideBottomLeft':
  6992. x += distance;
  6993. y += height - distance;
  6994. textVerticalAlign = 'bottom';
  6995. break;
  6996. case 'insideBottomRight':
  6997. x += width - distance;
  6998. y += height - distance;
  6999. textAlign = 'right';
  7000. textVerticalAlign = 'bottom';
  7001. break;
  7002. }
  7003. out = out || {};
  7004. out.x = x;
  7005. out.y = y;
  7006. out.textAlign = textAlign;
  7007. out.textVerticalAlign = textVerticalAlign;
  7008. return out;
  7009. }
  7010. /**
  7011. * To be removed. But still do not remove in case that some one has imported it.
  7012. * @deprecated
  7013. * @public
  7014. * @param {stirng} textPosition
  7015. * @param {Object} rect {x, y, width, height}
  7016. * @param {number} distance
  7017. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7018. */
  7019. /**
  7020. * Show ellipsis if overflow.
  7021. *
  7022. * @public
  7023. * @param {string} text
  7024. * @param {string} containerWidth
  7025. * @param {string} font
  7026. * @param {number} [ellipsis='...']
  7027. * @param {Object} [options]
  7028. * @param {number} [options.maxIterations=3]
  7029. * @param {number} [options.minChar=0] If truncate result are less
  7030. * then minChar, ellipsis will not show, which is
  7031. * better for user hint in some cases.
  7032. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7033. * @return {string}
  7034. */
  7035. function truncateText(text, containerWidth, font, ellipsis, options) {
  7036. if (!containerWidth) {
  7037. return '';
  7038. }
  7039. var textLines = (text + '').split('\n');
  7040. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7041. // FIXME
  7042. // It is not appropriate that every line has '...' when truncate multiple lines.
  7043. for (var i = 0, len = textLines.length; i < len; i++) {
  7044. textLines[i] = truncateSingleLine(textLines[i], options);
  7045. }
  7046. return textLines.join('\n');
  7047. }
  7048. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7049. options = extend({}, options);
  7050. options.font = font;
  7051. var ellipsis = retrieve2(ellipsis, '...');
  7052. options.maxIterations = retrieve2(options.maxIterations, 2);
  7053. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7054. // FIXME
  7055. // Other languages?
  7056. options.cnCharWidth = getWidth('国', font);
  7057. // FIXME
  7058. // Consider proportional font?
  7059. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7060. options.placeholder = retrieve2(options.placeholder, '');
  7061. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7062. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7063. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7064. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7065. contentWidth -= ascCharWidth;
  7066. }
  7067. var ellipsisWidth = getWidth(ellipsis, font);
  7068. if (ellipsisWidth > contentWidth) {
  7069. ellipsis = '';
  7070. ellipsisWidth = 0;
  7071. }
  7072. contentWidth = containerWidth - ellipsisWidth;
  7073. options.ellipsis = ellipsis;
  7074. options.ellipsisWidth = ellipsisWidth;
  7075. options.contentWidth = contentWidth;
  7076. options.containerWidth = containerWidth;
  7077. return options;
  7078. }
  7079. function truncateSingleLine(textLine, options) {
  7080. var containerWidth = options.containerWidth;
  7081. var font = options.font;
  7082. var contentWidth = options.contentWidth;
  7083. if (!containerWidth) {
  7084. return '';
  7085. }
  7086. var lineWidth = getWidth(textLine, font);
  7087. if (lineWidth <= containerWidth) {
  7088. return textLine;
  7089. }
  7090. for (var j = 0; ; j++) {
  7091. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7092. textLine += options.ellipsis;
  7093. break;
  7094. }
  7095. var subLength = j === 0
  7096. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7097. : lineWidth > 0
  7098. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7099. : 0;
  7100. textLine = textLine.substr(0, subLength);
  7101. lineWidth = getWidth(textLine, font);
  7102. }
  7103. if (textLine === '') {
  7104. textLine = options.placeholder;
  7105. }
  7106. return textLine;
  7107. }
  7108. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7109. var width = 0;
  7110. var i = 0;
  7111. for (var len = text.length; i < len && width < contentWidth; i++) {
  7112. var charCode = text.charCodeAt(i);
  7113. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7114. }
  7115. return i;
  7116. }
  7117. /**
  7118. * @public
  7119. * @param {string} font
  7120. * @return {number} line height
  7121. */
  7122. function getLineHeight(font) {
  7123. // FIXME A rough approach.
  7124. return getWidth('国', font);
  7125. }
  7126. /**
  7127. * @public
  7128. * @param {string} text
  7129. * @param {string} font
  7130. * @return {Object} width
  7131. */
  7132. function measureText(text, font) {
  7133. return methods$1.measureText(text, font);
  7134. }
  7135. // Avoid assign to an exported variable, for transforming to cjs.
  7136. methods$1.measureText = function (text, font) {
  7137. var ctx = getContext();
  7138. ctx.font = font || DEFAULT_FONT$1;
  7139. return ctx.measureText(text);
  7140. };
  7141. /**
  7142. * @public
  7143. * @param {string} text
  7144. * @param {string} font
  7145. * @param {Object} [truncate]
  7146. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7147. * Notice: for performance, do not calculate outerWidth util needed.
  7148. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7149. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7150. * without travel the result `lines`.
  7151. */
  7152. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7153. text != null && (text += '');
  7154. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7155. var lines = text ? text.split('\n') : [];
  7156. var height = lines.length * lineHeight;
  7157. var outerHeight = height;
  7158. var canCacheByTextString = true;
  7159. if (padding) {
  7160. outerHeight += padding[0] + padding[2];
  7161. }
  7162. if (text && truncate) {
  7163. canCacheByTextString = false;
  7164. var truncOuterHeight = truncate.outerHeight;
  7165. var truncOuterWidth = truncate.outerWidth;
  7166. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7167. text = '';
  7168. lines = [];
  7169. }
  7170. else if (truncOuterWidth != null) {
  7171. var options = prepareTruncateOptions(
  7172. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7173. font,
  7174. truncate.ellipsis,
  7175. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7176. );
  7177. // FIXME
  7178. // It is not appropriate that every line has '...' when truncate multiple lines.
  7179. for (var i = 0, len = lines.length; i < len; i++) {
  7180. lines[i] = truncateSingleLine(lines[i], options);
  7181. }
  7182. }
  7183. }
  7184. return {
  7185. lines: lines,
  7186. height: height,
  7187. outerHeight: outerHeight,
  7188. lineHeight: lineHeight,
  7189. canCacheByTextString: canCacheByTextString
  7190. };
  7191. }
  7192. /**
  7193. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7194. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7195. *
  7196. * @public
  7197. * @param {string} text
  7198. * @param {Object} style
  7199. * @return {Object} block
  7200. * {
  7201. * width,
  7202. * height,
  7203. * lines: [{
  7204. * lineHeight,
  7205. * width,
  7206. * tokens: [[{
  7207. * styleName,
  7208. * text,
  7209. * width, // include textPadding
  7210. * height, // include textPadding
  7211. * textWidth, // pure text width
  7212. * textHeight, // pure text height
  7213. * lineHeihgt,
  7214. * font,
  7215. * textAlign,
  7216. * textVerticalAlign
  7217. * }], [...], ...]
  7218. * }, ...]
  7219. * }
  7220. * If styleName is undefined, it is plain text.
  7221. */
  7222. function parseRichText(text, style) {
  7223. var contentBlock = {lines: [], width: 0, height: 0};
  7224. text != null && (text += '');
  7225. if (!text) {
  7226. return contentBlock;
  7227. }
  7228. var lastIndex = STYLE_REG.lastIndex = 0;
  7229. var result;
  7230. while ((result = STYLE_REG.exec(text)) != null) {
  7231. var matchedIndex = result.index;
  7232. if (matchedIndex > lastIndex) {
  7233. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7234. }
  7235. pushTokens(contentBlock, result[2], result[1]);
  7236. lastIndex = STYLE_REG.lastIndex;
  7237. }
  7238. if (lastIndex < text.length) {
  7239. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7240. }
  7241. var lines = contentBlock.lines;
  7242. var contentHeight = 0;
  7243. var contentWidth = 0;
  7244. // For `textWidth: 100%`
  7245. var pendingList = [];
  7246. var stlPadding = style.textPadding;
  7247. var truncate = style.truncate;
  7248. var truncateWidth = truncate && truncate.outerWidth;
  7249. var truncateHeight = truncate && truncate.outerHeight;
  7250. if (stlPadding) {
  7251. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7252. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7253. }
  7254. // Calculate layout info of tokens.
  7255. for (var i = 0; i < lines.length; i++) {
  7256. var line = lines[i];
  7257. var lineHeight = 0;
  7258. var lineWidth = 0;
  7259. for (var j = 0; j < line.tokens.length; j++) {
  7260. var token = line.tokens[j];
  7261. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7262. // textPadding should not inherit from style.
  7263. var textPadding = token.textPadding = tokenStyle.textPadding;
  7264. // textFont has been asigned to font by `normalizeStyle`.
  7265. var font = token.font = tokenStyle.font || style.font;
  7266. // textHeight can be used when textVerticalAlign is specified in token.
  7267. var tokenHeight = token.textHeight = retrieve2(
  7268. // textHeight should not be inherited, consider it can be specified
  7269. // as box height of the block.
  7270. tokenStyle.textHeight, getLineHeight(font)
  7271. );
  7272. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7273. token.height = tokenHeight;
  7274. token.lineHeight = retrieve3(
  7275. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7276. );
  7277. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7278. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7279. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7280. return {lines: [], width: 0, height: 0};
  7281. }
  7282. token.textWidth = getWidth(token.text, font);
  7283. var tokenWidth = tokenStyle.textWidth;
  7284. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7285. // Percent width, can be `100%`, can be used in drawing separate
  7286. // line when box width is needed to be auto.
  7287. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7288. token.percentWidth = tokenWidth;
  7289. pendingList.push(token);
  7290. tokenWidth = 0;
  7291. // Do not truncate in this case, because there is no user case
  7292. // and it is too complicated.
  7293. }
  7294. else {
  7295. if (tokenWidthNotSpecified) {
  7296. tokenWidth = token.textWidth;
  7297. // FIXME: If image is not loaded and textWidth is not specified, calling
  7298. // `getBoundingRect()` will not get correct result.
  7299. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7300. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7301. // Use cases:
  7302. // (1) If image is not loaded, it will be loaded at render phase and call
  7303. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7304. // image, and then the right size will be calculated here at the next tick.
  7305. // See `graphic/helper/text.js`.
  7306. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7307. // use `imageHelper.findExistImage` to find cached image.
  7308. // `imageHelper.findExistImage` will always be called here before
  7309. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7310. // which ensures that image will not be rendered before correct size calcualted.
  7311. if (bgImg) {
  7312. bgImg = findExistImage(bgImg);
  7313. if (isImageReady(bgImg)) {
  7314. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7315. }
  7316. }
  7317. }
  7318. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7319. tokenWidth += paddingW;
  7320. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7321. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7322. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7323. token.text = '';
  7324. token.textWidth = tokenWidth = 0;
  7325. }
  7326. else {
  7327. token.text = truncateText(
  7328. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7329. {minChar: truncate.minChar}
  7330. );
  7331. token.textWidth = getWidth(token.text, font);
  7332. tokenWidth = token.textWidth + paddingW;
  7333. }
  7334. }
  7335. }
  7336. lineWidth += (token.width = tokenWidth);
  7337. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7338. }
  7339. line.width = lineWidth;
  7340. line.lineHeight = lineHeight;
  7341. contentHeight += lineHeight;
  7342. contentWidth = Math.max(contentWidth, lineWidth);
  7343. }
  7344. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7345. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7346. if (stlPadding) {
  7347. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7348. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7349. }
  7350. for (var i = 0; i < pendingList.length; i++) {
  7351. var token = pendingList[i];
  7352. var percentWidth = token.percentWidth;
  7353. // Should not base on outerWidth, because token can not be placed out of padding.
  7354. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7355. }
  7356. return contentBlock;
  7357. }
  7358. function pushTokens(block, str, styleName) {
  7359. var isEmptyStr = str === '';
  7360. var strs = str.split('\n');
  7361. var lines = block.lines;
  7362. for (var i = 0; i < strs.length; i++) {
  7363. var text = strs[i];
  7364. var token = {
  7365. styleName: styleName,
  7366. text: text,
  7367. isLineHolder: !text && !isEmptyStr
  7368. };
  7369. // The first token should be appended to the last line.
  7370. if (!i) {
  7371. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7372. // Consider cases:
  7373. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7374. // (which is a placeholder) should be replaced by new token.
  7375. // (2) A image backage, where token likes {a|}.
  7376. // (3) A redundant '' will affect textAlign in line.
  7377. // (4) tokens with the same tplName should not be merged, because
  7378. // they should be displayed in different box (with border and padding).
  7379. var tokensLen = tokens.length;
  7380. (tokensLen === 1 && tokens[0].isLineHolder)
  7381. ? (tokens[0] = token)
  7382. // Consider text is '', only insert when it is the "lineHolder" or
  7383. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7384. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7385. }
  7386. // Other tokens always start a new line.
  7387. else {
  7388. // If there is '', insert it as a placeholder.
  7389. lines.push({tokens: [token]});
  7390. }
  7391. }
  7392. }
  7393. function makeFont(style) {
  7394. // FIXME in node-canvas fontWeight is before fontStyle
  7395. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7396. var font = (style.fontSize || style.fontFamily) && [
  7397. style.fontStyle,
  7398. style.fontWeight,
  7399. (style.fontSize || 12) + 'px',
  7400. // If font properties are defined, `fontFamily` should not be ignored.
  7401. style.fontFamily || 'sans-serif'
  7402. ].join(' ');
  7403. return font && trim(font) || style.textFont || style.font;
  7404. }
  7405. /**
  7406. * @param {Object} ctx
  7407. * @param {Object} shape
  7408. * @param {number} shape.x
  7409. * @param {number} shape.y
  7410. * @param {number} shape.width
  7411. * @param {number} shape.height
  7412. * @param {number} shape.r
  7413. */
  7414. function buildPath(ctx, shape) {
  7415. var x = shape.x;
  7416. var y = shape.y;
  7417. var width = shape.width;
  7418. var height = shape.height;
  7419. var r = shape.r;
  7420. var r1;
  7421. var r2;
  7422. var r3;
  7423. var r4;
  7424. // Convert width and height to positive for better borderRadius
  7425. if (width < 0) {
  7426. x = x + width;
  7427. width = -width;
  7428. }
  7429. if (height < 0) {
  7430. y = y + height;
  7431. height = -height;
  7432. }
  7433. if (typeof r === 'number') {
  7434. r1 = r2 = r3 = r4 = r;
  7435. }
  7436. else if (r instanceof Array) {
  7437. if (r.length === 1) {
  7438. r1 = r2 = r3 = r4 = r[0];
  7439. }
  7440. else if (r.length === 2) {
  7441. r1 = r3 = r[0];
  7442. r2 = r4 = r[1];
  7443. }
  7444. else if (r.length === 3) {
  7445. r1 = r[0];
  7446. r2 = r4 = r[1];
  7447. r3 = r[2];
  7448. }
  7449. else {
  7450. r1 = r[0];
  7451. r2 = r[1];
  7452. r3 = r[2];
  7453. r4 = r[3];
  7454. }
  7455. }
  7456. else {
  7457. r1 = r2 = r3 = r4 = 0;
  7458. }
  7459. var total;
  7460. if (r1 + r2 > width) {
  7461. total = r1 + r2;
  7462. r1 *= width / total;
  7463. r2 *= width / total;
  7464. }
  7465. if (r3 + r4 > width) {
  7466. total = r3 + r4;
  7467. r3 *= width / total;
  7468. r4 *= width / total;
  7469. }
  7470. if (r2 + r3 > height) {
  7471. total = r2 + r3;
  7472. r2 *= height / total;
  7473. r3 *= height / total;
  7474. }
  7475. if (r1 + r4 > height) {
  7476. total = r1 + r4;
  7477. r1 *= height / total;
  7478. r4 *= height / total;
  7479. }
  7480. ctx.moveTo(x + r1, y);
  7481. ctx.lineTo(x + width - r2, y);
  7482. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7483. ctx.lineTo(x + width, y + height - r3);
  7484. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7485. ctx.lineTo(x + r4, y + height);
  7486. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7487. ctx.lineTo(x, y + r1);
  7488. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7489. }
  7490. var DEFAULT_FONT = DEFAULT_FONT$1;
  7491. // TODO: Have not support 'start', 'end' yet.
  7492. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7493. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7494. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7495. // the default value of shadowColor is `'transparent'`.
  7496. var SHADOW_STYLE_COMMON_PROPS = [
  7497. ['textShadowBlur', 'shadowBlur', 0],
  7498. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7499. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7500. ['textShadowColor', 'shadowColor', 'transparent']
  7501. ];
  7502. var _tmpTextPositionResult = {};
  7503. var _tmpBoxPositionResult = {};
  7504. /**
  7505. * @param {module:zrender/graphic/Style} style
  7506. * @return {module:zrender/graphic/Style} The input style.
  7507. */
  7508. function normalizeTextStyle(style) {
  7509. normalizeStyle(style);
  7510. each$1(style.rich, normalizeStyle);
  7511. return style;
  7512. }
  7513. function normalizeStyle(style) {
  7514. if (style) {
  7515. style.font = makeFont(style);
  7516. var textAlign = style.textAlign;
  7517. textAlign === 'middle' && (textAlign = 'center');
  7518. style.textAlign = (
  7519. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7520. ) ? textAlign : 'left';
  7521. // Compatible with textBaseline.
  7522. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7523. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7524. style.textVerticalAlign = (
  7525. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7526. ) ? textVerticalAlign : 'top';
  7527. var textPadding = style.textPadding;
  7528. if (textPadding) {
  7529. style.textPadding = normalizeCssArray(style.textPadding);
  7530. }
  7531. }
  7532. }
  7533. /**
  7534. * @param {CanvasRenderingContext2D} ctx
  7535. * @param {string} text
  7536. * @param {module:zrender/graphic/Style} style
  7537. * @param {Object|boolean} [rect] {x, y, width, height}
  7538. * If set false, rect text is not used.
  7539. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7540. */
  7541. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7542. style.rich
  7543. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7544. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7545. }
  7546. // Avoid setting to ctx according to prevEl if possible for
  7547. // performance in scenarios of large amount text.
  7548. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7549. 'use strict';
  7550. var needDrawBg = needDrawBackground(style);
  7551. var prevStyle;
  7552. var checkCache = false;
  7553. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7554. // Only take and check cache for `Text` el, but not RectText.
  7555. if (prevEl !== WILL_BE_RESTORED) {
  7556. if (prevEl) {
  7557. prevStyle = prevEl.style;
  7558. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7559. }
  7560. // Prevent from using cache in `Style::bind`, because of the case:
  7561. // ctx property is modified by other properties than `Style::bind`
  7562. // used, and Style::bind is called next.
  7563. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7564. }
  7565. // Since this will be restored, prevent from using these props to check cache in the next
  7566. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7567. else if (cachedByMe) {
  7568. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7569. }
  7570. var styleFont = style.font || DEFAULT_FONT;
  7571. // PENDING
  7572. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7573. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7574. // But layer save/restore needed to be considered.
  7575. // if (styleFont !== ctx.__fontCache) {
  7576. // ctx.font = styleFont;
  7577. // if (prevEl !== WILL_BE_RESTORED) {
  7578. // ctx.__fontCache = styleFont;
  7579. // }
  7580. // }
  7581. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7582. ctx.font = styleFont;
  7583. }
  7584. // Use the final font from context-2d, because the final
  7585. // font might not be the style.font when it is illegal.
  7586. // But get `ctx.font` might be time consuming.
  7587. var computedFont = hostEl.__computedFont;
  7588. if (hostEl.__styleFont !== styleFont) {
  7589. hostEl.__styleFont = styleFont;
  7590. computedFont = hostEl.__computedFont = ctx.font;
  7591. }
  7592. var textPadding = style.textPadding;
  7593. var textLineHeight = style.textLineHeight;
  7594. var contentBlock = hostEl.__textCotentBlock;
  7595. if (!contentBlock || hostEl.__dirtyText) {
  7596. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7597. text, computedFont, textPadding, textLineHeight, style.truncate
  7598. );
  7599. }
  7600. var outerHeight = contentBlock.outerHeight;
  7601. var textLines = contentBlock.lines;
  7602. var lineHeight = contentBlock.lineHeight;
  7603. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7604. var baseX = boxPos.baseX;
  7605. var baseY = boxPos.baseY;
  7606. var textAlign = boxPos.textAlign || 'left';
  7607. var textVerticalAlign = boxPos.textVerticalAlign;
  7608. // Origin of textRotation should be the base point of text drawing.
  7609. applyTextRotation(ctx, style, rect, baseX, baseY);
  7610. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7611. var textX = baseX;
  7612. var textY = boxY;
  7613. if (needDrawBg || textPadding) {
  7614. // Consider performance, do not call getTextWidth util necessary.
  7615. var textWidth = getWidth(text, computedFont);
  7616. var outerWidth = textWidth;
  7617. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7618. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7619. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7620. if (textPadding) {
  7621. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7622. textY += textPadding[0];
  7623. }
  7624. }
  7625. // Always set textAlign and textBase line, because it is difficute to calculate
  7626. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7627. // font set happened.
  7628. ctx.textAlign = textAlign;
  7629. // Force baseline to be "middle". Otherwise, if using "top", the
  7630. // text will offset downward a little bit in font "Microsoft YaHei".
  7631. ctx.textBaseline = 'middle';
  7632. // Set text opacity
  7633. ctx.globalAlpha = style.opacity || 1;
  7634. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7635. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7636. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7637. var styleProp = propItem[0];
  7638. var ctxProp = propItem[1];
  7639. var val = style[styleProp];
  7640. if (!checkCache || val !== prevStyle[styleProp]) {
  7641. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7642. }
  7643. }
  7644. // `textBaseline` is set as 'middle'.
  7645. textY += lineHeight / 2;
  7646. var textStrokeWidth = style.textStrokeWidth;
  7647. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7648. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7649. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7650. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7651. var textFill = getFill(style.textFill);
  7652. if (textStroke) {
  7653. if (strokeWidthChanged) {
  7654. ctx.lineWidth = textStrokeWidth;
  7655. }
  7656. if (strokeChanged) {
  7657. ctx.strokeStyle = textStroke;
  7658. }
  7659. }
  7660. if (textFill) {
  7661. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7662. ctx.fillStyle = textFill;
  7663. }
  7664. }
  7665. // Optimize simply, in most cases only one line exists.
  7666. if (textLines.length === 1) {
  7667. // Fill after stroke so the outline will not cover the main part.
  7668. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7669. textFill && ctx.fillText(textLines[0], textX, textY);
  7670. }
  7671. else {
  7672. for (var i = 0; i < textLines.length; i++) {
  7673. // Fill after stroke so the outline will not cover the main part.
  7674. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7675. textFill && ctx.fillText(textLines[i], textX, textY);
  7676. textY += lineHeight;
  7677. }
  7678. }
  7679. }
  7680. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7681. // Do not do cache for rich text because of the complexity.
  7682. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7683. if (prevEl !== WILL_BE_RESTORED) {
  7684. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7685. }
  7686. var contentBlock = hostEl.__textCotentBlock;
  7687. if (!contentBlock || hostEl.__dirtyText) {
  7688. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7689. }
  7690. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7691. }
  7692. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7693. var contentWidth = contentBlock.width;
  7694. var outerWidth = contentBlock.outerWidth;
  7695. var outerHeight = contentBlock.outerHeight;
  7696. var textPadding = style.textPadding;
  7697. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7698. var baseX = boxPos.baseX;
  7699. var baseY = boxPos.baseY;
  7700. var textAlign = boxPos.textAlign;
  7701. var textVerticalAlign = boxPos.textVerticalAlign;
  7702. // Origin of textRotation should be the base point of text drawing.
  7703. applyTextRotation(ctx, style, rect, baseX, baseY);
  7704. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7705. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7706. var xLeft = boxX;
  7707. var lineTop = boxY;
  7708. if (textPadding) {
  7709. xLeft += textPadding[3];
  7710. lineTop += textPadding[0];
  7711. }
  7712. var xRight = xLeft + contentWidth;
  7713. needDrawBackground(style) && drawBackground(
  7714. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7715. );
  7716. for (var i = 0; i < contentBlock.lines.length; i++) {
  7717. var line = contentBlock.lines[i];
  7718. var tokens = line.tokens;
  7719. var tokenCount = tokens.length;
  7720. var lineHeight = line.lineHeight;
  7721. var usedWidth = line.width;
  7722. var leftIndex = 0;
  7723. var lineXLeft = xLeft;
  7724. var lineXRight = xRight;
  7725. var rightIndex = tokenCount - 1;
  7726. var token;
  7727. while (
  7728. leftIndex < tokenCount
  7729. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7730. ) {
  7731. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7732. usedWidth -= token.width;
  7733. lineXLeft += token.width;
  7734. leftIndex++;
  7735. }
  7736. while (
  7737. rightIndex >= 0
  7738. && (token = tokens[rightIndex], token.textAlign === 'right')
  7739. ) {
  7740. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7741. usedWidth -= token.width;
  7742. lineXRight -= token.width;
  7743. rightIndex--;
  7744. }
  7745. // The other tokens are placed as textAlign 'center' if there is enough space.
  7746. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7747. while (leftIndex <= rightIndex) {
  7748. token = tokens[leftIndex];
  7749. // Consider width specified by user, use 'center' rather than 'left'.
  7750. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7751. lineXLeft += token.width;
  7752. leftIndex++;
  7753. }
  7754. lineTop += lineHeight;
  7755. }
  7756. }
  7757. function applyTextRotation(ctx, style, rect, x, y) {
  7758. // textRotation only apply in RectText.
  7759. if (rect && style.textRotation) {
  7760. var origin = style.textOrigin;
  7761. if (origin === 'center') {
  7762. x = rect.width / 2 + rect.x;
  7763. y = rect.height / 2 + rect.y;
  7764. }
  7765. else if (origin) {
  7766. x = origin[0] + rect.x;
  7767. y = origin[1] + rect.y;
  7768. }
  7769. ctx.translate(x, y);
  7770. // Positive: anticlockwise
  7771. ctx.rotate(-style.textRotation);
  7772. ctx.translate(-x, -y);
  7773. }
  7774. }
  7775. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7776. var tokenStyle = style.rich[token.styleName] || {};
  7777. tokenStyle.text = token.text;
  7778. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7779. // the bias of "Microsoft YaHei".
  7780. var textVerticalAlign = token.textVerticalAlign;
  7781. var y = lineTop + lineHeight / 2;
  7782. if (textVerticalAlign === 'top') {
  7783. y = lineTop + token.height / 2;
  7784. }
  7785. else if (textVerticalAlign === 'bottom') {
  7786. y = lineTop + lineHeight - token.height / 2;
  7787. }
  7788. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7789. hostEl,
  7790. ctx,
  7791. tokenStyle,
  7792. textAlign === 'right'
  7793. ? x - token.width
  7794. : textAlign === 'center'
  7795. ? x - token.width / 2
  7796. : x,
  7797. y - token.height / 2,
  7798. token.width,
  7799. token.height
  7800. );
  7801. var textPadding = token.textPadding;
  7802. if (textPadding) {
  7803. x = getTextXForPadding(x, textAlign, textPadding);
  7804. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7805. }
  7806. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7807. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7808. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7809. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7810. setCtx(ctx, 'textAlign', textAlign);
  7811. // Force baseline to be "middle". Otherwise, if using "top", the
  7812. // text will offset downward a little bit in font "Microsoft YaHei".
  7813. setCtx(ctx, 'textBaseline', 'middle');
  7814. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7815. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7816. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7817. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7818. // Fill after stroke so the outline will not cover the main part.
  7819. if (textStroke) {
  7820. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7821. setCtx(ctx, 'strokeStyle', textStroke);
  7822. ctx.strokeText(token.text, x, y);
  7823. }
  7824. if (textFill) {
  7825. setCtx(ctx, 'fillStyle', textFill);
  7826. ctx.fillText(token.text, x, y);
  7827. }
  7828. }
  7829. function needDrawBackground(style) {
  7830. return !!(
  7831. style.textBackgroundColor
  7832. || (style.textBorderWidth && style.textBorderColor)
  7833. );
  7834. }
  7835. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7836. // shape: {x, y, width, height}
  7837. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7838. var textBackgroundColor = style.textBackgroundColor;
  7839. var textBorderWidth = style.textBorderWidth;
  7840. var textBorderColor = style.textBorderColor;
  7841. var isPlainBg = isString(textBackgroundColor);
  7842. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7843. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7844. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7845. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7846. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7847. ctx.beginPath();
  7848. var textBorderRadius = style.textBorderRadius;
  7849. if (!textBorderRadius) {
  7850. ctx.rect(x, y, width, height);
  7851. }
  7852. else {
  7853. buildPath(ctx, {
  7854. x: x, y: y, width: width, height: height, r: textBorderRadius
  7855. });
  7856. }
  7857. ctx.closePath();
  7858. }
  7859. if (isPlainBg) {
  7860. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7861. if (style.fillOpacity != null) {
  7862. var originalGlobalAlpha = ctx.globalAlpha;
  7863. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7864. ctx.fill();
  7865. ctx.globalAlpha = originalGlobalAlpha;
  7866. }
  7867. else {
  7868. ctx.fill();
  7869. }
  7870. }
  7871. else if (isObject$1(textBackgroundColor)) {
  7872. var image = textBackgroundColor.image;
  7873. image = createOrUpdateImage(
  7874. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7875. );
  7876. if (image && isImageReady(image)) {
  7877. ctx.drawImage(image, x, y, width, height);
  7878. }
  7879. }
  7880. if (textBorderWidth && textBorderColor) {
  7881. setCtx(ctx, 'lineWidth', textBorderWidth);
  7882. setCtx(ctx, 'strokeStyle', textBorderColor);
  7883. if (style.strokeOpacity != null) {
  7884. var originalGlobalAlpha = ctx.globalAlpha;
  7885. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7886. ctx.stroke();
  7887. ctx.globalAlpha = originalGlobalAlpha;
  7888. }
  7889. else {
  7890. ctx.stroke();
  7891. }
  7892. }
  7893. }
  7894. function onBgImageLoaded(image, textBackgroundColor) {
  7895. // Replace image, so that `contain/text.js#parseRichText`
  7896. // will get correct result in next tick.
  7897. textBackgroundColor.image = image;
  7898. }
  7899. function getBoxPosition(out, hostEl, style, rect) {
  7900. var baseX = style.x || 0;
  7901. var baseY = style.y || 0;
  7902. var textAlign = style.textAlign;
  7903. var textVerticalAlign = style.textVerticalAlign;
  7904. // Text position represented by coord
  7905. if (rect) {
  7906. var textPosition = style.textPosition;
  7907. if (textPosition instanceof Array) {
  7908. // Percent
  7909. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7910. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7911. }
  7912. else {
  7913. var res = (hostEl && hostEl.calculateTextPosition)
  7914. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7915. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7916. baseX = res.x;
  7917. baseY = res.y;
  7918. // Default align and baseline when has textPosition
  7919. textAlign = textAlign || res.textAlign;
  7920. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7921. }
  7922. // textOffset is only support in RectText, otherwise
  7923. // we have to adjust boundingRect for textOffset.
  7924. var textOffset = style.textOffset;
  7925. if (textOffset) {
  7926. baseX += textOffset[0];
  7927. baseY += textOffset[1];
  7928. }
  7929. }
  7930. out = out || {};
  7931. out.baseX = baseX;
  7932. out.baseY = baseY;
  7933. out.textAlign = textAlign;
  7934. out.textVerticalAlign = textVerticalAlign;
  7935. return out;
  7936. }
  7937. function setCtx(ctx, prop, value) {
  7938. ctx[prop] = fixShadow(ctx, prop, value);
  7939. return ctx[prop];
  7940. }
  7941. /**
  7942. * @param {string} [stroke] If specified, do not check style.textStroke.
  7943. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7944. * @param {number} style
  7945. */
  7946. function getStroke(stroke, lineWidth) {
  7947. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7948. ? null
  7949. // TODO pattern and gradient?
  7950. : (stroke.image || stroke.colorStops)
  7951. ? '#000'
  7952. : stroke;
  7953. }
  7954. function getFill(fill) {
  7955. return (fill == null || fill === 'none')
  7956. ? null
  7957. // TODO pattern and gradient?
  7958. : (fill.image || fill.colorStops)
  7959. ? '#000'
  7960. : fill;
  7961. }
  7962. function parsePercent(value, maxValue) {
  7963. if (typeof value === 'string') {
  7964. if (value.lastIndexOf('%') >= 0) {
  7965. return parseFloat(value) / 100 * maxValue;
  7966. }
  7967. return parseFloat(value);
  7968. }
  7969. return value;
  7970. }
  7971. function getTextXForPadding(x, textAlign, textPadding) {
  7972. return textAlign === 'right'
  7973. ? (x - textPadding[1])
  7974. : textAlign === 'center'
  7975. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7976. : (x + textPadding[3]);
  7977. }
  7978. /**
  7979. * @param {string} text
  7980. * @param {module:zrender/Style} style
  7981. * @return {boolean}
  7982. */
  7983. function needDrawText(text, style) {
  7984. return text != null
  7985. && (text
  7986. || style.textBackgroundColor
  7987. || (style.textBorderWidth && style.textBorderColor)
  7988. || style.textPadding
  7989. );
  7990. }
  7991. /**
  7992. * Mixin for drawing text in a element bounding rect
  7993. * @module zrender/mixin/RectText
  7994. */
  7995. var tmpRect$1 = new BoundingRect();
  7996. var RectText = function () {};
  7997. RectText.prototype = {
  7998. constructor: RectText,
  7999. /**
  8000. * Draw text in a rect with specified position.
  8001. * @param {CanvasRenderingContext2D} ctx
  8002. * @param {Object} rect Displayable rect
  8003. */
  8004. drawRectText: function (ctx, rect) {
  8005. var style = this.style;
  8006. rect = style.textRect || rect;
  8007. // Optimize, avoid normalize every time.
  8008. this.__dirty && normalizeTextStyle(style, true);
  8009. var text = style.text;
  8010. // Convert to string
  8011. text != null && (text += '');
  8012. if (!needDrawText(text, style)) {
  8013. return;
  8014. }
  8015. // FIXME
  8016. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8017. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8018. // text propably break the cache for its host elements.
  8019. ctx.save();
  8020. // Transform rect to view space
  8021. var transform = this.transform;
  8022. if (!style.transformText) {
  8023. if (transform) {
  8024. tmpRect$1.copy(rect);
  8025. tmpRect$1.applyTransform(transform);
  8026. rect = tmpRect$1;
  8027. }
  8028. }
  8029. else {
  8030. this.setTransform(ctx);
  8031. }
  8032. // transformText and textRotation can not be used at the same time.
  8033. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8034. ctx.restore();
  8035. }
  8036. };
  8037. /**
  8038. * Base class of all displayable graphic objects
  8039. * @module zrender/graphic/Displayable
  8040. */
  8041. /**
  8042. * @alias module:zrender/graphic/Displayable
  8043. * @extends module:zrender/Element
  8044. * @extends module:zrender/graphic/mixin/RectText
  8045. */
  8046. function Displayable(opts) {
  8047. opts = opts || {};
  8048. Element.call(this, opts);
  8049. // Extend properties
  8050. for (var name in opts) {
  8051. if (
  8052. opts.hasOwnProperty(name)
  8053. && name !== 'style'
  8054. ) {
  8055. this[name] = opts[name];
  8056. }
  8057. }
  8058. /**
  8059. * @type {module:zrender/graphic/Style}
  8060. */
  8061. this.style = new Style(opts.style, this);
  8062. this._rect = null;
  8063. // Shapes for cascade clipping.
  8064. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8065. // because it is easy to only using null to check whether clipPaths changed.
  8066. this.__clipPaths = null;
  8067. // FIXME Stateful must be mixined after style is setted
  8068. // Stateful.call(this, opts);
  8069. }
  8070. Displayable.prototype = {
  8071. constructor: Displayable,
  8072. type: 'displayable',
  8073. /**
  8074. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8075. * @name module:zrender/graphic/Displayable#__dirty
  8076. * @type {boolean}
  8077. */
  8078. __dirty: true,
  8079. /**
  8080. * Whether the displayable object is visible. when it is true, the displayable object
  8081. * is not drawn, but the mouse event can still trigger the object.
  8082. * @name module:/zrender/graphic/Displayable#invisible
  8083. * @type {boolean}
  8084. * @default false
  8085. */
  8086. invisible: false,
  8087. /**
  8088. * @name module:/zrender/graphic/Displayable#z
  8089. * @type {number}
  8090. * @default 0
  8091. */
  8092. z: 0,
  8093. /**
  8094. * @name module:/zrender/graphic/Displayable#z
  8095. * @type {number}
  8096. * @default 0
  8097. */
  8098. z2: 0,
  8099. /**
  8100. * The z level determines the displayable object can be drawn in which layer canvas.
  8101. * @name module:/zrender/graphic/Displayable#zlevel
  8102. * @type {number}
  8103. * @default 0
  8104. */
  8105. zlevel: 0,
  8106. /**
  8107. * Whether it can be dragged.
  8108. * @name module:/zrender/graphic/Displayable#draggable
  8109. * @type {boolean}
  8110. * @default false
  8111. */
  8112. draggable: false,
  8113. /**
  8114. * Whether is it dragging.
  8115. * @name module:/zrender/graphic/Displayable#draggable
  8116. * @type {boolean}
  8117. * @default false
  8118. */
  8119. dragging: false,
  8120. /**
  8121. * Whether to respond to mouse events.
  8122. * @name module:/zrender/graphic/Displayable#silent
  8123. * @type {boolean}
  8124. * @default false
  8125. */
  8126. silent: false,
  8127. /**
  8128. * If enable culling
  8129. * @type {boolean}
  8130. * @default false
  8131. */
  8132. culling: false,
  8133. /**
  8134. * Mouse cursor when hovered
  8135. * @name module:/zrender/graphic/Displayable#cursor
  8136. * @type {string}
  8137. */
  8138. cursor: 'pointer',
  8139. /**
  8140. * If hover area is bounding rect
  8141. * @name module:/zrender/graphic/Displayable#rectHover
  8142. * @type {string}
  8143. */
  8144. rectHover: false,
  8145. /**
  8146. * Render the element progressively when the value >= 0,
  8147. * usefull for large data.
  8148. * @type {boolean}
  8149. */
  8150. progressive: false,
  8151. /**
  8152. * @type {boolean}
  8153. */
  8154. incremental: false,
  8155. /**
  8156. * Scale ratio for global scale.
  8157. * @type {boolean}
  8158. */
  8159. globalScaleRatio: 1,
  8160. beforeBrush: function (ctx) {},
  8161. afterBrush: function (ctx) {},
  8162. /**
  8163. * Graphic drawing method.
  8164. * @param {CanvasRenderingContext2D} ctx
  8165. */
  8166. // Interface
  8167. brush: function (ctx, prevEl) {},
  8168. /**
  8169. * Get the minimum bounding box.
  8170. * @return {module:zrender/core/BoundingRect}
  8171. */
  8172. // Interface
  8173. getBoundingRect: function () {},
  8174. /**
  8175. * If displayable element contain coord x, y
  8176. * @param {number} x
  8177. * @param {number} y
  8178. * @return {boolean}
  8179. */
  8180. contain: function (x, y) {
  8181. return this.rectContain(x, y);
  8182. },
  8183. /**
  8184. * @param {Function} cb
  8185. * @param {} context
  8186. */
  8187. traverse: function (cb, context) {
  8188. cb.call(context, this);
  8189. },
  8190. /**
  8191. * If bounding rect of element contain coord x, y
  8192. * @param {number} x
  8193. * @param {number} y
  8194. * @return {boolean}
  8195. */
  8196. rectContain: function (x, y) {
  8197. var coord = this.transformCoordToLocal(x, y);
  8198. var rect = this.getBoundingRect();
  8199. return rect.contain(coord[0], coord[1]);
  8200. },
  8201. /**
  8202. * Mark displayable element dirty and refresh next frame
  8203. */
  8204. dirty: function () {
  8205. this.__dirty = this.__dirtyText = true;
  8206. this._rect = null;
  8207. this.__zr && this.__zr.refresh();
  8208. },
  8209. /**
  8210. * If displayable object binded any event
  8211. * @return {boolean}
  8212. */
  8213. // TODO, events bound by bind
  8214. // isSilent: function () {
  8215. // return !(
  8216. // this.hoverable || this.draggable
  8217. // || this.onmousemove || this.onmouseover || this.onmouseout
  8218. // || this.onmousedown || this.onmouseup || this.onclick
  8219. // || this.ondragenter || this.ondragover || this.ondragleave
  8220. // || this.ondrop
  8221. // );
  8222. // },
  8223. /**
  8224. * Alias for animate('style')
  8225. * @param {boolean} loop
  8226. */
  8227. animateStyle: function (loop) {
  8228. return this.animate('style', loop);
  8229. },
  8230. attrKV: function (key, value) {
  8231. if (key !== 'style') {
  8232. Element.prototype.attrKV.call(this, key, value);
  8233. }
  8234. else {
  8235. this.style.set(value);
  8236. }
  8237. },
  8238. /**
  8239. * @param {Object|string} key
  8240. * @param {*} value
  8241. */
  8242. setStyle: function (key, value) {
  8243. this.style.set(key, value);
  8244. this.dirty(false);
  8245. return this;
  8246. },
  8247. /**
  8248. * Use given style object
  8249. * @param {Object} obj
  8250. */
  8251. useStyle: function (obj) {
  8252. this.style = new Style(obj, this);
  8253. this.dirty(false);
  8254. return this;
  8255. },
  8256. /**
  8257. * The string value of `textPosition` needs to be calculated to a real postion.
  8258. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8259. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8260. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8261. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8262. * for those shapes. It will be called if the `style.textPosition` is a string.
  8263. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8264. * be responsible for creating one.
  8265. * @param {module:zrender/graphic/Style} style
  8266. * @param {Object} rect {x, y, width, height}
  8267. * @return {Obejct} out The same as the input out.
  8268. * {
  8269. * x: number. mandatory.
  8270. * y: number. mandatory.
  8271. * textAlign: string. optional. use style.textAlign by default.
  8272. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8273. * }
  8274. */
  8275. calculateTextPosition: null
  8276. };
  8277. inherits(Displayable, Element);
  8278. mixin(Displayable, RectText);
  8279. /**
  8280. * @alias zrender/graphic/Image
  8281. * @extends module:zrender/graphic/Displayable
  8282. * @constructor
  8283. * @param {Object} opts
  8284. */
  8285. function ZImage(opts) {
  8286. Displayable.call(this, opts);
  8287. }
  8288. ZImage.prototype = {
  8289. constructor: ZImage,
  8290. type: 'image',
  8291. brush: function (ctx, prevEl) {
  8292. var style = this.style;
  8293. var src = style.image;
  8294. // Must bind each time
  8295. style.bind(ctx, this, prevEl);
  8296. var image = this._image = createOrUpdateImage(
  8297. src,
  8298. this._image,
  8299. this,
  8300. this.onload
  8301. );
  8302. if (!image || !isImageReady(image)) {
  8303. return;
  8304. }
  8305. // 图片已经加载完成
  8306. // if (image.nodeName.toUpperCase() == 'IMG') {
  8307. // if (!image.complete) {
  8308. // return;
  8309. // }
  8310. // }
  8311. // Else is canvas
  8312. var x = style.x || 0;
  8313. var y = style.y || 0;
  8314. var width = style.width;
  8315. var height = style.height;
  8316. var aspect = image.width / image.height;
  8317. if (width == null && height != null) {
  8318. // Keep image/height ratio
  8319. width = height * aspect;
  8320. }
  8321. else if (height == null && width != null) {
  8322. height = width / aspect;
  8323. }
  8324. else if (width == null && height == null) {
  8325. width = image.width;
  8326. height = image.height;
  8327. }
  8328. // 设置transform
  8329. this.setTransform(ctx);
  8330. if (style.sWidth && style.sHeight) {
  8331. var sx = style.sx || 0;
  8332. var sy = style.sy || 0;
  8333. ctx.drawImage(
  8334. image,
  8335. sx, sy, style.sWidth, style.sHeight,
  8336. x, y, width, height
  8337. );
  8338. }
  8339. else if (style.sx && style.sy) {
  8340. var sx = style.sx;
  8341. var sy = style.sy;
  8342. var sWidth = width - sx;
  8343. var sHeight = height - sy;
  8344. ctx.drawImage(
  8345. image,
  8346. sx, sy, sWidth, sHeight,
  8347. x, y, width, height
  8348. );
  8349. }
  8350. else {
  8351. ctx.drawImage(image, x, y, width, height);
  8352. }
  8353. // Draw rect text
  8354. if (style.text != null) {
  8355. // Only restore transform when needs draw text.
  8356. this.restoreTransform(ctx);
  8357. this.drawRectText(ctx, this.getBoundingRect());
  8358. }
  8359. },
  8360. getBoundingRect: function () {
  8361. var style = this.style;
  8362. if (!this._rect) {
  8363. this._rect = new BoundingRect(
  8364. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8365. );
  8366. }
  8367. return this._rect;
  8368. }
  8369. };
  8370. inherits(ZImage, Displayable);
  8371. var HOVER_LAYER_ZLEVEL = 1e5;
  8372. var CANVAS_ZLEVEL = 314159;
  8373. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8374. var INCREMENTAL_INC = 0.001;
  8375. function parseInt10(val) {
  8376. return parseInt(val, 10);
  8377. }
  8378. function isLayerValid(layer) {
  8379. if (!layer) {
  8380. return false;
  8381. }
  8382. if (layer.__builtin__) {
  8383. return true;
  8384. }
  8385. if (typeof (layer.resize) !== 'function'
  8386. || typeof (layer.refresh) !== 'function'
  8387. ) {
  8388. return false;
  8389. }
  8390. return true;
  8391. }
  8392. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8393. var viewRect = new BoundingRect(0, 0, 0, 0);
  8394. function isDisplayableCulled(el, width, height) {
  8395. tmpRect.copy(el.getBoundingRect());
  8396. if (el.transform) {
  8397. tmpRect.applyTransform(el.transform);
  8398. }
  8399. viewRect.width = width;
  8400. viewRect.height = height;
  8401. return !tmpRect.intersect(viewRect);
  8402. }
  8403. function isClipPathChanged(clipPaths, prevClipPaths) {
  8404. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8405. if (clipPaths === prevClipPaths) {
  8406. return false;
  8407. }
  8408. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8409. return true;
  8410. }
  8411. for (var i = 0; i < clipPaths.length; i++) {
  8412. if (clipPaths[i] !== prevClipPaths[i]) {
  8413. return true;
  8414. }
  8415. }
  8416. return false;
  8417. }
  8418. function doClip(clipPaths, ctx) {
  8419. for (var i = 0; i < clipPaths.length; i++) {
  8420. var clipPath = clipPaths[i];
  8421. clipPath.setTransform(ctx);
  8422. ctx.beginPath();
  8423. clipPath.buildPath(ctx, clipPath.shape);
  8424. ctx.clip();
  8425. // Transform back
  8426. clipPath.restoreTransform(ctx);
  8427. }
  8428. }
  8429. function createRoot(width, height) {
  8430. var domRoot = document.createElement('div');
  8431. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8432. domRoot.style.cssText = [
  8433. 'position:relative',
  8434. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8435. // dom does not act as expected) when some of the parent dom has
  8436. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8437. // the canvas is not at the top part of the page.
  8438. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8439. // this `overflow:hidden` to avoid the bug.
  8440. // 'overflow:hidden',
  8441. 'width:' + width + 'px',
  8442. 'height:' + height + 'px',
  8443. 'padding:0',
  8444. 'margin:0',
  8445. 'border-width:0'
  8446. ].join(';') + ';';
  8447. return domRoot;
  8448. }
  8449. /**
  8450. * @alias module:zrender/Painter
  8451. * @constructor
  8452. * @param {HTMLElement} root 绘图容器
  8453. * @param {module:zrender/Storage} storage
  8454. * @param {Object} opts
  8455. */
  8456. var Painter = function (root, storage, opts) {
  8457. this.type = 'canvas';
  8458. // In node environment using node-canvas
  8459. var singleCanvas = !root.nodeName // In node ?
  8460. || root.nodeName.toUpperCase() === 'CANVAS';
  8461. this._opts = opts = extend({}, opts || {});
  8462. /**
  8463. * @type {number}
  8464. */
  8465. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8466. /**
  8467. * @type {boolean}
  8468. * @private
  8469. */
  8470. this._singleCanvas = singleCanvas;
  8471. /**
  8472. * 绘图容器
  8473. * @type {HTMLElement}
  8474. */
  8475. this.root = root;
  8476. var rootStyle = root.style;
  8477. if (rootStyle) {
  8478. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8479. rootStyle['-webkit-user-select'] =
  8480. rootStyle['user-select'] =
  8481. rootStyle['-webkit-touch-callout'] = 'none';
  8482. root.innerHTML = '';
  8483. }
  8484. /**
  8485. * @type {module:zrender/Storage}
  8486. */
  8487. this.storage = storage;
  8488. /**
  8489. * @type {Array.<number>}
  8490. * @private
  8491. */
  8492. var zlevelList = this._zlevelList = [];
  8493. /**
  8494. * @type {Object.<string, module:zrender/Layer>}
  8495. * @private
  8496. */
  8497. var layers = this._layers = {};
  8498. /**
  8499. * @type {Object.<string, Object>}
  8500. * @private
  8501. */
  8502. this._layerConfig = {};
  8503. /**
  8504. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8505. */
  8506. this._needsManuallyCompositing = false;
  8507. if (!singleCanvas) {
  8508. this._width = this._getSize(0);
  8509. this._height = this._getSize(1);
  8510. var domRoot = this._domRoot = createRoot(
  8511. this._width, this._height
  8512. );
  8513. root.appendChild(domRoot);
  8514. }
  8515. else {
  8516. var width = root.width;
  8517. var height = root.height;
  8518. if (opts.width != null) {
  8519. width = opts.width;
  8520. }
  8521. if (opts.height != null) {
  8522. height = opts.height;
  8523. }
  8524. this.dpr = opts.devicePixelRatio || 1;
  8525. // Use canvas width and height directly
  8526. root.width = width * this.dpr;
  8527. root.height = height * this.dpr;
  8528. this._width = width;
  8529. this._height = height;
  8530. // Create layer if only one given canvas
  8531. // Device can be specified to create a high dpi image.
  8532. var mainLayer = new Layer(root, this, this.dpr);
  8533. mainLayer.__builtin__ = true;
  8534. mainLayer.initContext();
  8535. // FIXME Use canvas width and height
  8536. // mainLayer.resize(width, height);
  8537. layers[CANVAS_ZLEVEL] = mainLayer;
  8538. mainLayer.zlevel = CANVAS_ZLEVEL;
  8539. // Not use common zlevel.
  8540. zlevelList.push(CANVAS_ZLEVEL);
  8541. this._domRoot = root;
  8542. }
  8543. /**
  8544. * @type {module:zrender/Layer}
  8545. * @private
  8546. */
  8547. this._hoverlayer = null;
  8548. this._hoverElements = [];
  8549. };
  8550. Painter.prototype = {
  8551. constructor: Painter,
  8552. getType: function () {
  8553. return 'canvas';
  8554. },
  8555. /**
  8556. * If painter use a single canvas
  8557. * @return {boolean}
  8558. */
  8559. isSingleCanvas: function () {
  8560. return this._singleCanvas;
  8561. },
  8562. /**
  8563. * @return {HTMLDivElement}
  8564. */
  8565. getViewportRoot: function () {
  8566. return this._domRoot;
  8567. },
  8568. getViewportRootOffset: function () {
  8569. var viewportRoot = this.getViewportRoot();
  8570. if (viewportRoot) {
  8571. return {
  8572. offsetLeft: viewportRoot.offsetLeft || 0,
  8573. offsetTop: viewportRoot.offsetTop || 0
  8574. };
  8575. }
  8576. },
  8577. /**
  8578. * 刷新
  8579. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8580. */
  8581. refresh: function (paintAll) {
  8582. var list = this.storage.getDisplayList(true);
  8583. var zlevelList = this._zlevelList;
  8584. this._redrawId = Math.random();
  8585. this._paintList(list, paintAll, this._redrawId);
  8586. // Paint custum layers
  8587. for (var i = 0; i < zlevelList.length; i++) {
  8588. var z = zlevelList[i];
  8589. var layer = this._layers[z];
  8590. if (!layer.__builtin__ && layer.refresh) {
  8591. var clearColor = i === 0 ? this._backgroundColor : null;
  8592. layer.refresh(clearColor);
  8593. }
  8594. }
  8595. this.refreshHover();
  8596. return this;
  8597. },
  8598. addHover: function (el, hoverStyle) {
  8599. if (el.__hoverMir) {
  8600. return;
  8601. }
  8602. var elMirror = new el.constructor({
  8603. style: el.style,
  8604. shape: el.shape,
  8605. z: el.z,
  8606. z2: el.z2,
  8607. silent: el.silent
  8608. });
  8609. elMirror.__from = el;
  8610. el.__hoverMir = elMirror;
  8611. hoverStyle && elMirror.setStyle(hoverStyle);
  8612. this._hoverElements.push(elMirror);
  8613. return elMirror;
  8614. },
  8615. removeHover: function (el) {
  8616. var elMirror = el.__hoverMir;
  8617. var hoverElements = this._hoverElements;
  8618. var idx = indexOf(hoverElements, elMirror);
  8619. if (idx >= 0) {
  8620. hoverElements.splice(idx, 1);
  8621. }
  8622. el.__hoverMir = null;
  8623. },
  8624. clearHover: function (el) {
  8625. var hoverElements = this._hoverElements;
  8626. for (var i = 0; i < hoverElements.length; i++) {
  8627. var from = hoverElements[i].__from;
  8628. if (from) {
  8629. from.__hoverMir = null;
  8630. }
  8631. }
  8632. hoverElements.length = 0;
  8633. },
  8634. refreshHover: function () {
  8635. var hoverElements = this._hoverElements;
  8636. var len = hoverElements.length;
  8637. var hoverLayer = this._hoverlayer;
  8638. hoverLayer && hoverLayer.clear();
  8639. if (!len) {
  8640. return;
  8641. }
  8642. sort(hoverElements, this.storage.displayableSortFunc);
  8643. // Use a extream large zlevel
  8644. // FIXME?
  8645. if (!hoverLayer) {
  8646. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8647. }
  8648. var scope = {};
  8649. hoverLayer.ctx.save();
  8650. for (var i = 0; i < len;) {
  8651. var el = hoverElements[i];
  8652. var originalEl = el.__from;
  8653. // Original el is removed
  8654. // PENDING
  8655. if (!(originalEl && originalEl.__zr)) {
  8656. hoverElements.splice(i, 1);
  8657. originalEl.__hoverMir = null;
  8658. len--;
  8659. continue;
  8660. }
  8661. i++;
  8662. // Use transform
  8663. // FIXME style and shape ?
  8664. if (!originalEl.invisible) {
  8665. el.transform = originalEl.transform;
  8666. el.invTransform = originalEl.invTransform;
  8667. el.__clipPaths = originalEl.__clipPaths;
  8668. // el.
  8669. this._doPaintEl(el, hoverLayer, true, scope);
  8670. }
  8671. }
  8672. hoverLayer.ctx.restore();
  8673. },
  8674. getHoverLayer: function () {
  8675. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8676. },
  8677. _paintList: function (list, paintAll, redrawId) {
  8678. if (this._redrawId !== redrawId) {
  8679. return;
  8680. }
  8681. paintAll = paintAll || false;
  8682. this._updateLayerStatus(list);
  8683. var finished = this._doPaintList(list, paintAll);
  8684. if (this._needsManuallyCompositing) {
  8685. this._compositeManually();
  8686. }
  8687. if (!finished) {
  8688. var self = this;
  8689. requestAnimationFrame(function () {
  8690. self._paintList(list, paintAll, redrawId);
  8691. });
  8692. }
  8693. },
  8694. _compositeManually: function () {
  8695. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8696. var width = this._domRoot.width;
  8697. var height = this._domRoot.height;
  8698. ctx.clearRect(0, 0, width, height);
  8699. // PENDING, If only builtin layer?
  8700. this.eachBuiltinLayer(function (layer) {
  8701. if (layer.virtual) {
  8702. ctx.drawImage(layer.dom, 0, 0, width, height);
  8703. }
  8704. });
  8705. },
  8706. _doPaintList: function (list, paintAll) {
  8707. var layerList = [];
  8708. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8709. var zlevel = this._zlevelList[zi];
  8710. var layer = this._layers[zlevel];
  8711. if (layer.__builtin__
  8712. && layer !== this._hoverlayer
  8713. && (layer.__dirty || paintAll)
  8714. ) {
  8715. layerList.push(layer);
  8716. }
  8717. }
  8718. var finished = true;
  8719. for (var k = 0; k < layerList.length; k++) {
  8720. var layer = layerList[k];
  8721. var ctx = layer.ctx;
  8722. var scope = {};
  8723. ctx.save();
  8724. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8725. var useTimer = !paintAll && layer.incremental && Date.now;
  8726. var startTime = useTimer && Date.now();
  8727. var clearColor = layer.zlevel === this._zlevelList[0]
  8728. ? this._backgroundColor : null;
  8729. // All elements in this layer are cleared.
  8730. if (layer.__startIndex === layer.__endIndex) {
  8731. layer.clear(false, clearColor);
  8732. }
  8733. else if (start === layer.__startIndex) {
  8734. var firstEl = list[start];
  8735. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8736. layer.clear(false, clearColor);
  8737. }
  8738. }
  8739. if (start === -1) {
  8740. console.error('For some unknown reason. drawIndex is -1');
  8741. start = layer.__startIndex;
  8742. }
  8743. for (var i = start; i < layer.__endIndex; i++) {
  8744. var el = list[i];
  8745. this._doPaintEl(el, layer, paintAll, scope);
  8746. el.__dirty = el.__dirtyText = false;
  8747. if (useTimer) {
  8748. // Date.now can be executed in 13,025,305 ops/second.
  8749. var dTime = Date.now() - startTime;
  8750. // Give 15 millisecond to draw.
  8751. // The rest elements will be drawn in the next frame.
  8752. if (dTime > 15) {
  8753. break;
  8754. }
  8755. }
  8756. }
  8757. layer.__drawIndex = i;
  8758. if (layer.__drawIndex < layer.__endIndex) {
  8759. finished = false;
  8760. }
  8761. if (scope.prevElClipPaths) {
  8762. // Needs restore the state. If last drawn element is in the clipping area.
  8763. ctx.restore();
  8764. }
  8765. ctx.restore();
  8766. }
  8767. if (env$1.wxa) {
  8768. // Flush for weixin application
  8769. each$1(this._layers, function (layer) {
  8770. if (layer && layer.ctx && layer.ctx.draw) {
  8771. layer.ctx.draw();
  8772. }
  8773. });
  8774. }
  8775. return finished;
  8776. },
  8777. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8778. var ctx = currentLayer.ctx;
  8779. var m = el.transform;
  8780. if (
  8781. (currentLayer.__dirty || forcePaint)
  8782. // Ignore invisible element
  8783. && !el.invisible
  8784. // Ignore transparent element
  8785. && el.style.opacity !== 0
  8786. // Ignore scale 0 element, in some environment like node-canvas
  8787. // Draw a scale 0 element can cause all following draw wrong
  8788. // And setTransform with scale 0 will cause set back transform failed.
  8789. && !(m && !m[0] && !m[3])
  8790. // Ignore culled element
  8791. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8792. ) {
  8793. var clipPaths = el.__clipPaths;
  8794. var prevElClipPaths = scope.prevElClipPaths;
  8795. // Optimize when clipping on group with several elements
  8796. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8797. // If has previous clipping state, restore from it
  8798. if (prevElClipPaths) {
  8799. ctx.restore();
  8800. scope.prevElClipPaths = null;
  8801. // Reset prevEl since context has been restored
  8802. scope.prevEl = null;
  8803. }
  8804. // New clipping state
  8805. if (clipPaths) {
  8806. ctx.save();
  8807. doClip(clipPaths, ctx);
  8808. scope.prevElClipPaths = clipPaths;
  8809. }
  8810. }
  8811. el.beforeBrush && el.beforeBrush(ctx);
  8812. el.brush(ctx, scope.prevEl || null);
  8813. scope.prevEl = el;
  8814. el.afterBrush && el.afterBrush(ctx);
  8815. }
  8816. },
  8817. /**
  8818. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8819. * @param {number} zlevel
  8820. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8821. * @return {module:zrender/Layer}
  8822. */
  8823. getLayer: function (zlevel, virtual) {
  8824. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8825. zlevel = CANVAS_ZLEVEL;
  8826. }
  8827. var layer = this._layers[zlevel];
  8828. if (!layer) {
  8829. // Create a new layer
  8830. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8831. layer.zlevel = zlevel;
  8832. layer.__builtin__ = true;
  8833. if (this._layerConfig[zlevel]) {
  8834. merge(layer, this._layerConfig[zlevel], true);
  8835. }
  8836. if (virtual) {
  8837. layer.virtual = virtual;
  8838. }
  8839. this.insertLayer(zlevel, layer);
  8840. // Context is created after dom inserted to document
  8841. // Or excanvas will get 0px clientWidth and clientHeight
  8842. layer.initContext();
  8843. }
  8844. return layer;
  8845. },
  8846. insertLayer: function (zlevel, layer) {
  8847. var layersMap = this._layers;
  8848. var zlevelList = this._zlevelList;
  8849. var len = zlevelList.length;
  8850. var prevLayer = null;
  8851. var i = -1;
  8852. var domRoot = this._domRoot;
  8853. if (layersMap[zlevel]) {
  8854. logError$1('ZLevel ' + zlevel + ' has been used already');
  8855. return;
  8856. }
  8857. // Check if is a valid layer
  8858. if (!isLayerValid(layer)) {
  8859. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8860. return;
  8861. }
  8862. if (len > 0 && zlevel > zlevelList[0]) {
  8863. for (i = 0; i < len - 1; i++) {
  8864. if (
  8865. zlevelList[i] < zlevel
  8866. && zlevelList[i + 1] > zlevel
  8867. ) {
  8868. break;
  8869. }
  8870. }
  8871. prevLayer = layersMap[zlevelList[i]];
  8872. }
  8873. zlevelList.splice(i + 1, 0, zlevel);
  8874. layersMap[zlevel] = layer;
  8875. // Vitual layer will not directly show on the screen.
  8876. // (It can be a WebGL layer and assigned to a ZImage element)
  8877. // But it still under management of zrender.
  8878. if (!layer.virtual) {
  8879. if (prevLayer) {
  8880. var prevDom = prevLayer.dom;
  8881. if (prevDom.nextSibling) {
  8882. domRoot.insertBefore(
  8883. layer.dom,
  8884. prevDom.nextSibling
  8885. );
  8886. }
  8887. else {
  8888. domRoot.appendChild(layer.dom);
  8889. }
  8890. }
  8891. else {
  8892. if (domRoot.firstChild) {
  8893. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8894. }
  8895. else {
  8896. domRoot.appendChild(layer.dom);
  8897. }
  8898. }
  8899. }
  8900. },
  8901. // Iterate each layer
  8902. eachLayer: function (cb, context) {
  8903. var zlevelList = this._zlevelList;
  8904. var z;
  8905. var i;
  8906. for (i = 0; i < zlevelList.length; i++) {
  8907. z = zlevelList[i];
  8908. cb.call(context, this._layers[z], z);
  8909. }
  8910. },
  8911. // Iterate each buildin layer
  8912. eachBuiltinLayer: function (cb, context) {
  8913. var zlevelList = this._zlevelList;
  8914. var layer;
  8915. var z;
  8916. var i;
  8917. for (i = 0; i < zlevelList.length; i++) {
  8918. z = zlevelList[i];
  8919. layer = this._layers[z];
  8920. if (layer.__builtin__) {
  8921. cb.call(context, layer, z);
  8922. }
  8923. }
  8924. },
  8925. // Iterate each other layer except buildin layer
  8926. eachOtherLayer: function (cb, context) {
  8927. var zlevelList = this._zlevelList;
  8928. var layer;
  8929. var z;
  8930. var i;
  8931. for (i = 0; i < zlevelList.length; i++) {
  8932. z = zlevelList[i];
  8933. layer = this._layers[z];
  8934. if (!layer.__builtin__) {
  8935. cb.call(context, layer, z);
  8936. }
  8937. }
  8938. },
  8939. /**
  8940. * 获取所有已创建的层
  8941. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8942. */
  8943. getLayers: function () {
  8944. return this._layers;
  8945. },
  8946. _updateLayerStatus: function (list) {
  8947. this.eachBuiltinLayer(function (layer, z) {
  8948. layer.__dirty = layer.__used = false;
  8949. });
  8950. function updatePrevLayer(idx) {
  8951. if (prevLayer) {
  8952. if (prevLayer.__endIndex !== idx) {
  8953. prevLayer.__dirty = true;
  8954. }
  8955. prevLayer.__endIndex = idx;
  8956. }
  8957. }
  8958. if (this._singleCanvas) {
  8959. for (var i = 1; i < list.length; i++) {
  8960. var el = list[i];
  8961. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8962. this._needsManuallyCompositing = true;
  8963. break;
  8964. }
  8965. }
  8966. }
  8967. var prevLayer = null;
  8968. var incrementalLayerCount = 0;
  8969. for (var i = 0; i < list.length; i++) {
  8970. var el = list[i];
  8971. var zlevel = el.zlevel;
  8972. var layer;
  8973. // PENDING If change one incremental element style ?
  8974. // TODO Where there are non-incremental elements between incremental elements.
  8975. if (el.incremental) {
  8976. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8977. layer.incremental = true;
  8978. incrementalLayerCount = 1;
  8979. }
  8980. else {
  8981. layer = this.getLayer(
  8982. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8983. this._needsManuallyCompositing
  8984. );
  8985. }
  8986. if (!layer.__builtin__) {
  8987. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8988. }
  8989. if (layer !== prevLayer) {
  8990. layer.__used = true;
  8991. if (layer.__startIndex !== i) {
  8992. layer.__dirty = true;
  8993. }
  8994. layer.__startIndex = i;
  8995. if (!layer.incremental) {
  8996. layer.__drawIndex = i;
  8997. }
  8998. else {
  8999. // Mark layer draw index needs to update.
  9000. layer.__drawIndex = -1;
  9001. }
  9002. updatePrevLayer(i);
  9003. prevLayer = layer;
  9004. }
  9005. if (el.__dirty) {
  9006. layer.__dirty = true;
  9007. if (layer.incremental && layer.__drawIndex < 0) {
  9008. // Start draw from the first dirty element.
  9009. layer.__drawIndex = i;
  9010. }
  9011. }
  9012. }
  9013. updatePrevLayer(i);
  9014. this.eachBuiltinLayer(function (layer, z) {
  9015. // Used in last frame but not in this frame. Needs clear
  9016. if (!layer.__used && layer.getElementCount() > 0) {
  9017. layer.__dirty = true;
  9018. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9019. }
  9020. // For incremental layer. In case start index changed and no elements are dirty.
  9021. if (layer.__dirty && layer.__drawIndex < 0) {
  9022. layer.__drawIndex = layer.__startIndex;
  9023. }
  9024. });
  9025. },
  9026. /**
  9027. * 清除hover层外所有内容
  9028. */
  9029. clear: function () {
  9030. this.eachBuiltinLayer(this._clearLayer);
  9031. return this;
  9032. },
  9033. _clearLayer: function (layer) {
  9034. layer.clear();
  9035. },
  9036. setBackgroundColor: function (backgroundColor) {
  9037. this._backgroundColor = backgroundColor;
  9038. },
  9039. /**
  9040. * 修改指定zlevel的绘制参数
  9041. *
  9042. * @param {string} zlevel
  9043. * @param {Object} config 配置对象
  9044. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9045. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9046. * @param {number} [config.lastFrameAlpha=0.7]
  9047. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9048. */
  9049. configLayer: function (zlevel, config) {
  9050. if (config) {
  9051. var layerConfig = this._layerConfig;
  9052. if (!layerConfig[zlevel]) {
  9053. layerConfig[zlevel] = config;
  9054. }
  9055. else {
  9056. merge(layerConfig[zlevel], config, true);
  9057. }
  9058. for (var i = 0; i < this._zlevelList.length; i++) {
  9059. var _zlevel = this._zlevelList[i];
  9060. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9061. var layer = this._layers[_zlevel];
  9062. merge(layer, layerConfig[zlevel], true);
  9063. }
  9064. }
  9065. }
  9066. },
  9067. /**
  9068. * 删除指定层
  9069. * @param {number} zlevel 层所在的zlevel
  9070. */
  9071. delLayer: function (zlevel) {
  9072. var layers = this._layers;
  9073. var zlevelList = this._zlevelList;
  9074. var layer = layers[zlevel];
  9075. if (!layer) {
  9076. return;
  9077. }
  9078. layer.dom.parentNode.removeChild(layer.dom);
  9079. delete layers[zlevel];
  9080. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9081. },
  9082. /**
  9083. * 区域大小变化后重绘
  9084. */
  9085. resize: function (width, height) {
  9086. if (!this._domRoot.style) { // Maybe in node or worker
  9087. if (width == null || height == null) {
  9088. return;
  9089. }
  9090. this._width = width;
  9091. this._height = height;
  9092. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9093. }
  9094. else {
  9095. var domRoot = this._domRoot;
  9096. // FIXME Why ?
  9097. domRoot.style.display = 'none';
  9098. // Save input w/h
  9099. var opts = this._opts;
  9100. width != null && (opts.width = width);
  9101. height != null && (opts.height = height);
  9102. width = this._getSize(0);
  9103. height = this._getSize(1);
  9104. domRoot.style.display = '';
  9105. // 优化没有实际改变的resize
  9106. if (this._width !== width || height !== this._height) {
  9107. domRoot.style.width = width + 'px';
  9108. domRoot.style.height = height + 'px';
  9109. for (var id in this._layers) {
  9110. if (this._layers.hasOwnProperty(id)) {
  9111. this._layers[id].resize(width, height);
  9112. }
  9113. }
  9114. each$1(this._progressiveLayers, function (layer) {
  9115. layer.resize(width, height);
  9116. });
  9117. this.refresh(true);
  9118. }
  9119. this._width = width;
  9120. this._height = height;
  9121. }
  9122. return this;
  9123. },
  9124. /**
  9125. * 清除单独的一个层
  9126. * @param {number} zlevel
  9127. */
  9128. clearLayer: function (zlevel) {
  9129. var layer = this._layers[zlevel];
  9130. if (layer) {
  9131. layer.clear();
  9132. }
  9133. },
  9134. /**
  9135. * 释放
  9136. */
  9137. dispose: function () {
  9138. this.root.innerHTML = '';
  9139. this.root =
  9140. this.storage =
  9141. this._domRoot =
  9142. this._layers = null;
  9143. },
  9144. /**
  9145. * Get canvas which has all thing rendered
  9146. * @param {Object} opts
  9147. * @param {string} [opts.backgroundColor]
  9148. * @param {number} [opts.pixelRatio]
  9149. */
  9150. getRenderedCanvas: function (opts) {
  9151. opts = opts || {};
  9152. if (this._singleCanvas && !this._compositeManually) {
  9153. return this._layers[CANVAS_ZLEVEL].dom;
  9154. }
  9155. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9156. imageLayer.initContext();
  9157. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9158. if (opts.pixelRatio <= this.dpr) {
  9159. this.refresh();
  9160. var width = imageLayer.dom.width;
  9161. var height = imageLayer.dom.height;
  9162. var ctx = imageLayer.ctx;
  9163. this.eachLayer(function (layer) {
  9164. if (layer.__builtin__) {
  9165. ctx.drawImage(layer.dom, 0, 0, width, height);
  9166. }
  9167. else if (layer.renderToCanvas) {
  9168. imageLayer.ctx.save();
  9169. layer.renderToCanvas(imageLayer.ctx);
  9170. imageLayer.ctx.restore();
  9171. }
  9172. });
  9173. }
  9174. else {
  9175. // PENDING, echarts-gl and incremental rendering.
  9176. var scope = {};
  9177. var displayList = this.storage.getDisplayList(true);
  9178. for (var i = 0; i < displayList.length; i++) {
  9179. var el = displayList[i];
  9180. this._doPaintEl(el, imageLayer, true, scope);
  9181. }
  9182. }
  9183. return imageLayer.dom;
  9184. },
  9185. /**
  9186. * 获取绘图区域宽度
  9187. */
  9188. getWidth: function () {
  9189. return this._width;
  9190. },
  9191. /**
  9192. * 获取绘图区域高度
  9193. */
  9194. getHeight: function () {
  9195. return this._height;
  9196. },
  9197. _getSize: function (whIdx) {
  9198. var opts = this._opts;
  9199. var wh = ['width', 'height'][whIdx];
  9200. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9201. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9202. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9203. if (opts[wh] != null && opts[wh] !== 'auto') {
  9204. return parseFloat(opts[wh]);
  9205. }
  9206. var root = this.root;
  9207. // IE8 does not support getComputedStyle, but it use VML.
  9208. var stl = document.defaultView.getComputedStyle(root);
  9209. return (
  9210. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9211. - (parseInt10(stl[plt]) || 0)
  9212. - (parseInt10(stl[prb]) || 0)
  9213. ) | 0;
  9214. },
  9215. pathToImage: function (path, dpr) {
  9216. dpr = dpr || this.dpr;
  9217. var canvas = document.createElement('canvas');
  9218. var ctx = canvas.getContext('2d');
  9219. var rect = path.getBoundingRect();
  9220. var style = path.style;
  9221. var shadowBlurSize = style.shadowBlur * dpr;
  9222. var shadowOffsetX = style.shadowOffsetX * dpr;
  9223. var shadowOffsetY = style.shadowOffsetY * dpr;
  9224. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9225. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9226. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9227. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9228. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9229. var width = rect.width + leftMargin + rightMargin;
  9230. var height = rect.height + topMargin + bottomMargin;
  9231. canvas.width = width * dpr;
  9232. canvas.height = height * dpr;
  9233. ctx.scale(dpr, dpr);
  9234. ctx.clearRect(0, 0, width, height);
  9235. ctx.dpr = dpr;
  9236. var pathTransform = {
  9237. position: path.position,
  9238. rotation: path.rotation,
  9239. scale: path.scale
  9240. };
  9241. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9242. path.rotation = 0;
  9243. path.scale = [1, 1];
  9244. path.updateTransform();
  9245. if (path) {
  9246. path.brush(ctx);
  9247. }
  9248. var ImageShape = ZImage;
  9249. var imgShape = new ImageShape({
  9250. style: {
  9251. x: 0,
  9252. y: 0,
  9253. image: canvas
  9254. }
  9255. });
  9256. if (pathTransform.position != null) {
  9257. imgShape.position = path.position = pathTransform.position;
  9258. }
  9259. if (pathTransform.rotation != null) {
  9260. imgShape.rotation = path.rotation = pathTransform.rotation;
  9261. }
  9262. if (pathTransform.scale != null) {
  9263. imgShape.scale = path.scale = pathTransform.scale;
  9264. }
  9265. return imgShape;
  9266. }
  9267. };
  9268. /**
  9269. * 动画主类, 调度和管理所有动画控制器
  9270. *
  9271. * @module zrender/animation/Animation
  9272. * @author pissang(https://github.com/pissang)
  9273. */
  9274. // TODO Additive animation
  9275. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9276. // https://developer.apple.com/videos/wwdc2014/#236
  9277. /**
  9278. * @typedef {Object} IZRenderStage
  9279. * @property {Function} update
  9280. */
  9281. /**
  9282. * @alias module:zrender/animation/Animation
  9283. * @constructor
  9284. * @param {Object} [options]
  9285. * @param {Function} [options.onframe]
  9286. * @param {IZRenderStage} [options.stage]
  9287. * @example
  9288. * var animation = new Animation();
  9289. * var obj = {
  9290. * x: 100,
  9291. * y: 100
  9292. * };
  9293. * animation.animate(node.position)
  9294. * .when(1000, {
  9295. * x: 500,
  9296. * y: 500
  9297. * })
  9298. * .when(2000, {
  9299. * x: 100,
  9300. * y: 100
  9301. * })
  9302. * .start('spline');
  9303. */
  9304. var Animation = function (options) {
  9305. options = options || {};
  9306. this.stage = options.stage || {};
  9307. this.onframe = options.onframe || function () {};
  9308. // private properties
  9309. this._clips = [];
  9310. this._running = false;
  9311. this._time;
  9312. this._pausedTime;
  9313. this._pauseStart;
  9314. this._paused = false;
  9315. Eventful.call(this);
  9316. };
  9317. Animation.prototype = {
  9318. constructor: Animation,
  9319. /**
  9320. * 添加 clip
  9321. * @param {module:zrender/animation/Clip} clip
  9322. */
  9323. addClip: function (clip) {
  9324. this._clips.push(clip);
  9325. },
  9326. /**
  9327. * 添加 animator
  9328. * @param {module:zrender/animation/Animator} animator
  9329. */
  9330. addAnimator: function (animator) {
  9331. animator.animation = this;
  9332. var clips = animator.getClips();
  9333. for (var i = 0; i < clips.length; i++) {
  9334. this.addClip(clips[i]);
  9335. }
  9336. },
  9337. /**
  9338. * 删除动画片段
  9339. * @param {module:zrender/animation/Clip} clip
  9340. */
  9341. removeClip: function (clip) {
  9342. var idx = indexOf(this._clips, clip);
  9343. if (idx >= 0) {
  9344. this._clips.splice(idx, 1);
  9345. }
  9346. },
  9347. /**
  9348. * 删除动画片段
  9349. * @param {module:zrender/animation/Animator} animator
  9350. */
  9351. removeAnimator: function (animator) {
  9352. var clips = animator.getClips();
  9353. for (var i = 0; i < clips.length; i++) {
  9354. this.removeClip(clips[i]);
  9355. }
  9356. animator.animation = null;
  9357. },
  9358. _update: function () {
  9359. var time = new Date().getTime() - this._pausedTime;
  9360. var delta = time - this._time;
  9361. var clips = this._clips;
  9362. var len = clips.length;
  9363. var deferredEvents = [];
  9364. var deferredClips = [];
  9365. for (var i = 0; i < len; i++) {
  9366. var clip = clips[i];
  9367. var e = clip.step(time, delta);
  9368. // Throw out the events need to be called after
  9369. // stage.update, like destroy
  9370. if (e) {
  9371. deferredEvents.push(e);
  9372. deferredClips.push(clip);
  9373. }
  9374. }
  9375. // Remove the finished clip
  9376. for (var i = 0; i < len;) {
  9377. if (clips[i]._needsRemove) {
  9378. clips[i] = clips[len - 1];
  9379. clips.pop();
  9380. len--;
  9381. }
  9382. else {
  9383. i++;
  9384. }
  9385. }
  9386. len = deferredEvents.length;
  9387. for (var i = 0; i < len; i++) {
  9388. deferredClips[i].fire(deferredEvents[i]);
  9389. }
  9390. this._time = time;
  9391. this.onframe(delta);
  9392. // 'frame' should be triggered before stage, because upper application
  9393. // depends on the sequence (e.g., echarts-stream and finish
  9394. // event judge)
  9395. this.trigger('frame', delta);
  9396. if (this.stage.update) {
  9397. this.stage.update();
  9398. }
  9399. },
  9400. _startLoop: function () {
  9401. var self = this;
  9402. this._running = true;
  9403. function step() {
  9404. if (self._running) {
  9405. requestAnimationFrame(step);
  9406. !self._paused && self._update();
  9407. }
  9408. }
  9409. requestAnimationFrame(step);
  9410. },
  9411. /**
  9412. * Start animation.
  9413. */
  9414. start: function () {
  9415. this._time = new Date().getTime();
  9416. this._pausedTime = 0;
  9417. this._startLoop();
  9418. },
  9419. /**
  9420. * Stop animation.
  9421. */
  9422. stop: function () {
  9423. this._running = false;
  9424. },
  9425. /**
  9426. * Pause animation.
  9427. */
  9428. pause: function () {
  9429. if (!this._paused) {
  9430. this._pauseStart = new Date().getTime();
  9431. this._paused = true;
  9432. }
  9433. },
  9434. /**
  9435. * Resume animation.
  9436. */
  9437. resume: function () {
  9438. if (this._paused) {
  9439. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9440. this._paused = false;
  9441. }
  9442. },
  9443. /**
  9444. * Clear animation.
  9445. */
  9446. clear: function () {
  9447. this._clips = [];
  9448. },
  9449. /**
  9450. * Whether animation finished.
  9451. */
  9452. isFinished: function () {
  9453. return !this._clips.length;
  9454. },
  9455. /**
  9456. * Creat animator for a target, whose props can be animated.
  9457. *
  9458. * @param {Object} target
  9459. * @param {Object} options
  9460. * @param {boolean} [options.loop=false] Whether loop animation.
  9461. * @param {Function} [options.getter=null] Get value from target.
  9462. * @param {Function} [options.setter=null] Set value to target.
  9463. * @return {module:zrender/animation/Animation~Animator}
  9464. */
  9465. // TODO Gap
  9466. animate: function (target, options) {
  9467. options = options || {};
  9468. var animator = new Animator(
  9469. target,
  9470. options.loop,
  9471. options.getter,
  9472. options.setter
  9473. );
  9474. this.addAnimator(animator);
  9475. return animator;
  9476. }
  9477. };
  9478. mixin(Animation, Eventful);
  9479. /* global document */
  9480. var TOUCH_CLICK_DELAY = 300;
  9481. var globalEventSupported = env$1.domSupported;
  9482. var localNativeListenerNames = (function () {
  9483. var mouseHandlerNames = [
  9484. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9485. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9486. ];
  9487. var touchHandlerNames = [
  9488. 'touchstart', 'touchend', 'touchmove'
  9489. ];
  9490. var pointerEventNameMap = {
  9491. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9492. };
  9493. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9494. var nm = name.replace('mouse', 'pointer');
  9495. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9496. });
  9497. return {
  9498. mouse: mouseHandlerNames,
  9499. touch: touchHandlerNames,
  9500. pointer: pointerHandlerNames
  9501. };
  9502. })();
  9503. var globalNativeListenerNames = {
  9504. mouse: ['mousemove', 'mouseup'],
  9505. pointer: ['pointermove', 'pointerup']
  9506. };
  9507. function eventNameFix(name) {
  9508. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9509. }
  9510. function isPointerFromTouch(event) {
  9511. var pointerType = event.pointerType;
  9512. return pointerType === 'pen' || pointerType === 'touch';
  9513. }
  9514. // function useMSGuesture(handlerProxy, event) {
  9515. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9516. // }
  9517. // function onMSGestureChange(proxy, event) {
  9518. // if (event.translationX || event.translationY) {
  9519. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9520. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9521. // }
  9522. // if (event.scale !== 1) {
  9523. // event.pinchX = event.offsetX;
  9524. // event.pinchY = event.offsetY;
  9525. // event.pinchScale = event.scale;
  9526. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9527. // }
  9528. // }
  9529. /**
  9530. * Prevent mouse event from being dispatched after Touch Events action
  9531. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9532. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9533. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9534. * Result: Blocking Mouse Events for 700ms.
  9535. *
  9536. * @param {DOMHandlerScope} scope
  9537. */
  9538. function setTouchTimer(scope) {
  9539. scope.touching = true;
  9540. if (scope.touchTimer != null) {
  9541. clearTimeout(scope.touchTimer);
  9542. scope.touchTimer = null;
  9543. }
  9544. scope.touchTimer = setTimeout(function () {
  9545. scope.touching = false;
  9546. scope.touchTimer = null;
  9547. }, 700);
  9548. }
  9549. // Mark touch, which is useful in distinguish touch and
  9550. // mouse event in upper applicatoin.
  9551. function markTouch(event) {
  9552. event && (event.zrByTouch = true);
  9553. }
  9554. // function markTriggeredFromLocal(event) {
  9555. // event && (event.__zrIsFromLocal = true);
  9556. // }
  9557. // function isTriggeredFromLocal(instance, event) {
  9558. // return !!(event && event.__zrIsFromLocal);
  9559. // }
  9560. function normalizeGlobalEvent(instance, event) {
  9561. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9562. // handlers of the upper applications. Set `true` to force calculate them.
  9563. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9564. }
  9565. /**
  9566. * Detect whether the given el is in `painterRoot`.
  9567. */
  9568. function isLocalEl(instance, el) {
  9569. var isLocal = false;
  9570. do {
  9571. el = el && el.parentNode;
  9572. }
  9573. while (el && el.nodeType !== 9 && !(
  9574. isLocal = el === instance.painterRoot
  9575. ));
  9576. return isLocal;
  9577. }
  9578. /**
  9579. * Make a fake event but not change the original event,
  9580. * becuase the global event probably be used by other
  9581. * listeners not belonging to zrender.
  9582. * @class
  9583. */
  9584. function FakeGlobalEvent(instance, event) {
  9585. this.type = event.type;
  9586. this.target = this.currentTarget = instance.dom;
  9587. this.pointerType = event.pointerType;
  9588. // Necessray for the force calculation of zrX, zrY
  9589. this.clientX = event.clientX;
  9590. this.clientY = event.clientY;
  9591. // Because we do not mount global listeners to touch events,
  9592. // we do not copy `targetTouches` and `changedTouches` here.
  9593. }
  9594. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9595. // we make the default methods on the event do nothing,
  9596. // otherwise it is dangerous. See more details in
  9597. // [Drag outside] in `Handler.js`.
  9598. fakeGlobalEventProto.stopPropagation =
  9599. fakeGlobalEventProto.stopImmediatePropagation =
  9600. fakeGlobalEventProto.preventDefault = noop;
  9601. /**
  9602. * Local DOM Handlers
  9603. * @this {HandlerProxy}
  9604. */
  9605. var localDOMHandlers = {
  9606. mousedown: function (event) {
  9607. event = normalizeEvent(this.dom, event);
  9608. this._mayPointerCapture = [event.zrX, event.zrY];
  9609. this.trigger('mousedown', event);
  9610. },
  9611. mousemove: function (event) {
  9612. event = normalizeEvent(this.dom, event);
  9613. var downPoint = this._mayPointerCapture;
  9614. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9615. togglePointerCapture(this, true);
  9616. }
  9617. this.trigger('mousemove', event);
  9618. },
  9619. mouseup: function (event) {
  9620. event = normalizeEvent(this.dom, event);
  9621. togglePointerCapture(this, false);
  9622. this.trigger('mouseup', event);
  9623. },
  9624. mouseout: function (event) {
  9625. event = normalizeEvent(this.dom, event);
  9626. // Similarly to the browser did on `document` and touch event,
  9627. // `globalout` will be delayed to final pointer cature release.
  9628. if (this._pointerCapturing) {
  9629. event.zrEventControl = 'no_globalout';
  9630. }
  9631. // There might be some doms created by upper layer application
  9632. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9633. // dom created by echarts), where 'globalout' event should not
  9634. // be triggered when mouse enters these doms. (But 'mouseout'
  9635. // should be triggered at the original hovered element as usual).
  9636. var element = event.toElement || event.relatedTarget;
  9637. event.zrIsToLocalDOM = isLocalEl(this, element);
  9638. this.trigger('mouseout', event);
  9639. },
  9640. touchstart: function (event) {
  9641. // Default mouse behaviour should not be disabled here.
  9642. // For example, page may needs to be slided.
  9643. event = normalizeEvent(this.dom, event);
  9644. markTouch(event);
  9645. this._lastTouchMoment = new Date();
  9646. this.handler.processGesture(event, 'start');
  9647. // For consistent event listener for both touch device and mouse device,
  9648. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9649. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9650. // `mousedown`.
  9651. localDOMHandlers.mousemove.call(this, event);
  9652. localDOMHandlers.mousedown.call(this, event);
  9653. },
  9654. touchmove: function (event) {
  9655. event = normalizeEvent(this.dom, event);
  9656. markTouch(event);
  9657. this.handler.processGesture(event, 'change');
  9658. // Mouse move should always be triggered no matter whether
  9659. // there is gestrue event, because mouse move and pinch may
  9660. // be used at the same time.
  9661. localDOMHandlers.mousemove.call(this, event);
  9662. },
  9663. touchend: function (event) {
  9664. event = normalizeEvent(this.dom, event);
  9665. markTouch(event);
  9666. this.handler.processGesture(event, 'end');
  9667. localDOMHandlers.mouseup.call(this, event);
  9668. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9669. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9670. // we can conveniently implement "hover style" in both PC and touch device just
  9671. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9672. // to remove "hover style" on an element, without any additional code for
  9673. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9674. // style" will remain for user view)
  9675. // click event should always be triggered no matter whether
  9676. // there is gestrue event. System click can not be prevented.
  9677. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9678. localDOMHandlers.click.call(this, event);
  9679. }
  9680. },
  9681. pointerdown: function (event) {
  9682. localDOMHandlers.mousedown.call(this, event);
  9683. // if (useMSGuesture(this, event)) {
  9684. // this._msGesture.addPointer(event.pointerId);
  9685. // }
  9686. },
  9687. pointermove: function (event) {
  9688. // FIXME
  9689. // pointermove is so sensitive that it always triggered when
  9690. // tap(click) on touch screen, which affect some judgement in
  9691. // upper application. So, we dont support mousemove on MS touch
  9692. // device yet.
  9693. if (!isPointerFromTouch(event)) {
  9694. localDOMHandlers.mousemove.call(this, event);
  9695. }
  9696. },
  9697. pointerup: function (event) {
  9698. localDOMHandlers.mouseup.call(this, event);
  9699. },
  9700. pointerout: function (event) {
  9701. // pointerout will be triggered when tap on touch screen
  9702. // (IE11+/Edge on MS Surface) after click event triggered,
  9703. // which is inconsistent with the mousout behavior we defined
  9704. // in touchend. So we unify them.
  9705. // (check localDOMHandlers.touchend for detailed explanation)
  9706. if (!isPointerFromTouch(event)) {
  9707. localDOMHandlers.mouseout.call(this, event);
  9708. }
  9709. }
  9710. };
  9711. /**
  9712. * Othere DOM UI Event handlers for zr dom.
  9713. * @this {HandlerProxy}
  9714. */
  9715. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9716. localDOMHandlers[name] = function (event) {
  9717. event = normalizeEvent(this.dom, event);
  9718. this.trigger(name, event);
  9719. };
  9720. });
  9721. /**
  9722. * DOM UI Event handlers for global page.
  9723. *
  9724. * [Caution]:
  9725. * those handlers should both support in capture phase and bubble phase!
  9726. *
  9727. * @this {HandlerProxy}
  9728. */
  9729. var globalDOMHandlers = {
  9730. pointermove: function (event) {
  9731. // FIXME
  9732. // pointermove is so sensitive that it always triggered when
  9733. // tap(click) on touch screen, which affect some judgement in
  9734. // upper application. So, we dont support mousemove on MS touch
  9735. // device yet.
  9736. if (!isPointerFromTouch(event)) {
  9737. globalDOMHandlers.mousemove.call(this, event);
  9738. }
  9739. },
  9740. pointerup: function (event) {
  9741. globalDOMHandlers.mouseup.call(this, event);
  9742. },
  9743. mousemove: function (event) {
  9744. this.trigger('mousemove', event);
  9745. },
  9746. mouseup: function (event) {
  9747. var pointerCaptureReleasing = this._pointerCapturing;
  9748. togglePointerCapture(this, false);
  9749. this.trigger('mouseup', event);
  9750. if (pointerCaptureReleasing) {
  9751. event.zrEventControl = 'only_globalout';
  9752. this.trigger('mouseout', event);
  9753. }
  9754. }
  9755. };
  9756. /**
  9757. * @param {HandlerProxy} instance
  9758. * @param {DOMHandlerScope} scope
  9759. */
  9760. function mountLocalDOMEventListeners(instance, scope) {
  9761. var domHandlers = scope.domHandlers;
  9762. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9763. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9764. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9765. // at the same time.
  9766. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9767. // screen, which do not occurs in pointer event.
  9768. // So we use pointer event to both detect touch gesture and mouse behavior.
  9769. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9770. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9771. // markTriggeredFromLocal(event);
  9772. domHandlers[nativeEventName].call(instance, event);
  9773. });
  9774. });
  9775. // FIXME
  9776. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9777. // which does not prevent defuault behavior occasionally (which may cause view port
  9778. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9779. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9780. // touch screen. And we only support click behavior on MS touch screen now.
  9781. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9782. // We dont support touch on IE on win7.
  9783. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9784. // if (typeof MSGesture === 'function') {
  9785. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9786. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9787. // }
  9788. }
  9789. else {
  9790. if (env$1.touchEventsSupported) {
  9791. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9792. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9793. // markTriggeredFromLocal(event);
  9794. domHandlers[nativeEventName].call(instance, event);
  9795. setTouchTimer(scope);
  9796. });
  9797. });
  9798. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9799. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9800. }
  9801. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9802. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9803. // mouse event can not be handle in those devices.
  9804. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9805. // mouseevent after touch event triggered, see `setTouchTimer`.
  9806. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9807. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9808. event = getNativeEvent(event);
  9809. if (!scope.touching) {
  9810. // markTriggeredFromLocal(event);
  9811. domHandlers[nativeEventName].call(instance, event);
  9812. }
  9813. });
  9814. });
  9815. }
  9816. }
  9817. /**
  9818. * @param {HandlerProxy} instance
  9819. * @param {DOMHandlerScope} scope
  9820. */
  9821. function mountGlobalDOMEventListeners(instance, scope) {
  9822. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9823. if (env$1.pointerEventsSupported) {
  9824. each$1(globalNativeListenerNames.pointer, mount);
  9825. }
  9826. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9827. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9828. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9829. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9830. else if (!env$1.touchEventsSupported) {
  9831. each$1(globalNativeListenerNames.mouse, mount);
  9832. }
  9833. function mount(nativeEventName) {
  9834. function nativeEventListener(event) {
  9835. event = getNativeEvent(event);
  9836. // See the reason in [Drag outside] in `Handler.js`
  9837. // This checking supports both `useCapture` or not.
  9838. // PENDING: if there is performance issue in some devices,
  9839. // we probably can not use `useCapture` and change a easier
  9840. // to judes whether local (mark).
  9841. if (!isLocalEl(instance, event.target)) {
  9842. event = normalizeGlobalEvent(instance, event);
  9843. scope.domHandlers[nativeEventName].call(instance, event);
  9844. }
  9845. }
  9846. mountSingleDOMEventListener(
  9847. scope, nativeEventName, nativeEventListener,
  9848. {capture: true} // See [Drag Outside] in `Handler.js`
  9849. );
  9850. }
  9851. }
  9852. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9853. scope.mounted[nativeEventName] = listener;
  9854. scope.listenerOpts[nativeEventName] = opt;
  9855. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9856. }
  9857. function unmountDOMEventListeners(scope) {
  9858. var mounted = scope.mounted;
  9859. for (var nativeEventName in mounted) {
  9860. if (mounted.hasOwnProperty(nativeEventName)) {
  9861. removeEventListener(
  9862. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9863. scope.listenerOpts[nativeEventName]
  9864. );
  9865. }
  9866. }
  9867. scope.mounted = {};
  9868. }
  9869. /**
  9870. * See [Drag Outside] in `Handler.js`.
  9871. * @implement
  9872. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9873. * `true`: start to capture pointer if it is not capturing.
  9874. * `false`: end the capture if it is capturing.
  9875. */
  9876. function togglePointerCapture(instance, isPointerCapturing) {
  9877. instance._mayPointerCapture = null;
  9878. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9879. instance._pointerCapturing = isPointerCapturing;
  9880. var globalHandlerScope = instance._globalHandlerScope;
  9881. isPointerCapturing
  9882. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9883. : unmountDOMEventListeners(globalHandlerScope);
  9884. }
  9885. }
  9886. /**
  9887. * @inner
  9888. * @class
  9889. */
  9890. function DOMHandlerScope(domTarget, domHandlers) {
  9891. this.domTarget = domTarget;
  9892. this.domHandlers = domHandlers;
  9893. // Key: eventName, value: mounted handler funcitons.
  9894. // Used for unmount.
  9895. this.mounted = {};
  9896. this.listenerOpts = {};
  9897. this.touchTimer = null;
  9898. this.touching = false;
  9899. }
  9900. /**
  9901. * @public
  9902. * @class
  9903. */
  9904. function HandlerDomProxy(dom, painterRoot) {
  9905. Eventful.call(this);
  9906. this.dom = dom;
  9907. this.painterRoot = painterRoot;
  9908. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9909. if (globalEventSupported) {
  9910. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9911. }
  9912. /**
  9913. * @type {boolean}
  9914. */
  9915. this._pointerCapturing = false;
  9916. /**
  9917. * @type {Array.<number>} [x, y] or null.
  9918. */
  9919. this._mayPointerCapture = null;
  9920. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9921. }
  9922. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9923. handlerDomProxyProto.dispose = function () {
  9924. unmountDOMEventListeners(this._localHandlerScope);
  9925. if (globalEventSupported) {
  9926. unmountDOMEventListeners(this._globalHandlerScope);
  9927. }
  9928. };
  9929. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9930. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9931. };
  9932. mixin(HandlerDomProxy, Eventful);
  9933. /*!
  9934. * ZRender, a high performance 2d drawing library.
  9935. *
  9936. * Copyright (c) 2013, Baidu Inc.
  9937. * All rights reserved.
  9938. *
  9939. * LICENSE
  9940. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9941. */
  9942. var useVML = !env$1.canvasSupported;
  9943. var painterCtors = {
  9944. canvas: Painter
  9945. };
  9946. var instances$1 = {}; // ZRender实例map索引
  9947. /**
  9948. * @type {string}
  9949. */
  9950. var version$1 = '4.2.0';
  9951. /**
  9952. * Initializing a zrender instance
  9953. * @param {HTMLElement} dom
  9954. * @param {Object} [opts]
  9955. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9956. * @param {number} [opts.devicePixelRatio]
  9957. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9958. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9959. * @return {module:zrender/ZRender}
  9960. */
  9961. function init$1(dom, opts) {
  9962. var zr = new ZRender(guid(), dom, opts);
  9963. instances$1[zr.id] = zr;
  9964. return zr;
  9965. }
  9966. /**
  9967. * Dispose zrender instance
  9968. * @param {module:zrender/ZRender} zr
  9969. */
  9970. function dispose$1(zr) {
  9971. if (zr) {
  9972. zr.dispose();
  9973. }
  9974. else {
  9975. for (var key in instances$1) {
  9976. if (instances$1.hasOwnProperty(key)) {
  9977. instances$1[key].dispose();
  9978. }
  9979. }
  9980. instances$1 = {};
  9981. }
  9982. return this;
  9983. }
  9984. /**
  9985. * Get zrender instance by id
  9986. * @param {string} id zrender instance id
  9987. * @return {module:zrender/ZRender}
  9988. */
  9989. function getInstance(id) {
  9990. return instances$1[id];
  9991. }
  9992. function registerPainter(name, Ctor) {
  9993. painterCtors[name] = Ctor;
  9994. }
  9995. function delInstance(id) {
  9996. delete instances$1[id];
  9997. }
  9998. /**
  9999. * @module zrender/ZRender
  10000. */
  10001. /**
  10002. * @constructor
  10003. * @alias module:zrender/ZRender
  10004. * @param {string} id
  10005. * @param {HTMLElement} dom
  10006. * @param {Object} opts
  10007. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10008. * @param {number} [opts.devicePixelRatio]
  10009. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10010. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10011. */
  10012. var ZRender = function (id, dom, opts) {
  10013. opts = opts || {};
  10014. /**
  10015. * @type {HTMLDomElement}
  10016. */
  10017. this.dom = dom;
  10018. /**
  10019. * @type {string}
  10020. */
  10021. this.id = id;
  10022. var self = this;
  10023. var storage = new Storage();
  10024. var rendererType = opts.renderer;
  10025. // TODO WebGL
  10026. if (useVML) {
  10027. if (!painterCtors.vml) {
  10028. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10029. }
  10030. rendererType = 'vml';
  10031. }
  10032. else if (!rendererType || !painterCtors[rendererType]) {
  10033. rendererType = 'canvas';
  10034. }
  10035. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10036. this.storage = storage;
  10037. this.painter = painter;
  10038. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10039. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10040. /**
  10041. * @type {module:zrender/animation/Animation}
  10042. */
  10043. this.animation = new Animation({
  10044. stage: {
  10045. update: bind(this.flush, this)
  10046. }
  10047. });
  10048. this.animation.start();
  10049. /**
  10050. * @type {boolean}
  10051. * @private
  10052. */
  10053. this._needsRefresh;
  10054. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10055. // FIXME 有点ugly
  10056. var oldDelFromStorage = storage.delFromStorage;
  10057. var oldAddToStorage = storage.addToStorage;
  10058. storage.delFromStorage = function (el) {
  10059. oldDelFromStorage.call(storage, el);
  10060. el && el.removeSelfFromZr(self);
  10061. };
  10062. storage.addToStorage = function (el) {
  10063. oldAddToStorage.call(storage, el);
  10064. el.addSelfToZr(self);
  10065. };
  10066. };
  10067. ZRender.prototype = {
  10068. constructor: ZRender,
  10069. /**
  10070. * 获取实例唯一标识
  10071. * @return {string}
  10072. */
  10073. getId: function () {
  10074. return this.id;
  10075. },
  10076. /**
  10077. * 添加元素
  10078. * @param {module:zrender/Element} el
  10079. */
  10080. add: function (el) {
  10081. this.storage.addRoot(el);
  10082. this._needsRefresh = true;
  10083. },
  10084. /**
  10085. * 删除元素
  10086. * @param {module:zrender/Element} el
  10087. */
  10088. remove: function (el) {
  10089. this.storage.delRoot(el);
  10090. this._needsRefresh = true;
  10091. },
  10092. /**
  10093. * Change configuration of layer
  10094. * @param {string} zLevel
  10095. * @param {Object} config
  10096. * @param {string} [config.clearColor=0] Clear color
  10097. * @param {string} [config.motionBlur=false] If enable motion blur
  10098. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10099. */
  10100. configLayer: function (zLevel, config) {
  10101. if (this.painter.configLayer) {
  10102. this.painter.configLayer(zLevel, config);
  10103. }
  10104. this._needsRefresh = true;
  10105. },
  10106. /**
  10107. * Set background color
  10108. * @param {string} backgroundColor
  10109. */
  10110. setBackgroundColor: function (backgroundColor) {
  10111. if (this.painter.setBackgroundColor) {
  10112. this.painter.setBackgroundColor(backgroundColor);
  10113. }
  10114. this._needsRefresh = true;
  10115. },
  10116. /**
  10117. * Repaint the canvas immediately
  10118. */
  10119. refreshImmediately: function () {
  10120. // var start = new Date();
  10121. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10122. // Or it will cause zrender refreshes again and again.
  10123. this._needsRefresh = this._needsRefreshHover = false;
  10124. this.painter.refresh();
  10125. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10126. this._needsRefresh = this._needsRefreshHover = false;
  10127. // var end = new Date();
  10128. // var log = document.getElementById('log');
  10129. // if (log) {
  10130. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10131. // }
  10132. },
  10133. /**
  10134. * Mark and repaint the canvas in the next frame of browser
  10135. */
  10136. refresh: function () {
  10137. this._needsRefresh = true;
  10138. },
  10139. /**
  10140. * Perform all refresh
  10141. */
  10142. flush: function () {
  10143. var triggerRendered;
  10144. if (this._needsRefresh) {
  10145. triggerRendered = true;
  10146. this.refreshImmediately();
  10147. }
  10148. if (this._needsRefreshHover) {
  10149. triggerRendered = true;
  10150. this.refreshHoverImmediately();
  10151. }
  10152. triggerRendered && this.trigger('rendered');
  10153. },
  10154. /**
  10155. * Add element to hover layer
  10156. * @param {module:zrender/Element} el
  10157. * @param {Object} style
  10158. */
  10159. addHover: function (el, style) {
  10160. if (this.painter.addHover) {
  10161. var elMirror = this.painter.addHover(el, style);
  10162. this.refreshHover();
  10163. return elMirror;
  10164. }
  10165. },
  10166. /**
  10167. * Add element from hover layer
  10168. * @param {module:zrender/Element} el
  10169. */
  10170. removeHover: function (el) {
  10171. if (this.painter.removeHover) {
  10172. this.painter.removeHover(el);
  10173. this.refreshHover();
  10174. }
  10175. },
  10176. /**
  10177. * Clear all hover elements in hover layer
  10178. * @param {module:zrender/Element} el
  10179. */
  10180. clearHover: function () {
  10181. if (this.painter.clearHover) {
  10182. this.painter.clearHover();
  10183. this.refreshHover();
  10184. }
  10185. },
  10186. /**
  10187. * Refresh hover in next frame
  10188. */
  10189. refreshHover: function () {
  10190. this._needsRefreshHover = true;
  10191. },
  10192. /**
  10193. * Refresh hover immediately
  10194. */
  10195. refreshHoverImmediately: function () {
  10196. this._needsRefreshHover = false;
  10197. this.painter.refreshHover && this.painter.refreshHover();
  10198. },
  10199. /**
  10200. * Resize the canvas.
  10201. * Should be invoked when container size is changed
  10202. * @param {Object} [opts]
  10203. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10204. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10205. */
  10206. resize: function (opts) {
  10207. opts = opts || {};
  10208. this.painter.resize(opts.width, opts.height);
  10209. this.handler.resize();
  10210. },
  10211. /**
  10212. * Stop and clear all animation immediately
  10213. */
  10214. clearAnimation: function () {
  10215. this.animation.clear();
  10216. },
  10217. /**
  10218. * Get container width
  10219. */
  10220. getWidth: function () {
  10221. return this.painter.getWidth();
  10222. },
  10223. /**
  10224. * Get container height
  10225. */
  10226. getHeight: function () {
  10227. return this.painter.getHeight();
  10228. },
  10229. /**
  10230. * Export the canvas as Base64 URL
  10231. * @param {string} type
  10232. * @param {string} [backgroundColor='#fff']
  10233. * @return {string} Base64 URL
  10234. */
  10235. // toDataURL: function(type, backgroundColor) {
  10236. // return this.painter.getRenderedCanvas({
  10237. // backgroundColor: backgroundColor
  10238. // }).toDataURL(type);
  10239. // },
  10240. /**
  10241. * Converting a path to image.
  10242. * It has much better performance of drawing image rather than drawing a vector path.
  10243. * @param {module:zrender/graphic/Path} e
  10244. * @param {number} width
  10245. * @param {number} height
  10246. */
  10247. pathToImage: function (e, dpr) {
  10248. return this.painter.pathToImage(e, dpr);
  10249. },
  10250. /**
  10251. * Set default cursor
  10252. * @param {string} [cursorStyle='default'] 例如 crosshair
  10253. */
  10254. setCursorStyle: function (cursorStyle) {
  10255. this.handler.setCursorStyle(cursorStyle);
  10256. },
  10257. /**
  10258. * Find hovered element
  10259. * @param {number} x
  10260. * @param {number} y
  10261. * @return {Object} {target, topTarget}
  10262. */
  10263. findHover: function (x, y) {
  10264. return this.handler.findHover(x, y);
  10265. },
  10266. /**
  10267. * Bind event
  10268. *
  10269. * @param {string} eventName Event name
  10270. * @param {Function} eventHandler Handler function
  10271. * @param {Object} [context] Context object
  10272. */
  10273. on: function (eventName, eventHandler, context) {
  10274. this.handler.on(eventName, eventHandler, context);
  10275. },
  10276. /**
  10277. * Unbind event
  10278. * @param {string} eventName Event name
  10279. * @param {Function} [eventHandler] Handler function
  10280. */
  10281. off: function (eventName, eventHandler) {
  10282. this.handler.off(eventName, eventHandler);
  10283. },
  10284. /**
  10285. * Trigger event manually
  10286. *
  10287. * @param {string} eventName Event name
  10288. * @param {event=} event Event object
  10289. */
  10290. trigger: function (eventName, event) {
  10291. this.handler.trigger(eventName, event);
  10292. },
  10293. /**
  10294. * Clear all objects and the canvas.
  10295. */
  10296. clear: function () {
  10297. this.storage.delRoot();
  10298. this.painter.clear();
  10299. },
  10300. /**
  10301. * Dispose self.
  10302. */
  10303. dispose: function () {
  10304. this.animation.stop();
  10305. this.clear();
  10306. this.storage.dispose();
  10307. this.painter.dispose();
  10308. this.handler.dispose();
  10309. this.animation =
  10310. this.storage =
  10311. this.painter =
  10312. this.handler = null;
  10313. delInstance(this.id);
  10314. }
  10315. };
  10316. var zrender = (Object.freeze || Object)({
  10317. version: version$1,
  10318. init: init$1,
  10319. dispose: dispose$1,
  10320. getInstance: getInstance,
  10321. registerPainter: registerPainter
  10322. });
  10323. /*
  10324. * Licensed to the Apache Software Foundation (ASF) under one
  10325. * or more contributor license agreements. See the NOTICE file
  10326. * distributed with this work for additional information
  10327. * regarding copyright ownership. The ASF licenses this file
  10328. * to you under the Apache License, Version 2.0 (the
  10329. * "License"); you may not use this file except in compliance
  10330. * with the License. You may obtain a copy of the License at
  10331. *
  10332. * http://www.apache.org/licenses/LICENSE-2.0
  10333. *
  10334. * Unless required by applicable law or agreed to in writing,
  10335. * software distributed under the License is distributed on an
  10336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10337. * KIND, either express or implied. See the License for the
  10338. * specific language governing permissions and limitations
  10339. * under the License.
  10340. */
  10341. var each$2 = each$1;
  10342. var isObject$2 = isObject$1;
  10343. var isArray$1 = isArray;
  10344. /**
  10345. * Make the name displayable. But we should
  10346. * make sure it is not duplicated with user
  10347. * specified name, so use '\0';
  10348. */
  10349. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10350. /**
  10351. * If value is not array, then translate it to array.
  10352. * @param {*} value
  10353. * @return {Array} [value] or value
  10354. */
  10355. function normalizeToArray(value) {
  10356. return value instanceof Array
  10357. ? value
  10358. : value == null
  10359. ? []
  10360. : [value];
  10361. }
  10362. /**
  10363. * Sync default option between normal and emphasis like `position` and `show`
  10364. * In case some one will write code like
  10365. * label: {
  10366. * show: false,
  10367. * position: 'outside',
  10368. * fontSize: 18
  10369. * },
  10370. * emphasis: {
  10371. * label: { show: true }
  10372. * }
  10373. * @param {Object} opt
  10374. * @param {string} key
  10375. * @param {Array.<string>} subOpts
  10376. */
  10377. function defaultEmphasis(opt, key, subOpts) {
  10378. // Caution: performance sensitive.
  10379. if (opt) {
  10380. opt[key] = opt[key] || {};
  10381. opt.emphasis = opt.emphasis || {};
  10382. opt.emphasis[key] = opt.emphasis[key] || {};
  10383. // Default emphasis option from normal
  10384. for (var i = 0, len = subOpts.length; i < len; i++) {
  10385. var subOptName = subOpts[i];
  10386. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10387. && opt[key].hasOwnProperty(subOptName)
  10388. ) {
  10389. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10390. }
  10391. }
  10392. }
  10393. }
  10394. var TEXT_STYLE_OPTIONS = [
  10395. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10396. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10397. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10398. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10399. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10400. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10401. ];
  10402. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10403. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10404. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10405. // // FIXME: deprecated, check and remove it.
  10406. // 'textStyle'
  10407. // ]);
  10408. /**
  10409. * The method do not ensure performance.
  10410. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10411. * This helper method retieves value from data.
  10412. * @param {string|number|Date|Array|Object} dataItem
  10413. * @return {number|string|Date|Array.<number|string|Date>}
  10414. */
  10415. function getDataItemValue(dataItem) {
  10416. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10417. ? dataItem.value : dataItem;
  10418. }
  10419. /**
  10420. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10421. * This helper method determine if dataItem has extra option besides value
  10422. * @param {string|number|Date|Array|Object} dataItem
  10423. */
  10424. function isDataItemOption(dataItem) {
  10425. return isObject$2(dataItem)
  10426. && !(dataItem instanceof Array);
  10427. // // markLine data can be array
  10428. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10429. }
  10430. /**
  10431. * Mapping to exists for merge.
  10432. *
  10433. * @public
  10434. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10435. * @param {Object|Array.<Object>} newCptOptions
  10436. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10437. * index of which is the same as exists.
  10438. */
  10439. function mappingToExists(exists, newCptOptions) {
  10440. // Mapping by the order by original option (but not order of
  10441. // new option) in merge mode. Because we should ensure
  10442. // some specified index (like xAxisIndex) is consistent with
  10443. // original option, which is easy to understand, espatially in
  10444. // media query. And in most case, merge option is used to
  10445. // update partial option but not be expected to change order.
  10446. newCptOptions = (newCptOptions || []).slice();
  10447. var result = map(exists || [], function (obj, index) {
  10448. return {exist: obj};
  10449. });
  10450. // Mapping by id or name if specified.
  10451. each$2(newCptOptions, function (cptOption, index) {
  10452. if (!isObject$2(cptOption)) {
  10453. return;
  10454. }
  10455. // id has highest priority.
  10456. for (var i = 0; i < result.length; i++) {
  10457. if (!result[i].option // Consider name: two map to one.
  10458. && cptOption.id != null
  10459. && result[i].exist.id === cptOption.id + ''
  10460. ) {
  10461. result[i].option = cptOption;
  10462. newCptOptions[index] = null;
  10463. return;
  10464. }
  10465. }
  10466. for (var i = 0; i < result.length; i++) {
  10467. var exist = result[i].exist;
  10468. if (!result[i].option // Consider name: two map to one.
  10469. // Can not match when both ids exist but different.
  10470. && (exist.id == null || cptOption.id == null)
  10471. && cptOption.name != null
  10472. && !isIdInner(cptOption)
  10473. && !isIdInner(exist)
  10474. && exist.name === cptOption.name + ''
  10475. ) {
  10476. result[i].option = cptOption;
  10477. newCptOptions[index] = null;
  10478. return;
  10479. }
  10480. }
  10481. });
  10482. // Otherwise mapping by index.
  10483. each$2(newCptOptions, function (cptOption, index) {
  10484. if (!isObject$2(cptOption)) {
  10485. return;
  10486. }
  10487. var i = 0;
  10488. for (; i < result.length; i++) {
  10489. var exist = result[i].exist;
  10490. if (!result[i].option
  10491. // Existing model that already has id should be able to
  10492. // mapped to (because after mapping performed model may
  10493. // be assigned with a id, whish should not affect next
  10494. // mapping), except those has inner id.
  10495. && !isIdInner(exist)
  10496. // Caution:
  10497. // Do not overwrite id. But name can be overwritten,
  10498. // because axis use name as 'show label text'.
  10499. // 'exist' always has id and name and we dont
  10500. // need to check it.
  10501. && cptOption.id == null
  10502. ) {
  10503. result[i].option = cptOption;
  10504. break;
  10505. }
  10506. }
  10507. if (i >= result.length) {
  10508. result.push({option: cptOption});
  10509. }
  10510. });
  10511. return result;
  10512. }
  10513. /**
  10514. * Make id and name for mapping result (result of mappingToExists)
  10515. * into `keyInfo` field.
  10516. *
  10517. * @public
  10518. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10519. * which order is the same as exists.
  10520. * @return {Array.<Object>} The input.
  10521. */
  10522. function makeIdAndName(mapResult) {
  10523. // We use this id to hash component models and view instances
  10524. // in echarts. id can be specified by user, or auto generated.
  10525. // The id generation rule ensures new view instance are able
  10526. // to mapped to old instance when setOption are called in
  10527. // no-merge mode. So we generate model id by name and plus
  10528. // type in view id.
  10529. // name can be duplicated among components, which is convenient
  10530. // to specify multi components (like series) by one name.
  10531. // Ensure that each id is distinct.
  10532. var idMap = createHashMap();
  10533. each$2(mapResult, function (item, index) {
  10534. var existCpt = item.exist;
  10535. existCpt && idMap.set(existCpt.id, item);
  10536. });
  10537. each$2(mapResult, function (item, index) {
  10538. var opt = item.option;
  10539. assert$1(
  10540. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10541. 'id duplicates: ' + (opt && opt.id)
  10542. );
  10543. opt && opt.id != null && idMap.set(opt.id, item);
  10544. !item.keyInfo && (item.keyInfo = {});
  10545. });
  10546. // Make name and id.
  10547. each$2(mapResult, function (item, index) {
  10548. var existCpt = item.exist;
  10549. var opt = item.option;
  10550. var keyInfo = item.keyInfo;
  10551. if (!isObject$2(opt)) {
  10552. return;
  10553. }
  10554. // name can be overwitten. Consider case: axis.name = '20km'.
  10555. // But id generated by name will not be changed, which affect
  10556. // only in that case: setOption with 'not merge mode' and view
  10557. // instance will be recreated, which can be accepted.
  10558. keyInfo.name = opt.name != null
  10559. ? opt.name + ''
  10560. : existCpt
  10561. ? existCpt.name
  10562. // Avoid diffferent series has the same name,
  10563. // because name may be used like in color pallet.
  10564. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10565. if (existCpt) {
  10566. keyInfo.id = existCpt.id;
  10567. }
  10568. else if (opt.id != null) {
  10569. keyInfo.id = opt.id + '';
  10570. }
  10571. else {
  10572. // Consider this situatoin:
  10573. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10574. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10575. // Series with the same name between optionA and optionB
  10576. // should be mapped.
  10577. var idNum = 0;
  10578. do {
  10579. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10580. }
  10581. while (idMap.get(keyInfo.id));
  10582. }
  10583. idMap.set(keyInfo.id, item);
  10584. });
  10585. }
  10586. function isNameSpecified(componentModel) {
  10587. var name = componentModel.name;
  10588. // Is specified when `indexOf` get -1 or > 0.
  10589. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10590. }
  10591. /**
  10592. * @public
  10593. * @param {Object} cptOption
  10594. * @return {boolean}
  10595. */
  10596. function isIdInner(cptOption) {
  10597. return isObject$2(cptOption)
  10598. && cptOption.id
  10599. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10600. }
  10601. /**
  10602. * A helper for removing duplicate items between batchA and batchB,
  10603. * and in themselves, and categorize by series.
  10604. *
  10605. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10606. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10607. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10608. */
  10609. function compressBatches(batchA, batchB) {
  10610. var mapA = {};
  10611. var mapB = {};
  10612. makeMap(batchA || [], mapA);
  10613. makeMap(batchB || [], mapB, mapA);
  10614. return [mapToArray(mapA), mapToArray(mapB)];
  10615. function makeMap(sourceBatch, map$$1, otherMap) {
  10616. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10617. var seriesId = sourceBatch[i].seriesId;
  10618. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10619. var otherDataIndices = otherMap && otherMap[seriesId];
  10620. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10621. var dataIndex = dataIndices[j];
  10622. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10623. otherDataIndices[dataIndex] = null;
  10624. }
  10625. else {
  10626. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10627. }
  10628. }
  10629. }
  10630. }
  10631. function mapToArray(map$$1, isData) {
  10632. var result = [];
  10633. for (var i in map$$1) {
  10634. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10635. if (isData) {
  10636. result.push(+i);
  10637. }
  10638. else {
  10639. var dataIndices = mapToArray(map$$1[i], true);
  10640. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  10641. }
  10642. }
  10643. }
  10644. return result;
  10645. }
  10646. }
  10647. /**
  10648. * @param {module:echarts/data/List} data
  10649. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10650. * each of which can be Array or primary type.
  10651. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10652. */
  10653. function queryDataIndex(data, payload) {
  10654. if (payload.dataIndexInside != null) {
  10655. return payload.dataIndexInside;
  10656. }
  10657. else if (payload.dataIndex != null) {
  10658. return isArray(payload.dataIndex)
  10659. ? map(payload.dataIndex, function (value) {
  10660. return data.indexOfRawIndex(value);
  10661. })
  10662. : data.indexOfRawIndex(payload.dataIndex);
  10663. }
  10664. else if (payload.name != null) {
  10665. return isArray(payload.name)
  10666. ? map(payload.name, function (value) {
  10667. return data.indexOfName(value);
  10668. })
  10669. : data.indexOfName(payload.name);
  10670. }
  10671. }
  10672. /**
  10673. * Enable property storage to any host object.
  10674. * Notice: Serialization is not supported.
  10675. *
  10676. * For example:
  10677. * var inner = zrUitl.makeInner();
  10678. *
  10679. * function some1(hostObj) {
  10680. * inner(hostObj).someProperty = 1212;
  10681. * ...
  10682. * }
  10683. * function some2() {
  10684. * var fields = inner(this);
  10685. * fields.someProperty1 = 1212;
  10686. * fields.someProperty2 = 'xx';
  10687. * ...
  10688. * }
  10689. *
  10690. * @return {Function}
  10691. */
  10692. function makeInner() {
  10693. // Consider different scope by es module import.
  10694. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10695. return function (hostObj) {
  10696. return hostObj[key] || (hostObj[key] = {});
  10697. };
  10698. }
  10699. var innerUniqueIndex = 0;
  10700. /**
  10701. * @param {module:echarts/model/Global} ecModel
  10702. * @param {string|Object} finder
  10703. * If string, e.g., 'geo', means {geoIndex: 0}.
  10704. * If Object, could contain some of these properties below:
  10705. * {
  10706. * seriesIndex, seriesId, seriesName,
  10707. * geoIndex, geoId, geoName,
  10708. * bmapIndex, bmapId, bmapName,
  10709. * xAxisIndex, xAxisId, xAxisName,
  10710. * yAxisIndex, yAxisId, yAxisName,
  10711. * gridIndex, gridId, gridName,
  10712. * ... (can be extended)
  10713. * }
  10714. * Each properties can be number|string|Array.<number>|Array.<string>
  10715. * For example, a finder could be
  10716. * {
  10717. * seriesIndex: 3,
  10718. * geoId: ['aa', 'cc'],
  10719. * gridName: ['xx', 'rr']
  10720. * }
  10721. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10722. * If nothing or null/undefined specified, return nothing.
  10723. * @param {Object} [opt]
  10724. * @param {string} [opt.defaultMainType]
  10725. * @param {Array.<string>} [opt.includeMainTypes]
  10726. * @return {Object} result like:
  10727. * {
  10728. * seriesModels: [seriesModel1, seriesModel2],
  10729. * seriesModel: seriesModel1, // The first model
  10730. * geoModels: [geoModel1, geoModel2],
  10731. * geoModel: geoModel1, // The first model
  10732. * ...
  10733. * }
  10734. */
  10735. function parseFinder(ecModel, finder, opt) {
  10736. if (isString(finder)) {
  10737. var obj = {};
  10738. obj[finder + 'Index'] = 0;
  10739. finder = obj;
  10740. }
  10741. var defaultMainType = opt && opt.defaultMainType;
  10742. if (defaultMainType
  10743. && !has(finder, defaultMainType + 'Index')
  10744. && !has(finder, defaultMainType + 'Id')
  10745. && !has(finder, defaultMainType + 'Name')
  10746. ) {
  10747. finder[defaultMainType + 'Index'] = 0;
  10748. }
  10749. var result = {};
  10750. each$2(finder, function (value, key) {
  10751. var value = finder[key];
  10752. // Exclude 'dataIndex' and other illgal keys.
  10753. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10754. result[key] = value;
  10755. return;
  10756. }
  10757. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10758. var mainType = parsedKey[1];
  10759. var queryType = (parsedKey[2] || '').toLowerCase();
  10760. if (!mainType
  10761. || !queryType
  10762. || value == null
  10763. || (queryType === 'index' && value === 'none')
  10764. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10765. ) {
  10766. return;
  10767. }
  10768. var queryParam = {mainType: mainType};
  10769. if (queryType !== 'index' || value !== 'all') {
  10770. queryParam[queryType] = value;
  10771. }
  10772. var models = ecModel.queryComponents(queryParam);
  10773. result[mainType + 'Models'] = models;
  10774. result[mainType + 'Model'] = models[0];
  10775. });
  10776. return result;
  10777. }
  10778. function has(obj, prop) {
  10779. return obj && obj.hasOwnProperty(prop);
  10780. }
  10781. function setAttribute(dom, key, value) {
  10782. dom.setAttribute
  10783. ? dom.setAttribute(key, value)
  10784. : (dom[key] = value);
  10785. }
  10786. function getAttribute(dom, key) {
  10787. return dom.getAttribute
  10788. ? dom.getAttribute(key)
  10789. : dom[key];
  10790. }
  10791. function getTooltipRenderMode(renderModeOption) {
  10792. if (renderModeOption === 'auto') {
  10793. // Using html when `document` exists, use richText otherwise
  10794. return env$1.domSupported ? 'html' : 'richText';
  10795. }
  10796. else {
  10797. return renderModeOption || 'html';
  10798. }
  10799. }
  10800. /**
  10801. * Group a list by key.
  10802. *
  10803. * @param {Array} array
  10804. * @param {Function} getKey
  10805. * param {*} Array item
  10806. * return {string} key
  10807. * @return {Object} Result
  10808. * {Array}: keys,
  10809. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10810. */
  10811. function groupData(array, getKey) {
  10812. var buckets = createHashMap();
  10813. var keys = [];
  10814. each$1(array, function (item) {
  10815. var key = getKey(item);
  10816. (buckets.get(key)
  10817. || (keys.push(key), buckets.set(key, []))
  10818. ).push(item);
  10819. });
  10820. return {keys: keys, buckets: buckets};
  10821. }
  10822. /*
  10823. * Licensed to the Apache Software Foundation (ASF) under one
  10824. * or more contributor license agreements. See the NOTICE file
  10825. * distributed with this work for additional information
  10826. * regarding copyright ownership. The ASF licenses this file
  10827. * to you under the Apache License, Version 2.0 (the
  10828. * "License"); you may not use this file except in compliance
  10829. * with the License. You may obtain a copy of the License at
  10830. *
  10831. * http://www.apache.org/licenses/LICENSE-2.0
  10832. *
  10833. * Unless required by applicable law or agreed to in writing,
  10834. * software distributed under the License is distributed on an
  10835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10836. * KIND, either express or implied. See the License for the
  10837. * specific language governing permissions and limitations
  10838. * under the License.
  10839. */
  10840. var TYPE_DELIMITER = '.';
  10841. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10842. /**
  10843. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10844. * @public
  10845. */
  10846. function parseClassType$1(componentType) {
  10847. var ret = {main: '', sub: ''};
  10848. if (componentType) {
  10849. componentType = componentType.split(TYPE_DELIMITER);
  10850. ret.main = componentType[0] || '';
  10851. ret.sub = componentType[1] || '';
  10852. }
  10853. return ret;
  10854. }
  10855. /**
  10856. * @public
  10857. */
  10858. function checkClassType(componentType) {
  10859. assert$1(
  10860. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10861. 'componentType "' + componentType + '" illegal'
  10862. );
  10863. }
  10864. /**
  10865. * @public
  10866. */
  10867. function enableClassExtend(RootClass, mandatoryMethods) {
  10868. RootClass.$constructor = RootClass;
  10869. RootClass.extend = function (proto) {
  10870. if (__DEV__) {
  10871. each$1(mandatoryMethods, function (method) {
  10872. if (!proto[method]) {
  10873. console.warn(
  10874. 'Method `' + method + '` should be implemented'
  10875. + (proto.type ? ' in ' + proto.type : '') + '.'
  10876. );
  10877. }
  10878. });
  10879. }
  10880. var superClass = this;
  10881. var ExtendedClass = function () {
  10882. if (!proto.$constructor) {
  10883. superClass.apply(this, arguments);
  10884. }
  10885. else {
  10886. proto.$constructor.apply(this, arguments);
  10887. }
  10888. };
  10889. extend(ExtendedClass.prototype, proto);
  10890. ExtendedClass.extend = this.extend;
  10891. ExtendedClass.superCall = superCall;
  10892. ExtendedClass.superApply = superApply;
  10893. inherits(ExtendedClass, this);
  10894. ExtendedClass.superClass = superClass;
  10895. return ExtendedClass;
  10896. };
  10897. }
  10898. var classBase = 0;
  10899. /**
  10900. * Can not use instanceof, consider different scope by
  10901. * cross domain or es module import in ec extensions.
  10902. * Mount a method "isInstance()" to Clz.
  10903. */
  10904. function enableClassCheck(Clz) {
  10905. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10906. Clz.prototype[classAttr] = true;
  10907. if (__DEV__) {
  10908. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10909. }
  10910. Clz.isInstance = function (obj) {
  10911. return !!(obj && obj[classAttr]);
  10912. };
  10913. }
  10914. // superCall should have class info, which can not be fetch from 'this'.
  10915. // Consider this case:
  10916. // class A has method f,
  10917. // class B inherits class A, overrides method f, f call superApply('f'),
  10918. // class C inherits class B, do not overrides method f,
  10919. // then when method of class C is called, dead loop occured.
  10920. function superCall(context, methodName) {
  10921. var args = slice(arguments, 2);
  10922. return this.superClass.prototype[methodName].apply(context, args);
  10923. }
  10924. function superApply(context, methodName, args) {
  10925. return this.superClass.prototype[methodName].apply(context, args);
  10926. }
  10927. /**
  10928. * @param {Object} entity
  10929. * @param {Object} options
  10930. * @param {boolean} [options.registerWhenExtend]
  10931. * @public
  10932. */
  10933. function enableClassManagement(entity, options) {
  10934. options = options || {};
  10935. /**
  10936. * Component model classes
  10937. * key: componentType,
  10938. * value:
  10939. * componentClass, when componentType is 'xxx'
  10940. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10941. * @type {Object}
  10942. */
  10943. var storage = {};
  10944. entity.registerClass = function (Clazz, componentType) {
  10945. if (componentType) {
  10946. checkClassType(componentType);
  10947. componentType = parseClassType$1(componentType);
  10948. if (!componentType.sub) {
  10949. if (__DEV__) {
  10950. if (storage[componentType.main]) {
  10951. console.warn(componentType.main + ' exists.');
  10952. }
  10953. }
  10954. storage[componentType.main] = Clazz;
  10955. }
  10956. else if (componentType.sub !== IS_CONTAINER) {
  10957. var container = makeContainer(componentType);
  10958. container[componentType.sub] = Clazz;
  10959. }
  10960. }
  10961. return Clazz;
  10962. };
  10963. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10964. var Clazz = storage[componentMainType];
  10965. if (Clazz && Clazz[IS_CONTAINER]) {
  10966. Clazz = subType ? Clazz[subType] : null;
  10967. }
  10968. if (throwWhenNotFound && !Clazz) {
  10969. throw new Error(
  10970. !subType
  10971. ? componentMainType + '.' + 'type should be specified.'
  10972. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10973. );
  10974. }
  10975. return Clazz;
  10976. };
  10977. entity.getClassesByMainType = function (componentType) {
  10978. componentType = parseClassType$1(componentType);
  10979. var result = [];
  10980. var obj = storage[componentType.main];
  10981. if (obj && obj[IS_CONTAINER]) {
  10982. each$1(obj, function (o, type) {
  10983. type !== IS_CONTAINER && result.push(o);
  10984. });
  10985. }
  10986. else {
  10987. result.push(obj);
  10988. }
  10989. return result;
  10990. };
  10991. entity.hasClass = function (componentType) {
  10992. // Just consider componentType.main.
  10993. componentType = parseClassType$1(componentType);
  10994. return !!storage[componentType.main];
  10995. };
  10996. /**
  10997. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10998. */
  10999. entity.getAllClassMainTypes = function () {
  11000. var types = [];
  11001. each$1(storage, function (obj, type) {
  11002. types.push(type);
  11003. });
  11004. return types;
  11005. };
  11006. /**
  11007. * If a main type is container and has sub types
  11008. * @param {string} mainType
  11009. * @return {boolean}
  11010. */
  11011. entity.hasSubTypes = function (componentType) {
  11012. componentType = parseClassType$1(componentType);
  11013. var obj = storage[componentType.main];
  11014. return obj && obj[IS_CONTAINER];
  11015. };
  11016. entity.parseClassType = parseClassType$1;
  11017. function makeContainer(componentType) {
  11018. var container = storage[componentType.main];
  11019. if (!container || !container[IS_CONTAINER]) {
  11020. container = storage[componentType.main] = {};
  11021. container[IS_CONTAINER] = true;
  11022. }
  11023. return container;
  11024. }
  11025. if (options.registerWhenExtend) {
  11026. var originalExtend = entity.extend;
  11027. if (originalExtend) {
  11028. entity.extend = function (proto) {
  11029. var ExtendedClass = originalExtend.call(this, proto);
  11030. return entity.registerClass(ExtendedClass, proto.type);
  11031. };
  11032. }
  11033. }
  11034. return entity;
  11035. }
  11036. /**
  11037. * @param {string|Array.<string>} properties
  11038. */
  11039. /*
  11040. * Licensed to the Apache Software Foundation (ASF) under one
  11041. * or more contributor license agreements. See the NOTICE file
  11042. * distributed with this work for additional information
  11043. * regarding copyright ownership. The ASF licenses this file
  11044. * to you under the Apache License, Version 2.0 (the
  11045. * "License"); you may not use this file except in compliance
  11046. * with the License. You may obtain a copy of the License at
  11047. *
  11048. * http://www.apache.org/licenses/LICENSE-2.0
  11049. *
  11050. * Unless required by applicable law or agreed to in writing,
  11051. * software distributed under the License is distributed on an
  11052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11053. * KIND, either express or implied. See the License for the
  11054. * specific language governing permissions and limitations
  11055. * under the License.
  11056. */
  11057. // TODO Parse shadow style
  11058. // TODO Only shallow path support
  11059. var makeStyleMapper = function (properties) {
  11060. // Normalize
  11061. for (var i = 0; i < properties.length; i++) {
  11062. if (!properties[i][1]) {
  11063. properties[i][1] = properties[i][0];
  11064. }
  11065. }
  11066. return function (model, excludes, includes) {
  11067. var style = {};
  11068. for (var i = 0; i < properties.length; i++) {
  11069. var propName = properties[i][1];
  11070. if ((excludes && indexOf(excludes, propName) >= 0)
  11071. || (includes && indexOf(includes, propName) < 0)
  11072. ) {
  11073. continue;
  11074. }
  11075. var val = model.getShallow(propName);
  11076. if (val != null) {
  11077. style[properties[i][0]] = val;
  11078. }
  11079. }
  11080. return style;
  11081. };
  11082. };
  11083. /*
  11084. * Licensed to the Apache Software Foundation (ASF) under one
  11085. * or more contributor license agreements. See the NOTICE file
  11086. * distributed with this work for additional information
  11087. * regarding copyright ownership. The ASF licenses this file
  11088. * to you under the Apache License, Version 2.0 (the
  11089. * "License"); you may not use this file except in compliance
  11090. * with the License. You may obtain a copy of the License at
  11091. *
  11092. * http://www.apache.org/licenses/LICENSE-2.0
  11093. *
  11094. * Unless required by applicable law or agreed to in writing,
  11095. * software distributed under the License is distributed on an
  11096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11097. * KIND, either express or implied. See the License for the
  11098. * specific language governing permissions and limitations
  11099. * under the License.
  11100. */
  11101. var getLineStyle = makeStyleMapper(
  11102. [
  11103. ['lineWidth', 'width'],
  11104. ['stroke', 'color'],
  11105. ['opacity'],
  11106. ['shadowBlur'],
  11107. ['shadowOffsetX'],
  11108. ['shadowOffsetY'],
  11109. ['shadowColor']
  11110. ]
  11111. );
  11112. var lineStyleMixin = {
  11113. getLineStyle: function (excludes) {
  11114. var style = getLineStyle(this, excludes);
  11115. // Always set lineDash whether dashed, otherwise we can not
  11116. // erase the previous style when assigning to el.style.
  11117. style.lineDash = this.getLineDash(style.lineWidth);
  11118. return style;
  11119. },
  11120. getLineDash: function (lineWidth) {
  11121. if (lineWidth == null) {
  11122. lineWidth = 1;
  11123. }
  11124. var lineType = this.get('type');
  11125. var dotSize = Math.max(lineWidth, 2);
  11126. var dashSize = lineWidth * 4;
  11127. return (lineType === 'solid' || lineType == null)
  11128. // Use `false` but not `null` for the solid line here, because `null` might be
  11129. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11130. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11131. // `lineDash` gotten form the latter one is not able to erase that from the former
  11132. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11133. ? false
  11134. : lineType === 'dashed'
  11135. ? [dashSize, dashSize]
  11136. : [dotSize, dotSize];
  11137. }
  11138. };
  11139. /*
  11140. * Licensed to the Apache Software Foundation (ASF) under one
  11141. * or more contributor license agreements. See the NOTICE file
  11142. * distributed with this work for additional information
  11143. * regarding copyright ownership. The ASF licenses this file
  11144. * to you under the Apache License, Version 2.0 (the
  11145. * "License"); you may not use this file except in compliance
  11146. * with the License. You may obtain a copy of the License at
  11147. *
  11148. * http://www.apache.org/licenses/LICENSE-2.0
  11149. *
  11150. * Unless required by applicable law or agreed to in writing,
  11151. * software distributed under the License is distributed on an
  11152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11153. * KIND, either express or implied. See the License for the
  11154. * specific language governing permissions and limitations
  11155. * under the License.
  11156. */
  11157. var getAreaStyle = makeStyleMapper(
  11158. [
  11159. ['fill', 'color'],
  11160. ['shadowBlur'],
  11161. ['shadowOffsetX'],
  11162. ['shadowOffsetY'],
  11163. ['opacity'],
  11164. ['shadowColor']
  11165. ]
  11166. );
  11167. var areaStyleMixin = {
  11168. getAreaStyle: function (excludes, includes) {
  11169. return getAreaStyle(this, excludes, includes);
  11170. }
  11171. };
  11172. /**
  11173. * 曲线辅助模块
  11174. * @module zrender/core/curve
  11175. * @author pissang(https://www.github.com/pissang)
  11176. */
  11177. var mathPow = Math.pow;
  11178. var mathSqrt$2 = Math.sqrt;
  11179. var EPSILON$1 = 1e-8;
  11180. var EPSILON_NUMERIC = 1e-4;
  11181. var THREE_SQRT = mathSqrt$2(3);
  11182. var ONE_THIRD = 1 / 3;
  11183. // 临时变量
  11184. var _v0 = create();
  11185. var _v1 = create();
  11186. var _v2 = create();
  11187. function isAroundZero(val) {
  11188. return val > -EPSILON$1 && val < EPSILON$1;
  11189. }
  11190. function isNotAroundZero$1(val) {
  11191. return val > EPSILON$1 || val < -EPSILON$1;
  11192. }
  11193. /**
  11194. * 计算三次贝塞尔值
  11195. * @memberOf module:zrender/core/curve
  11196. * @param {number} p0
  11197. * @param {number} p1
  11198. * @param {number} p2
  11199. * @param {number} p3
  11200. * @param {number} t
  11201. * @return {number}
  11202. */
  11203. function cubicAt(p0, p1, p2, p3, t) {
  11204. var onet = 1 - t;
  11205. return onet * onet * (onet * p0 + 3 * t * p1)
  11206. + t * t * (t * p3 + 3 * onet * p2);
  11207. }
  11208. /**
  11209. * 计算三次贝塞尔导数值
  11210. * @memberOf module:zrender/core/curve
  11211. * @param {number} p0
  11212. * @param {number} p1
  11213. * @param {number} p2
  11214. * @param {number} p3
  11215. * @param {number} t
  11216. * @return {number}
  11217. */
  11218. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11219. var onet = 1 - t;
  11220. return 3 * (
  11221. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11222. + (p3 - p2) * t * t
  11223. );
  11224. }
  11225. /**
  11226. * 计算三次贝塞尔方程根,使用盛金公式
  11227. * @memberOf module:zrender/core/curve
  11228. * @param {number} p0
  11229. * @param {number} p1
  11230. * @param {number} p2
  11231. * @param {number} p3
  11232. * @param {number} val
  11233. * @param {Array.<number>} roots
  11234. * @return {number} 有效根数目
  11235. */
  11236. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11237. // Evaluate roots of cubic functions
  11238. var a = p3 + 3 * (p1 - p2) - p0;
  11239. var b = 3 * (p2 - p1 * 2 + p0);
  11240. var c = 3 * (p1 - p0);
  11241. var d = p0 - val;
  11242. var A = b * b - 3 * a * c;
  11243. var B = b * c - 9 * a * d;
  11244. var C = c * c - 3 * b * d;
  11245. var n = 0;
  11246. if (isAroundZero(A) && isAroundZero(B)) {
  11247. if (isAroundZero(b)) {
  11248. roots[0] = 0;
  11249. }
  11250. else {
  11251. var t1 = -c / b; //t1, t2, t3, b is not zero
  11252. if (t1 >= 0 && t1 <= 1) {
  11253. roots[n++] = t1;
  11254. }
  11255. }
  11256. }
  11257. else {
  11258. var disc = B * B - 4 * A * C;
  11259. if (isAroundZero(disc)) {
  11260. var K = B / A;
  11261. var t1 = -b / a + K; // t1, a is not zero
  11262. var t2 = -K / 2; // t2, t3
  11263. if (t1 >= 0 && t1 <= 1) {
  11264. roots[n++] = t1;
  11265. }
  11266. if (t2 >= 0 && t2 <= 1) {
  11267. roots[n++] = t2;
  11268. }
  11269. }
  11270. else if (disc > 0) {
  11271. var discSqrt = mathSqrt$2(disc);
  11272. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11273. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11274. if (Y1 < 0) {
  11275. Y1 = -mathPow(-Y1, ONE_THIRD);
  11276. }
  11277. else {
  11278. Y1 = mathPow(Y1, ONE_THIRD);
  11279. }
  11280. if (Y2 < 0) {
  11281. Y2 = -mathPow(-Y2, ONE_THIRD);
  11282. }
  11283. else {
  11284. Y2 = mathPow(Y2, ONE_THIRD);
  11285. }
  11286. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11287. if (t1 >= 0 && t1 <= 1) {
  11288. roots[n++] = t1;
  11289. }
  11290. }
  11291. else {
  11292. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11293. var theta = Math.acos(T) / 3;
  11294. var ASqrt = mathSqrt$2(A);
  11295. var tmp = Math.cos(theta);
  11296. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11297. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11298. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11299. if (t1 >= 0 && t1 <= 1) {
  11300. roots[n++] = t1;
  11301. }
  11302. if (t2 >= 0 && t2 <= 1) {
  11303. roots[n++] = t2;
  11304. }
  11305. if (t3 >= 0 && t3 <= 1) {
  11306. roots[n++] = t3;
  11307. }
  11308. }
  11309. }
  11310. return n;
  11311. }
  11312. /**
  11313. * 计算三次贝塞尔方程极限值的位置
  11314. * @memberOf module:zrender/core/curve
  11315. * @param {number} p0
  11316. * @param {number} p1
  11317. * @param {number} p2
  11318. * @param {number} p3
  11319. * @param {Array.<number>} extrema
  11320. * @return {number} 有效数目
  11321. */
  11322. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11323. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11324. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11325. var c = 3 * p1 - 3 * p0;
  11326. var n = 0;
  11327. if (isAroundZero(a)) {
  11328. if (isNotAroundZero$1(b)) {
  11329. var t1 = -c / b;
  11330. if (t1 >= 0 && t1 <= 1) {
  11331. extrema[n++] = t1;
  11332. }
  11333. }
  11334. }
  11335. else {
  11336. var disc = b * b - 4 * a * c;
  11337. if (isAroundZero(disc)) {
  11338. extrema[0] = -b / (2 * a);
  11339. }
  11340. else if (disc > 0) {
  11341. var discSqrt = mathSqrt$2(disc);
  11342. var t1 = (-b + discSqrt) / (2 * a);
  11343. var t2 = (-b - discSqrt) / (2 * a);
  11344. if (t1 >= 0 && t1 <= 1) {
  11345. extrema[n++] = t1;
  11346. }
  11347. if (t2 >= 0 && t2 <= 1) {
  11348. extrema[n++] = t2;
  11349. }
  11350. }
  11351. }
  11352. return n;
  11353. }
  11354. /**
  11355. * 细分三次贝塞尔曲线
  11356. * @memberOf module:zrender/core/curve
  11357. * @param {number} p0
  11358. * @param {number} p1
  11359. * @param {number} p2
  11360. * @param {number} p3
  11361. * @param {number} t
  11362. * @param {Array.<number>} out
  11363. */
  11364. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11365. var p01 = (p1 - p0) * t + p0;
  11366. var p12 = (p2 - p1) * t + p1;
  11367. var p23 = (p3 - p2) * t + p2;
  11368. var p012 = (p12 - p01) * t + p01;
  11369. var p123 = (p23 - p12) * t + p12;
  11370. var p0123 = (p123 - p012) * t + p012;
  11371. // Seg0
  11372. out[0] = p0;
  11373. out[1] = p01;
  11374. out[2] = p012;
  11375. out[3] = p0123;
  11376. // Seg1
  11377. out[4] = p0123;
  11378. out[5] = p123;
  11379. out[6] = p23;
  11380. out[7] = p3;
  11381. }
  11382. /**
  11383. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11384. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11385. * @param {number} x0
  11386. * @param {number} y0
  11387. * @param {number} x1
  11388. * @param {number} y1
  11389. * @param {number} x2
  11390. * @param {number} y2
  11391. * @param {number} x3
  11392. * @param {number} y3
  11393. * @param {number} x
  11394. * @param {number} y
  11395. * @param {Array.<number>} [out] 投射点
  11396. * @return {number}
  11397. */
  11398. function cubicProjectPoint(
  11399. x0, y0, x1, y1, x2, y2, x3, y3,
  11400. x, y, out
  11401. ) {
  11402. // http://pomax.github.io/bezierinfo/#projections
  11403. var t;
  11404. var interval = 0.005;
  11405. var d = Infinity;
  11406. var prev;
  11407. var next;
  11408. var d1;
  11409. var d2;
  11410. _v0[0] = x;
  11411. _v0[1] = y;
  11412. // 先粗略估计一下可能的最小距离的 t 值
  11413. // PENDING
  11414. for (var _t = 0; _t < 1; _t += 0.05) {
  11415. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11416. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11417. d1 = distSquare(_v0, _v1);
  11418. if (d1 < d) {
  11419. t = _t;
  11420. d = d1;
  11421. }
  11422. }
  11423. d = Infinity;
  11424. // At most 32 iteration
  11425. for (var i = 0; i < 32; i++) {
  11426. if (interval < EPSILON_NUMERIC) {
  11427. break;
  11428. }
  11429. prev = t - interval;
  11430. next = t + interval;
  11431. // t - interval
  11432. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11433. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11434. d1 = distSquare(_v1, _v0);
  11435. if (prev >= 0 && d1 < d) {
  11436. t = prev;
  11437. d = d1;
  11438. }
  11439. else {
  11440. // t + interval
  11441. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11442. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11443. d2 = distSquare(_v2, _v0);
  11444. if (next <= 1 && d2 < d) {
  11445. t = next;
  11446. d = d2;
  11447. }
  11448. else {
  11449. interval *= 0.5;
  11450. }
  11451. }
  11452. }
  11453. // t
  11454. if (out) {
  11455. out[0] = cubicAt(x0, x1, x2, x3, t);
  11456. out[1] = cubicAt(y0, y1, y2, y3, t);
  11457. }
  11458. // console.log(interval, i);
  11459. return mathSqrt$2(d);
  11460. }
  11461. /**
  11462. * 计算二次方贝塞尔值
  11463. * @param {number} p0
  11464. * @param {number} p1
  11465. * @param {number} p2
  11466. * @param {number} t
  11467. * @return {number}
  11468. */
  11469. function quadraticAt(p0, p1, p2, t) {
  11470. var onet = 1 - t;
  11471. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11472. }
  11473. /**
  11474. * 计算二次方贝塞尔导数值
  11475. * @param {number} p0
  11476. * @param {number} p1
  11477. * @param {number} p2
  11478. * @param {number} t
  11479. * @return {number}
  11480. */
  11481. function quadraticDerivativeAt(p0, p1, p2, t) {
  11482. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11483. }
  11484. /**
  11485. * 计算二次方贝塞尔方程根
  11486. * @param {number} p0
  11487. * @param {number} p1
  11488. * @param {number} p2
  11489. * @param {number} t
  11490. * @param {Array.<number>} roots
  11491. * @return {number} 有效根数目
  11492. */
  11493. function quadraticRootAt(p0, p1, p2, val, roots) {
  11494. var a = p0 - 2 * p1 + p2;
  11495. var b = 2 * (p1 - p0);
  11496. var c = p0 - val;
  11497. var n = 0;
  11498. if (isAroundZero(a)) {
  11499. if (isNotAroundZero$1(b)) {
  11500. var t1 = -c / b;
  11501. if (t1 >= 0 && t1 <= 1) {
  11502. roots[n++] = t1;
  11503. }
  11504. }
  11505. }
  11506. else {
  11507. var disc = b * b - 4 * a * c;
  11508. if (isAroundZero(disc)) {
  11509. var t1 = -b / (2 * a);
  11510. if (t1 >= 0 && t1 <= 1) {
  11511. roots[n++] = t1;
  11512. }
  11513. }
  11514. else if (disc > 0) {
  11515. var discSqrt = mathSqrt$2(disc);
  11516. var t1 = (-b + discSqrt) / (2 * a);
  11517. var t2 = (-b - discSqrt) / (2 * a);
  11518. if (t1 >= 0 && t1 <= 1) {
  11519. roots[n++] = t1;
  11520. }
  11521. if (t2 >= 0 && t2 <= 1) {
  11522. roots[n++] = t2;
  11523. }
  11524. }
  11525. }
  11526. return n;
  11527. }
  11528. /**
  11529. * 计算二次贝塞尔方程极限值
  11530. * @memberOf module:zrender/core/curve
  11531. * @param {number} p0
  11532. * @param {number} p1
  11533. * @param {number} p2
  11534. * @return {number}
  11535. */
  11536. function quadraticExtremum(p0, p1, p2) {
  11537. var divider = p0 + p2 - 2 * p1;
  11538. if (divider === 0) {
  11539. // p1 is center of p0 and p2
  11540. return 0.5;
  11541. }
  11542. else {
  11543. return (p0 - p1) / divider;
  11544. }
  11545. }
  11546. /**
  11547. * 细分二次贝塞尔曲线
  11548. * @memberOf module:zrender/core/curve
  11549. * @param {number} p0
  11550. * @param {number} p1
  11551. * @param {number} p2
  11552. * @param {number} t
  11553. * @param {Array.<number>} out
  11554. */
  11555. function quadraticSubdivide(p0, p1, p2, t, out) {
  11556. var p01 = (p1 - p0) * t + p0;
  11557. var p12 = (p2 - p1) * t + p1;
  11558. var p012 = (p12 - p01) * t + p01;
  11559. // Seg0
  11560. out[0] = p0;
  11561. out[1] = p01;
  11562. out[2] = p012;
  11563. // Seg1
  11564. out[3] = p012;
  11565. out[4] = p12;
  11566. out[5] = p2;
  11567. }
  11568. /**
  11569. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11570. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11571. * @param {number} x0
  11572. * @param {number} y0
  11573. * @param {number} x1
  11574. * @param {number} y1
  11575. * @param {number} x2
  11576. * @param {number} y2
  11577. * @param {number} x
  11578. * @param {number} y
  11579. * @param {Array.<number>} out 投射点
  11580. * @return {number}
  11581. */
  11582. function quadraticProjectPoint(
  11583. x0, y0, x1, y1, x2, y2,
  11584. x, y, out
  11585. ) {
  11586. // http://pomax.github.io/bezierinfo/#projections
  11587. var t;
  11588. var interval = 0.005;
  11589. var d = Infinity;
  11590. _v0[0] = x;
  11591. _v0[1] = y;
  11592. // 先粗略估计一下可能的最小距离的 t 值
  11593. // PENDING
  11594. for (var _t = 0; _t < 1; _t += 0.05) {
  11595. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11596. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11597. var d1 = distSquare(_v0, _v1);
  11598. if (d1 < d) {
  11599. t = _t;
  11600. d = d1;
  11601. }
  11602. }
  11603. d = Infinity;
  11604. // At most 32 iteration
  11605. for (var i = 0; i < 32; i++) {
  11606. if (interval < EPSILON_NUMERIC) {
  11607. break;
  11608. }
  11609. var prev = t - interval;
  11610. var next = t + interval;
  11611. // t - interval
  11612. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11613. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11614. var d1 = distSquare(_v1, _v0);
  11615. if (prev >= 0 && d1 < d) {
  11616. t = prev;
  11617. d = d1;
  11618. }
  11619. else {
  11620. // t + interval
  11621. _v2[0] = quadraticAt(x0, x1, x2, next);
  11622. _v2[1] = quadraticAt(y0, y1, y2, next);
  11623. var d2 = distSquare(_v2, _v0);
  11624. if (next <= 1 && d2 < d) {
  11625. t = next;
  11626. d = d2;
  11627. }
  11628. else {
  11629. interval *= 0.5;
  11630. }
  11631. }
  11632. }
  11633. // t
  11634. if (out) {
  11635. out[0] = quadraticAt(x0, x1, x2, t);
  11636. out[1] = quadraticAt(y0, y1, y2, t);
  11637. }
  11638. // console.log(interval, i);
  11639. return mathSqrt$2(d);
  11640. }
  11641. /**
  11642. * @author Yi Shen(https://github.com/pissang)
  11643. */
  11644. var mathMin$3 = Math.min;
  11645. var mathMax$3 = Math.max;
  11646. var mathSin$2 = Math.sin;
  11647. var mathCos$2 = Math.cos;
  11648. var PI2 = Math.PI * 2;
  11649. var start = create();
  11650. var end = create();
  11651. var extremity = create();
  11652. /**
  11653. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11654. * @module zrender/core/bbox
  11655. * @param {Array<Object>} points 顶点数组
  11656. * @param {number} min
  11657. * @param {number} max
  11658. */
  11659. function fromPoints(points, min$$1, max$$1) {
  11660. if (points.length === 0) {
  11661. return;
  11662. }
  11663. var p = points[0];
  11664. var left = p[0];
  11665. var right = p[0];
  11666. var top = p[1];
  11667. var bottom = p[1];
  11668. var i;
  11669. for (i = 1; i < points.length; i++) {
  11670. p = points[i];
  11671. left = mathMin$3(left, p[0]);
  11672. right = mathMax$3(right, p[0]);
  11673. top = mathMin$3(top, p[1]);
  11674. bottom = mathMax$3(bottom, p[1]);
  11675. }
  11676. min$$1[0] = left;
  11677. min$$1[1] = top;
  11678. max$$1[0] = right;
  11679. max$$1[1] = bottom;
  11680. }
  11681. /**
  11682. * @memberOf module:zrender/core/bbox
  11683. * @param {number} x0
  11684. * @param {number} y0
  11685. * @param {number} x1
  11686. * @param {number} y1
  11687. * @param {Array.<number>} min
  11688. * @param {Array.<number>} max
  11689. */
  11690. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11691. min$$1[0] = mathMin$3(x0, x1);
  11692. min$$1[1] = mathMin$3(y0, y1);
  11693. max$$1[0] = mathMax$3(x0, x1);
  11694. max$$1[1] = mathMax$3(y0, y1);
  11695. }
  11696. var xDim = [];
  11697. var yDim = [];
  11698. /**
  11699. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11700. * @memberOf module:zrender/core/bbox
  11701. * @param {number} x0
  11702. * @param {number} y0
  11703. * @param {number} x1
  11704. * @param {number} y1
  11705. * @param {number} x2
  11706. * @param {number} y2
  11707. * @param {number} x3
  11708. * @param {number} y3
  11709. * @param {Array.<number>} min
  11710. * @param {Array.<number>} max
  11711. */
  11712. function fromCubic(
  11713. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11714. ) {
  11715. var cubicExtrema$$1 = cubicExtrema;
  11716. var cubicAt$$1 = cubicAt;
  11717. var i;
  11718. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11719. min$$1[0] = Infinity;
  11720. min$$1[1] = Infinity;
  11721. max$$1[0] = -Infinity;
  11722. max$$1[1] = -Infinity;
  11723. for (i = 0; i < n; i++) {
  11724. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11725. min$$1[0] = mathMin$3(x, min$$1[0]);
  11726. max$$1[0] = mathMax$3(x, max$$1[0]);
  11727. }
  11728. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11729. for (i = 0; i < n; i++) {
  11730. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11731. min$$1[1] = mathMin$3(y, min$$1[1]);
  11732. max$$1[1] = mathMax$3(y, max$$1[1]);
  11733. }
  11734. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11735. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11736. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11737. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11738. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11739. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11740. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11741. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11742. }
  11743. /**
  11744. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11745. * @memberOf module:zrender/core/bbox
  11746. * @param {number} x0
  11747. * @param {number} y0
  11748. * @param {number} x1
  11749. * @param {number} y1
  11750. * @param {number} x2
  11751. * @param {number} y2
  11752. * @param {Array.<number>} min
  11753. * @param {Array.<number>} max
  11754. */
  11755. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11756. var quadraticExtremum$$1 = quadraticExtremum;
  11757. var quadraticAt$$1 = quadraticAt;
  11758. // Find extremities, where derivative in x dim or y dim is zero
  11759. var tx =
  11760. mathMax$3(
  11761. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11762. );
  11763. var ty =
  11764. mathMax$3(
  11765. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11766. );
  11767. var x = quadraticAt$$1(x0, x1, x2, tx);
  11768. var y = quadraticAt$$1(y0, y1, y2, ty);
  11769. min$$1[0] = mathMin$3(x0, x2, x);
  11770. min$$1[1] = mathMin$3(y0, y2, y);
  11771. max$$1[0] = mathMax$3(x0, x2, x);
  11772. max$$1[1] = mathMax$3(y0, y2, y);
  11773. }
  11774. /**
  11775. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11776. * @method
  11777. * @memberOf module:zrender/core/bbox
  11778. * @param {number} x
  11779. * @param {number} y
  11780. * @param {number} rx
  11781. * @param {number} ry
  11782. * @param {number} startAngle
  11783. * @param {number} endAngle
  11784. * @param {number} anticlockwise
  11785. * @param {Array.<number>} min
  11786. * @param {Array.<number>} max
  11787. */
  11788. function fromArc(
  11789. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11790. ) {
  11791. var vec2Min = min;
  11792. var vec2Max = max;
  11793. var diff = Math.abs(startAngle - endAngle);
  11794. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11795. // Is a circle
  11796. min$$1[0] = x - rx;
  11797. min$$1[1] = y - ry;
  11798. max$$1[0] = x + rx;
  11799. max$$1[1] = y + ry;
  11800. return;
  11801. }
  11802. start[0] = mathCos$2(startAngle) * rx + x;
  11803. start[1] = mathSin$2(startAngle) * ry + y;
  11804. end[0] = mathCos$2(endAngle) * rx + x;
  11805. end[1] = mathSin$2(endAngle) * ry + y;
  11806. vec2Min(min$$1, start, end);
  11807. vec2Max(max$$1, start, end);
  11808. // Thresh to [0, Math.PI * 2]
  11809. startAngle = startAngle % (PI2);
  11810. if (startAngle < 0) {
  11811. startAngle = startAngle + PI2;
  11812. }
  11813. endAngle = endAngle % (PI2);
  11814. if (endAngle < 0) {
  11815. endAngle = endAngle + PI2;
  11816. }
  11817. if (startAngle > endAngle && !anticlockwise) {
  11818. endAngle += PI2;
  11819. }
  11820. else if (startAngle < endAngle && anticlockwise) {
  11821. startAngle += PI2;
  11822. }
  11823. if (anticlockwise) {
  11824. var tmp = endAngle;
  11825. endAngle = startAngle;
  11826. startAngle = tmp;
  11827. }
  11828. // var number = 0;
  11829. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11830. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11831. if (angle > startAngle) {
  11832. extremity[0] = mathCos$2(angle) * rx + x;
  11833. extremity[1] = mathSin$2(angle) * ry + y;
  11834. vec2Min(min$$1, extremity, min$$1);
  11835. vec2Max(max$$1, extremity, max$$1);
  11836. }
  11837. }
  11838. }
  11839. /**
  11840. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11841. * 可以用于 isInsidePath 判断以及获取boundingRect
  11842. *
  11843. * @module zrender/core/PathProxy
  11844. * @author Yi Shen (http://www.github.com/pissang)
  11845. */
  11846. // TODO getTotalLength, getPointAtLength
  11847. /* global Float32Array */
  11848. var CMD = {
  11849. M: 1,
  11850. L: 2,
  11851. C: 3,
  11852. Q: 4,
  11853. A: 5,
  11854. Z: 6,
  11855. // Rect
  11856. R: 7
  11857. };
  11858. // var CMD_MEM_SIZE = {
  11859. // M: 3,
  11860. // L: 3,
  11861. // C: 7,
  11862. // Q: 5,
  11863. // A: 9,
  11864. // R: 5,
  11865. // Z: 1
  11866. // };
  11867. var min$1 = [];
  11868. var max$1 = [];
  11869. var min2 = [];
  11870. var max2 = [];
  11871. var mathMin$2 = Math.min;
  11872. var mathMax$2 = Math.max;
  11873. var mathCos$1 = Math.cos;
  11874. var mathSin$1 = Math.sin;
  11875. var mathSqrt$1 = Math.sqrt;
  11876. var mathAbs = Math.abs;
  11877. var hasTypedArray = typeof Float32Array !== 'undefined';
  11878. /**
  11879. * @alias module:zrender/core/PathProxy
  11880. * @constructor
  11881. */
  11882. var PathProxy = function (notSaveData) {
  11883. this._saveData = !(notSaveData || false);
  11884. if (this._saveData) {
  11885. /**
  11886. * Path data. Stored as flat array
  11887. * @type {Array.<Object>}
  11888. */
  11889. this.data = [];
  11890. }
  11891. this._ctx = null;
  11892. };
  11893. /**
  11894. * 快速计算Path包围盒(并不是最小包围盒)
  11895. * @return {Object}
  11896. */
  11897. PathProxy.prototype = {
  11898. constructor: PathProxy,
  11899. _xi: 0,
  11900. _yi: 0,
  11901. _x0: 0,
  11902. _y0: 0,
  11903. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11904. _ux: 0,
  11905. _uy: 0,
  11906. _len: 0,
  11907. _lineDash: null,
  11908. _dashOffset: 0,
  11909. _dashIdx: 0,
  11910. _dashSum: 0,
  11911. /**
  11912. * @readOnly
  11913. */
  11914. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11915. // Compat. Previously there is no segmentIgnoreThreshold.
  11916. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11917. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11918. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11919. },
  11920. getContext: function () {
  11921. return this._ctx;
  11922. },
  11923. /**
  11924. * @param {CanvasRenderingContext2D} ctx
  11925. * @return {module:zrender/core/PathProxy}
  11926. */
  11927. beginPath: function (ctx) {
  11928. this._ctx = ctx;
  11929. ctx && ctx.beginPath();
  11930. ctx && (this.dpr = ctx.dpr);
  11931. // Reset
  11932. if (this._saveData) {
  11933. this._len = 0;
  11934. }
  11935. if (this._lineDash) {
  11936. this._lineDash = null;
  11937. this._dashOffset = 0;
  11938. }
  11939. return this;
  11940. },
  11941. /**
  11942. * @param {number} x
  11943. * @param {number} y
  11944. * @return {module:zrender/core/PathProxy}
  11945. */
  11946. moveTo: function (x, y) {
  11947. this.addData(CMD.M, x, y);
  11948. this._ctx && this._ctx.moveTo(x, y);
  11949. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11950. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11951. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11952. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11953. this._x0 = x;
  11954. this._y0 = y;
  11955. this._xi = x;
  11956. this._yi = y;
  11957. return this;
  11958. },
  11959. /**
  11960. * @param {number} x
  11961. * @param {number} y
  11962. * @return {module:zrender/core/PathProxy}
  11963. */
  11964. lineTo: function (x, y) {
  11965. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11966. || mathAbs(y - this._yi) > this._uy
  11967. // Force draw the first segment
  11968. || this._len < 5;
  11969. this.addData(CMD.L, x, y);
  11970. if (this._ctx && exceedUnit) {
  11971. this._needsDash() ? this._dashedLineTo(x, y)
  11972. : this._ctx.lineTo(x, y);
  11973. }
  11974. if (exceedUnit) {
  11975. this._xi = x;
  11976. this._yi = y;
  11977. }
  11978. return this;
  11979. },
  11980. /**
  11981. * @param {number} x1
  11982. * @param {number} y1
  11983. * @param {number} x2
  11984. * @param {number} y2
  11985. * @param {number} x3
  11986. * @param {number} y3
  11987. * @return {module:zrender/core/PathProxy}
  11988. */
  11989. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11990. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11991. if (this._ctx) {
  11992. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11993. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11994. }
  11995. this._xi = x3;
  11996. this._yi = y3;
  11997. return this;
  11998. },
  11999. /**
  12000. * @param {number} x1
  12001. * @param {number} y1
  12002. * @param {number} x2
  12003. * @param {number} y2
  12004. * @return {module:zrender/core/PathProxy}
  12005. */
  12006. quadraticCurveTo: function (x1, y1, x2, y2) {
  12007. this.addData(CMD.Q, x1, y1, x2, y2);
  12008. if (this._ctx) {
  12009. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  12010. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  12011. }
  12012. this._xi = x2;
  12013. this._yi = y2;
  12014. return this;
  12015. },
  12016. /**
  12017. * @param {number} cx
  12018. * @param {number} cy
  12019. * @param {number} r
  12020. * @param {number} startAngle
  12021. * @param {number} endAngle
  12022. * @param {boolean} anticlockwise
  12023. * @return {module:zrender/core/PathProxy}
  12024. */
  12025. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  12026. this.addData(
  12027. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  12028. );
  12029. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  12030. this._xi = mathCos$1(endAngle) * r + cx;
  12031. this._yi = mathSin$1(endAngle) * r + cy;
  12032. return this;
  12033. },
  12034. // TODO
  12035. arcTo: function (x1, y1, x2, y2, radius) {
  12036. if (this._ctx) {
  12037. this._ctx.arcTo(x1, y1, x2, y2, radius);
  12038. }
  12039. return this;
  12040. },
  12041. // TODO
  12042. rect: function (x, y, w, h) {
  12043. this._ctx && this._ctx.rect(x, y, w, h);
  12044. this.addData(CMD.R, x, y, w, h);
  12045. return this;
  12046. },
  12047. /**
  12048. * @return {module:zrender/core/PathProxy}
  12049. */
  12050. closePath: function () {
  12051. this.addData(CMD.Z);
  12052. var ctx = this._ctx;
  12053. var x0 = this._x0;
  12054. var y0 = this._y0;
  12055. if (ctx) {
  12056. this._needsDash() && this._dashedLineTo(x0, y0);
  12057. ctx.closePath();
  12058. }
  12059. this._xi = x0;
  12060. this._yi = y0;
  12061. return this;
  12062. },
  12063. /**
  12064. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12065. * stroke 同样
  12066. * @param {CanvasRenderingContext2D} ctx
  12067. * @return {module:zrender/core/PathProxy}
  12068. */
  12069. fill: function (ctx) {
  12070. ctx && ctx.fill();
  12071. this.toStatic();
  12072. },
  12073. /**
  12074. * @param {CanvasRenderingContext2D} ctx
  12075. * @return {module:zrender/core/PathProxy}
  12076. */
  12077. stroke: function (ctx) {
  12078. ctx && ctx.stroke();
  12079. this.toStatic();
  12080. },
  12081. /**
  12082. * 必须在其它绘制命令前调用
  12083. * Must be invoked before all other path drawing methods
  12084. * @return {module:zrender/core/PathProxy}
  12085. */
  12086. setLineDash: function (lineDash) {
  12087. if (lineDash instanceof Array) {
  12088. this._lineDash = lineDash;
  12089. this._dashIdx = 0;
  12090. var lineDashSum = 0;
  12091. for (var i = 0; i < lineDash.length; i++) {
  12092. lineDashSum += lineDash[i];
  12093. }
  12094. this._dashSum = lineDashSum;
  12095. }
  12096. return this;
  12097. },
  12098. /**
  12099. * 必须在其它绘制命令前调用
  12100. * Must be invoked before all other path drawing methods
  12101. * @return {module:zrender/core/PathProxy}
  12102. */
  12103. setLineDashOffset: function (offset) {
  12104. this._dashOffset = offset;
  12105. return this;
  12106. },
  12107. /**
  12108. *
  12109. * @return {boolean}
  12110. */
  12111. len: function () {
  12112. return this._len;
  12113. },
  12114. /**
  12115. * 直接设置 Path 数据
  12116. */
  12117. setData: function (data) {
  12118. var len$$1 = data.length;
  12119. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12120. this.data = new Float32Array(len$$1);
  12121. }
  12122. for (var i = 0; i < len$$1; i++) {
  12123. this.data[i] = data[i];
  12124. }
  12125. this._len = len$$1;
  12126. },
  12127. /**
  12128. * 添加子路径
  12129. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12130. */
  12131. appendPath: function (path) {
  12132. if (!(path instanceof Array)) {
  12133. path = [path];
  12134. }
  12135. var len$$1 = path.length;
  12136. var appendSize = 0;
  12137. var offset = this._len;
  12138. for (var i = 0; i < len$$1; i++) {
  12139. appendSize += path[i].len();
  12140. }
  12141. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12142. this.data = new Float32Array(offset + appendSize);
  12143. }
  12144. for (var i = 0; i < len$$1; i++) {
  12145. var appendPathData = path[i].data;
  12146. for (var k = 0; k < appendPathData.length; k++) {
  12147. this.data[offset++] = appendPathData[k];
  12148. }
  12149. }
  12150. this._len = offset;
  12151. },
  12152. /**
  12153. * 填充 Path 数据。
  12154. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12155. */
  12156. addData: function (cmd) {
  12157. if (!this._saveData) {
  12158. return;
  12159. }
  12160. var data = this.data;
  12161. if (this._len + arguments.length > data.length) {
  12162. // 因为之前的数组已经转换成静态的 Float32Array
  12163. // 所以不够用时需要扩展一个新的动态数组
  12164. this._expandData();
  12165. data = this.data;
  12166. }
  12167. for (var i = 0; i < arguments.length; i++) {
  12168. data[this._len++] = arguments[i];
  12169. }
  12170. this._prevCmd = cmd;
  12171. },
  12172. _expandData: function () {
  12173. // Only if data is Float32Array
  12174. if (!(this.data instanceof Array)) {
  12175. var newData = [];
  12176. for (var i = 0; i < this._len; i++) {
  12177. newData[i] = this.data[i];
  12178. }
  12179. this.data = newData;
  12180. }
  12181. },
  12182. /**
  12183. * If needs js implemented dashed line
  12184. * @return {boolean}
  12185. * @private
  12186. */
  12187. _needsDash: function () {
  12188. return this._lineDash;
  12189. },
  12190. _dashedLineTo: function (x1, y1) {
  12191. var dashSum = this._dashSum;
  12192. var offset = this._dashOffset;
  12193. var lineDash = this._lineDash;
  12194. var ctx = this._ctx;
  12195. var x0 = this._xi;
  12196. var y0 = this._yi;
  12197. var dx = x1 - x0;
  12198. var dy = y1 - y0;
  12199. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12200. var x = x0;
  12201. var y = y0;
  12202. var dash;
  12203. var nDash = lineDash.length;
  12204. var idx;
  12205. dx /= dist$$1;
  12206. dy /= dist$$1;
  12207. if (offset < 0) {
  12208. // Convert to positive offset
  12209. offset = dashSum + offset;
  12210. }
  12211. offset %= dashSum;
  12212. x -= offset * dx;
  12213. y -= offset * dy;
  12214. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12215. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12216. idx = this._dashIdx;
  12217. dash = lineDash[idx];
  12218. x += dx * dash;
  12219. y += dy * dash;
  12220. this._dashIdx = (idx + 1) % nDash;
  12221. // Skip positive offset
  12222. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12223. continue;
  12224. }
  12225. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12226. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12227. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12228. );
  12229. }
  12230. // Offset for next lineTo
  12231. dx = x - x1;
  12232. dy = y - y1;
  12233. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12234. },
  12235. // Not accurate dashed line to
  12236. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12237. var dashSum = this._dashSum;
  12238. var offset = this._dashOffset;
  12239. var lineDash = this._lineDash;
  12240. var ctx = this._ctx;
  12241. var x0 = this._xi;
  12242. var y0 = this._yi;
  12243. var t;
  12244. var dx;
  12245. var dy;
  12246. var cubicAt$$1 = cubicAt;
  12247. var bezierLen = 0;
  12248. var idx = this._dashIdx;
  12249. var nDash = lineDash.length;
  12250. var x;
  12251. var y;
  12252. var tmpLen = 0;
  12253. if (offset < 0) {
  12254. // Convert to positive offset
  12255. offset = dashSum + offset;
  12256. }
  12257. offset %= dashSum;
  12258. // Bezier approx length
  12259. for (t = 0; t < 1; t += 0.1) {
  12260. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12261. - cubicAt$$1(x0, x1, x2, x3, t);
  12262. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12263. - cubicAt$$1(y0, y1, y2, y3, t);
  12264. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12265. }
  12266. // Find idx after add offset
  12267. for (; idx < nDash; idx++) {
  12268. tmpLen += lineDash[idx];
  12269. if (tmpLen > offset) {
  12270. break;
  12271. }
  12272. }
  12273. t = (tmpLen - offset) / bezierLen;
  12274. while (t <= 1) {
  12275. x = cubicAt$$1(x0, x1, x2, x3, t);
  12276. y = cubicAt$$1(y0, y1, y2, y3, t);
  12277. // Use line to approximate dashed bezier
  12278. // Bad result if dash is long
  12279. idx % 2 ? ctx.moveTo(x, y)
  12280. : ctx.lineTo(x, y);
  12281. t += lineDash[idx] / bezierLen;
  12282. idx = (idx + 1) % nDash;
  12283. }
  12284. // Finish the last segment and calculate the new offset
  12285. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12286. dx = x3 - x;
  12287. dy = y3 - y;
  12288. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12289. },
  12290. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12291. // Convert quadratic to cubic using degree elevation
  12292. var x3 = x2;
  12293. var y3 = y2;
  12294. x2 = (x2 + 2 * x1) / 3;
  12295. y2 = (y2 + 2 * y1) / 3;
  12296. x1 = (this._xi + 2 * x1) / 3;
  12297. y1 = (this._yi + 2 * y1) / 3;
  12298. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12299. },
  12300. /**
  12301. * 转成静态的 Float32Array 减少堆内存占用
  12302. * Convert dynamic array to static Float32Array
  12303. */
  12304. toStatic: function () {
  12305. var data = this.data;
  12306. if (data instanceof Array) {
  12307. data.length = this._len;
  12308. if (hasTypedArray) {
  12309. this.data = new Float32Array(data);
  12310. }
  12311. }
  12312. },
  12313. /**
  12314. * @return {module:zrender/core/BoundingRect}
  12315. */
  12316. getBoundingRect: function () {
  12317. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12318. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12319. var data = this.data;
  12320. var xi = 0;
  12321. var yi = 0;
  12322. var x0 = 0;
  12323. var y0 = 0;
  12324. for (var i = 0; i < data.length;) {
  12325. var cmd = data[i++];
  12326. if (i === 1) {
  12327. // 如果第一个命令是 L, C, Q
  12328. // 则 previous point 同绘制命令的第一个 point
  12329. //
  12330. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12331. xi = data[i];
  12332. yi = data[i + 1];
  12333. x0 = xi;
  12334. y0 = yi;
  12335. }
  12336. switch (cmd) {
  12337. case CMD.M:
  12338. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12339. // 在 closePath 的时候使用
  12340. x0 = data[i++];
  12341. y0 = data[i++];
  12342. xi = x0;
  12343. yi = y0;
  12344. min2[0] = x0;
  12345. min2[1] = y0;
  12346. max2[0] = x0;
  12347. max2[1] = y0;
  12348. break;
  12349. case CMD.L:
  12350. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12351. xi = data[i++];
  12352. yi = data[i++];
  12353. break;
  12354. case CMD.C:
  12355. fromCubic(
  12356. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12357. min2, max2
  12358. );
  12359. xi = data[i++];
  12360. yi = data[i++];
  12361. break;
  12362. case CMD.Q:
  12363. fromQuadratic(
  12364. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12365. min2, max2
  12366. );
  12367. xi = data[i++];
  12368. yi = data[i++];
  12369. break;
  12370. case CMD.A:
  12371. // TODO Arc 判断的开销比较大
  12372. var cx = data[i++];
  12373. var cy = data[i++];
  12374. var rx = data[i++];
  12375. var ry = data[i++];
  12376. var startAngle = data[i++];
  12377. var endAngle = data[i++] + startAngle;
  12378. // TODO Arc 旋转
  12379. i += 1;
  12380. var anticlockwise = 1 - data[i++];
  12381. if (i === 1) {
  12382. // 直接使用 arc 命令
  12383. // 第一个命令起点还未定义
  12384. x0 = mathCos$1(startAngle) * rx + cx;
  12385. y0 = mathSin$1(startAngle) * ry + cy;
  12386. }
  12387. fromArc(
  12388. cx, cy, rx, ry, startAngle, endAngle,
  12389. anticlockwise, min2, max2
  12390. );
  12391. xi = mathCos$1(endAngle) * rx + cx;
  12392. yi = mathSin$1(endAngle) * ry + cy;
  12393. break;
  12394. case CMD.R:
  12395. x0 = xi = data[i++];
  12396. y0 = yi = data[i++];
  12397. var width = data[i++];
  12398. var height = data[i++];
  12399. // Use fromLine
  12400. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12401. break;
  12402. case CMD.Z:
  12403. xi = x0;
  12404. yi = y0;
  12405. break;
  12406. }
  12407. // Union
  12408. min(min$1, min$1, min2);
  12409. max(max$1, max$1, max2);
  12410. }
  12411. // No data
  12412. if (i === 0) {
  12413. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12414. }
  12415. return new BoundingRect(
  12416. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12417. );
  12418. },
  12419. /**
  12420. * Rebuild path from current data
  12421. * Rebuild path will not consider javascript implemented line dash.
  12422. * @param {CanvasRenderingContext2D} ctx
  12423. */
  12424. rebuildPath: function (ctx) {
  12425. var d = this.data;
  12426. var x0;
  12427. var y0;
  12428. var xi;
  12429. var yi;
  12430. var x;
  12431. var y;
  12432. var ux = this._ux;
  12433. var uy = this._uy;
  12434. var len$$1 = this._len;
  12435. for (var i = 0; i < len$$1;) {
  12436. var cmd = d[i++];
  12437. if (i === 1) {
  12438. // 如果第一个命令是 L, C, Q
  12439. // 则 previous point 同绘制命令的第一个 point
  12440. //
  12441. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12442. xi = d[i];
  12443. yi = d[i + 1];
  12444. x0 = xi;
  12445. y0 = yi;
  12446. }
  12447. switch (cmd) {
  12448. case CMD.M:
  12449. x0 = xi = d[i++];
  12450. y0 = yi = d[i++];
  12451. ctx.moveTo(xi, yi);
  12452. break;
  12453. case CMD.L:
  12454. x = d[i++];
  12455. y = d[i++];
  12456. // Not draw too small seg between
  12457. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12458. ctx.lineTo(x, y);
  12459. xi = x;
  12460. yi = y;
  12461. }
  12462. break;
  12463. case CMD.C:
  12464. ctx.bezierCurveTo(
  12465. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12466. );
  12467. xi = d[i - 2];
  12468. yi = d[i - 1];
  12469. break;
  12470. case CMD.Q:
  12471. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12472. xi = d[i - 2];
  12473. yi = d[i - 1];
  12474. break;
  12475. case CMD.A:
  12476. var cx = d[i++];
  12477. var cy = d[i++];
  12478. var rx = d[i++];
  12479. var ry = d[i++];
  12480. var theta = d[i++];
  12481. var dTheta = d[i++];
  12482. var psi = d[i++];
  12483. var fs = d[i++];
  12484. var r = (rx > ry) ? rx : ry;
  12485. var scaleX = (rx > ry) ? 1 : rx / ry;
  12486. var scaleY = (rx > ry) ? ry / rx : 1;
  12487. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12488. var endAngle = theta + dTheta;
  12489. if (isEllipse) {
  12490. ctx.translate(cx, cy);
  12491. ctx.rotate(psi);
  12492. ctx.scale(scaleX, scaleY);
  12493. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12494. ctx.scale(1 / scaleX, 1 / scaleY);
  12495. ctx.rotate(-psi);
  12496. ctx.translate(-cx, -cy);
  12497. }
  12498. else {
  12499. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12500. }
  12501. if (i === 1) {
  12502. // 直接使用 arc 命令
  12503. // 第一个命令起点还未定义
  12504. x0 = mathCos$1(theta) * rx + cx;
  12505. y0 = mathSin$1(theta) * ry + cy;
  12506. }
  12507. xi = mathCos$1(endAngle) * rx + cx;
  12508. yi = mathSin$1(endAngle) * ry + cy;
  12509. break;
  12510. case CMD.R:
  12511. x0 = xi = d[i];
  12512. y0 = yi = d[i + 1];
  12513. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12514. break;
  12515. case CMD.Z:
  12516. ctx.closePath();
  12517. xi = x0;
  12518. yi = y0;
  12519. }
  12520. }
  12521. }
  12522. };
  12523. PathProxy.CMD = CMD;
  12524. /**
  12525. * 线段包含判断
  12526. * @param {number} x0
  12527. * @param {number} y0
  12528. * @param {number} x1
  12529. * @param {number} y1
  12530. * @param {number} lineWidth
  12531. * @param {number} x
  12532. * @param {number} y
  12533. * @return {boolean}
  12534. */
  12535. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12536. if (lineWidth === 0) {
  12537. return false;
  12538. }
  12539. var _l = lineWidth;
  12540. var _a = 0;
  12541. var _b = x0;
  12542. // Quick reject
  12543. if (
  12544. (y > y0 + _l && y > y1 + _l)
  12545. || (y < y0 - _l && y < y1 - _l)
  12546. || (x > x0 + _l && x > x1 + _l)
  12547. || (x < x0 - _l && x < x1 - _l)
  12548. ) {
  12549. return false;
  12550. }
  12551. if (x0 !== x1) {
  12552. _a = (y0 - y1) / (x0 - x1);
  12553. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12554. }
  12555. else {
  12556. return Math.abs(x - x0) <= _l / 2;
  12557. }
  12558. var tmp = _a * x - y + _b;
  12559. var _s = tmp * tmp / (_a * _a + 1);
  12560. return _s <= _l / 2 * _l / 2;
  12561. }
  12562. /**
  12563. * 三次贝塞尔曲线描边包含判断
  12564. * @param {number} x0
  12565. * @param {number} y0
  12566. * @param {number} x1
  12567. * @param {number} y1
  12568. * @param {number} x2
  12569. * @param {number} y2
  12570. * @param {number} x3
  12571. * @param {number} y3
  12572. * @param {number} lineWidth
  12573. * @param {number} x
  12574. * @param {number} y
  12575. * @return {boolean}
  12576. */
  12577. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12578. if (lineWidth === 0) {
  12579. return false;
  12580. }
  12581. var _l = lineWidth;
  12582. // Quick reject
  12583. if (
  12584. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12585. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12586. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12587. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12588. ) {
  12589. return false;
  12590. }
  12591. var d = cubicProjectPoint(
  12592. x0, y0, x1, y1, x2, y2, x3, y3,
  12593. x, y, null
  12594. );
  12595. return d <= _l / 2;
  12596. }
  12597. /**
  12598. * 二次贝塞尔曲线描边包含判断
  12599. * @param {number} x0
  12600. * @param {number} y0
  12601. * @param {number} x1
  12602. * @param {number} y1
  12603. * @param {number} x2
  12604. * @param {number} y2
  12605. * @param {number} lineWidth
  12606. * @param {number} x
  12607. * @param {number} y
  12608. * @return {boolean}
  12609. */
  12610. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12611. if (lineWidth === 0) {
  12612. return false;
  12613. }
  12614. var _l = lineWidth;
  12615. // Quick reject
  12616. if (
  12617. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12618. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12619. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12620. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12621. ) {
  12622. return false;
  12623. }
  12624. var d = quadraticProjectPoint(
  12625. x0, y0, x1, y1, x2, y2,
  12626. x, y, null
  12627. );
  12628. return d <= _l / 2;
  12629. }
  12630. var PI2$3 = Math.PI * 2;
  12631. function normalizeRadian(angle) {
  12632. angle %= PI2$3;
  12633. if (angle < 0) {
  12634. angle += PI2$3;
  12635. }
  12636. return angle;
  12637. }
  12638. var PI2$2 = Math.PI * 2;
  12639. /**
  12640. * 圆弧描边包含判断
  12641. * @param {number} cx
  12642. * @param {number} cy
  12643. * @param {number} r
  12644. * @param {number} startAngle
  12645. * @param {number} endAngle
  12646. * @param {boolean} anticlockwise
  12647. * @param {number} lineWidth
  12648. * @param {number} x
  12649. * @param {number} y
  12650. * @return {Boolean}
  12651. */
  12652. function containStroke$4(
  12653. cx, cy, r, startAngle, endAngle, anticlockwise,
  12654. lineWidth, x, y
  12655. ) {
  12656. if (lineWidth === 0) {
  12657. return false;
  12658. }
  12659. var _l = lineWidth;
  12660. x -= cx;
  12661. y -= cy;
  12662. var d = Math.sqrt(x * x + y * y);
  12663. if ((d - _l > r) || (d + _l < r)) {
  12664. return false;
  12665. }
  12666. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12667. // Is a circle
  12668. return true;
  12669. }
  12670. if (anticlockwise) {
  12671. var tmp = startAngle;
  12672. startAngle = normalizeRadian(endAngle);
  12673. endAngle = normalizeRadian(tmp);
  12674. }
  12675. else {
  12676. startAngle = normalizeRadian(startAngle);
  12677. endAngle = normalizeRadian(endAngle);
  12678. }
  12679. if (startAngle > endAngle) {
  12680. endAngle += PI2$2;
  12681. }
  12682. var angle = Math.atan2(y, x);
  12683. if (angle < 0) {
  12684. angle += PI2$2;
  12685. }
  12686. return (angle >= startAngle && angle <= endAngle)
  12687. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12688. }
  12689. function windingLine(x0, y0, x1, y1, x, y) {
  12690. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12691. return 0;
  12692. }
  12693. // Ignore horizontal line
  12694. if (y1 === y0) {
  12695. return 0;
  12696. }
  12697. var dir = y1 < y0 ? 1 : -1;
  12698. var t = (y - y0) / (y1 - y0);
  12699. // Avoid winding error when intersection point is the connect point of two line of polygon
  12700. if (t === 1 || t === 0) {
  12701. dir = y1 < y0 ? 0.5 : -0.5;
  12702. }
  12703. var x_ = t * (x1 - x0) + x0;
  12704. // If (x, y) on the line, considered as "contain".
  12705. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12706. }
  12707. var CMD$1 = PathProxy.CMD;
  12708. var PI2$1 = Math.PI * 2;
  12709. var EPSILON$2 = 1e-4;
  12710. function isAroundEqual(a, b) {
  12711. return Math.abs(a - b) < EPSILON$2;
  12712. }
  12713. // 临时数组
  12714. var roots = [-1, -1, -1];
  12715. var extrema = [-1, -1];
  12716. function swapExtrema() {
  12717. var tmp = extrema[0];
  12718. extrema[0] = extrema[1];
  12719. extrema[1] = tmp;
  12720. }
  12721. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12722. // Quick reject
  12723. if (
  12724. (y > y0 && y > y1 && y > y2 && y > y3)
  12725. || (y < y0 && y < y1 && y < y2 && y < y3)
  12726. ) {
  12727. return 0;
  12728. }
  12729. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12730. if (nRoots === 0) {
  12731. return 0;
  12732. }
  12733. else {
  12734. var w = 0;
  12735. var nExtrema = -1;
  12736. var y0_;
  12737. var y1_;
  12738. for (var i = 0; i < nRoots; i++) {
  12739. var t = roots[i];
  12740. // Avoid winding error when intersection point is the connect point of two line of polygon
  12741. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12742. var x_ = cubicAt(x0, x1, x2, x3, t);
  12743. if (x_ < x) { // Quick reject
  12744. continue;
  12745. }
  12746. if (nExtrema < 0) {
  12747. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12748. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12749. swapExtrema();
  12750. }
  12751. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12752. if (nExtrema > 1) {
  12753. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12754. }
  12755. }
  12756. if (nExtrema === 2) {
  12757. // 分成三段单调函数
  12758. if (t < extrema[0]) {
  12759. w += y0_ < y0 ? unit : -unit;
  12760. }
  12761. else if (t < extrema[1]) {
  12762. w += y1_ < y0_ ? unit : -unit;
  12763. }
  12764. else {
  12765. w += y3 < y1_ ? unit : -unit;
  12766. }
  12767. }
  12768. else {
  12769. // 分成两段单调函数
  12770. if (t < extrema[0]) {
  12771. w += y0_ < y0 ? unit : -unit;
  12772. }
  12773. else {
  12774. w += y3 < y0_ ? unit : -unit;
  12775. }
  12776. }
  12777. }
  12778. return w;
  12779. }
  12780. }
  12781. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12782. // Quick reject
  12783. if (
  12784. (y > y0 && y > y1 && y > y2)
  12785. || (y < y0 && y < y1 && y < y2)
  12786. ) {
  12787. return 0;
  12788. }
  12789. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12790. if (nRoots === 0) {
  12791. return 0;
  12792. }
  12793. else {
  12794. var t = quadraticExtremum(y0, y1, y2);
  12795. if (t >= 0 && t <= 1) {
  12796. var w = 0;
  12797. var y_ = quadraticAt(y0, y1, y2, t);
  12798. for (var i = 0; i < nRoots; i++) {
  12799. // Remove one endpoint.
  12800. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12801. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12802. if (x_ < x) { // Quick reject
  12803. continue;
  12804. }
  12805. if (roots[i] < t) {
  12806. w += y_ < y0 ? unit : -unit;
  12807. }
  12808. else {
  12809. w += y2 < y_ ? unit : -unit;
  12810. }
  12811. }
  12812. return w;
  12813. }
  12814. else {
  12815. // Remove one endpoint.
  12816. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12817. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12818. if (x_ < x) { // Quick reject
  12819. return 0;
  12820. }
  12821. return y2 < y0 ? unit : -unit;
  12822. }
  12823. }
  12824. }
  12825. // TODO
  12826. // Arc 旋转
  12827. function windingArc(
  12828. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12829. ) {
  12830. y -= cy;
  12831. if (y > r || y < -r) {
  12832. return 0;
  12833. }
  12834. var tmp = Math.sqrt(r * r - y * y);
  12835. roots[0] = -tmp;
  12836. roots[1] = tmp;
  12837. var diff = Math.abs(startAngle - endAngle);
  12838. if (diff < 1e-4) {
  12839. return 0;
  12840. }
  12841. if (diff % PI2$1 < 1e-4) {
  12842. // Is a circle
  12843. startAngle = 0;
  12844. endAngle = PI2$1;
  12845. var dir = anticlockwise ? 1 : -1;
  12846. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12847. return dir;
  12848. }
  12849. else {
  12850. return 0;
  12851. }
  12852. }
  12853. if (anticlockwise) {
  12854. var tmp = startAngle;
  12855. startAngle = normalizeRadian(endAngle);
  12856. endAngle = normalizeRadian(tmp);
  12857. }
  12858. else {
  12859. startAngle = normalizeRadian(startAngle);
  12860. endAngle = normalizeRadian(endAngle);
  12861. }
  12862. if (startAngle > endAngle) {
  12863. endAngle += PI2$1;
  12864. }
  12865. var w = 0;
  12866. for (var i = 0; i < 2; i++) {
  12867. var x_ = roots[i];
  12868. if (x_ + cx > x) {
  12869. var angle = Math.atan2(y, x_);
  12870. var dir = anticlockwise ? 1 : -1;
  12871. if (angle < 0) {
  12872. angle = PI2$1 + angle;
  12873. }
  12874. if (
  12875. (angle >= startAngle && angle <= endAngle)
  12876. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12877. ) {
  12878. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12879. dir = -dir;
  12880. }
  12881. w += dir;
  12882. }
  12883. }
  12884. }
  12885. return w;
  12886. }
  12887. function containPath(data, lineWidth, isStroke, x, y) {
  12888. var w = 0;
  12889. var xi = 0;
  12890. var yi = 0;
  12891. var x0 = 0;
  12892. var y0 = 0;
  12893. for (var i = 0; i < data.length;) {
  12894. var cmd = data[i++];
  12895. // Begin a new subpath
  12896. if (cmd === CMD$1.M && i > 1) {
  12897. // Close previous subpath
  12898. if (!isStroke) {
  12899. w += windingLine(xi, yi, x0, y0, x, y);
  12900. }
  12901. // 如果被任何一个 subpath 包含
  12902. // if (w !== 0) {
  12903. // return true;
  12904. // }
  12905. }
  12906. if (i === 1) {
  12907. // 如果第一个命令是 L, C, Q
  12908. // 则 previous point 同绘制命令的第一个 point
  12909. //
  12910. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12911. xi = data[i];
  12912. yi = data[i + 1];
  12913. x0 = xi;
  12914. y0 = yi;
  12915. }
  12916. switch (cmd) {
  12917. case CMD$1.M:
  12918. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12919. // 在 closePath 的时候使用
  12920. x0 = data[i++];
  12921. y0 = data[i++];
  12922. xi = x0;
  12923. yi = y0;
  12924. break;
  12925. case CMD$1.L:
  12926. if (isStroke) {
  12927. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12928. return true;
  12929. }
  12930. }
  12931. else {
  12932. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12933. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12934. }
  12935. xi = data[i++];
  12936. yi = data[i++];
  12937. break;
  12938. case CMD$1.C:
  12939. if (isStroke) {
  12940. if (containStroke$2(xi, yi,
  12941. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12942. lineWidth, x, y
  12943. )) {
  12944. return true;
  12945. }
  12946. }
  12947. else {
  12948. w += windingCubic(
  12949. xi, yi,
  12950. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12951. x, y
  12952. ) || 0;
  12953. }
  12954. xi = data[i++];
  12955. yi = data[i++];
  12956. break;
  12957. case CMD$1.Q:
  12958. if (isStroke) {
  12959. if (containStroke$3(xi, yi,
  12960. data[i++], data[i++], data[i], data[i + 1],
  12961. lineWidth, x, y
  12962. )) {
  12963. return true;
  12964. }
  12965. }
  12966. else {
  12967. w += windingQuadratic(
  12968. xi, yi,
  12969. data[i++], data[i++], data[i], data[i + 1],
  12970. x, y
  12971. ) || 0;
  12972. }
  12973. xi = data[i++];
  12974. yi = data[i++];
  12975. break;
  12976. case CMD$1.A:
  12977. // TODO Arc 判断的开销比较大
  12978. var cx = data[i++];
  12979. var cy = data[i++];
  12980. var rx = data[i++];
  12981. var ry = data[i++];
  12982. var theta = data[i++];
  12983. var dTheta = data[i++];
  12984. // TODO Arc 旋转
  12985. i += 1;
  12986. var anticlockwise = 1 - data[i++];
  12987. var x1 = Math.cos(theta) * rx + cx;
  12988. var y1 = Math.sin(theta) * ry + cy;
  12989. // 不是直接使用 arc 命令
  12990. if (i > 1) {
  12991. w += windingLine(xi, yi, x1, y1, x, y);
  12992. }
  12993. else {
  12994. // 第一个命令起点还未定义
  12995. x0 = x1;
  12996. y0 = y1;
  12997. }
  12998. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12999. var _x = (x - cx) * ry / rx + cx;
  13000. if (isStroke) {
  13001. if (containStroke$4(
  13002. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13003. lineWidth, _x, y
  13004. )) {
  13005. return true;
  13006. }
  13007. }
  13008. else {
  13009. w += windingArc(
  13010. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13011. _x, y
  13012. );
  13013. }
  13014. xi = Math.cos(theta + dTheta) * rx + cx;
  13015. yi = Math.sin(theta + dTheta) * ry + cy;
  13016. break;
  13017. case CMD$1.R:
  13018. x0 = xi = data[i++];
  13019. y0 = yi = data[i++];
  13020. var width = data[i++];
  13021. var height = data[i++];
  13022. var x1 = x0 + width;
  13023. var y1 = y0 + height;
  13024. if (isStroke) {
  13025. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  13026. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  13027. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  13028. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  13029. ) {
  13030. return true;
  13031. }
  13032. }
  13033. else {
  13034. // FIXME Clockwise ?
  13035. w += windingLine(x1, y0, x1, y1, x, y);
  13036. w += windingLine(x0, y1, x0, y0, x, y);
  13037. }
  13038. break;
  13039. case CMD$1.Z:
  13040. if (isStroke) {
  13041. if (containStroke$1(
  13042. xi, yi, x0, y0, lineWidth, x, y
  13043. )) {
  13044. return true;
  13045. }
  13046. }
  13047. else {
  13048. // Close a subpath
  13049. w += windingLine(xi, yi, x0, y0, x, y);
  13050. // 如果被任何一个 subpath 包含
  13051. // FIXME subpaths may overlap
  13052. // if (w !== 0) {
  13053. // return true;
  13054. // }
  13055. }
  13056. xi = x0;
  13057. yi = y0;
  13058. break;
  13059. }
  13060. }
  13061. if (!isStroke && !isAroundEqual(yi, y0)) {
  13062. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13063. }
  13064. return w !== 0;
  13065. }
  13066. function contain(pathData, x, y) {
  13067. return containPath(pathData, 0, false, x, y);
  13068. }
  13069. function containStroke(pathData, lineWidth, x, y) {
  13070. return containPath(pathData, lineWidth, true, x, y);
  13071. }
  13072. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13073. var abs = Math.abs;
  13074. var pathProxyForDraw = new PathProxy(true);
  13075. /**
  13076. * @alias module:zrender/graphic/Path
  13077. * @extends module:zrender/graphic/Displayable
  13078. * @constructor
  13079. * @param {Object} opts
  13080. */
  13081. function Path(opts) {
  13082. Displayable.call(this, opts);
  13083. /**
  13084. * @type {module:zrender/core/PathProxy}
  13085. * @readOnly
  13086. */
  13087. this.path = null;
  13088. }
  13089. Path.prototype = {
  13090. constructor: Path,
  13091. type: 'path',
  13092. __dirtyPath: true,
  13093. strokeContainThreshold: 5,
  13094. // This item default to be false. But in map series in echarts,
  13095. // in order to improve performance, it should be set to true,
  13096. // so the shorty segment won't draw.
  13097. segmentIgnoreThreshold: 0,
  13098. /**
  13099. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13100. * @type {boolean}
  13101. */
  13102. subPixelOptimize: false,
  13103. brush: function (ctx, prevEl) {
  13104. var style = this.style;
  13105. var path = this.path || pathProxyForDraw;
  13106. var hasStroke = style.hasStroke();
  13107. var hasFill = style.hasFill();
  13108. var fill = style.fill;
  13109. var stroke = style.stroke;
  13110. var hasFillGradient = hasFill && !!(fill.colorStops);
  13111. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13112. var hasFillPattern = hasFill && !!(fill.image);
  13113. var hasStrokePattern = hasStroke && !!(stroke.image);
  13114. style.bind(ctx, this, prevEl);
  13115. this.setTransform(ctx);
  13116. if (this.__dirty) {
  13117. var rect;
  13118. // Update gradient because bounding rect may changed
  13119. if (hasFillGradient) {
  13120. rect = rect || this.getBoundingRect();
  13121. this._fillGradient = style.getGradient(ctx, fill, rect);
  13122. }
  13123. if (hasStrokeGradient) {
  13124. rect = rect || this.getBoundingRect();
  13125. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13126. }
  13127. }
  13128. // Use the gradient or pattern
  13129. if (hasFillGradient) {
  13130. // PENDING If may have affect the state
  13131. ctx.fillStyle = this._fillGradient;
  13132. }
  13133. else if (hasFillPattern) {
  13134. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13135. }
  13136. if (hasStrokeGradient) {
  13137. ctx.strokeStyle = this._strokeGradient;
  13138. }
  13139. else if (hasStrokePattern) {
  13140. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13141. }
  13142. var lineDash = style.lineDash;
  13143. var lineDashOffset = style.lineDashOffset;
  13144. var ctxLineDash = !!ctx.setLineDash;
  13145. // Update path sx, sy
  13146. var scale = this.getGlobalScale();
  13147. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13148. // Proxy context
  13149. // Rebuild path in following 2 cases
  13150. // 1. Path is dirty
  13151. // 2. Path needs javascript implemented lineDash stroking.
  13152. // In this case, lineDash information will not be saved in PathProxy
  13153. if (this.__dirtyPath
  13154. || (lineDash && !ctxLineDash && hasStroke)
  13155. ) {
  13156. path.beginPath(ctx);
  13157. // Setting line dash before build path
  13158. if (lineDash && !ctxLineDash) {
  13159. path.setLineDash(lineDash);
  13160. path.setLineDashOffset(lineDashOffset);
  13161. }
  13162. this.buildPath(path, this.shape, false);
  13163. // Clear path dirty flag
  13164. if (this.path) {
  13165. this.__dirtyPath = false;
  13166. }
  13167. }
  13168. else {
  13169. // Replay path building
  13170. ctx.beginPath();
  13171. this.path.rebuildPath(ctx);
  13172. }
  13173. if (hasFill) {
  13174. if (style.fillOpacity != null) {
  13175. var originalGlobalAlpha = ctx.globalAlpha;
  13176. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13177. path.fill(ctx);
  13178. ctx.globalAlpha = originalGlobalAlpha;
  13179. }
  13180. else {
  13181. path.fill(ctx);
  13182. }
  13183. }
  13184. if (lineDash && ctxLineDash) {
  13185. ctx.setLineDash(lineDash);
  13186. ctx.lineDashOffset = lineDashOffset;
  13187. }
  13188. if (hasStroke) {
  13189. if (style.strokeOpacity != null) {
  13190. var originalGlobalAlpha = ctx.globalAlpha;
  13191. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13192. path.stroke(ctx);
  13193. ctx.globalAlpha = originalGlobalAlpha;
  13194. }
  13195. else {
  13196. path.stroke(ctx);
  13197. }
  13198. }
  13199. if (lineDash && ctxLineDash) {
  13200. // PENDING
  13201. // Remove lineDash
  13202. ctx.setLineDash([]);
  13203. }
  13204. // Draw rect text
  13205. if (style.text != null) {
  13206. // Only restore transform when needs draw text.
  13207. this.restoreTransform(ctx);
  13208. this.drawRectText(ctx, this.getBoundingRect());
  13209. }
  13210. },
  13211. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13212. // Like in circle
  13213. buildPath: function (ctx, shapeCfg, inBundle) {},
  13214. createPathProxy: function () {
  13215. this.path = new PathProxy();
  13216. },
  13217. getBoundingRect: function () {
  13218. var rect = this._rect;
  13219. var style = this.style;
  13220. var needsUpdateRect = !rect;
  13221. if (needsUpdateRect) {
  13222. var path = this.path;
  13223. if (!path) {
  13224. // Create path on demand.
  13225. path = this.path = new PathProxy();
  13226. }
  13227. if (this.__dirtyPath) {
  13228. path.beginPath();
  13229. this.buildPath(path, this.shape, false);
  13230. }
  13231. rect = path.getBoundingRect();
  13232. }
  13233. this._rect = rect;
  13234. if (style.hasStroke()) {
  13235. // Needs update rect with stroke lineWidth when
  13236. // 1. Element changes scale or lineWidth
  13237. // 2. Shape is changed
  13238. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13239. if (this.__dirty || needsUpdateRect) {
  13240. rectWithStroke.copy(rect);
  13241. // FIXME Must after updateTransform
  13242. var w = style.lineWidth;
  13243. // PENDING, Min line width is needed when line is horizontal or vertical
  13244. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13245. // Only add extra hover lineWidth when there are no fill
  13246. if (!style.hasFill()) {
  13247. w = Math.max(w, this.strokeContainThreshold || 4);
  13248. }
  13249. // Consider line width
  13250. // Line scale can't be 0;
  13251. if (lineScale > 1e-10) {
  13252. rectWithStroke.width += w / lineScale;
  13253. rectWithStroke.height += w / lineScale;
  13254. rectWithStroke.x -= w / lineScale / 2;
  13255. rectWithStroke.y -= w / lineScale / 2;
  13256. }
  13257. }
  13258. // Return rect with stroke
  13259. return rectWithStroke;
  13260. }
  13261. return rect;
  13262. },
  13263. contain: function (x, y) {
  13264. var localPos = this.transformCoordToLocal(x, y);
  13265. var rect = this.getBoundingRect();
  13266. var style = this.style;
  13267. x = localPos[0];
  13268. y = localPos[1];
  13269. if (rect.contain(x, y)) {
  13270. var pathData = this.path.data;
  13271. if (style.hasStroke()) {
  13272. var lineWidth = style.lineWidth;
  13273. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13274. // Line scale can't be 0;
  13275. if (lineScale > 1e-10) {
  13276. // Only add extra hover lineWidth when there are no fill
  13277. if (!style.hasFill()) {
  13278. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13279. }
  13280. if (containStroke(
  13281. pathData, lineWidth / lineScale, x, y
  13282. )) {
  13283. return true;
  13284. }
  13285. }
  13286. }
  13287. if (style.hasFill()) {
  13288. return contain(pathData, x, y);
  13289. }
  13290. }
  13291. return false;
  13292. },
  13293. /**
  13294. * @param {boolean} dirtyPath
  13295. */
  13296. dirty: function (dirtyPath) {
  13297. if (dirtyPath == null) {
  13298. dirtyPath = true;
  13299. }
  13300. // Only mark dirty, not mark clean
  13301. if (dirtyPath) {
  13302. this.__dirtyPath = dirtyPath;
  13303. this._rect = null;
  13304. }
  13305. this.__dirty = this.__dirtyText = true;
  13306. this.__zr && this.__zr.refresh();
  13307. // Used as a clipping path
  13308. if (this.__clipTarget) {
  13309. this.__clipTarget.dirty();
  13310. }
  13311. },
  13312. /**
  13313. * Alias for animate('shape')
  13314. * @param {boolean} loop
  13315. */
  13316. animateShape: function (loop) {
  13317. return this.animate('shape', loop);
  13318. },
  13319. // Overwrite attrKV
  13320. attrKV: function (key, value) {
  13321. // FIXME
  13322. if (key === 'shape') {
  13323. this.setShape(value);
  13324. this.__dirtyPath = true;
  13325. this._rect = null;
  13326. }
  13327. else {
  13328. Displayable.prototype.attrKV.call(this, key, value);
  13329. }
  13330. },
  13331. /**
  13332. * @param {Object|string} key
  13333. * @param {*} value
  13334. */
  13335. setShape: function (key, value) {
  13336. var shape = this.shape;
  13337. // Path from string may not have shape
  13338. if (shape) {
  13339. if (isObject$1(key)) {
  13340. for (var name in key) {
  13341. if (key.hasOwnProperty(name)) {
  13342. shape[name] = key[name];
  13343. }
  13344. }
  13345. }
  13346. else {
  13347. shape[key] = value;
  13348. }
  13349. this.dirty(true);
  13350. }
  13351. return this;
  13352. },
  13353. getLineScale: function () {
  13354. var m = this.transform;
  13355. // Get the line scale.
  13356. // Determinant of `m` means how much the area is enlarged by the
  13357. // transformation. So its square root can be used as a scale factor
  13358. // for width.
  13359. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13360. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13361. : 1;
  13362. }
  13363. };
  13364. /**
  13365. * 扩展一个 Path element, 比如星形,圆等。
  13366. * Extend a path element
  13367. * @param {Object} props
  13368. * @param {string} props.type Path type
  13369. * @param {Function} props.init Initialize
  13370. * @param {Function} props.buildPath Overwrite buildPath method
  13371. * @param {Object} [props.style] Extended default style config
  13372. * @param {Object} [props.shape] Extended default shape config
  13373. */
  13374. Path.extend = function (defaults$$1) {
  13375. var Sub = function (opts) {
  13376. Path.call(this, opts);
  13377. if (defaults$$1.style) {
  13378. // Extend default style
  13379. this.style.extendFrom(defaults$$1.style, false);
  13380. }
  13381. // Extend default shape
  13382. var defaultShape = defaults$$1.shape;
  13383. if (defaultShape) {
  13384. this.shape = this.shape || {};
  13385. var thisShape = this.shape;
  13386. for (var name in defaultShape) {
  13387. if (
  13388. !thisShape.hasOwnProperty(name)
  13389. && defaultShape.hasOwnProperty(name)
  13390. ) {
  13391. thisShape[name] = defaultShape[name];
  13392. }
  13393. }
  13394. }
  13395. defaults$$1.init && defaults$$1.init.call(this, opts);
  13396. };
  13397. inherits(Sub, Path);
  13398. // FIXME 不能 extend position, rotation 等引用对象
  13399. for (var name in defaults$$1) {
  13400. // Extending prototype values and methods
  13401. if (name !== 'style' && name !== 'shape') {
  13402. Sub.prototype[name] = defaults$$1[name];
  13403. }
  13404. }
  13405. return Sub;
  13406. };
  13407. inherits(Path, Displayable);
  13408. var CMD$2 = PathProxy.CMD;
  13409. var points = [[], [], []];
  13410. var mathSqrt$3 = Math.sqrt;
  13411. var mathAtan2 = Math.atan2;
  13412. var transformPath = function (path, m) {
  13413. var data = path.data;
  13414. var cmd;
  13415. var nPoint;
  13416. var i;
  13417. var j;
  13418. var k;
  13419. var p;
  13420. var M = CMD$2.M;
  13421. var C = CMD$2.C;
  13422. var L = CMD$2.L;
  13423. var R = CMD$2.R;
  13424. var A = CMD$2.A;
  13425. var Q = CMD$2.Q;
  13426. for (i = 0, j = 0; i < data.length;) {
  13427. cmd = data[i++];
  13428. j = i;
  13429. nPoint = 0;
  13430. switch (cmd) {
  13431. case M:
  13432. nPoint = 1;
  13433. break;
  13434. case L:
  13435. nPoint = 1;
  13436. break;
  13437. case C:
  13438. nPoint = 3;
  13439. break;
  13440. case Q:
  13441. nPoint = 2;
  13442. break;
  13443. case A:
  13444. var x = m[4];
  13445. var y = m[5];
  13446. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13447. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13448. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13449. // cx
  13450. data[i] *= sx;
  13451. data[i++] += x;
  13452. // cy
  13453. data[i] *= sy;
  13454. data[i++] += y;
  13455. // Scale rx and ry
  13456. // FIXME Assume psi is 0 here
  13457. data[i++] *= sx;
  13458. data[i++] *= sy;
  13459. // Start angle
  13460. data[i++] += angle;
  13461. // end angle
  13462. data[i++] += angle;
  13463. // FIXME psi
  13464. i += 2;
  13465. j = i;
  13466. break;
  13467. case R:
  13468. // x0, y0
  13469. p[0] = data[i++];
  13470. p[1] = data[i++];
  13471. applyTransform(p, p, m);
  13472. data[j++] = p[0];
  13473. data[j++] = p[1];
  13474. // x1, y1
  13475. p[0] += data[i++];
  13476. p[1] += data[i++];
  13477. applyTransform(p, p, m);
  13478. data[j++] = p[0];
  13479. data[j++] = p[1];
  13480. }
  13481. for (k = 0; k < nPoint; k++) {
  13482. var p = points[k];
  13483. p[0] = data[i++];
  13484. p[1] = data[i++];
  13485. applyTransform(p, p, m);
  13486. // Write back
  13487. data[j++] = p[0];
  13488. data[j++] = p[1];
  13489. }
  13490. }
  13491. };
  13492. // command chars
  13493. // var cc = [
  13494. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13495. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13496. // ];
  13497. var mathSqrt = Math.sqrt;
  13498. var mathSin = Math.sin;
  13499. var mathCos = Math.cos;
  13500. var PI = Math.PI;
  13501. var vMag = function (v) {
  13502. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13503. };
  13504. var vRatio = function (u, v) {
  13505. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13506. };
  13507. var vAngle = function (u, v) {
  13508. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13509. * Math.acos(vRatio(u, v));
  13510. };
  13511. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13512. var psi = psiDeg * (PI / 180.0);
  13513. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13514. + mathSin(psi) * (y1 - y2) / 2.0;
  13515. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13516. + mathCos(psi) * (y1 - y2) / 2.0;
  13517. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13518. if (lambda > 1) {
  13519. rx *= mathSqrt(lambda);
  13520. ry *= mathSqrt(lambda);
  13521. }
  13522. var f = (fa === fs ? -1 : 1)
  13523. * mathSqrt((((rx * rx) * (ry * ry))
  13524. - ((rx * rx) * (yp * yp))
  13525. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13526. + (ry * ry) * (xp * xp))
  13527. ) || 0;
  13528. var cxp = f * rx * yp / ry;
  13529. var cyp = f * -ry * xp / rx;
  13530. var cx = (x1 + x2) / 2.0
  13531. + mathCos(psi) * cxp
  13532. - mathSin(psi) * cyp;
  13533. var cy = (y1 + y2) / 2.0
  13534. + mathSin(psi) * cxp
  13535. + mathCos(psi) * cyp;
  13536. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13537. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13538. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13539. var dTheta = vAngle(u, v);
  13540. if (vRatio(u, v) <= -1) {
  13541. dTheta = PI;
  13542. }
  13543. if (vRatio(u, v) >= 1) {
  13544. dTheta = 0;
  13545. }
  13546. if (fs === 0 && dTheta > 0) {
  13547. dTheta = dTheta - 2 * PI;
  13548. }
  13549. if (fs === 1 && dTheta < 0) {
  13550. dTheta = dTheta + 2 * PI;
  13551. }
  13552. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13553. }
  13554. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13555. // Consider case:
  13556. // (1) delimiter can be comma or space, where continuous commas
  13557. // or spaces should be seen as one comma.
  13558. // (2) value can be like:
  13559. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13560. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13561. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13562. // var valueSplitReg = /[\s,]+/;
  13563. function createPathProxyFromString(data) {
  13564. if (!data) {
  13565. return new PathProxy();
  13566. }
  13567. // var data = data.replace(/-/g, ' -')
  13568. // .replace(/ /g, ' ')
  13569. // .replace(/ /g, ',')
  13570. // .replace(/,,/g, ',');
  13571. // var n;
  13572. // create pipes so that we can split the data
  13573. // for (n = 0; n < cc.length; n++) {
  13574. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13575. // }
  13576. // data = data.replace(/-/g, ',-');
  13577. // create array
  13578. // var arr = cs.split('|');
  13579. // init context point
  13580. var cpx = 0;
  13581. var cpy = 0;
  13582. var subpathX = cpx;
  13583. var subpathY = cpy;
  13584. var prevCmd;
  13585. var path = new PathProxy();
  13586. var CMD = PathProxy.CMD;
  13587. // commandReg.lastIndex = 0;
  13588. // var cmdResult;
  13589. // while ((cmdResult = commandReg.exec(data)) != null) {
  13590. // var cmdStr = cmdResult[1];
  13591. // var cmdContent = cmdResult[2];
  13592. var cmdList = data.match(commandReg);
  13593. for (var l = 0; l < cmdList.length; l++) {
  13594. var cmdText = cmdList[l];
  13595. var cmdStr = cmdText.charAt(0);
  13596. var cmd;
  13597. // String#split is faster a little bit than String#replace or RegExp#exec.
  13598. // var p = cmdContent.split(valueSplitReg);
  13599. // var pLen = 0;
  13600. // for (var i = 0; i < p.length; i++) {
  13601. // // '' and other invalid str => NaN
  13602. // var val = parseFloat(p[i]);
  13603. // !isNaN(val) && (p[pLen++] = val);
  13604. // }
  13605. var p = cmdText.match(numberReg) || [];
  13606. var pLen = p.length;
  13607. for (var i = 0; i < pLen; i++) {
  13608. p[i] = parseFloat(p[i]);
  13609. }
  13610. var off = 0;
  13611. while (off < pLen) {
  13612. var ctlPtx;
  13613. var ctlPty;
  13614. var rx;
  13615. var ry;
  13616. var psi;
  13617. var fa;
  13618. var fs;
  13619. var x1 = cpx;
  13620. var y1 = cpy;
  13621. // convert l, H, h, V, and v to L
  13622. switch (cmdStr) {
  13623. case 'l':
  13624. cpx += p[off++];
  13625. cpy += p[off++];
  13626. cmd = CMD.L;
  13627. path.addData(cmd, cpx, cpy);
  13628. break;
  13629. case 'L':
  13630. cpx = p[off++];
  13631. cpy = p[off++];
  13632. cmd = CMD.L;
  13633. path.addData(cmd, cpx, cpy);
  13634. break;
  13635. case 'm':
  13636. cpx += p[off++];
  13637. cpy += p[off++];
  13638. cmd = CMD.M;
  13639. path.addData(cmd, cpx, cpy);
  13640. subpathX = cpx;
  13641. subpathY = cpy;
  13642. cmdStr = 'l';
  13643. break;
  13644. case 'M':
  13645. cpx = p[off++];
  13646. cpy = p[off++];
  13647. cmd = CMD.M;
  13648. path.addData(cmd, cpx, cpy);
  13649. subpathX = cpx;
  13650. subpathY = cpy;
  13651. cmdStr = 'L';
  13652. break;
  13653. case 'h':
  13654. cpx += p[off++];
  13655. cmd = CMD.L;
  13656. path.addData(cmd, cpx, cpy);
  13657. break;
  13658. case 'H':
  13659. cpx = p[off++];
  13660. cmd = CMD.L;
  13661. path.addData(cmd, cpx, cpy);
  13662. break;
  13663. case 'v':
  13664. cpy += p[off++];
  13665. cmd = CMD.L;
  13666. path.addData(cmd, cpx, cpy);
  13667. break;
  13668. case 'V':
  13669. cpy = p[off++];
  13670. cmd = CMD.L;
  13671. path.addData(cmd, cpx, cpy);
  13672. break;
  13673. case 'C':
  13674. cmd = CMD.C;
  13675. path.addData(
  13676. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13677. );
  13678. cpx = p[off - 2];
  13679. cpy = p[off - 1];
  13680. break;
  13681. case 'c':
  13682. cmd = CMD.C;
  13683. path.addData(
  13684. cmd,
  13685. p[off++] + cpx, p[off++] + cpy,
  13686. p[off++] + cpx, p[off++] + cpy,
  13687. p[off++] + cpx, p[off++] + cpy
  13688. );
  13689. cpx += p[off - 2];
  13690. cpy += p[off - 1];
  13691. break;
  13692. case 'S':
  13693. ctlPtx = cpx;
  13694. ctlPty = cpy;
  13695. var len = path.len();
  13696. var pathData = path.data;
  13697. if (prevCmd === CMD.C) {
  13698. ctlPtx += cpx - pathData[len - 4];
  13699. ctlPty += cpy - pathData[len - 3];
  13700. }
  13701. cmd = CMD.C;
  13702. x1 = p[off++];
  13703. y1 = p[off++];
  13704. cpx = p[off++];
  13705. cpy = p[off++];
  13706. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13707. break;
  13708. case 's':
  13709. ctlPtx = cpx;
  13710. ctlPty = cpy;
  13711. var len = path.len();
  13712. var pathData = path.data;
  13713. if (prevCmd === CMD.C) {
  13714. ctlPtx += cpx - pathData[len - 4];
  13715. ctlPty += cpy - pathData[len - 3];
  13716. }
  13717. cmd = CMD.C;
  13718. x1 = cpx + p[off++];
  13719. y1 = cpy + p[off++];
  13720. cpx += p[off++];
  13721. cpy += p[off++];
  13722. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13723. break;
  13724. case 'Q':
  13725. x1 = p[off++];
  13726. y1 = p[off++];
  13727. cpx = p[off++];
  13728. cpy = p[off++];
  13729. cmd = CMD.Q;
  13730. path.addData(cmd, x1, y1, cpx, cpy);
  13731. break;
  13732. case 'q':
  13733. x1 = p[off++] + cpx;
  13734. y1 = p[off++] + cpy;
  13735. cpx += p[off++];
  13736. cpy += p[off++];
  13737. cmd = CMD.Q;
  13738. path.addData(cmd, x1, y1, cpx, cpy);
  13739. break;
  13740. case 'T':
  13741. ctlPtx = cpx;
  13742. ctlPty = cpy;
  13743. var len = path.len();
  13744. var pathData = path.data;
  13745. if (prevCmd === CMD.Q) {
  13746. ctlPtx += cpx - pathData[len - 4];
  13747. ctlPty += cpy - pathData[len - 3];
  13748. }
  13749. cpx = p[off++];
  13750. cpy = p[off++];
  13751. cmd = CMD.Q;
  13752. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13753. break;
  13754. case 't':
  13755. ctlPtx = cpx;
  13756. ctlPty = cpy;
  13757. var len = path.len();
  13758. var pathData = path.data;
  13759. if (prevCmd === CMD.Q) {
  13760. ctlPtx += cpx - pathData[len - 4];
  13761. ctlPty += cpy - pathData[len - 3];
  13762. }
  13763. cpx += p[off++];
  13764. cpy += p[off++];
  13765. cmd = CMD.Q;
  13766. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13767. break;
  13768. case 'A':
  13769. rx = p[off++];
  13770. ry = p[off++];
  13771. psi = p[off++];
  13772. fa = p[off++];
  13773. fs = p[off++];
  13774. x1 = cpx, y1 = cpy;
  13775. cpx = p[off++];
  13776. cpy = p[off++];
  13777. cmd = CMD.A;
  13778. processArc(
  13779. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13780. );
  13781. break;
  13782. case 'a':
  13783. rx = p[off++];
  13784. ry = p[off++];
  13785. psi = p[off++];
  13786. fa = p[off++];
  13787. fs = p[off++];
  13788. x1 = cpx, y1 = cpy;
  13789. cpx += p[off++];
  13790. cpy += p[off++];
  13791. cmd = CMD.A;
  13792. processArc(
  13793. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13794. );
  13795. break;
  13796. }
  13797. }
  13798. if (cmdStr === 'z' || cmdStr === 'Z') {
  13799. cmd = CMD.Z;
  13800. path.addData(cmd);
  13801. // z may be in the middle of the path.
  13802. cpx = subpathX;
  13803. cpy = subpathY;
  13804. }
  13805. prevCmd = cmd;
  13806. }
  13807. path.toStatic();
  13808. return path;
  13809. }
  13810. // TODO Optimize double memory cost problem
  13811. function createPathOptions(str, opts) {
  13812. var pathProxy = createPathProxyFromString(str);
  13813. opts = opts || {};
  13814. opts.buildPath = function (path) {
  13815. if (path.setData) {
  13816. path.setData(pathProxy.data);
  13817. // Svg and vml renderer don't have context
  13818. var ctx = path.getContext();
  13819. if (ctx) {
  13820. path.rebuildPath(ctx);
  13821. }
  13822. }
  13823. else {
  13824. var ctx = path;
  13825. pathProxy.rebuildPath(ctx);
  13826. }
  13827. };
  13828. opts.applyTransform = function (m) {
  13829. transformPath(pathProxy, m);
  13830. this.dirty(true);
  13831. };
  13832. return opts;
  13833. }
  13834. /**
  13835. * Create a Path object from path string data
  13836. * http://www.w3.org/TR/SVG/paths.html#PathData
  13837. * @param {Object} opts Other options
  13838. */
  13839. function createFromString(str, opts) {
  13840. return new Path(createPathOptions(str, opts));
  13841. }
  13842. /**
  13843. * Create a Path class from path string data
  13844. * @param {string} str
  13845. * @param {Object} opts Other options
  13846. */
  13847. function extendFromString(str, opts) {
  13848. return Path.extend(createPathOptions(str, opts));
  13849. }
  13850. /**
  13851. * Merge multiple paths
  13852. */
  13853. // TODO Apply transform
  13854. // TODO stroke dash
  13855. // TODO Optimize double memory cost problem
  13856. function mergePath$1(pathEls, opts) {
  13857. var pathList = [];
  13858. var len = pathEls.length;
  13859. for (var i = 0; i < len; i++) {
  13860. var pathEl = pathEls[i];
  13861. if (!pathEl.path) {
  13862. pathEl.createPathProxy();
  13863. }
  13864. if (pathEl.__dirtyPath) {
  13865. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13866. }
  13867. pathList.push(pathEl.path);
  13868. }
  13869. var pathBundle = new Path(opts);
  13870. // Need path proxy.
  13871. pathBundle.createPathProxy();
  13872. pathBundle.buildPath = function (path) {
  13873. path.appendPath(pathList);
  13874. // Svg and vml renderer don't have context
  13875. var ctx = path.getContext();
  13876. if (ctx) {
  13877. path.rebuildPath(ctx);
  13878. }
  13879. };
  13880. return pathBundle;
  13881. }
  13882. /**
  13883. * @alias zrender/graphic/Text
  13884. * @extends module:zrender/graphic/Displayable
  13885. * @constructor
  13886. * @param {Object} opts
  13887. */
  13888. var Text = function (opts) { // jshint ignore:line
  13889. Displayable.call(this, opts);
  13890. };
  13891. Text.prototype = {
  13892. constructor: Text,
  13893. type: 'text',
  13894. brush: function (ctx, prevEl) {
  13895. var style = this.style;
  13896. // Optimize, avoid normalize every time.
  13897. this.__dirty && normalizeTextStyle(style, true);
  13898. // Use props with prefix 'text'.
  13899. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13900. style.shadowOffsetX = style.shadowOffsetY = null;
  13901. var text = style.text;
  13902. // Convert to string
  13903. text != null && (text += '');
  13904. // Do not apply style.bind in Text node. Because the real bind job
  13905. // is in textHelper.renderText, and performance of text render should
  13906. // be considered.
  13907. // style.bind(ctx, this, prevEl);
  13908. if (!needDrawText(text, style)) {
  13909. // The current el.style is not applied
  13910. // and should not be used as cache.
  13911. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13912. return;
  13913. }
  13914. this.setTransform(ctx);
  13915. renderText(this, ctx, text, style, null, prevEl);
  13916. this.restoreTransform(ctx);
  13917. },
  13918. getBoundingRect: function () {
  13919. var style = this.style;
  13920. // Optimize, avoid normalize every time.
  13921. this.__dirty && normalizeTextStyle(style, true);
  13922. if (!this._rect) {
  13923. var text = style.text;
  13924. text != null ? (text += '') : (text = '');
  13925. var rect = getBoundingRect(
  13926. style.text + '',
  13927. style.font,
  13928. style.textAlign,
  13929. style.textVerticalAlign,
  13930. style.textPadding,
  13931. style.textLineHeight,
  13932. style.rich
  13933. );
  13934. rect.x += style.x || 0;
  13935. rect.y += style.y || 0;
  13936. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13937. var w = style.textStrokeWidth;
  13938. rect.x -= w / 2;
  13939. rect.y -= w / 2;
  13940. rect.width += w;
  13941. rect.height += w;
  13942. }
  13943. this._rect = rect;
  13944. }
  13945. return this._rect;
  13946. }
  13947. };
  13948. inherits(Text, Displayable);
  13949. /**
  13950. * 圆形
  13951. * @module zrender/shape/Circle
  13952. */
  13953. var Circle = Path.extend({
  13954. type: 'circle',
  13955. shape: {
  13956. cx: 0,
  13957. cy: 0,
  13958. r: 0
  13959. },
  13960. buildPath: function (ctx, shape, inBundle) {
  13961. // Better stroking in ShapeBundle
  13962. // Always do it may have performence issue ( fill may be 2x more cost)
  13963. if (inBundle) {
  13964. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13965. }
  13966. // else {
  13967. // if (ctx.allocate && !ctx.data.length) {
  13968. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13969. // }
  13970. // }
  13971. // Better stroking in ShapeBundle
  13972. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13973. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13974. }
  13975. });
  13976. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13977. // where exception "unexpected call to method or property access"
  13978. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13979. // whose area size is zero is drawn and ctx.clip() is called and
  13980. // shadowBlur is set. See #4572, #3112, #5777.
  13981. // (e.g.,
  13982. // ctx.moveTo(10, 10);
  13983. // ctx.lineTo(20, 10);
  13984. // ctx.closePath();
  13985. // ctx.clip();
  13986. // ctx.shadowBlur = 10;
  13987. // ...
  13988. // ctx.fill();
  13989. // )
  13990. var shadowTemp = [
  13991. ['shadowBlur', 0],
  13992. ['shadowColor', '#000'],
  13993. ['shadowOffsetX', 0],
  13994. ['shadowOffsetY', 0]
  13995. ];
  13996. var fixClipWithShadow = function (orignalBrush) {
  13997. // version string can be: '11.0'
  13998. return (env$1.browser.ie && env$1.browser.version >= 11)
  13999. ? function () {
  14000. var clipPaths = this.__clipPaths;
  14001. var style = this.style;
  14002. var modified;
  14003. if (clipPaths) {
  14004. for (var i = 0; i < clipPaths.length; i++) {
  14005. var clipPath = clipPaths[i];
  14006. var shape = clipPath && clipPath.shape;
  14007. var type = clipPath && clipPath.type;
  14008. if (shape && (
  14009. (type === 'sector' && shape.startAngle === shape.endAngle)
  14010. || (type === 'rect' && (!shape.width || !shape.height))
  14011. )) {
  14012. for (var j = 0; j < shadowTemp.length; j++) {
  14013. // It is save to put shadowTemp static, because shadowTemp
  14014. // will be all modified each item brush called.
  14015. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14016. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14017. }
  14018. modified = true;
  14019. break;
  14020. }
  14021. }
  14022. }
  14023. orignalBrush.apply(this, arguments);
  14024. if (modified) {
  14025. for (var j = 0; j < shadowTemp.length; j++) {
  14026. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14027. }
  14028. }
  14029. }
  14030. : orignalBrush;
  14031. };
  14032. /**
  14033. * 扇形
  14034. * @module zrender/graphic/shape/Sector
  14035. */
  14036. var Sector = Path.extend({
  14037. type: 'sector',
  14038. shape: {
  14039. cx: 0,
  14040. cy: 0,
  14041. r0: 0,
  14042. r: 0,
  14043. startAngle: 0,
  14044. endAngle: Math.PI * 2,
  14045. clockwise: true
  14046. },
  14047. brush: fixClipWithShadow(Path.prototype.brush),
  14048. buildPath: function (ctx, shape) {
  14049. var x = shape.cx;
  14050. var y = shape.cy;
  14051. var r0 = Math.max(shape.r0 || 0, 0);
  14052. var r = Math.max(shape.r, 0);
  14053. var startAngle = shape.startAngle;
  14054. var endAngle = shape.endAngle;
  14055. var clockwise = shape.clockwise;
  14056. var unitX = Math.cos(startAngle);
  14057. var unitY = Math.sin(startAngle);
  14058. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14059. ctx.lineTo(unitX * r + x, unitY * r + y);
  14060. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14061. ctx.lineTo(
  14062. Math.cos(endAngle) * r0 + x,
  14063. Math.sin(endAngle) * r0 + y
  14064. );
  14065. if (r0 !== 0) {
  14066. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14067. }
  14068. ctx.closePath();
  14069. }
  14070. });
  14071. /**
  14072. * 圆环
  14073. * @module zrender/graphic/shape/Ring
  14074. */
  14075. var Ring = Path.extend({
  14076. type: 'ring',
  14077. shape: {
  14078. cx: 0,
  14079. cy: 0,
  14080. r: 0,
  14081. r0: 0
  14082. },
  14083. buildPath: function (ctx, shape) {
  14084. var x = shape.cx;
  14085. var y = shape.cy;
  14086. var PI2 = Math.PI * 2;
  14087. ctx.moveTo(x + shape.r, y);
  14088. ctx.arc(x, y, shape.r, 0, PI2, false);
  14089. ctx.moveTo(x + shape.r0, y);
  14090. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14091. }
  14092. });
  14093. /**
  14094. * Catmull-Rom spline 插值折线
  14095. * @module zrender/shape/util/smoothSpline
  14096. * @author pissang (https://www.github.com/pissang)
  14097. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14098. * errorrik (errorrik@gmail.com)
  14099. */
  14100. /**
  14101. * @inner
  14102. */
  14103. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14104. var v0 = (p2 - p0) * 0.5;
  14105. var v1 = (p3 - p1) * 0.5;
  14106. return (2 * (p1 - p2) + v0 + v1) * t3
  14107. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14108. + v0 * t + p1;
  14109. }
  14110. /**
  14111. * @alias module:zrender/shape/util/smoothSpline
  14112. * @param {Array} points 线段顶点数组
  14113. * @param {boolean} isLoop
  14114. * @return {Array}
  14115. */
  14116. var smoothSpline = function (points, isLoop) {
  14117. var len$$1 = points.length;
  14118. var ret = [];
  14119. var distance$$1 = 0;
  14120. for (var i = 1; i < len$$1; i++) {
  14121. distance$$1 += distance(points[i - 1], points[i]);
  14122. }
  14123. var segs = distance$$1 / 2;
  14124. segs = segs < len$$1 ? len$$1 : segs;
  14125. for (var i = 0; i < segs; i++) {
  14126. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14127. var idx = Math.floor(pos);
  14128. var w = pos - idx;
  14129. var p0;
  14130. var p1 = points[idx % len$$1];
  14131. var p2;
  14132. var p3;
  14133. if (!isLoop) {
  14134. p0 = points[idx === 0 ? idx : idx - 1];
  14135. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14136. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14137. }
  14138. else {
  14139. p0 = points[(idx - 1 + len$$1) % len$$1];
  14140. p2 = points[(idx + 1) % len$$1];
  14141. p3 = points[(idx + 2) % len$$1];
  14142. }
  14143. var w2 = w * w;
  14144. var w3 = w * w2;
  14145. ret.push([
  14146. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14147. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14148. ]);
  14149. }
  14150. return ret;
  14151. };
  14152. /**
  14153. * 贝塞尔平滑曲线
  14154. * @module zrender/shape/util/smoothBezier
  14155. * @author pissang (https://www.github.com/pissang)
  14156. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14157. * errorrik (errorrik@gmail.com)
  14158. */
  14159. /**
  14160. * 贝塞尔平滑曲线
  14161. * @alias module:zrender/shape/util/smoothBezier
  14162. * @param {Array} points 线段顶点数组
  14163. * @param {number} smooth 平滑等级, 0-1
  14164. * @param {boolean} isLoop
  14165. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14166. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14167. * 整个折线的包围盒做一个并集用来约束控制点。
  14168. * @param {Array} 计算出来的控制点数组
  14169. */
  14170. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14171. var cps = [];
  14172. var v = [];
  14173. var v1 = [];
  14174. var v2 = [];
  14175. var prevPoint;
  14176. var nextPoint;
  14177. var min$$1;
  14178. var max$$1;
  14179. if (constraint) {
  14180. min$$1 = [Infinity, Infinity];
  14181. max$$1 = [-Infinity, -Infinity];
  14182. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14183. min(min$$1, min$$1, points[i]);
  14184. max(max$$1, max$$1, points[i]);
  14185. }
  14186. // 与指定的包围盒做并集
  14187. min(min$$1, min$$1, constraint[0]);
  14188. max(max$$1, max$$1, constraint[1]);
  14189. }
  14190. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14191. var point = points[i];
  14192. if (isLoop) {
  14193. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14194. nextPoint = points[(i + 1) % len$$1];
  14195. }
  14196. else {
  14197. if (i === 0 || i === len$$1 - 1) {
  14198. cps.push(clone$1(points[i]));
  14199. continue;
  14200. }
  14201. else {
  14202. prevPoint = points[i - 1];
  14203. nextPoint = points[i + 1];
  14204. }
  14205. }
  14206. sub(v, nextPoint, prevPoint);
  14207. // use degree to scale the handle length
  14208. scale(v, v, smooth);
  14209. var d0 = distance(point, prevPoint);
  14210. var d1 = distance(point, nextPoint);
  14211. var sum = d0 + d1;
  14212. if (sum !== 0) {
  14213. d0 /= sum;
  14214. d1 /= sum;
  14215. }
  14216. scale(v1, v, -d0);
  14217. scale(v2, v, d1);
  14218. var cp0 = add([], point, v1);
  14219. var cp1 = add([], point, v2);
  14220. if (constraint) {
  14221. max(cp0, cp0, min$$1);
  14222. min(cp0, cp0, max$$1);
  14223. max(cp1, cp1, min$$1);
  14224. min(cp1, cp1, max$$1);
  14225. }
  14226. cps.push(cp0);
  14227. cps.push(cp1);
  14228. }
  14229. if (isLoop) {
  14230. cps.push(cps.shift());
  14231. }
  14232. return cps;
  14233. };
  14234. function buildPath$1(ctx, shape, closePath) {
  14235. var points = shape.points;
  14236. var smooth = shape.smooth;
  14237. if (points && points.length >= 2) {
  14238. if (smooth && smooth !== 'spline') {
  14239. var controlPoints = smoothBezier(
  14240. points, smooth, closePath, shape.smoothConstraint
  14241. );
  14242. ctx.moveTo(points[0][0], points[0][1]);
  14243. var len = points.length;
  14244. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14245. var cp1 = controlPoints[i * 2];
  14246. var cp2 = controlPoints[i * 2 + 1];
  14247. var p = points[(i + 1) % len];
  14248. ctx.bezierCurveTo(
  14249. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14250. );
  14251. }
  14252. }
  14253. else {
  14254. if (smooth === 'spline') {
  14255. points = smoothSpline(points, closePath);
  14256. }
  14257. ctx.moveTo(points[0][0], points[0][1]);
  14258. for (var i = 1, l = points.length; i < l; i++) {
  14259. ctx.lineTo(points[i][0], points[i][1]);
  14260. }
  14261. }
  14262. closePath && ctx.closePath();
  14263. }
  14264. }
  14265. /**
  14266. * 多边形
  14267. * @module zrender/shape/Polygon
  14268. */
  14269. var Polygon = Path.extend({
  14270. type: 'polygon',
  14271. shape: {
  14272. points: null,
  14273. smooth: false,
  14274. smoothConstraint: null
  14275. },
  14276. buildPath: function (ctx, shape) {
  14277. buildPath$1(ctx, shape, true);
  14278. }
  14279. });
  14280. /**
  14281. * @module zrender/graphic/shape/Polyline
  14282. */
  14283. var Polyline = Path.extend({
  14284. type: 'polyline',
  14285. shape: {
  14286. points: null,
  14287. smooth: false,
  14288. smoothConstraint: null
  14289. },
  14290. style: {
  14291. stroke: '#000',
  14292. fill: null
  14293. },
  14294. buildPath: function (ctx, shape) {
  14295. buildPath$1(ctx, shape, false);
  14296. }
  14297. });
  14298. /**
  14299. * Sub-pixel optimize for canvas rendering, prevent from blur
  14300. * when rendering a thin vertical/horizontal line.
  14301. */
  14302. var round = Math.round;
  14303. /**
  14304. * Sub pixel optimize line for canvas
  14305. *
  14306. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14307. * `outputShape` and `inputShape` can be the same object.
  14308. * `outputShape` object can be used repeatly, because all of
  14309. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14310. * @param {Object} [inputShape]
  14311. * @param {number} [inputShape.x1]
  14312. * @param {number} [inputShape.y1]
  14313. * @param {number} [inputShape.x2]
  14314. * @param {number} [inputShape.y2]
  14315. * @param {Object} [style]
  14316. * @param {number} [style.lineWidth]
  14317. */
  14318. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14319. var lineWidth = style && style.lineWidth;
  14320. if (!inputShape || !lineWidth) {
  14321. return;
  14322. }
  14323. var x1 = inputShape.x1;
  14324. var x2 = inputShape.x2;
  14325. var y1 = inputShape.y1;
  14326. var y2 = inputShape.y2;
  14327. if (round(x1 * 2) === round(x2 * 2)) {
  14328. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14329. }
  14330. else {
  14331. outputShape.x1 = x1;
  14332. outputShape.x2 = x2;
  14333. }
  14334. if (round(y1 * 2) === round(y2 * 2)) {
  14335. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14336. }
  14337. else {
  14338. outputShape.y1 = y1;
  14339. outputShape.y2 = y2;
  14340. }
  14341. }
  14342. /**
  14343. * Sub pixel optimize rect for canvas
  14344. *
  14345. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14346. * `outputShape` and `inputShape` can be the same object.
  14347. * `outputShape` object can be used repeatly, because all of
  14348. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14349. * @param {Object} [inputShape]
  14350. * @param {number} [inputShape.x]
  14351. * @param {number} [inputShape.y]
  14352. * @param {number} [inputShape.width]
  14353. * @param {number} [inputShape.height]
  14354. * @param {Object} [style]
  14355. * @param {number} [style.lineWidth]
  14356. */
  14357. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14358. var lineWidth = style && style.lineWidth;
  14359. if (!inputShape || !lineWidth) {
  14360. return;
  14361. }
  14362. var originX = inputShape.x;
  14363. var originY = inputShape.y;
  14364. var originWidth = inputShape.width;
  14365. var originHeight = inputShape.height;
  14366. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14367. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14368. outputShape.width = Math.max(
  14369. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14370. originWidth === 0 ? 0 : 1
  14371. );
  14372. outputShape.height = Math.max(
  14373. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14374. originHeight === 0 ? 0 : 1
  14375. );
  14376. }
  14377. /**
  14378. * Sub pixel optimize for canvas
  14379. *
  14380. * @param {number} position Coordinate, such as x, y
  14381. * @param {number} lineWidth Should be nonnegative integer.
  14382. * @param {boolean=} positiveOrNegative Default false (negative).
  14383. * @return {number} Optimized position.
  14384. */
  14385. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14386. // Assure that (position + lineWidth / 2) is near integer edge,
  14387. // otherwise line will be fuzzy in canvas.
  14388. var doubledPosition = round(position * 2);
  14389. return (doubledPosition + round(lineWidth)) % 2 === 0
  14390. ? doubledPosition / 2
  14391. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14392. }
  14393. /**
  14394. * 矩形
  14395. * @module zrender/graphic/shape/Rect
  14396. */
  14397. // Avoid create repeatly.
  14398. var subPixelOptimizeOutputShape = {};
  14399. var Rect = Path.extend({
  14400. type: 'rect',
  14401. shape: {
  14402. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14403. // r缩写为1 相当于 [1, 1, 1, 1]
  14404. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14405. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14406. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14407. r: 0,
  14408. x: 0,
  14409. y: 0,
  14410. width: 0,
  14411. height: 0
  14412. },
  14413. buildPath: function (ctx, shape) {
  14414. var x;
  14415. var y;
  14416. var width;
  14417. var height;
  14418. if (this.subPixelOptimize) {
  14419. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14420. x = subPixelOptimizeOutputShape.x;
  14421. y = subPixelOptimizeOutputShape.y;
  14422. width = subPixelOptimizeOutputShape.width;
  14423. height = subPixelOptimizeOutputShape.height;
  14424. subPixelOptimizeOutputShape.r = shape.r;
  14425. shape = subPixelOptimizeOutputShape;
  14426. }
  14427. else {
  14428. x = shape.x;
  14429. y = shape.y;
  14430. width = shape.width;
  14431. height = shape.height;
  14432. }
  14433. if (!shape.r) {
  14434. ctx.rect(x, y, width, height);
  14435. }
  14436. else {
  14437. buildPath(ctx, shape);
  14438. }
  14439. ctx.closePath();
  14440. return;
  14441. }
  14442. });
  14443. /**
  14444. * 直线
  14445. * @module zrender/graphic/shape/Line
  14446. */
  14447. // Avoid create repeatly.
  14448. var subPixelOptimizeOutputShape$1 = {};
  14449. var Line = Path.extend({
  14450. type: 'line',
  14451. shape: {
  14452. // Start point
  14453. x1: 0,
  14454. y1: 0,
  14455. // End point
  14456. x2: 0,
  14457. y2: 0,
  14458. percent: 1
  14459. },
  14460. style: {
  14461. stroke: '#000',
  14462. fill: null
  14463. },
  14464. buildPath: function (ctx, shape) {
  14465. var x1;
  14466. var y1;
  14467. var x2;
  14468. var y2;
  14469. if (this.subPixelOptimize) {
  14470. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14471. x1 = subPixelOptimizeOutputShape$1.x1;
  14472. y1 = subPixelOptimizeOutputShape$1.y1;
  14473. x2 = subPixelOptimizeOutputShape$1.x2;
  14474. y2 = subPixelOptimizeOutputShape$1.y2;
  14475. }
  14476. else {
  14477. x1 = shape.x1;
  14478. y1 = shape.y1;
  14479. x2 = shape.x2;
  14480. y2 = shape.y2;
  14481. }
  14482. var percent = shape.percent;
  14483. if (percent === 0) {
  14484. return;
  14485. }
  14486. ctx.moveTo(x1, y1);
  14487. if (percent < 1) {
  14488. x2 = x1 * (1 - percent) + x2 * percent;
  14489. y2 = y1 * (1 - percent) + y2 * percent;
  14490. }
  14491. ctx.lineTo(x2, y2);
  14492. },
  14493. /**
  14494. * Get point at percent
  14495. * @param {number} percent
  14496. * @return {Array.<number>}
  14497. */
  14498. pointAt: function (p) {
  14499. var shape = this.shape;
  14500. return [
  14501. shape.x1 * (1 - p) + shape.x2 * p,
  14502. shape.y1 * (1 - p) + shape.y2 * p
  14503. ];
  14504. }
  14505. });
  14506. /**
  14507. * 贝塞尔曲线
  14508. * @module zrender/shape/BezierCurve
  14509. */
  14510. var out = [];
  14511. function someVectorAt(shape, t, isTangent) {
  14512. var cpx2 = shape.cpx2;
  14513. var cpy2 = shape.cpy2;
  14514. if (cpx2 === null || cpy2 === null) {
  14515. return [
  14516. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14517. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14518. ];
  14519. }
  14520. else {
  14521. return [
  14522. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14523. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14524. ];
  14525. }
  14526. }
  14527. var BezierCurve = Path.extend({
  14528. type: 'bezier-curve',
  14529. shape: {
  14530. x1: 0,
  14531. y1: 0,
  14532. x2: 0,
  14533. y2: 0,
  14534. cpx1: 0,
  14535. cpy1: 0,
  14536. // cpx2: 0,
  14537. // cpy2: 0
  14538. // Curve show percent, for animating
  14539. percent: 1
  14540. },
  14541. style: {
  14542. stroke: '#000',
  14543. fill: null
  14544. },
  14545. buildPath: function (ctx, shape) {
  14546. var x1 = shape.x1;
  14547. var y1 = shape.y1;
  14548. var x2 = shape.x2;
  14549. var y2 = shape.y2;
  14550. var cpx1 = shape.cpx1;
  14551. var cpy1 = shape.cpy1;
  14552. var cpx2 = shape.cpx2;
  14553. var cpy2 = shape.cpy2;
  14554. var percent = shape.percent;
  14555. if (percent === 0) {
  14556. return;
  14557. }
  14558. ctx.moveTo(x1, y1);
  14559. if (cpx2 == null || cpy2 == null) {
  14560. if (percent < 1) {
  14561. quadraticSubdivide(
  14562. x1, cpx1, x2, percent, out
  14563. );
  14564. cpx1 = out[1];
  14565. x2 = out[2];
  14566. quadraticSubdivide(
  14567. y1, cpy1, y2, percent, out
  14568. );
  14569. cpy1 = out[1];
  14570. y2 = out[2];
  14571. }
  14572. ctx.quadraticCurveTo(
  14573. cpx1, cpy1,
  14574. x2, y2
  14575. );
  14576. }
  14577. else {
  14578. if (percent < 1) {
  14579. cubicSubdivide(
  14580. x1, cpx1, cpx2, x2, percent, out
  14581. );
  14582. cpx1 = out[1];
  14583. cpx2 = out[2];
  14584. x2 = out[3];
  14585. cubicSubdivide(
  14586. y1, cpy1, cpy2, y2, percent, out
  14587. );
  14588. cpy1 = out[1];
  14589. cpy2 = out[2];
  14590. y2 = out[3];
  14591. }
  14592. ctx.bezierCurveTo(
  14593. cpx1, cpy1,
  14594. cpx2, cpy2,
  14595. x2, y2
  14596. );
  14597. }
  14598. },
  14599. /**
  14600. * Get point at percent
  14601. * @param {number} t
  14602. * @return {Array.<number>}
  14603. */
  14604. pointAt: function (t) {
  14605. return someVectorAt(this.shape, t, false);
  14606. },
  14607. /**
  14608. * Get tangent at percent
  14609. * @param {number} t
  14610. * @return {Array.<number>}
  14611. */
  14612. tangentAt: function (t) {
  14613. var p = someVectorAt(this.shape, t, true);
  14614. return normalize(p, p);
  14615. }
  14616. });
  14617. /**
  14618. * 圆弧
  14619. * @module zrender/graphic/shape/Arc
  14620. */
  14621. var Arc = Path.extend({
  14622. type: 'arc',
  14623. shape: {
  14624. cx: 0,
  14625. cy: 0,
  14626. r: 0,
  14627. startAngle: 0,
  14628. endAngle: Math.PI * 2,
  14629. clockwise: true
  14630. },
  14631. style: {
  14632. stroke: '#000',
  14633. fill: null
  14634. },
  14635. buildPath: function (ctx, shape) {
  14636. var x = shape.cx;
  14637. var y = shape.cy;
  14638. var r = Math.max(shape.r, 0);
  14639. var startAngle = shape.startAngle;
  14640. var endAngle = shape.endAngle;
  14641. var clockwise = shape.clockwise;
  14642. var unitX = Math.cos(startAngle);
  14643. var unitY = Math.sin(startAngle);
  14644. ctx.moveTo(unitX * r + x, unitY * r + y);
  14645. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14646. }
  14647. });
  14648. // CompoundPath to improve performance
  14649. var CompoundPath = Path.extend({
  14650. type: 'compound',
  14651. shape: {
  14652. paths: null
  14653. },
  14654. _updatePathDirty: function () {
  14655. var dirtyPath = this.__dirtyPath;
  14656. var paths = this.shape.paths;
  14657. for (var i = 0; i < paths.length; i++) {
  14658. // Mark as dirty if any subpath is dirty
  14659. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14660. }
  14661. this.__dirtyPath = dirtyPath;
  14662. this.__dirty = this.__dirty || dirtyPath;
  14663. },
  14664. beforeBrush: function () {
  14665. this._updatePathDirty();
  14666. var paths = this.shape.paths || [];
  14667. var scale = this.getGlobalScale();
  14668. // Update path scale
  14669. for (var i = 0; i < paths.length; i++) {
  14670. if (!paths[i].path) {
  14671. paths[i].createPathProxy();
  14672. }
  14673. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14674. }
  14675. },
  14676. buildPath: function (ctx, shape) {
  14677. var paths = shape.paths || [];
  14678. for (var i = 0; i < paths.length; i++) {
  14679. paths[i].buildPath(ctx, paths[i].shape, true);
  14680. }
  14681. },
  14682. afterBrush: function () {
  14683. var paths = this.shape.paths || [];
  14684. for (var i = 0; i < paths.length; i++) {
  14685. paths[i].__dirtyPath = false;
  14686. }
  14687. },
  14688. getBoundingRect: function () {
  14689. this._updatePathDirty();
  14690. return Path.prototype.getBoundingRect.call(this);
  14691. }
  14692. });
  14693. /**
  14694. * @param {Array.<Object>} colorStops
  14695. */
  14696. var Gradient = function (colorStops) {
  14697. this.colorStops = colorStops || [];
  14698. };
  14699. Gradient.prototype = {
  14700. constructor: Gradient,
  14701. addColorStop: function (offset, color) {
  14702. this.colorStops.push({
  14703. offset: offset,
  14704. color: color
  14705. });
  14706. }
  14707. };
  14708. /**
  14709. * x, y, x2, y2 are all percent from 0 to 1
  14710. * @param {number} [x=0]
  14711. * @param {number} [y=0]
  14712. * @param {number} [x2=1]
  14713. * @param {number} [y2=0]
  14714. * @param {Array.<Object>} colorStops
  14715. * @param {boolean} [globalCoord=false]
  14716. */
  14717. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14718. // Should do nothing more in this constructor. Because gradient can be
  14719. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14720. // this constructor will not be called.
  14721. this.x = x == null ? 0 : x;
  14722. this.y = y == null ? 0 : y;
  14723. this.x2 = x2 == null ? 1 : x2;
  14724. this.y2 = y2 == null ? 0 : y2;
  14725. // Can be cloned
  14726. this.type = 'linear';
  14727. // If use global coord
  14728. this.global = globalCoord || false;
  14729. Gradient.call(this, colorStops);
  14730. };
  14731. LinearGradient.prototype = {
  14732. constructor: LinearGradient
  14733. };
  14734. inherits(LinearGradient, Gradient);
  14735. /**
  14736. * x, y, r are all percent from 0 to 1
  14737. * @param {number} [x=0.5]
  14738. * @param {number} [y=0.5]
  14739. * @param {number} [r=0.5]
  14740. * @param {Array.<Object>} [colorStops]
  14741. * @param {boolean} [globalCoord=false]
  14742. */
  14743. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14744. // Should do nothing more in this constructor. Because gradient can be
  14745. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14746. // this constructor will not be called.
  14747. this.x = x == null ? 0.5 : x;
  14748. this.y = y == null ? 0.5 : y;
  14749. this.r = r == null ? 0.5 : r;
  14750. // Can be cloned
  14751. this.type = 'radial';
  14752. // If use global coord
  14753. this.global = globalCoord || false;
  14754. Gradient.call(this, colorStops);
  14755. };
  14756. RadialGradient.prototype = {
  14757. constructor: RadialGradient
  14758. };
  14759. inherits(RadialGradient, Gradient);
  14760. /**
  14761. * Displayable for incremental rendering. It will be rendered in a separate layer
  14762. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14763. * addDisplayables will render the added displayables incremetally.
  14764. *
  14765. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14766. */
  14767. // TODO Style override ?
  14768. function IncrementalDisplayble(opts) {
  14769. Displayable.call(this, opts);
  14770. this._displayables = [];
  14771. this._temporaryDisplayables = [];
  14772. this._cursor = 0;
  14773. this.notClear = true;
  14774. }
  14775. IncrementalDisplayble.prototype.incremental = true;
  14776. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14777. this._displayables = [];
  14778. this._temporaryDisplayables = [];
  14779. this._cursor = 0;
  14780. this.dirty();
  14781. this.notClear = false;
  14782. };
  14783. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14784. if (notPersistent) {
  14785. this._temporaryDisplayables.push(displayable);
  14786. }
  14787. else {
  14788. this._displayables.push(displayable);
  14789. }
  14790. this.dirty();
  14791. };
  14792. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14793. notPersistent = notPersistent || false;
  14794. for (var i = 0; i < displayables.length; i++) {
  14795. this.addDisplayable(displayables[i], notPersistent);
  14796. }
  14797. };
  14798. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14799. for (var i = this._cursor; i < this._displayables.length; i++) {
  14800. cb && cb(this._displayables[i]);
  14801. }
  14802. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14803. cb && cb(this._temporaryDisplayables[i]);
  14804. }
  14805. };
  14806. IncrementalDisplayble.prototype.update = function () {
  14807. this.updateTransform();
  14808. for (var i = this._cursor; i < this._displayables.length; i++) {
  14809. var displayable = this._displayables[i];
  14810. // PENDING
  14811. displayable.parent = this;
  14812. displayable.update();
  14813. displayable.parent = null;
  14814. }
  14815. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14816. var displayable = this._temporaryDisplayables[i];
  14817. // PENDING
  14818. displayable.parent = this;
  14819. displayable.update();
  14820. displayable.parent = null;
  14821. }
  14822. };
  14823. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14824. // Render persistant displayables.
  14825. for (var i = this._cursor; i < this._displayables.length; i++) {
  14826. var displayable = this._displayables[i];
  14827. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14828. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14829. displayable.afterBrush && displayable.afterBrush(ctx);
  14830. }
  14831. this._cursor = i;
  14832. // Render temporary displayables.
  14833. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14834. var displayable = this._temporaryDisplayables[i];
  14835. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14836. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14837. displayable.afterBrush && displayable.afterBrush(ctx);
  14838. }
  14839. this._temporaryDisplayables = [];
  14840. this.notClear = true;
  14841. };
  14842. var m = [];
  14843. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14844. if (!this._rect) {
  14845. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14846. for (var i = 0; i < this._displayables.length; i++) {
  14847. var displayable = this._displayables[i];
  14848. var childRect = displayable.getBoundingRect().clone();
  14849. if (displayable.needLocalTransform()) {
  14850. childRect.applyTransform(displayable.getLocalTransform(m));
  14851. }
  14852. rect.union(childRect);
  14853. }
  14854. this._rect = rect;
  14855. }
  14856. return this._rect;
  14857. };
  14858. IncrementalDisplayble.prototype.contain = function (x, y) {
  14859. var localPos = this.transformCoordToLocal(x, y);
  14860. var rect = this.getBoundingRect();
  14861. if (rect.contain(localPos[0], localPos[1])) {
  14862. for (var i = 0; i < this._displayables.length; i++) {
  14863. var displayable = this._displayables[i];
  14864. if (displayable.contain(x, y)) {
  14865. return true;
  14866. }
  14867. }
  14868. }
  14869. return false;
  14870. };
  14871. inherits(IncrementalDisplayble, Displayable);
  14872. /*
  14873. * Licensed to the Apache Software Foundation (ASF) under one
  14874. * or more contributor license agreements. See the NOTICE file
  14875. * distributed with this work for additional information
  14876. * regarding copyright ownership. The ASF licenses this file
  14877. * to you under the Apache License, Version 2.0 (the
  14878. * "License"); you may not use this file except in compliance
  14879. * with the License. You may obtain a copy of the License at
  14880. *
  14881. * http://www.apache.org/licenses/LICENSE-2.0
  14882. *
  14883. * Unless required by applicable law or agreed to in writing,
  14884. * software distributed under the License is distributed on an
  14885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14886. * KIND, either express or implied. See the License for the
  14887. * specific language governing permissions and limitations
  14888. * under the License.
  14889. */
  14890. var mathMax$1 = Math.max;
  14891. var mathMin$1 = Math.min;
  14892. var EMPTY_OBJ = {};
  14893. var Z2_EMPHASIS_LIFT = 1;
  14894. // key: label model property nane, value: style property name.
  14895. var CACHED_LABEL_STYLE_PROPERTIES = {
  14896. color: 'textFill',
  14897. textBorderColor: 'textStroke',
  14898. textBorderWidth: 'textStrokeWidth'
  14899. };
  14900. var EMPHASIS = 'emphasis';
  14901. var NORMAL = 'normal';
  14902. // Reserve 0 as default.
  14903. var _highlightNextDigit = 1;
  14904. var _highlightKeyMap = {};
  14905. var _customShapeMap = {};
  14906. /**
  14907. * Extend shape with parameters
  14908. */
  14909. function extendShape(opts) {
  14910. return Path.extend(opts);
  14911. }
  14912. /**
  14913. * Extend path
  14914. */
  14915. function extendPath(pathData, opts) {
  14916. return extendFromString(pathData, opts);
  14917. }
  14918. /**
  14919. * Register a user defined shape.
  14920. * The shape class can be fetched by `getShapeClass`
  14921. * This method will overwrite the registered shapes, including
  14922. * the registered built-in shapes, if using the same `name`.
  14923. * The shape can be used in `custom series` and
  14924. * `graphic component` by declaring `{type: name}`.
  14925. *
  14926. * @param {string} name
  14927. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14928. */
  14929. function registerShape(name, ShapeClass) {
  14930. _customShapeMap[name] = ShapeClass;
  14931. }
  14932. /**
  14933. * Find shape class registered by `registerShape`. Usually used in
  14934. * fetching user defined shape.
  14935. *
  14936. * [Caution]:
  14937. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14938. * to use user registered shapes.
  14939. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14940. * `registerShape` by default. That enables users to get both built-in
  14941. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14942. * the built-in shapes by using names like 'circle', 'rect' via calling
  14943. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14944. * in case that it is overwritten by users, except that some features, like
  14945. * `custom series`, `graphic component`, do it deliberately.
  14946. *
  14947. * (2) In the features like `custom series`, `graphic component`, the user input
  14948. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14949. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14950. * are reserved names, that is, if some user register a shape named `'image'`,
  14951. * the shape will not be used. If we intending to add some more reserved names
  14952. * in feature, that might bring break changes (disable some existing user shape
  14953. * names). But that case probably rearly happen. So we dont make more mechanism
  14954. * to resolve this issue here.
  14955. *
  14956. * @param {string} name
  14957. * @return {Object} The shape class. If not found, return nothing.
  14958. */
  14959. function getShapeClass(name) {
  14960. if (_customShapeMap.hasOwnProperty(name)) {
  14961. return _customShapeMap[name];
  14962. }
  14963. }
  14964. /**
  14965. * Create a path element from path data string
  14966. * @param {string} pathData
  14967. * @param {Object} opts
  14968. * @param {module:zrender/core/BoundingRect} rect
  14969. * @param {string} [layout=cover] 'center' or 'cover'
  14970. */
  14971. function makePath(pathData, opts, rect, layout) {
  14972. var path = createFromString(pathData, opts);
  14973. if (rect) {
  14974. if (layout === 'center') {
  14975. rect = centerGraphic(rect, path.getBoundingRect());
  14976. }
  14977. resizePath(path, rect);
  14978. }
  14979. return path;
  14980. }
  14981. /**
  14982. * Create a image element from image url
  14983. * @param {string} imageUrl image url
  14984. * @param {Object} opts options
  14985. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14986. * @param {string} [layout=cover] 'center' or 'cover'
  14987. */
  14988. function makeImage(imageUrl, rect, layout) {
  14989. var path = new ZImage({
  14990. style: {
  14991. image: imageUrl,
  14992. x: rect.x,
  14993. y: rect.y,
  14994. width: rect.width,
  14995. height: rect.height
  14996. },
  14997. onload: function (img) {
  14998. if (layout === 'center') {
  14999. var boundingRect = {
  15000. width: img.width,
  15001. height: img.height
  15002. };
  15003. path.setStyle(centerGraphic(rect, boundingRect));
  15004. }
  15005. }
  15006. });
  15007. return path;
  15008. }
  15009. /**
  15010. * Get position of centered element in bounding box.
  15011. *
  15012. * @param {Object} rect element local bounding box
  15013. * @param {Object} boundingRect constraint bounding box
  15014. * @return {Object} element position containing x, y, width, and height
  15015. */
  15016. function centerGraphic(rect, boundingRect) {
  15017. // Set rect to center, keep width / height ratio.
  15018. var aspect = boundingRect.width / boundingRect.height;
  15019. var width = rect.height * aspect;
  15020. var height;
  15021. if (width <= rect.width) {
  15022. height = rect.height;
  15023. }
  15024. else {
  15025. width = rect.width;
  15026. height = width / aspect;
  15027. }
  15028. var cx = rect.x + rect.width / 2;
  15029. var cy = rect.y + rect.height / 2;
  15030. return {
  15031. x: cx - width / 2,
  15032. y: cy - height / 2,
  15033. width: width,
  15034. height: height
  15035. };
  15036. }
  15037. var mergePath = mergePath$1;
  15038. /**
  15039. * Resize a path to fit the rect
  15040. * @param {module:zrender/graphic/Path} path
  15041. * @param {Object} rect
  15042. */
  15043. function resizePath(path, rect) {
  15044. if (!path.applyTransform) {
  15045. return;
  15046. }
  15047. var pathRect = path.getBoundingRect();
  15048. var m = pathRect.calculateTransform(rect);
  15049. path.applyTransform(m);
  15050. }
  15051. /**
  15052. * Sub pixel optimize line for canvas
  15053. *
  15054. * @param {Object} param
  15055. * @param {Object} [param.shape]
  15056. * @param {number} [param.shape.x1]
  15057. * @param {number} [param.shape.y1]
  15058. * @param {number} [param.shape.x2]
  15059. * @param {number} [param.shape.y2]
  15060. * @param {Object} [param.style]
  15061. * @param {number} [param.style.lineWidth]
  15062. * @return {Object} Modified param
  15063. */
  15064. function subPixelOptimizeLine(param) {
  15065. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15066. return param;
  15067. }
  15068. /**
  15069. * Sub pixel optimize rect for canvas
  15070. *
  15071. * @param {Object} param
  15072. * @param {Object} [param.shape]
  15073. * @param {number} [param.shape.x]
  15074. * @param {number} [param.shape.y]
  15075. * @param {number} [param.shape.width]
  15076. * @param {number} [param.shape.height]
  15077. * @param {Object} [param.style]
  15078. * @param {number} [param.style.lineWidth]
  15079. * @return {Object} Modified param
  15080. */
  15081. function subPixelOptimizeRect(param) {
  15082. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15083. return param;
  15084. }
  15085. /**
  15086. * Sub pixel optimize for canvas
  15087. *
  15088. * @param {number} position Coordinate, such as x, y
  15089. * @param {number} lineWidth Should be nonnegative integer.
  15090. * @param {boolean=} positiveOrNegative Default false (negative).
  15091. * @return {number} Optimized position.
  15092. */
  15093. var subPixelOptimize = subPixelOptimize$1;
  15094. function hasFillOrStroke(fillOrStroke) {
  15095. return fillOrStroke != null && fillOrStroke !== 'none';
  15096. }
  15097. // Most lifted color are duplicated.
  15098. var liftedColorMap = createHashMap();
  15099. var liftedColorCount = 0;
  15100. function liftColor(color) {
  15101. if (typeof color !== 'string') {
  15102. return color;
  15103. }
  15104. var liftedColor = liftedColorMap.get(color);
  15105. if (!liftedColor) {
  15106. liftedColor = lift(color, -0.1);
  15107. if (liftedColorCount < 10000) {
  15108. liftedColorMap.set(color, liftedColor);
  15109. liftedColorCount++;
  15110. }
  15111. }
  15112. return liftedColor;
  15113. }
  15114. function cacheElementStl(el) {
  15115. if (!el.__hoverStlDirty) {
  15116. return;
  15117. }
  15118. el.__hoverStlDirty = false;
  15119. var hoverStyle = el.__hoverStl;
  15120. if (!hoverStyle) {
  15121. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15122. return;
  15123. }
  15124. var normalStyle = el.__cachedNormalStl = {};
  15125. el.__cachedNormalZ2 = el.z2;
  15126. var elStyle = el.style;
  15127. for (var name in hoverStyle) {
  15128. // See comment in `singleEnterEmphasis`.
  15129. if (hoverStyle[name] != null) {
  15130. normalStyle[name] = elStyle[name];
  15131. }
  15132. }
  15133. // Always cache fill and stroke to normalStyle for lifting color.
  15134. normalStyle.fill = elStyle.fill;
  15135. normalStyle.stroke = elStyle.stroke;
  15136. }
  15137. function singleEnterEmphasis(el) {
  15138. var hoverStl = el.__hoverStl;
  15139. if (!hoverStl || el.__highlighted) {
  15140. return;
  15141. }
  15142. var zr = el.__zr;
  15143. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15144. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15145. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15146. return;
  15147. }
  15148. var elTarget = el;
  15149. var targetStyle = el.style;
  15150. if (useHoverLayer) {
  15151. elTarget = zr.addHover(el);
  15152. targetStyle = elTarget.style;
  15153. }
  15154. rollbackDefaultTextStyle(targetStyle);
  15155. if (!useHoverLayer) {
  15156. cacheElementStl(elTarget);
  15157. }
  15158. // styles can be:
  15159. // {
  15160. // label: {
  15161. // show: false,
  15162. // position: 'outside',
  15163. // fontSize: 18
  15164. // },
  15165. // emphasis: {
  15166. // label: {
  15167. // show: true
  15168. // }
  15169. // }
  15170. // },
  15171. // where properties of `emphasis` may not appear in `normal`. We previously use
  15172. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15173. // But consider rich text and setOption in merge mode, it is impossible to cover
  15174. // all properties in merge. So we use merge mode when setting style here.
  15175. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15176. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15177. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15178. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15179. // style any more in `emphasis`. Users can both set properties directly on normal and
  15180. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15181. targetStyle.extendFrom(hoverStl);
  15182. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15183. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15184. applyDefaultTextStyle(targetStyle);
  15185. if (!useHoverLayer) {
  15186. el.dirty(false);
  15187. el.z2 += Z2_EMPHASIS_LIFT;
  15188. }
  15189. }
  15190. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15191. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15192. targetStyle[prop] = liftColor(targetStyle[prop]);
  15193. }
  15194. }
  15195. function singleEnterNormal(el) {
  15196. var highlighted = el.__highlighted;
  15197. if (!highlighted) {
  15198. return;
  15199. }
  15200. el.__highlighted = false;
  15201. if (el.isGroup) {
  15202. return;
  15203. }
  15204. if (highlighted === 'layer') {
  15205. el.__zr && el.__zr.removeHover(el);
  15206. }
  15207. else {
  15208. var style = el.style;
  15209. var normalStl = el.__cachedNormalStl;
  15210. if (normalStl) {
  15211. rollbackDefaultTextStyle(style);
  15212. el.setStyle(normalStl);
  15213. applyDefaultTextStyle(style);
  15214. }
  15215. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15216. // when `el` is on emphasis state. So here by comparing with 1, we try
  15217. // hard to make the bug case rare.
  15218. var normalZ2 = el.__cachedNormalZ2;
  15219. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15220. el.z2 = normalZ2;
  15221. }
  15222. }
  15223. }
  15224. function traverseUpdate(el, updater, commonParam) {
  15225. // If root is group, also enter updater for `highDownOnUpdate`.
  15226. var fromState = NORMAL;
  15227. var toState = NORMAL;
  15228. var trigger;
  15229. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15230. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15231. updater(el, commonParam);
  15232. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15233. el.isGroup && el.traverse(function (child) {
  15234. !child.isGroup && updater(child, commonParam);
  15235. });
  15236. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15237. }
  15238. /**
  15239. * Set hover style (namely "emphasis style") of element, based on the current
  15240. * style of the given `el`.
  15241. * This method should be called after all of the normal styles have been adopted
  15242. * to the `el`. See the reason on `setHoverStyle`.
  15243. *
  15244. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15245. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15246. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15247. * Often used when item group has a label element and it's hoverStyle is different.
  15248. * @param {Object|boolean} [hoverStl] The specified hover style.
  15249. * If set as `false`, disable the hover style.
  15250. * Similarly, The `el.hoverStyle` can alse be set
  15251. * as `false` to disable the hover style.
  15252. * Otherwise, use the default hover style if not provided.
  15253. */
  15254. function setElementHoverStyle(el, hoverStl) {
  15255. // For performance consideration, it might be better to make the "hover style" only the
  15256. // difference properties from the "normal style", but not a entire copy of all styles.
  15257. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15258. el.__hoverStlDirty = true;
  15259. // FIXME
  15260. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15261. // It probably should be saved on `data` of series. Consider the cases:
  15262. // (1) A highlighted elements are moved out of the view port and re-enter
  15263. // again by dataZoom.
  15264. // (2) call `setOption` and replace elements totally when they are highlighted.
  15265. if (el.__highlighted) {
  15266. // Consider the case:
  15267. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15268. // should be adapted to the `el`. Notice here new "normal styles" should have
  15269. // been set outside and the cached "normal style" is out of date.
  15270. el.__cachedNormalStl = null;
  15271. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15272. // of this method. In most cases, `z2` is not set and hover style should be able
  15273. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15274. // `doSingleLeaveHover` for details.
  15275. singleEnterNormal(el);
  15276. singleEnterEmphasis(el);
  15277. }
  15278. }
  15279. function onElementMouseOver(e) {
  15280. !shouldSilent(this, e)
  15281. // "emphasis" event highlight has higher priority than mouse highlight.
  15282. && !this.__highByOuter
  15283. && traverseUpdate(this, singleEnterEmphasis);
  15284. }
  15285. function onElementMouseOut(e) {
  15286. !shouldSilent(this, e)
  15287. // "emphasis" event highlight has higher priority than mouse highlight.
  15288. && !this.__highByOuter
  15289. && traverseUpdate(this, singleEnterNormal);
  15290. }
  15291. function onElementEmphasisEvent(highlightDigit) {
  15292. this.__highByOuter |= 1 << (highlightDigit || 0);
  15293. traverseUpdate(this, singleEnterEmphasis);
  15294. }
  15295. function onElementNormalEvent(highlightDigit) {
  15296. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15297. && traverseUpdate(this, singleEnterNormal);
  15298. }
  15299. function shouldSilent(el, e) {
  15300. return el.__highDownSilentOnTouch && e.zrByTouch;
  15301. }
  15302. /**
  15303. * Set hover style (namely "emphasis style") of element,
  15304. * based on the current style of the given `el`.
  15305. *
  15306. * (1)
  15307. * **CONSTRAINTS** for this method:
  15308. * <A> This method MUST be called after all of the normal styles having been adopted
  15309. * to the `el`.
  15310. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15311. * "normal style" having been set to the el.
  15312. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15313. * a default hover style).
  15314. *
  15315. * The reason: this method treat the current style of the `el` as the "normal style"
  15316. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15317. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15318. * logic, where the el should shift from the original emphasis style to the new
  15319. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15320. *
  15321. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15322. * not found a better solution yet to fit the backward compatibility, performance and
  15323. * the current programming style.
  15324. *
  15325. * (2)
  15326. * Call the method for a "root" element once. Do not call it for each descendants.
  15327. * If the descendants elemenets of a group has itself hover style different from the
  15328. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15329. * not call this method for them.
  15330. *
  15331. * (3) These input parameters can be set directly on `el`:
  15332. *
  15333. * @param {module:zrender/Element} el
  15334. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15335. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15336. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15337. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15338. */
  15339. function setHoverStyle(el, hoverStyle) {
  15340. setAsHighDownDispatcher(el, true);
  15341. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15342. }
  15343. /**
  15344. * @param {module:zrender/Element} el
  15345. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15346. * Since `setHoverStyle` has the constraint that it must be called after
  15347. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15348. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15349. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15350. * to sync outside style settings to "emphasis" state.
  15351. * @this {string} This dispatcher `el`.
  15352. * @param {string} fromState Can be "normal" or "emphasis".
  15353. * `fromState` might equal to `toState`,
  15354. * for example, when this method is called when `el` is
  15355. * on "emphasis" state.
  15356. * @param {string} toState Can be "normal" or "emphasis".
  15357. *
  15358. * FIXME
  15359. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15360. * Because it is not a complete solution. The update
  15361. * listener should not have been mount in element,
  15362. * and the normal/emphasis state should not have
  15363. * mantained on elements.
  15364. *
  15365. * @param {boolean} [el.highDownSilentOnTouch=false]
  15366. * In touch device, mouseover event will be trigger on touchstart event
  15367. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15368. * conveniently use hoverStyle when tap on touch screen without additional
  15369. * code for compatibility.
  15370. * But if the chart/component has select feature, which usually also use
  15371. * hoverStyle, there might be conflict between 'select-highlight' and
  15372. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15373. * In this case, `highDownSilentOnTouch` should be used to disable
  15374. * hover-highlight on touch device.
  15375. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15376. */
  15377. function setAsHighDownDispatcher(el, asDispatcher) {
  15378. var disable = asDispatcher === false;
  15379. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15380. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15381. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15382. el.__highDownOnUpdate = el.highDownOnUpdate;
  15383. // Simple optimize, since this method might be
  15384. // called for each elements of a group in some cases.
  15385. if (!disable || el.__highDownDispatcher) {
  15386. var method = disable ? 'off' : 'on';
  15387. // Duplicated function will be auto-ignored, see Eventful.js.
  15388. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15389. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15390. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15391. // Also keep previous record.
  15392. el.__highByOuter = el.__highByOuter || 0;
  15393. el.__highDownDispatcher = !disable;
  15394. }
  15395. }
  15396. /**
  15397. * @param {module:zrender/src/Element} el
  15398. * @return {boolean}
  15399. */
  15400. function isHighDownDispatcher(el) {
  15401. return !!(el && el.__highDownDispatcher);
  15402. }
  15403. /**
  15404. * Support hightlight/downplay record on each elements.
  15405. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15406. * user triggerred hightlight/downplay should not conflict.
  15407. * Only all of the highlightDigit cleared, return to normal.
  15408. * @param {string} highlightKey
  15409. * @return {number} highlightDigit
  15410. */
  15411. function getHighlightDigit(highlightKey) {
  15412. var highlightDigit = _highlightKeyMap[highlightKey];
  15413. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15414. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15415. }
  15416. return highlightDigit;
  15417. }
  15418. /**
  15419. * See more info in `setTextStyleCommon`.
  15420. * @param {Object|module:zrender/graphic/Style} normalStyle
  15421. * @param {Object} emphasisStyle
  15422. * @param {module:echarts/model/Model} normalModel
  15423. * @param {module:echarts/model/Model} emphasisModel
  15424. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15425. * @param {string|Function} [opt.defaultText]
  15426. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15427. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15428. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15429. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15430. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15431. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15432. * @param {Object} [normalSpecified]
  15433. * @param {Object} [emphasisSpecified]
  15434. */
  15435. function setLabelStyle(
  15436. normalStyle, emphasisStyle,
  15437. normalModel, emphasisModel,
  15438. opt,
  15439. normalSpecified, emphasisSpecified
  15440. ) {
  15441. opt = opt || EMPTY_OBJ;
  15442. var labelFetcher = opt.labelFetcher;
  15443. var labelDataIndex = opt.labelDataIndex;
  15444. var labelDimIndex = opt.labelDimIndex;
  15445. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15446. // is not supported util someone requests.
  15447. var showNormal = normalModel.getShallow('show');
  15448. var showEmphasis = emphasisModel.getShallow('show');
  15449. // Consider performance, only fetch label when necessary.
  15450. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15451. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15452. var baseText;
  15453. if (showNormal || showEmphasis) {
  15454. if (labelFetcher) {
  15455. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15456. }
  15457. if (baseText == null) {
  15458. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15459. }
  15460. }
  15461. var normalStyleText = showNormal ? baseText : null;
  15462. var emphasisStyleText = showEmphasis
  15463. ? retrieve2(
  15464. labelFetcher
  15465. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15466. : null,
  15467. baseText
  15468. )
  15469. : null;
  15470. // Optimize: If style.text is null, text will not be drawn.
  15471. if (normalStyleText != null || emphasisStyleText != null) {
  15472. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15473. // values have to be set on `normalStyle`.
  15474. // If we set default values on `emphasisStyle`, consider case:
  15475. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15476. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15477. // Then the 'red' will not work on emphasis.
  15478. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15479. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15480. }
  15481. normalStyle.text = normalStyleText;
  15482. emphasisStyle.text = emphasisStyleText;
  15483. }
  15484. /**
  15485. * Modify label style manually.
  15486. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15487. *
  15488. * @param {module:zrender/src/Element} el
  15489. * @param {Object} [normalStyleProps] optional
  15490. * @param {Object} [emphasisStyleProps] optional
  15491. */
  15492. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15493. var elStyle = el.style;
  15494. if (normalStyleProps) {
  15495. rollbackDefaultTextStyle(elStyle);
  15496. el.setStyle(normalStyleProps);
  15497. applyDefaultTextStyle(elStyle);
  15498. }
  15499. elStyle = el.__hoverStl;
  15500. if (emphasisStyleProps && elStyle) {
  15501. rollbackDefaultTextStyle(elStyle);
  15502. extend(elStyle, emphasisStyleProps);
  15503. applyDefaultTextStyle(elStyle);
  15504. }
  15505. }
  15506. /**
  15507. * Set basic textStyle properties.
  15508. * See more info in `setTextStyleCommon`.
  15509. * @param {Object|module:zrender/graphic/Style} textStyle
  15510. * @param {module:echarts/model/Model} model
  15511. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15512. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15513. * @param {boolean} [isEmphasis]
  15514. */
  15515. function setTextStyle(
  15516. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15517. ) {
  15518. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15519. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15520. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15521. return textStyle;
  15522. }
  15523. /**
  15524. * Set text option in the style.
  15525. * See more info in `setTextStyleCommon`.
  15526. * @deprecated
  15527. * @param {Object} textStyle
  15528. * @param {module:echarts/model/Model} labelModel
  15529. * @param {string|boolean} defaultColor Default text color.
  15530. * If set as false, it will be processed as a emphasis style.
  15531. */
  15532. function setText(textStyle, labelModel, defaultColor) {
  15533. var opt = {isRectText: true};
  15534. var isEmphasis;
  15535. if (defaultColor === false) {
  15536. isEmphasis = true;
  15537. }
  15538. else {
  15539. // Support setting color as 'auto' to get visual color.
  15540. opt.autoColor = defaultColor;
  15541. }
  15542. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15543. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15544. }
  15545. /**
  15546. * The uniform entry of set text style, that is, retrieve style definitions
  15547. * from `model` and set to `textStyle` object.
  15548. *
  15549. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15550. * properties will be set. (Consider the states of normal and emphasis and
  15551. * default value can be adopted, merge would make the logic too complicated
  15552. * to manage.)
  15553. *
  15554. * The `textStyle` object can either be a plain object or an instance of
  15555. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15556. * After this mothod called, the `textStyle` object can then be used in
  15557. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15558. *
  15559. * Default value will be adopted and `insideRollbackOpt` will be created.
  15560. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15561. *
  15562. * opt: {
  15563. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15564. * isRectText: boolean,
  15565. * autoColor: string, specify a color when color is 'auto',
  15566. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15567. * If autoColor specified, it is used as default textFill.
  15568. * useInsideStyle:
  15569. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15570. * if `textFill` is not specified.
  15571. * `false`: Do not use inside style.
  15572. * `null/undefined`: use inside style if `isRectText` is true and
  15573. * `textFill` is not specified and textPosition contains `'inside'`.
  15574. * forceRich: boolean
  15575. * }
  15576. */
  15577. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15578. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15579. opt = opt || EMPTY_OBJ;
  15580. if (opt.isRectText) {
  15581. var textPosition;
  15582. if (opt.getTextPosition) {
  15583. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15584. }
  15585. else {
  15586. textPosition = textStyleModel.getShallow('position')
  15587. || (isEmphasis ? null : 'inside');
  15588. // 'outside' is not a valid zr textPostion value, but used
  15589. // in bar series, and magric type should be considered.
  15590. textPosition === 'outside' && (textPosition = 'top');
  15591. }
  15592. textStyle.textPosition = textPosition;
  15593. textStyle.textOffset = textStyleModel.getShallow('offset');
  15594. var labelRotate = textStyleModel.getShallow('rotate');
  15595. labelRotate != null && (labelRotate *= Math.PI / 180);
  15596. textStyle.textRotation = labelRotate;
  15597. textStyle.textDistance = retrieve2(
  15598. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15599. );
  15600. }
  15601. var ecModel = textStyleModel.ecModel;
  15602. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15603. // Consider case:
  15604. // {
  15605. // data: [{
  15606. // value: 12,
  15607. // label: {
  15608. // rich: {
  15609. // // no 'a' here but using parent 'a'.
  15610. // }
  15611. // }
  15612. // }],
  15613. // rich: {
  15614. // a: { ... }
  15615. // }
  15616. // }
  15617. var richItemNames = getRichItemNames(textStyleModel);
  15618. var richResult;
  15619. if (richItemNames) {
  15620. richResult = {};
  15621. for (var name in richItemNames) {
  15622. if (richItemNames.hasOwnProperty(name)) {
  15623. // Cascade is supported in rich.
  15624. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15625. // In rich, never `disableBox`.
  15626. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15627. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15628. // That might confuses users. So probably we should put `textStyleModel` as the
  15629. // root ancestor of the `richTextStyle`. But that would be a break change.
  15630. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15631. }
  15632. }
  15633. }
  15634. textStyle.rich = richResult;
  15635. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15636. if (opt.forceRich && !opt.textStyle) {
  15637. opt.textStyle = {};
  15638. }
  15639. return textStyle;
  15640. }
  15641. // Consider case:
  15642. // {
  15643. // data: [{
  15644. // value: 12,
  15645. // label: {
  15646. // rich: {
  15647. // // no 'a' here but using parent 'a'.
  15648. // }
  15649. // }
  15650. // }],
  15651. // rich: {
  15652. // a: { ... }
  15653. // }
  15654. // }
  15655. function getRichItemNames(textStyleModel) {
  15656. // Use object to remove duplicated names.
  15657. var richItemNameMap;
  15658. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15659. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15660. if (rich) {
  15661. richItemNameMap = richItemNameMap || {};
  15662. for (var name in rich) {
  15663. if (rich.hasOwnProperty(name)) {
  15664. richItemNameMap[name] = 1;
  15665. }
  15666. }
  15667. }
  15668. textStyleModel = textStyleModel.parentModel;
  15669. }
  15670. return richItemNameMap;
  15671. }
  15672. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15673. // In merge mode, default value should not be given.
  15674. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15675. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15676. || globalTextStyle.color;
  15677. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15678. || globalTextStyle.textBorderColor;
  15679. textStyle.textStrokeWidth = retrieve2(
  15680. textStyleModel.getShallow('textBorderWidth'),
  15681. globalTextStyle.textBorderWidth
  15682. );
  15683. if (!isEmphasis) {
  15684. if (isBlock) {
  15685. textStyle.insideRollbackOpt = opt;
  15686. applyDefaultTextStyle(textStyle);
  15687. }
  15688. // Set default finally.
  15689. if (textStyle.textFill == null) {
  15690. textStyle.textFill = opt.autoColor;
  15691. }
  15692. }
  15693. // Do not use `getFont` here, because merge should be supported, where
  15694. // part of these properties may be changed in emphasis style, and the
  15695. // others should remain their original value got from normal style.
  15696. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15697. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15698. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15699. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15700. textStyle.textAlign = textStyleModel.getShallow('align');
  15701. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15702. || textStyleModel.getShallow('baseline');
  15703. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15704. textStyle.textWidth = textStyleModel.getShallow('width');
  15705. textStyle.textHeight = textStyleModel.getShallow('height');
  15706. textStyle.textTag = textStyleModel.getShallow('tag');
  15707. if (!isBlock || !opt.disableBox) {
  15708. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15709. textStyle.textPadding = textStyleModel.getShallow('padding');
  15710. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15711. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15712. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15713. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15714. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15715. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15716. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15717. }
  15718. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15719. || globalTextStyle.textShadowColor;
  15720. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15721. || globalTextStyle.textShadowBlur;
  15722. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15723. || globalTextStyle.textShadowOffsetX;
  15724. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15725. || globalTextStyle.textShadowOffsetY;
  15726. }
  15727. function getAutoColor(color, opt) {
  15728. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15729. }
  15730. /**
  15731. * Give some default value to the input `textStyle` object, based on the current settings
  15732. * in this `textStyle` object.
  15733. *
  15734. * The Scenario:
  15735. * when text position is `inside` and `textFill` is not specified, we show
  15736. * text border by default for better view. But it should be considered that text position
  15737. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15738. * restore the style.
  15739. *
  15740. * Usage (& NOTICE):
  15741. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15742. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15743. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15744. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15745. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15746. */
  15747. function applyDefaultTextStyle(textStyle) {
  15748. var textPosition = textStyle.textPosition;
  15749. var opt = textStyle.insideRollbackOpt;
  15750. var insideRollback;
  15751. if (opt && textStyle.textFill == null) {
  15752. var autoColor = opt.autoColor;
  15753. var isRectText = opt.isRectText;
  15754. var useInsideStyle = opt.useInsideStyle;
  15755. var useInsideStyleCache = useInsideStyle !== false
  15756. && (useInsideStyle === true
  15757. || (isRectText
  15758. && textPosition
  15759. // textPosition can be [10, 30]
  15760. && typeof textPosition === 'string'
  15761. && textPosition.indexOf('inside') >= 0
  15762. )
  15763. );
  15764. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15765. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15766. if (useInsideStyleCache || useAutoColorCache) {
  15767. insideRollback = {
  15768. textFill: textStyle.textFill,
  15769. textStroke: textStyle.textStroke,
  15770. textStrokeWidth: textStyle.textStrokeWidth
  15771. };
  15772. }
  15773. if (useInsideStyleCache) {
  15774. textStyle.textFill = '#fff';
  15775. // Consider text with #fff overflow its container.
  15776. if (textStyle.textStroke == null) {
  15777. textStyle.textStroke = autoColor;
  15778. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15779. }
  15780. }
  15781. if (useAutoColorCache) {
  15782. textStyle.textFill = autoColor;
  15783. }
  15784. }
  15785. // Always set `insideRollback`, so that the previous one can be cleared.
  15786. textStyle.insideRollback = insideRollback;
  15787. }
  15788. /**
  15789. * Consider the case: in a scatter,
  15790. * label: {
  15791. * normal: {position: 'inside'},
  15792. * emphasis: {position: 'top'}
  15793. * }
  15794. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15795. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15796. * should be retured to 'autoColor', but not keep '#fff'.
  15797. */
  15798. function rollbackDefaultTextStyle(style) {
  15799. var insideRollback = style.insideRollback;
  15800. if (insideRollback) {
  15801. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15802. style.textFill = insideRollback.textFill;
  15803. style.textStroke = insideRollback.textStroke;
  15804. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15805. style.insideRollback = null;
  15806. }
  15807. }
  15808. function getFont(opt, ecModel) {
  15809. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15810. return trim([
  15811. // FIXME in node-canvas fontWeight is before fontStyle
  15812. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15813. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15814. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15815. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15816. ].join(' '));
  15817. }
  15818. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15819. if (typeof dataIndex === 'function') {
  15820. cb = dataIndex;
  15821. dataIndex = null;
  15822. }
  15823. // Do not check 'animation' property directly here. Consider this case:
  15824. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15825. // but its parent model (`seriesModel`) does.
  15826. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15827. if (animationEnabled) {
  15828. var postfix = isUpdate ? 'Update' : '';
  15829. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15830. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15831. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15832. if (typeof animationDelay === 'function') {
  15833. animationDelay = animationDelay(
  15834. dataIndex,
  15835. animatableModel.getAnimationDelayParams
  15836. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15837. : null
  15838. );
  15839. }
  15840. if (typeof duration === 'function') {
  15841. duration = duration(dataIndex);
  15842. }
  15843. duration > 0
  15844. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15845. : (el.stopAnimation(), el.attr(props), cb && cb());
  15846. }
  15847. else {
  15848. el.stopAnimation();
  15849. el.attr(props);
  15850. cb && cb();
  15851. }
  15852. }
  15853. /**
  15854. * Update graphic element properties with or without animation according to the
  15855. * configuration in series.
  15856. *
  15857. * Caution: this method will stop previous animation.
  15858. * So if do not use this method to one element twice before
  15859. * animation starts, unless you know what you are doing.
  15860. *
  15861. * @param {module:zrender/Element} el
  15862. * @param {Object} props
  15863. * @param {module:echarts/model/Model} [animatableModel]
  15864. * @param {number} [dataIndex]
  15865. * @param {Function} [cb]
  15866. * @example
  15867. * graphic.updateProps(el, {
  15868. * position: [100, 100]
  15869. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15870. * // Or
  15871. * graphic.updateProps(el, {
  15872. * position: [100, 100]
  15873. * }, seriesModel, function () { console.log('Animation done!'); });
  15874. */
  15875. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15876. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15877. }
  15878. /**
  15879. * Init graphic element properties with or without animation according to the
  15880. * configuration in series.
  15881. *
  15882. * Caution: this method will stop previous animation.
  15883. * So if do not use this method to one element twice before
  15884. * animation starts, unless you know what you are doing.
  15885. *
  15886. * @param {module:zrender/Element} el
  15887. * @param {Object} props
  15888. * @param {module:echarts/model/Model} [animatableModel]
  15889. * @param {number} [dataIndex]
  15890. * @param {Function} cb
  15891. */
  15892. function initProps(el, props, animatableModel, dataIndex, cb) {
  15893. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15894. }
  15895. /**
  15896. * Get transform matrix of target (param target),
  15897. * in coordinate of its ancestor (param ancestor)
  15898. *
  15899. * @param {module:zrender/mixin/Transformable} target
  15900. * @param {module:zrender/mixin/Transformable} [ancestor]
  15901. */
  15902. function getTransform(target, ancestor) {
  15903. var mat = identity([]);
  15904. while (target && target !== ancestor) {
  15905. mul$1(mat, target.getLocalTransform(), mat);
  15906. target = target.parent;
  15907. }
  15908. return mat;
  15909. }
  15910. /**
  15911. * Apply transform to an vertex.
  15912. * @param {Array.<number>} target [x, y]
  15913. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15914. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15915. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15916. * @param {boolean=} invert Whether use invert matrix.
  15917. * @return {Array.<number>} [x, y]
  15918. */
  15919. function applyTransform$1(target, transform, invert$$1) {
  15920. if (transform && !isArrayLike(transform)) {
  15921. transform = Transformable.getLocalTransform(transform);
  15922. }
  15923. if (invert$$1) {
  15924. transform = invert([], transform);
  15925. }
  15926. return applyTransform([], target, transform);
  15927. }
  15928. /**
  15929. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15930. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15931. * @param {boolean=} invert Whether use invert matrix.
  15932. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15933. */
  15934. function transformDirection(direction, transform, invert$$1) {
  15935. // Pick a base, ensure that transform result will not be (0, 0).
  15936. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15937. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15938. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15939. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15940. var vertex = [
  15941. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15942. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15943. ];
  15944. vertex = applyTransform$1(vertex, transform, invert$$1);
  15945. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15946. ? (vertex[0] > 0 ? 'right' : 'left')
  15947. : (vertex[1] > 0 ? 'bottom' : 'top');
  15948. }
  15949. /**
  15950. * Apply group transition animation from g1 to g2.
  15951. * If no animatableModel, no animation.
  15952. */
  15953. function groupTransition(g1, g2, animatableModel, cb) {
  15954. if (!g1 || !g2) {
  15955. return;
  15956. }
  15957. function getElMap(g) {
  15958. var elMap = {};
  15959. g.traverse(function (el) {
  15960. if (!el.isGroup && el.anid) {
  15961. elMap[el.anid] = el;
  15962. }
  15963. });
  15964. return elMap;
  15965. }
  15966. function getAnimatableProps(el) {
  15967. var obj = {
  15968. position: clone$1(el.position),
  15969. rotation: el.rotation
  15970. };
  15971. if (el.shape) {
  15972. obj.shape = extend({}, el.shape);
  15973. }
  15974. return obj;
  15975. }
  15976. var elMap1 = getElMap(g1);
  15977. g2.traverse(function (el) {
  15978. if (!el.isGroup && el.anid) {
  15979. var oldEl = elMap1[el.anid];
  15980. if (oldEl) {
  15981. var newProp = getAnimatableProps(el);
  15982. el.attr(getAnimatableProps(oldEl));
  15983. updateProps(el, newProp, animatableModel, el.dataIndex);
  15984. }
  15985. // else {
  15986. // if (el.previousProps) {
  15987. // graphic.updateProps
  15988. // }
  15989. // }
  15990. }
  15991. });
  15992. }
  15993. /**
  15994. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15995. * @param {Object} rect {x, y, width, height}
  15996. * @return {Array.<Array.<number>>} A new clipped points.
  15997. */
  15998. function clipPointsByRect(points, rect) {
  15999. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  16000. // and when element have border.
  16001. return map(points, function (point) {
  16002. var x = point[0];
  16003. x = mathMax$1(x, rect.x);
  16004. x = mathMin$1(x, rect.x + rect.width);
  16005. var y = point[1];
  16006. y = mathMax$1(y, rect.y);
  16007. y = mathMin$1(y, rect.y + rect.height);
  16008. return [x, y];
  16009. });
  16010. }
  16011. /**
  16012. * @param {Object} targetRect {x, y, width, height}
  16013. * @param {Object} rect {x, y, width, height}
  16014. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  16015. */
  16016. function clipRectByRect(targetRect, rect) {
  16017. var x = mathMax$1(targetRect.x, rect.x);
  16018. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  16019. var y = mathMax$1(targetRect.y, rect.y);
  16020. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  16021. // If the total rect is cliped, nothing, including the border,
  16022. // should be painted. So return undefined.
  16023. if (x2 >= x && y2 >= y) {
  16024. return {
  16025. x: x,
  16026. y: y,
  16027. width: x2 - x,
  16028. height: y2 - y
  16029. };
  16030. }
  16031. }
  16032. /**
  16033. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  16034. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  16035. * @param {Object} [rect] {x, y, width, height}
  16036. * @return {module:zrender/Element} Icon path or image element.
  16037. */
  16038. function createIcon(iconStr, opt, rect) {
  16039. opt = extend({rectHover: true}, opt);
  16040. var style = opt.style = {strokeNoScale: true};
  16041. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  16042. if (iconStr) {
  16043. return iconStr.indexOf('image://') === 0
  16044. ? (
  16045. style.image = iconStr.slice(8),
  16046. defaults(style, rect),
  16047. new ZImage(opt)
  16048. )
  16049. : (
  16050. makePath(
  16051. iconStr.replace('path://', ''),
  16052. opt,
  16053. rect,
  16054. 'center'
  16055. )
  16056. );
  16057. }
  16058. }
  16059. /**
  16060. * Return `true` if the given line (line `a`) and the given polygon
  16061. * are intersect.
  16062. * Note that we do not count colinear as intersect here because no
  16063. * requirement for that. We could do that if required in future.
  16064. *
  16065. * @param {number} a1x
  16066. * @param {number} a1y
  16067. * @param {number} a2x
  16068. * @param {number} a2y
  16069. * @param {Array.<Array.<number>>} points Points of the polygon.
  16070. * @return {boolean}
  16071. */
  16072. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16073. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16074. var p = points[i];
  16075. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16076. return true;
  16077. }
  16078. p2 = p;
  16079. }
  16080. }
  16081. /**
  16082. * Return `true` if the given two lines (line `a` and line `b`)
  16083. * are intersect.
  16084. * Note that we do not count colinear as intersect here because no
  16085. * requirement for that. We could do that if required in future.
  16086. *
  16087. * @param {number} a1x
  16088. * @param {number} a1y
  16089. * @param {number} a2x
  16090. * @param {number} a2y
  16091. * @param {number} b1x
  16092. * @param {number} b1y
  16093. * @param {number} b2x
  16094. * @param {number} b2y
  16095. * @return {boolean}
  16096. */
  16097. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16098. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16099. var mx = a2x - a1x;
  16100. var my = a2y - a1y;
  16101. var nx = b2x - b1x;
  16102. var ny = b2y - b1y;
  16103. // `vec_m` and `vec_n` are parallel iff
  16104. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16105. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16106. if (nearZero(nmCrossProduct)) {
  16107. return false;
  16108. }
  16109. // `vec_m` and `vec_n` are intersect iff
  16110. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16111. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16112. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16113. var b1a1x = a1x - b1x;
  16114. var b1a1y = a1y - b1y;
  16115. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16116. if (q < 0 || q > 1) {
  16117. return false;
  16118. }
  16119. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16120. if (p < 0 || p > 1) {
  16121. return false;
  16122. }
  16123. return true;
  16124. }
  16125. /**
  16126. * Cross product of 2-dimension vector.
  16127. */
  16128. function crossProduct2d(x1, y1, x2, y2) {
  16129. return x1 * y2 - x2 * y1;
  16130. }
  16131. function nearZero(val) {
  16132. return val <= (1e-6) && val >= -(1e-6);
  16133. }
  16134. // Register built-in shapes. These shapes might be overwirtten
  16135. // by users, although we do not recommend that.
  16136. registerShape('circle', Circle);
  16137. registerShape('sector', Sector);
  16138. registerShape('ring', Ring);
  16139. registerShape('polygon', Polygon);
  16140. registerShape('polyline', Polyline);
  16141. registerShape('rect', Rect);
  16142. registerShape('line', Line);
  16143. registerShape('bezierCurve', BezierCurve);
  16144. registerShape('arc', Arc);
  16145. var graphic = (Object.freeze || Object)({
  16146. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16147. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16148. extendShape: extendShape,
  16149. extendPath: extendPath,
  16150. registerShape: registerShape,
  16151. getShapeClass: getShapeClass,
  16152. makePath: makePath,
  16153. makeImage: makeImage,
  16154. mergePath: mergePath,
  16155. resizePath: resizePath,
  16156. subPixelOptimizeLine: subPixelOptimizeLine,
  16157. subPixelOptimizeRect: subPixelOptimizeRect,
  16158. subPixelOptimize: subPixelOptimize,
  16159. setElementHoverStyle: setElementHoverStyle,
  16160. setHoverStyle: setHoverStyle,
  16161. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16162. isHighDownDispatcher: isHighDownDispatcher,
  16163. getHighlightDigit: getHighlightDigit,
  16164. setLabelStyle: setLabelStyle,
  16165. modifyLabelStyle: modifyLabelStyle,
  16166. setTextStyle: setTextStyle,
  16167. setText: setText,
  16168. getFont: getFont,
  16169. updateProps: updateProps,
  16170. initProps: initProps,
  16171. getTransform: getTransform,
  16172. applyTransform: applyTransform$1,
  16173. transformDirection: transformDirection,
  16174. groupTransition: groupTransition,
  16175. clipPointsByRect: clipPointsByRect,
  16176. clipRectByRect: clipRectByRect,
  16177. createIcon: createIcon,
  16178. linePolygonIntersect: linePolygonIntersect,
  16179. lineLineIntersect: lineLineIntersect,
  16180. Group: Group,
  16181. Image: ZImage,
  16182. Text: Text,
  16183. Circle: Circle,
  16184. Sector: Sector,
  16185. Ring: Ring,
  16186. Polygon: Polygon,
  16187. Polyline: Polyline,
  16188. Rect: Rect,
  16189. Line: Line,
  16190. BezierCurve: BezierCurve,
  16191. Arc: Arc,
  16192. IncrementalDisplayable: IncrementalDisplayble,
  16193. CompoundPath: CompoundPath,
  16194. LinearGradient: LinearGradient,
  16195. RadialGradient: RadialGradient,
  16196. BoundingRect: BoundingRect
  16197. });
  16198. /*
  16199. * Licensed to the Apache Software Foundation (ASF) under one
  16200. * or more contributor license agreements. See the NOTICE file
  16201. * distributed with this work for additional information
  16202. * regarding copyright ownership. The ASF licenses this file
  16203. * to you under the Apache License, Version 2.0 (the
  16204. * "License"); you may not use this file except in compliance
  16205. * with the License. You may obtain a copy of the License at
  16206. *
  16207. * http://www.apache.org/licenses/LICENSE-2.0
  16208. *
  16209. * Unless required by applicable law or agreed to in writing,
  16210. * software distributed under the License is distributed on an
  16211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16212. * KIND, either express or implied. See the License for the
  16213. * specific language governing permissions and limitations
  16214. * under the License.
  16215. */
  16216. var PATH_COLOR = ['textStyle', 'color'];
  16217. var textStyleMixin = {
  16218. /**
  16219. * Get color property or get color from option.textStyle.color
  16220. * @param {boolean} [isEmphasis]
  16221. * @return {string}
  16222. */
  16223. getTextColor: function (isEmphasis) {
  16224. var ecModel = this.ecModel;
  16225. return this.getShallow('color')
  16226. || (
  16227. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16228. );
  16229. },
  16230. /**
  16231. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16232. * @return {string}
  16233. */
  16234. getFont: function () {
  16235. return getFont({
  16236. fontStyle: this.getShallow('fontStyle'),
  16237. fontWeight: this.getShallow('fontWeight'),
  16238. fontSize: this.getShallow('fontSize'),
  16239. fontFamily: this.getShallow('fontFamily')
  16240. }, this.ecModel);
  16241. },
  16242. getTextRect: function (text) {
  16243. return getBoundingRect(
  16244. text,
  16245. this.getFont(),
  16246. this.getShallow('align'),
  16247. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16248. this.getShallow('padding'),
  16249. this.getShallow('lineHeight'),
  16250. this.getShallow('rich'),
  16251. this.getShallow('truncateText')
  16252. );
  16253. }
  16254. };
  16255. /*
  16256. * Licensed to the Apache Software Foundation (ASF) under one
  16257. * or more contributor license agreements. See the NOTICE file
  16258. * distributed with this work for additional information
  16259. * regarding copyright ownership. The ASF licenses this file
  16260. * to you under the Apache License, Version 2.0 (the
  16261. * "License"); you may not use this file except in compliance
  16262. * with the License. You may obtain a copy of the License at
  16263. *
  16264. * http://www.apache.org/licenses/LICENSE-2.0
  16265. *
  16266. * Unless required by applicable law or agreed to in writing,
  16267. * software distributed under the License is distributed on an
  16268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16269. * KIND, either express or implied. See the License for the
  16270. * specific language governing permissions and limitations
  16271. * under the License.
  16272. */
  16273. var getItemStyle = makeStyleMapper(
  16274. [
  16275. ['fill', 'color'],
  16276. ['stroke', 'borderColor'],
  16277. ['lineWidth', 'borderWidth'],
  16278. ['opacity'],
  16279. ['shadowBlur'],
  16280. ['shadowOffsetX'],
  16281. ['shadowOffsetY'],
  16282. ['shadowColor'],
  16283. ['textPosition'],
  16284. ['textAlign']
  16285. ]
  16286. );
  16287. var itemStyleMixin = {
  16288. getItemStyle: function (excludes, includes) {
  16289. var style = getItemStyle(this, excludes, includes);
  16290. var lineDash = this.getBorderLineDash();
  16291. lineDash && (style.lineDash = lineDash);
  16292. return style;
  16293. },
  16294. getBorderLineDash: function () {
  16295. var lineType = this.get('borderType');
  16296. return (lineType === 'solid' || lineType == null) ? null
  16297. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16298. }
  16299. };
  16300. /*
  16301. * Licensed to the Apache Software Foundation (ASF) under one
  16302. * or more contributor license agreements. See the NOTICE file
  16303. * distributed with this work for additional information
  16304. * regarding copyright ownership. The ASF licenses this file
  16305. * to you under the Apache License, Version 2.0 (the
  16306. * "License"); you may not use this file except in compliance
  16307. * with the License. You may obtain a copy of the License at
  16308. *
  16309. * http://www.apache.org/licenses/LICENSE-2.0
  16310. *
  16311. * Unless required by applicable law or agreed to in writing,
  16312. * software distributed under the License is distributed on an
  16313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16314. * KIND, either express or implied. See the License for the
  16315. * specific language governing permissions and limitations
  16316. * under the License.
  16317. */
  16318. /**
  16319. * @module echarts/model/Model
  16320. */
  16321. var mixin$1 = mixin;
  16322. var inner = makeInner();
  16323. /**
  16324. * @alias module:echarts/model/Model
  16325. * @constructor
  16326. * @param {Object} [option]
  16327. * @param {module:echarts/model/Model} [parentModel]
  16328. * @param {module:echarts/model/Global} [ecModel]
  16329. */
  16330. function Model(option, parentModel, ecModel) {
  16331. /**
  16332. * @type {module:echarts/model/Model}
  16333. * @readOnly
  16334. */
  16335. this.parentModel = parentModel;
  16336. /**
  16337. * @type {module:echarts/model/Global}
  16338. * @readOnly
  16339. */
  16340. this.ecModel = ecModel;
  16341. /**
  16342. * @type {Object}
  16343. * @protected
  16344. */
  16345. this.option = option;
  16346. // Simple optimization
  16347. // if (this.init) {
  16348. // if (arguments.length <= 4) {
  16349. // this.init(option, parentModel, ecModel, extraOpt);
  16350. // }
  16351. // else {
  16352. // this.init.apply(this, arguments);
  16353. // }
  16354. // }
  16355. }
  16356. Model.prototype = {
  16357. constructor: Model,
  16358. /**
  16359. * Model 的初始化函数
  16360. * @param {Object} option
  16361. */
  16362. init: null,
  16363. /**
  16364. * 从新的 Option merge
  16365. */
  16366. mergeOption: function (option) {
  16367. merge(this.option, option, true);
  16368. },
  16369. /**
  16370. * @param {string|Array.<string>} path
  16371. * @param {boolean} [ignoreParent=false]
  16372. * @return {*}
  16373. */
  16374. get: function (path, ignoreParent) {
  16375. if (path == null) {
  16376. return this.option;
  16377. }
  16378. return doGet(
  16379. this.option,
  16380. this.parsePath(path),
  16381. !ignoreParent && getParent(this, path)
  16382. );
  16383. },
  16384. /**
  16385. * @param {string} key
  16386. * @param {boolean} [ignoreParent=false]
  16387. * @return {*}
  16388. */
  16389. getShallow: function (key, ignoreParent) {
  16390. var option = this.option;
  16391. var val = option == null ? option : option[key];
  16392. var parentModel = !ignoreParent && getParent(this, key);
  16393. if (val == null && parentModel) {
  16394. val = parentModel.getShallow(key);
  16395. }
  16396. return val;
  16397. },
  16398. /**
  16399. * @param {string|Array.<string>} [path]
  16400. * @param {module:echarts/model/Model} [parentModel]
  16401. * @return {module:echarts/model/Model}
  16402. */
  16403. getModel: function (path, parentModel) {
  16404. var obj = path == null
  16405. ? this.option
  16406. : doGet(this.option, path = this.parsePath(path));
  16407. var thisParentModel;
  16408. parentModel = parentModel || (
  16409. (thisParentModel = getParent(this, path))
  16410. && thisParentModel.getModel(path)
  16411. );
  16412. return new Model(obj, parentModel, this.ecModel);
  16413. },
  16414. /**
  16415. * If model has option
  16416. */
  16417. isEmpty: function () {
  16418. return this.option == null;
  16419. },
  16420. restoreData: function () {},
  16421. // Pending
  16422. clone: function () {
  16423. var Ctor = this.constructor;
  16424. return new Ctor(clone(this.option));
  16425. },
  16426. setReadOnly: function (properties) {
  16427. // clazzUtil.setReadOnly(this, properties);
  16428. },
  16429. // If path is null/undefined, return null/undefined.
  16430. parsePath: function (path) {
  16431. if (typeof path === 'string') {
  16432. path = path.split('.');
  16433. }
  16434. return path;
  16435. },
  16436. /**
  16437. * @param {Function} getParentMethod
  16438. * param {Array.<string>|string} path
  16439. * return {module:echarts/model/Model}
  16440. */
  16441. customizeGetParent: function (getParentMethod) {
  16442. inner(this).getParent = getParentMethod;
  16443. },
  16444. isAnimationEnabled: function () {
  16445. if (!env$1.node) {
  16446. if (this.option.animation != null) {
  16447. return !!this.option.animation;
  16448. }
  16449. else if (this.parentModel) {
  16450. return this.parentModel.isAnimationEnabled();
  16451. }
  16452. }
  16453. }
  16454. };
  16455. function doGet(obj, pathArr, parentModel) {
  16456. for (var i = 0; i < pathArr.length; i++) {
  16457. // Ignore empty
  16458. if (!pathArr[i]) {
  16459. continue;
  16460. }
  16461. // obj could be number/string/... (like 0)
  16462. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16463. if (obj == null) {
  16464. break;
  16465. }
  16466. }
  16467. if (obj == null && parentModel) {
  16468. obj = parentModel.get(pathArr);
  16469. }
  16470. return obj;
  16471. }
  16472. // `path` can be null/undefined
  16473. function getParent(model, path) {
  16474. var getParentMethod = inner(model).getParent;
  16475. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16476. }
  16477. // Enable Model.extend.
  16478. enableClassExtend(Model);
  16479. enableClassCheck(Model);
  16480. mixin$1(Model, lineStyleMixin);
  16481. mixin$1(Model, areaStyleMixin);
  16482. mixin$1(Model, textStyleMixin);
  16483. mixin$1(Model, itemStyleMixin);
  16484. /*
  16485. * Licensed to the Apache Software Foundation (ASF) under one
  16486. * or more contributor license agreements. See the NOTICE file
  16487. * distributed with this work for additional information
  16488. * regarding copyright ownership. The ASF licenses this file
  16489. * to you under the Apache License, Version 2.0 (the
  16490. * "License"); you may not use this file except in compliance
  16491. * with the License. You may obtain a copy of the License at
  16492. *
  16493. * http://www.apache.org/licenses/LICENSE-2.0
  16494. *
  16495. * Unless required by applicable law or agreed to in writing,
  16496. * software distributed under the License is distributed on an
  16497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16498. * KIND, either express or implied. See the License for the
  16499. * specific language governing permissions and limitations
  16500. * under the License.
  16501. */
  16502. var base = 0;
  16503. /**
  16504. * @public
  16505. * @param {string} type
  16506. * @return {string}
  16507. */
  16508. function getUID(type) {
  16509. // Considering the case of crossing js context,
  16510. // use Math.random to make id as unique as possible.
  16511. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16512. }
  16513. /**
  16514. * @inner
  16515. */
  16516. function enableSubTypeDefaulter(entity) {
  16517. var subTypeDefaulters = {};
  16518. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16519. componentType = parseClassType$1(componentType);
  16520. subTypeDefaulters[componentType.main] = defaulter;
  16521. };
  16522. entity.determineSubType = function (componentType, option) {
  16523. var type = option.type;
  16524. if (!type) {
  16525. var componentTypeMain = parseClassType$1(componentType).main;
  16526. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16527. type = subTypeDefaulters[componentTypeMain](option);
  16528. }
  16529. }
  16530. return type;
  16531. };
  16532. return entity;
  16533. }
  16534. /**
  16535. * Topological travel on Activity Network (Activity On Vertices).
  16536. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16537. *
  16538. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16539. *
  16540. * If there is circle dependencey, Error will be thrown.
  16541. *
  16542. */
  16543. function enableTopologicalTravel(entity, dependencyGetter) {
  16544. /**
  16545. * @public
  16546. * @param {Array.<string>} targetNameList Target Component type list.
  16547. * Can be ['aa', 'bb', 'aa.xx']
  16548. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16549. * @param {Function} callback Params: componentType, dependencies.
  16550. * @param {Object} context Scope of callback.
  16551. */
  16552. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16553. if (!targetNameList.length) {
  16554. return;
  16555. }
  16556. var result = makeDepndencyGraph(fullNameList);
  16557. var graph = result.graph;
  16558. var stack = result.noEntryList;
  16559. var targetNameSet = {};
  16560. each$1(targetNameList, function (name) {
  16561. targetNameSet[name] = true;
  16562. });
  16563. while (stack.length) {
  16564. var currComponentType = stack.pop();
  16565. var currVertex = graph[currComponentType];
  16566. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16567. if (isInTargetNameSet) {
  16568. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16569. delete targetNameSet[currComponentType];
  16570. }
  16571. each$1(
  16572. currVertex.successor,
  16573. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16574. );
  16575. }
  16576. each$1(targetNameSet, function () {
  16577. throw new Error('Circle dependency may exists');
  16578. });
  16579. function removeEdge(succComponentType) {
  16580. graph[succComponentType].entryCount--;
  16581. if (graph[succComponentType].entryCount === 0) {
  16582. stack.push(succComponentType);
  16583. }
  16584. }
  16585. // Consider this case: legend depends on series, and we call
  16586. // chart.setOption({series: [...]}), where only series is in option.
  16587. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16588. // not be called, but only sereis.mergeOption is called. Thus legend
  16589. // have no chance to update its local record about series (like which
  16590. // name of series is available in legend).
  16591. function removeEdgeAndAdd(succComponentType) {
  16592. targetNameSet[succComponentType] = true;
  16593. removeEdge(succComponentType);
  16594. }
  16595. };
  16596. /**
  16597. * DepndencyGraph: {Object}
  16598. * key: conponentType,
  16599. * value: {
  16600. * successor: [conponentTypes...],
  16601. * originalDeps: [conponentTypes...],
  16602. * entryCount: {number}
  16603. * }
  16604. */
  16605. function makeDepndencyGraph(fullNameList) {
  16606. var graph = {};
  16607. var noEntryList = [];
  16608. each$1(fullNameList, function (name) {
  16609. var thisItem = createDependencyGraphItem(graph, name);
  16610. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16611. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16612. thisItem.entryCount = availableDeps.length;
  16613. if (thisItem.entryCount === 0) {
  16614. noEntryList.push(name);
  16615. }
  16616. each$1(availableDeps, function (dependentName) {
  16617. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16618. thisItem.predecessor.push(dependentName);
  16619. }
  16620. var thatItem = createDependencyGraphItem(graph, dependentName);
  16621. if (indexOf(thatItem.successor, dependentName) < 0) {
  16622. thatItem.successor.push(name);
  16623. }
  16624. });
  16625. });
  16626. return {graph: graph, noEntryList: noEntryList};
  16627. }
  16628. function createDependencyGraphItem(graph, name) {
  16629. if (!graph[name]) {
  16630. graph[name] = {predecessor: [], successor: []};
  16631. }
  16632. return graph[name];
  16633. }
  16634. function getAvailableDependencies(originalDeps, fullNameList) {
  16635. var availableDeps = [];
  16636. each$1(originalDeps, function (dep) {
  16637. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16638. });
  16639. return availableDeps;
  16640. }
  16641. }
  16642. /*
  16643. * Licensed to the Apache Software Foundation (ASF) under one
  16644. * or more contributor license agreements. See the NOTICE file
  16645. * distributed with this work for additional information
  16646. * regarding copyright ownership. The ASF licenses this file
  16647. * to you under the Apache License, Version 2.0 (the
  16648. * "License"); you may not use this file except in compliance
  16649. * with the License. You may obtain a copy of the License at
  16650. *
  16651. * http://www.apache.org/licenses/LICENSE-2.0
  16652. *
  16653. * Unless required by applicable law or agreed to in writing,
  16654. * software distributed under the License is distributed on an
  16655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16656. * KIND, either express or implied. See the License for the
  16657. * specific language governing permissions and limitations
  16658. * under the License.
  16659. */
  16660. /*
  16661. * A third-party license is embeded for some of the code in this file:
  16662. * The method "quantile" was copied from "d3.js".
  16663. * (See more details in the comment of the method below.)
  16664. * The use of the source code of this file is also subject to the terms
  16665. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16666. * </licenses/LICENSE-d3>).
  16667. */
  16668. var RADIAN_EPSILON = 1e-4;
  16669. function _trim(str) {
  16670. return str.replace(/^\s+|\s+$/g, '');
  16671. }
  16672. /**
  16673. * Linear mapping a value from domain to range
  16674. * @memberOf module:echarts/util/number
  16675. * @param {(number|Array.<number>)} val
  16676. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16677. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16678. * @param {boolean} clamp
  16679. * @return {(number|Array.<number>}
  16680. */
  16681. function linearMap(val, domain, range, clamp) {
  16682. var subDomain = domain[1] - domain[0];
  16683. var subRange = range[1] - range[0];
  16684. if (subDomain === 0) {
  16685. return subRange === 0
  16686. ? range[0]
  16687. : (range[0] + range[1]) / 2;
  16688. }
  16689. // Avoid accuracy problem in edge, such as
  16690. // 146.39 - 62.83 === 83.55999999999999.
  16691. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16692. // It is a little verbose for efficiency considering this method
  16693. // is a hotspot.
  16694. if (clamp) {
  16695. if (subDomain > 0) {
  16696. if (val <= domain[0]) {
  16697. return range[0];
  16698. }
  16699. else if (val >= domain[1]) {
  16700. return range[1];
  16701. }
  16702. }
  16703. else {
  16704. if (val >= domain[0]) {
  16705. return range[0];
  16706. }
  16707. else if (val <= domain[1]) {
  16708. return range[1];
  16709. }
  16710. }
  16711. }
  16712. else {
  16713. if (val === domain[0]) {
  16714. return range[0];
  16715. }
  16716. if (val === domain[1]) {
  16717. return range[1];
  16718. }
  16719. }
  16720. return (val - domain[0]) / subDomain * subRange + range[0];
  16721. }
  16722. /**
  16723. * Convert a percent string to absolute number.
  16724. * Returns NaN if percent is not a valid string or number
  16725. * @memberOf module:echarts/util/number
  16726. * @param {string|number} percent
  16727. * @param {number} all
  16728. * @return {number}
  16729. */
  16730. function parsePercent$1(percent, all) {
  16731. switch (percent) {
  16732. case 'center':
  16733. case 'middle':
  16734. percent = '50%';
  16735. break;
  16736. case 'left':
  16737. case 'top':
  16738. percent = '0%';
  16739. break;
  16740. case 'right':
  16741. case 'bottom':
  16742. percent = '100%';
  16743. break;
  16744. }
  16745. if (typeof percent === 'string') {
  16746. if (_trim(percent).match(/%$/)) {
  16747. return parseFloat(percent) / 100 * all;
  16748. }
  16749. return parseFloat(percent);
  16750. }
  16751. return percent == null ? NaN : +percent;
  16752. }
  16753. /**
  16754. * (1) Fix rounding error of float numbers.
  16755. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16756. *
  16757. * @param {number} x
  16758. * @param {number} [precision]
  16759. * @param {boolean} [returnStr]
  16760. * @return {number|string}
  16761. */
  16762. function round$1(x, precision, returnStr) {
  16763. if (precision == null) {
  16764. precision = 10;
  16765. }
  16766. // Avoid range error
  16767. precision = Math.min(Math.max(0, precision), 20);
  16768. x = (+x).toFixed(precision);
  16769. return returnStr ? x : +x;
  16770. }
  16771. /**
  16772. * asc sort arr.
  16773. * The input arr will be modified.
  16774. *
  16775. * @param {Array} arr
  16776. * @return {Array} The input arr.
  16777. */
  16778. function asc(arr) {
  16779. arr.sort(function (a, b) {
  16780. return a - b;
  16781. });
  16782. return arr;
  16783. }
  16784. /**
  16785. * Get precision
  16786. * @param {number} val
  16787. */
  16788. function getPrecision(val) {
  16789. val = +val;
  16790. if (isNaN(val)) {
  16791. return 0;
  16792. }
  16793. // It is much faster than methods converting number to string as follows
  16794. // var tmp = val.toString();
  16795. // return tmp.length - 1 - tmp.indexOf('.');
  16796. // especially when precision is low
  16797. var e = 1;
  16798. var count = 0;
  16799. while (Math.round(val * e) / e !== val) {
  16800. e *= 10;
  16801. count++;
  16802. }
  16803. return count;
  16804. }
  16805. /**
  16806. * @param {string|number} val
  16807. * @return {number}
  16808. */
  16809. function getPrecisionSafe(val) {
  16810. var str = val.toString();
  16811. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16812. var eIndex = str.indexOf('e');
  16813. if (eIndex > 0) {
  16814. var precision = +str.slice(eIndex + 1);
  16815. return precision < 0 ? -precision : 0;
  16816. }
  16817. else {
  16818. var dotIndex = str.indexOf('.');
  16819. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16820. }
  16821. }
  16822. /**
  16823. * Minimal dicernible data precisioin according to a single pixel.
  16824. *
  16825. * @param {Array.<number>} dataExtent
  16826. * @param {Array.<number>} pixelExtent
  16827. * @return {number} precision
  16828. */
  16829. function getPixelPrecision(dataExtent, pixelExtent) {
  16830. var log = Math.log;
  16831. var LN10 = Math.LN10;
  16832. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16833. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16834. // toFixed() digits argument must be between 0 and 20.
  16835. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16836. return !isFinite(precision) ? 20 : precision;
  16837. }
  16838. /**
  16839. * Get a data of given precision, assuring the sum of percentages
  16840. * in valueList is 1.
  16841. * The largest remainer method is used.
  16842. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16843. *
  16844. * @param {Array.<number>} valueList a list of all data
  16845. * @param {number} idx index of the data to be processed in valueList
  16846. * @param {number} precision integer number showing digits of precision
  16847. * @return {number} percent ranging from 0 to 100
  16848. */
  16849. function getPercentWithPrecision(valueList, idx, precision) {
  16850. if (!valueList[idx]) {
  16851. return 0;
  16852. }
  16853. var sum = reduce(valueList, function (acc, val) {
  16854. return acc + (isNaN(val) ? 0 : val);
  16855. }, 0);
  16856. if (sum === 0) {
  16857. return 0;
  16858. }
  16859. var digits = Math.pow(10, precision);
  16860. var votesPerQuota = map(valueList, function (val) {
  16861. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16862. });
  16863. var targetSeats = digits * 100;
  16864. var seats = map(votesPerQuota, function (votes) {
  16865. // Assign automatic seats.
  16866. return Math.floor(votes);
  16867. });
  16868. var currentSum = reduce(seats, function (acc, val) {
  16869. return acc + val;
  16870. }, 0);
  16871. var remainder = map(votesPerQuota, function (votes, idx) {
  16872. return votes - seats[idx];
  16873. });
  16874. // Has remainding votes.
  16875. while (currentSum < targetSeats) {
  16876. // Find next largest remainder.
  16877. var max = Number.NEGATIVE_INFINITY;
  16878. var maxId = null;
  16879. for (var i = 0, len = remainder.length; i < len; ++i) {
  16880. if (remainder[i] > max) {
  16881. max = remainder[i];
  16882. maxId = i;
  16883. }
  16884. }
  16885. // Add a vote to max remainder.
  16886. ++seats[maxId];
  16887. remainder[maxId] = 0;
  16888. ++currentSum;
  16889. }
  16890. return seats[idx] / digits;
  16891. }
  16892. // Number.MAX_SAFE_INTEGER, ie do not support.
  16893. var MAX_SAFE_INTEGER = 9007199254740991;
  16894. /**
  16895. * To 0 - 2 * PI, considering negative radian.
  16896. * @param {number} radian
  16897. * @return {number}
  16898. */
  16899. function remRadian(radian) {
  16900. var pi2 = Math.PI * 2;
  16901. return (radian % pi2 + pi2) % pi2;
  16902. }
  16903. /**
  16904. * @param {type} radian
  16905. * @return {boolean}
  16906. */
  16907. function isRadianAroundZero(val) {
  16908. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16909. }
  16910. /* eslint-disable */
  16911. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  16912. /* eslint-enable */
  16913. /**
  16914. * @param {string|Date|number} value These values can be accepted:
  16915. * + An instance of Date, represent a time in its own time zone.
  16916. * + Or string in a subset of ISO 8601, only including:
  16917. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16918. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16919. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16920. * all of which will be treated as local time if time zone is not specified
  16921. * (see <https://momentjs.com/>).
  16922. * + Or other string format, including (all of which will be treated as loacal time):
  16923. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16924. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16925. * + a timestamp, which represent a time in UTC.
  16926. * @return {Date} date
  16927. */
  16928. function parseDate(value) {
  16929. if (value instanceof Date) {
  16930. return value;
  16931. }
  16932. else if (typeof value === 'string') {
  16933. // Different browsers parse date in different way, so we parse it manually.
  16934. // Some other issues:
  16935. // new Date('1970-01-01') is UTC,
  16936. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16937. // See issue #3623
  16938. var match = TIME_REG.exec(value);
  16939. if (!match) {
  16940. // return Invalid Date.
  16941. return new Date(NaN);
  16942. }
  16943. // Use local time when no timezone offset specifed.
  16944. if (!match[8]) {
  16945. // match[n] can only be string or undefined.
  16946. // But take care of '12' + 1 => '121'.
  16947. return new Date(
  16948. +match[1],
  16949. +(match[2] || 1) - 1,
  16950. +match[3] || 1,
  16951. +match[4] || 0,
  16952. +(match[5] || 0),
  16953. +match[6] || 0,
  16954. +match[7] || 0
  16955. );
  16956. }
  16957. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16958. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16959. // For example, system timezone is set as "Time Zone: America/Toronto",
  16960. // then these code will get different result:
  16961. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16962. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16963. // So we should not use `new Date`, but use `Date.UTC`.
  16964. else {
  16965. var hour = +match[4] || 0;
  16966. if (match[8].toUpperCase() !== 'Z') {
  16967. hour -= match[8].slice(0, 3);
  16968. }
  16969. return new Date(Date.UTC(
  16970. +match[1],
  16971. +(match[2] || 1) - 1,
  16972. +match[3] || 1,
  16973. hour,
  16974. +(match[5] || 0),
  16975. +match[6] || 0,
  16976. +match[7] || 0
  16977. ));
  16978. }
  16979. }
  16980. else if (value == null) {
  16981. return new Date(NaN);
  16982. }
  16983. return new Date(Math.round(value));
  16984. }
  16985. /**
  16986. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16987. *
  16988. * @param {number} val
  16989. * @return {number}
  16990. */
  16991. function quantity(val) {
  16992. return Math.pow(10, quantityExponent(val));
  16993. }
  16994. /**
  16995. * Exponent of the quantity of a number
  16996. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16997. *
  16998. * @param {number} val non-negative value
  16999. * @return {number}
  17000. */
  17001. function quantityExponent(val) {
  17002. if (val === 0) {
  17003. return 0;
  17004. }
  17005. var exp = Math.floor(Math.log(val) / Math.LN10);
  17006. /**
  17007. * exp is expected to be the rounded-down result of the base-10 log of val.
  17008. * But due to the precision loss with Math.log(val), we need to restore it
  17009. * using 10^exp to make sure we can get val back from exp. #11249
  17010. */
  17011. if (val / Math.pow(10, exp) >= 10) {
  17012. exp++;
  17013. }
  17014. return exp;
  17015. }
  17016. /**
  17017. * find a “nice” number approximately equal to x. Round the number if round = true,
  17018. * take ceiling if round = false. The primary observation is that the “nicest”
  17019. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  17020. *
  17021. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  17022. *
  17023. * @param {number} val Non-negative value.
  17024. * @param {boolean} round
  17025. * @return {number}
  17026. */
  17027. function nice(val, round) {
  17028. var exponent = quantityExponent(val);
  17029. var exp10 = Math.pow(10, exponent);
  17030. var f = val / exp10; // 1 <= f < 10
  17031. var nf;
  17032. if (round) {
  17033. if (f < 1.5) {
  17034. nf = 1;
  17035. }
  17036. else if (f < 2.5) {
  17037. nf = 2;
  17038. }
  17039. else if (f < 4) {
  17040. nf = 3;
  17041. }
  17042. else if (f < 7) {
  17043. nf = 5;
  17044. }
  17045. else {
  17046. nf = 10;
  17047. }
  17048. }
  17049. else {
  17050. if (f < 1) {
  17051. nf = 1;
  17052. }
  17053. else if (f < 2) {
  17054. nf = 2;
  17055. }
  17056. else if (f < 3) {
  17057. nf = 3;
  17058. }
  17059. else if (f < 5) {
  17060. nf = 5;
  17061. }
  17062. else {
  17063. nf = 10;
  17064. }
  17065. }
  17066. val = nf * exp10;
  17067. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17068. // 20 is the uppper bound of toFixed.
  17069. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17070. }
  17071. /**
  17072. * This code was copied from "d3.js"
  17073. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17074. * See the license statement at the head of this file.
  17075. * @param {Array.<number>} ascArr
  17076. */
  17077. function quantile(ascArr, p) {
  17078. var H = (ascArr.length - 1) * p + 1;
  17079. var h = Math.floor(H);
  17080. var v = +ascArr[h - 1];
  17081. var e = H - h;
  17082. return e ? v + e * (ascArr[h] - v) : v;
  17083. }
  17084. /**
  17085. * Order intervals asc, and split them when overlap.
  17086. * expect(numberUtil.reformIntervals([
  17087. * {interval: [18, 62], close: [1, 1]},
  17088. * {interval: [-Infinity, -70], close: [0, 0]},
  17089. * {interval: [-70, -26], close: [1, 1]},
  17090. * {interval: [-26, 18], close: [1, 1]},
  17091. * {interval: [62, 150], close: [1, 1]},
  17092. * {interval: [106, 150], close: [1, 1]},
  17093. * {interval: [150, Infinity], close: [0, 0]}
  17094. * ])).toEqual([
  17095. * {interval: [-Infinity, -70], close: [0, 0]},
  17096. * {interval: [-70, -26], close: [1, 1]},
  17097. * {interval: [-26, 18], close: [0, 1]},
  17098. * {interval: [18, 62], close: [0, 1]},
  17099. * {interval: [62, 150], close: [0, 1]},
  17100. * {interval: [150, Infinity], close: [0, 0]}
  17101. * ]);
  17102. * @param {Array.<Object>} list, where `close` mean open or close
  17103. * of the interval, and Infinity can be used.
  17104. * @return {Array.<Object>} The origin list, which has been reformed.
  17105. */
  17106. function reformIntervals(list) {
  17107. list.sort(function (a, b) {
  17108. return littleThan(a, b, 0) ? -1 : 1;
  17109. });
  17110. var curr = -Infinity;
  17111. var currClose = 1;
  17112. for (var i = 0; i < list.length;) {
  17113. var interval = list[i].interval;
  17114. var close = list[i].close;
  17115. for (var lg = 0; lg < 2; lg++) {
  17116. if (interval[lg] <= curr) {
  17117. interval[lg] = curr;
  17118. close[lg] = !lg ? 1 - currClose : 1;
  17119. }
  17120. curr = interval[lg];
  17121. currClose = close[lg];
  17122. }
  17123. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17124. list.splice(i, 1);
  17125. }
  17126. else {
  17127. i++;
  17128. }
  17129. }
  17130. return list;
  17131. function littleThan(a, b, lg) {
  17132. return a.interval[lg] < b.interval[lg]
  17133. || (
  17134. a.interval[lg] === b.interval[lg]
  17135. && (
  17136. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17137. || (!lg && littleThan(a, b, 1))
  17138. )
  17139. );
  17140. }
  17141. }
  17142. /**
  17143. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17144. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17145. * subtraction forces infinities to NaN
  17146. *
  17147. * @param {*} v
  17148. * @return {boolean}
  17149. */
  17150. function isNumeric(v) {
  17151. return v - parseFloat(v) >= 0;
  17152. }
  17153. var number = (Object.freeze || Object)({
  17154. linearMap: linearMap,
  17155. parsePercent: parsePercent$1,
  17156. round: round$1,
  17157. asc: asc,
  17158. getPrecision: getPrecision,
  17159. getPrecisionSafe: getPrecisionSafe,
  17160. getPixelPrecision: getPixelPrecision,
  17161. getPercentWithPrecision: getPercentWithPrecision,
  17162. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17163. remRadian: remRadian,
  17164. isRadianAroundZero: isRadianAroundZero,
  17165. parseDate: parseDate,
  17166. quantity: quantity,
  17167. quantityExponent: quantityExponent,
  17168. nice: nice,
  17169. quantile: quantile,
  17170. reformIntervals: reformIntervals,
  17171. isNumeric: isNumeric
  17172. });
  17173. /*
  17174. * Licensed to the Apache Software Foundation (ASF) under one
  17175. * or more contributor license agreements. See the NOTICE file
  17176. * distributed with this work for additional information
  17177. * regarding copyright ownership. The ASF licenses this file
  17178. * to you under the Apache License, Version 2.0 (the
  17179. * "License"); you may not use this file except in compliance
  17180. * with the License. You may obtain a copy of the License at
  17181. *
  17182. * http://www.apache.org/licenses/LICENSE-2.0
  17183. *
  17184. * Unless required by applicable law or agreed to in writing,
  17185. * software distributed under the License is distributed on an
  17186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17187. * KIND, either express or implied. See the License for the
  17188. * specific language governing permissions and limitations
  17189. * under the License.
  17190. */
  17191. // import Text from 'zrender/src/graphic/Text';
  17192. /**
  17193. * 每三位默认加,格式化
  17194. * @param {string|number} x
  17195. * @return {string}
  17196. */
  17197. function addCommas(x) {
  17198. if (isNaN(x)) {
  17199. return '-';
  17200. }
  17201. x = (x + '').split('.');
  17202. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17203. + (x.length > 1 ? ('.' + x[1]) : '');
  17204. }
  17205. /**
  17206. * @param {string} str
  17207. * @param {boolean} [upperCaseFirst=false]
  17208. * @return {string} str
  17209. */
  17210. function toCamelCase(str, upperCaseFirst) {
  17211. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17212. return group1.toUpperCase();
  17213. });
  17214. if (upperCaseFirst && str) {
  17215. str = str.charAt(0).toUpperCase() + str.slice(1);
  17216. }
  17217. return str;
  17218. }
  17219. var normalizeCssArray$1 = normalizeCssArray;
  17220. var replaceReg = /([&<>"'])/g;
  17221. var replaceMap = {
  17222. '&': '&amp;',
  17223. '<': '&lt;',
  17224. '>': '&gt;',
  17225. '"': '&quot;',
  17226. '\'': '&#39;'
  17227. };
  17228. function encodeHTML(source) {
  17229. return source == null
  17230. ? ''
  17231. : (source + '').replace(replaceReg, function (str, c) {
  17232. return replaceMap[c];
  17233. });
  17234. }
  17235. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17236. var wrapVar = function (varName, seriesIdx) {
  17237. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17238. };
  17239. /**
  17240. * Template formatter
  17241. * @param {string} tpl
  17242. * @param {Array.<Object>|Object} paramsList
  17243. * @param {boolean} [encode=false]
  17244. * @return {string}
  17245. */
  17246. function formatTpl(tpl, paramsList, encode) {
  17247. if (!isArray(paramsList)) {
  17248. paramsList = [paramsList];
  17249. }
  17250. var seriesLen = paramsList.length;
  17251. if (!seriesLen) {
  17252. return '';
  17253. }
  17254. var $vars = paramsList[0].$vars || [];
  17255. for (var i = 0; i < $vars.length; i++) {
  17256. var alias = TPL_VAR_ALIAS[i];
  17257. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17258. }
  17259. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17260. for (var k = 0; k < $vars.length; k++) {
  17261. var val = paramsList[seriesIdx][$vars[k]];
  17262. tpl = tpl.replace(
  17263. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17264. encode ? encodeHTML(val) : val
  17265. );
  17266. }
  17267. }
  17268. return tpl;
  17269. }
  17270. /**
  17271. * simple Template formatter
  17272. *
  17273. * @param {string} tpl
  17274. * @param {Object} param
  17275. * @param {boolean} [encode=false]
  17276. * @return {string}
  17277. */
  17278. function formatTplSimple(tpl, param, encode) {
  17279. each$1(param, function (value, key) {
  17280. tpl = tpl.replace(
  17281. '{' + key + '}',
  17282. encode ? encodeHTML(value) : value
  17283. );
  17284. });
  17285. return tpl;
  17286. }
  17287. /**
  17288. * @param {Object|string} [opt] If string, means color.
  17289. * @param {string} [opt.color]
  17290. * @param {string} [opt.extraCssText]
  17291. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17292. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17293. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17294. * @return {string}
  17295. */
  17296. function getTooltipMarker(opt, extraCssText) {
  17297. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17298. var color = opt.color;
  17299. var type = opt.type;
  17300. var extraCssText = opt.extraCssText;
  17301. var renderMode = opt.renderMode || 'html';
  17302. var markerId = opt.markerId || 'X';
  17303. if (!color) {
  17304. return '';
  17305. }
  17306. if (renderMode === 'html') {
  17307. return type === 'subItem'
  17308. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17309. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17310. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17311. : '<span style="display:inline-block;margin-right:5px;'
  17312. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17313. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17314. }
  17315. else {
  17316. // Space for rich element marker
  17317. return {
  17318. renderMode: renderMode,
  17319. content: '{marker' + markerId + '|} ',
  17320. style: {
  17321. color: color
  17322. }
  17323. };
  17324. }
  17325. }
  17326. function pad(str, len) {
  17327. str += '';
  17328. return '0000'.substr(0, len - str.length) + str;
  17329. }
  17330. /**
  17331. * ISO Date format
  17332. * @param {string} tpl
  17333. * @param {number} value
  17334. * @param {boolean} [isUTC=false] Default in local time.
  17335. * see `module:echarts/scale/Time`
  17336. * and `module:echarts/util/number#parseDate`.
  17337. * @inner
  17338. */
  17339. function formatTime(tpl, value, isUTC) {
  17340. if (tpl === 'week'
  17341. || tpl === 'month'
  17342. || tpl === 'quarter'
  17343. || tpl === 'half-year'
  17344. || tpl === 'year'
  17345. ) {
  17346. tpl = 'MM-dd\nyyyy';
  17347. }
  17348. var date = parseDate(value);
  17349. var utc = isUTC ? 'UTC' : '';
  17350. var y = date['get' + utc + 'FullYear']();
  17351. var M = date['get' + utc + 'Month']() + 1;
  17352. var d = date['get' + utc + 'Date']();
  17353. var h = date['get' + utc + 'Hours']();
  17354. var m = date['get' + utc + 'Minutes']();
  17355. var s = date['get' + utc + 'Seconds']();
  17356. var S = date['get' + utc + 'Milliseconds']();
  17357. tpl = tpl.replace('MM', pad(M, 2))
  17358. .replace('M', M)
  17359. .replace('yyyy', y)
  17360. .replace('yy', y % 100)
  17361. .replace('dd', pad(d, 2))
  17362. .replace('d', d)
  17363. .replace('hh', pad(h, 2))
  17364. .replace('h', h)
  17365. .replace('mm', pad(m, 2))
  17366. .replace('m', m)
  17367. .replace('ss', pad(s, 2))
  17368. .replace('s', s)
  17369. .replace('SSS', pad(S, 3));
  17370. return tpl;
  17371. }
  17372. /**
  17373. * Capital first
  17374. * @param {string} str
  17375. * @return {string}
  17376. */
  17377. function capitalFirst(str) {
  17378. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17379. }
  17380. var truncateText$1 = truncateText;
  17381. /**
  17382. * @public
  17383. * @param {Object} opt
  17384. * @param {string} opt.text
  17385. * @param {string} opt.font
  17386. * @param {string} [opt.textAlign='left']
  17387. * @param {string} [opt.textVerticalAlign='top']
  17388. * @param {Array.<number>} [opt.textPadding]
  17389. * @param {number} [opt.textLineHeight]
  17390. * @param {Object} [opt.rich]
  17391. * @param {Object} [opt.truncate]
  17392. * @return {Object} {x, y, width, height, lineHeight}
  17393. */
  17394. function getTextBoundingRect(opt) {
  17395. return getBoundingRect(
  17396. opt.text,
  17397. opt.font,
  17398. opt.textAlign,
  17399. opt.textVerticalAlign,
  17400. opt.textPadding,
  17401. opt.textLineHeight,
  17402. opt.rich,
  17403. opt.truncate
  17404. );
  17405. }
  17406. /**
  17407. * @deprecated
  17408. * the `textLineHeight` was added later.
  17409. * For backward compatiblility, put it as the last parameter.
  17410. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17411. */
  17412. function getTextRect(
  17413. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17414. ) {
  17415. return getBoundingRect(
  17416. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17417. );
  17418. }
  17419. var format = (Object.freeze || Object)({
  17420. addCommas: addCommas,
  17421. toCamelCase: toCamelCase,
  17422. normalizeCssArray: normalizeCssArray$1,
  17423. encodeHTML: encodeHTML,
  17424. formatTpl: formatTpl,
  17425. formatTplSimple: formatTplSimple,
  17426. getTooltipMarker: getTooltipMarker,
  17427. formatTime: formatTime,
  17428. capitalFirst: capitalFirst,
  17429. truncateText: truncateText$1,
  17430. getTextBoundingRect: getTextBoundingRect,
  17431. getTextRect: getTextRect
  17432. });
  17433. /*
  17434. * Licensed to the Apache Software Foundation (ASF) under one
  17435. * or more contributor license agreements. See the NOTICE file
  17436. * distributed with this work for additional information
  17437. * regarding copyright ownership. The ASF licenses this file
  17438. * to you under the Apache License, Version 2.0 (the
  17439. * "License"); you may not use this file except in compliance
  17440. * with the License. You may obtain a copy of the License at
  17441. *
  17442. * http://www.apache.org/licenses/LICENSE-2.0
  17443. *
  17444. * Unless required by applicable law or agreed to in writing,
  17445. * software distributed under the License is distributed on an
  17446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17447. * KIND, either express or implied. See the License for the
  17448. * specific language governing permissions and limitations
  17449. * under the License.
  17450. */
  17451. // Layout helpers for each component positioning
  17452. var each$3 = each$1;
  17453. /**
  17454. * @public
  17455. */
  17456. var LOCATION_PARAMS = [
  17457. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17458. ];
  17459. /**
  17460. * @public
  17461. */
  17462. var HV_NAMES = [
  17463. ['width', 'left', 'right'],
  17464. ['height', 'top', 'bottom']
  17465. ];
  17466. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17467. var x = 0;
  17468. var y = 0;
  17469. if (maxWidth == null) {
  17470. maxWidth = Infinity;
  17471. }
  17472. if (maxHeight == null) {
  17473. maxHeight = Infinity;
  17474. }
  17475. var currentLineMaxSize = 0;
  17476. group.eachChild(function (child, idx) {
  17477. var position = child.position;
  17478. var rect = child.getBoundingRect();
  17479. var nextChild = group.childAt(idx + 1);
  17480. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17481. var nextX;
  17482. var nextY;
  17483. if (orient === 'horizontal') {
  17484. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17485. nextX = x + moveX;
  17486. // Wrap when width exceeds maxWidth or meet a `newline` group
  17487. // FIXME compare before adding gap?
  17488. if (nextX > maxWidth || child.newline) {
  17489. x = 0;
  17490. nextX = moveX;
  17491. y += currentLineMaxSize + gap;
  17492. currentLineMaxSize = rect.height;
  17493. }
  17494. else {
  17495. // FIXME: consider rect.y is not `0`?
  17496. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17497. }
  17498. }
  17499. else {
  17500. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17501. nextY = y + moveY;
  17502. // Wrap when width exceeds maxHeight or meet a `newline` group
  17503. if (nextY > maxHeight || child.newline) {
  17504. x += currentLineMaxSize + gap;
  17505. y = 0;
  17506. nextY = moveY;
  17507. currentLineMaxSize = rect.width;
  17508. }
  17509. else {
  17510. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17511. }
  17512. }
  17513. if (child.newline) {
  17514. return;
  17515. }
  17516. position[0] = x;
  17517. position[1] = y;
  17518. orient === 'horizontal'
  17519. ? (x = nextX + gap)
  17520. : (y = nextY + gap);
  17521. });
  17522. }
  17523. /**
  17524. * VBox or HBox layouting
  17525. * @param {string} orient
  17526. * @param {module:zrender/container/Group} group
  17527. * @param {number} gap
  17528. * @param {number} [width=Infinity]
  17529. * @param {number} [height=Infinity]
  17530. */
  17531. var box = boxLayout;
  17532. /**
  17533. * VBox layouting
  17534. * @param {module:zrender/container/Group} group
  17535. * @param {number} gap
  17536. * @param {number} [width=Infinity]
  17537. * @param {number} [height=Infinity]
  17538. */
  17539. var vbox = curry(boxLayout, 'vertical');
  17540. /**
  17541. * HBox layouting
  17542. * @param {module:zrender/container/Group} group
  17543. * @param {number} gap
  17544. * @param {number} [width=Infinity]
  17545. * @param {number} [height=Infinity]
  17546. */
  17547. var hbox = curry(boxLayout, 'horizontal');
  17548. /**
  17549. * If x or x2 is not specified or 'center' 'left' 'right',
  17550. * the width would be as long as possible.
  17551. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17552. * the height would be as long as possible.
  17553. *
  17554. * @param {Object} positionInfo
  17555. * @param {number|string} [positionInfo.x]
  17556. * @param {number|string} [positionInfo.y]
  17557. * @param {number|string} [positionInfo.x2]
  17558. * @param {number|string} [positionInfo.y2]
  17559. * @param {Object} containerRect {width, height}
  17560. * @param {string|number} margin
  17561. * @return {Object} {width, height}
  17562. */
  17563. function getAvailableSize(positionInfo, containerRect, margin) {
  17564. var containerWidth = containerRect.width;
  17565. var containerHeight = containerRect.height;
  17566. var x = parsePercent$1(positionInfo.x, containerWidth);
  17567. var y = parsePercent$1(positionInfo.y, containerHeight);
  17568. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  17569. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  17570. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  17571. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  17572. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  17573. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  17574. margin = normalizeCssArray$1(margin || 0);
  17575. return {
  17576. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  17577. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  17578. };
  17579. }
  17580. /**
  17581. * Parse position info.
  17582. *
  17583. * @param {Object} positionInfo
  17584. * @param {number|string} [positionInfo.left]
  17585. * @param {number|string} [positionInfo.top]
  17586. * @param {number|string} [positionInfo.right]
  17587. * @param {number|string} [positionInfo.bottom]
  17588. * @param {number|string} [positionInfo.width]
  17589. * @param {number|string} [positionInfo.height]
  17590. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17591. * @param {Object} containerRect
  17592. * @param {string|number} [margin]
  17593. *
  17594. * @return {module:zrender/core/BoundingRect}
  17595. */
  17596. function getLayoutRect(
  17597. positionInfo, containerRect, margin
  17598. ) {
  17599. margin = normalizeCssArray$1(margin || 0);
  17600. var containerWidth = containerRect.width;
  17601. var containerHeight = containerRect.height;
  17602. var left = parsePercent$1(positionInfo.left, containerWidth);
  17603. var top = parsePercent$1(positionInfo.top, containerHeight);
  17604. var right = parsePercent$1(positionInfo.right, containerWidth);
  17605. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17606. var width = parsePercent$1(positionInfo.width, containerWidth);
  17607. var height = parsePercent$1(positionInfo.height, containerHeight);
  17608. var verticalMargin = margin[2] + margin[0];
  17609. var horizontalMargin = margin[1] + margin[3];
  17610. var aspect = positionInfo.aspect;
  17611. // If width is not specified, calculate width from left and right
  17612. if (isNaN(width)) {
  17613. width = containerWidth - right - horizontalMargin - left;
  17614. }
  17615. if (isNaN(height)) {
  17616. height = containerHeight - bottom - verticalMargin - top;
  17617. }
  17618. if (aspect != null) {
  17619. // If width and height are not given
  17620. // 1. Graph should not exceeds the container
  17621. // 2. Aspect must be keeped
  17622. // 3. Graph should take the space as more as possible
  17623. // FIXME
  17624. // Margin is not considered, because there is no case that both
  17625. // using margin and aspect so far.
  17626. if (isNaN(width) && isNaN(height)) {
  17627. if (aspect > containerWidth / containerHeight) {
  17628. width = containerWidth * 0.8;
  17629. }
  17630. else {
  17631. height = containerHeight * 0.8;
  17632. }
  17633. }
  17634. // Calculate width or height with given aspect
  17635. if (isNaN(width)) {
  17636. width = aspect * height;
  17637. }
  17638. if (isNaN(height)) {
  17639. height = width / aspect;
  17640. }
  17641. }
  17642. // If left is not specified, calculate left from right and width
  17643. if (isNaN(left)) {
  17644. left = containerWidth - right - width - horizontalMargin;
  17645. }
  17646. if (isNaN(top)) {
  17647. top = containerHeight - bottom - height - verticalMargin;
  17648. }
  17649. // Align left and top
  17650. switch (positionInfo.left || positionInfo.right) {
  17651. case 'center':
  17652. left = containerWidth / 2 - width / 2 - margin[3];
  17653. break;
  17654. case 'right':
  17655. left = containerWidth - width - horizontalMargin;
  17656. break;
  17657. }
  17658. switch (positionInfo.top || positionInfo.bottom) {
  17659. case 'middle':
  17660. case 'center':
  17661. top = containerHeight / 2 - height / 2 - margin[0];
  17662. break;
  17663. case 'bottom':
  17664. top = containerHeight - height - verticalMargin;
  17665. break;
  17666. }
  17667. // If something is wrong and left, top, width, height are calculated as NaN
  17668. left = left || 0;
  17669. top = top || 0;
  17670. if (isNaN(width)) {
  17671. // Width may be NaN if only one value is given except width
  17672. width = containerWidth - horizontalMargin - left - (right || 0);
  17673. }
  17674. if (isNaN(height)) {
  17675. // Height may be NaN if only one value is given except height
  17676. height = containerHeight - verticalMargin - top - (bottom || 0);
  17677. }
  17678. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17679. rect.margin = margin;
  17680. return rect;
  17681. }
  17682. /**
  17683. * Position a zr element in viewport
  17684. * Group position is specified by either
  17685. * {left, top}, {right, bottom}
  17686. * If all properties exists, right and bottom will be igonred.
  17687. *
  17688. * Logic:
  17689. * 1. Scale (against origin point in parent coord)
  17690. * 2. Rotate (against origin point in parent coord)
  17691. * 3. Traslate (with el.position by this method)
  17692. * So this method only fixes the last step 'Traslate', which does not affect
  17693. * scaling and rotating.
  17694. *
  17695. * If be called repeatly with the same input el, the same result will be gotten.
  17696. *
  17697. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17698. * @param {Object} positionInfo
  17699. * @param {number|string} [positionInfo.left]
  17700. * @param {number|string} [positionInfo.top]
  17701. * @param {number|string} [positionInfo.right]
  17702. * @param {number|string} [positionInfo.bottom]
  17703. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17704. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17705. * @param {Object} containerRect
  17706. * @param {string|number} margin
  17707. * @param {Object} [opt]
  17708. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17709. * @param {Array.<number>} [opt.boundingMode='all']
  17710. * Specify how to calculate boundingRect when locating.
  17711. * 'all': Position the boundingRect that is transformed and uioned
  17712. * both itself and its descendants.
  17713. * This mode simplies confine the elements in the bounding
  17714. * of their container (e.g., using 'right: 0').
  17715. * 'raw': Position the boundingRect that is not transformed and only itself.
  17716. * This mode is useful when you want a element can overflow its
  17717. * container. (Consider a rotated circle needs to be located in a corner.)
  17718. * In this mode positionInfo.width/height can only be number.
  17719. */
  17720. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17721. var h = !opt || !opt.hv || opt.hv[0];
  17722. var v = !opt || !opt.hv || opt.hv[1];
  17723. var boundingMode = opt && opt.boundingMode || 'all';
  17724. if (!h && !v) {
  17725. return;
  17726. }
  17727. var rect;
  17728. if (boundingMode === 'raw') {
  17729. rect = el.type === 'group'
  17730. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17731. : el.getBoundingRect();
  17732. }
  17733. else {
  17734. rect = el.getBoundingRect();
  17735. if (el.needLocalTransform()) {
  17736. var transform = el.getLocalTransform();
  17737. // Notice: raw rect may be inner object of el,
  17738. // which should not be modified.
  17739. rect = rect.clone();
  17740. rect.applyTransform(transform);
  17741. }
  17742. }
  17743. // The real width and height can not be specified but calculated by the given el.
  17744. positionInfo = getLayoutRect(
  17745. defaults(
  17746. {width: rect.width, height: rect.height},
  17747. positionInfo
  17748. ),
  17749. containerRect,
  17750. margin
  17751. );
  17752. // Because 'tranlate' is the last step in transform
  17753. // (see zrender/core/Transformable#getLocalTransform),
  17754. // we can just only modify el.position to get final result.
  17755. var elPos = el.position;
  17756. var dx = h ? positionInfo.x - rect.x : 0;
  17757. var dy = v ? positionInfo.y - rect.y : 0;
  17758. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17759. }
  17760. /**
  17761. * @param {Object} option Contains some of the properties in HV_NAMES.
  17762. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17763. */
  17764. function sizeCalculable(option, hvIdx) {
  17765. return option[HV_NAMES[hvIdx][0]] != null
  17766. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  17767. }
  17768. /**
  17769. * Consider Case:
  17770. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17771. * through setOption or media query, using normal zrUtil.merge will cause
  17772. * {right: 0} does not take effect.
  17773. *
  17774. * @example
  17775. * ComponentModel.extend({
  17776. * init: function () {
  17777. * ...
  17778. * var inputPositionParams = layout.getLayoutParams(option);
  17779. * this.mergeOption(inputPositionParams);
  17780. * },
  17781. * mergeOption: function (newOption) {
  17782. * newOption && zrUtil.merge(thisOption, newOption, true);
  17783. * layout.mergeLayoutParam(thisOption, newOption);
  17784. * }
  17785. * });
  17786. *
  17787. * @param {Object} targetOption
  17788. * @param {Object} newOption
  17789. * @param {Object|string} [opt]
  17790. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17791. * that width (or height) should not be calculated by left and right (or top and bottom).
  17792. */
  17793. function mergeLayoutParam(targetOption, newOption, opt) {
  17794. !isObject$1(opt) && (opt = {});
  17795. var ignoreSize = opt.ignoreSize;
  17796. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17797. var hResult = merge$$1(HV_NAMES[0], 0);
  17798. var vResult = merge$$1(HV_NAMES[1], 1);
  17799. copy(HV_NAMES[0], targetOption, hResult);
  17800. copy(HV_NAMES[1], targetOption, vResult);
  17801. function merge$$1(names, hvIdx) {
  17802. var newParams = {};
  17803. var newValueCount = 0;
  17804. var merged = {};
  17805. var mergedValueCount = 0;
  17806. var enoughParamNumber = 2;
  17807. each$3(names, function (name) {
  17808. merged[name] = targetOption[name];
  17809. });
  17810. each$3(names, function (name) {
  17811. // Consider case: newOption.width is null, which is
  17812. // set by user for removing width setting.
  17813. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17814. hasValue(newParams, name) && newValueCount++;
  17815. hasValue(merged, name) && mergedValueCount++;
  17816. });
  17817. if (ignoreSize[hvIdx]) {
  17818. // Only one of left/right is premitted to exist.
  17819. if (hasValue(newOption, names[1])) {
  17820. merged[names[2]] = null;
  17821. }
  17822. else if (hasValue(newOption, names[2])) {
  17823. merged[names[1]] = null;
  17824. }
  17825. return merged;
  17826. }
  17827. // Case: newOption: {width: ..., right: ...},
  17828. // or targetOption: {right: ...} and newOption: {width: ...},
  17829. // There is no conflict when merged only has params count
  17830. // little than enoughParamNumber.
  17831. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17832. return merged;
  17833. }
  17834. // Case: newOption: {width: ..., right: ...},
  17835. // Than we can make sure user only want those two, and ignore
  17836. // all origin params in targetOption.
  17837. else if (newValueCount >= enoughParamNumber) {
  17838. return newParams;
  17839. }
  17840. else {
  17841. // Chose another param from targetOption by priority.
  17842. for (var i = 0; i < names.length; i++) {
  17843. var name = names[i];
  17844. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17845. newParams[name] = targetOption[name];
  17846. break;
  17847. }
  17848. }
  17849. return newParams;
  17850. }
  17851. }
  17852. function hasProp(obj, name) {
  17853. return obj.hasOwnProperty(name);
  17854. }
  17855. function hasValue(obj, name) {
  17856. return obj[name] != null && obj[name] !== 'auto';
  17857. }
  17858. function copy(names, target, source) {
  17859. each$3(names, function (name) {
  17860. target[name] = source[name];
  17861. });
  17862. }
  17863. }
  17864. /**
  17865. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17866. * @param {Object} source
  17867. * @return {Object} Result contains those props.
  17868. */
  17869. function getLayoutParams(source) {
  17870. return copyLayoutParams({}, source);
  17871. }
  17872. /**
  17873. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17874. * @param {Object} source
  17875. * @return {Object} Result contains those props.
  17876. */
  17877. function copyLayoutParams(target, source) {
  17878. source && target && each$3(LOCATION_PARAMS, function (name) {
  17879. source.hasOwnProperty(name) && (target[name] = source[name]);
  17880. });
  17881. return target;
  17882. }
  17883. /*
  17884. * Licensed to the Apache Software Foundation (ASF) under one
  17885. * or more contributor license agreements. See the NOTICE file
  17886. * distributed with this work for additional information
  17887. * regarding copyright ownership. The ASF licenses this file
  17888. * to you under the Apache License, Version 2.0 (the
  17889. * "License"); you may not use this file except in compliance
  17890. * with the License. You may obtain a copy of the License at
  17891. *
  17892. * http://www.apache.org/licenses/LICENSE-2.0
  17893. *
  17894. * Unless required by applicable law or agreed to in writing,
  17895. * software distributed under the License is distributed on an
  17896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17897. * KIND, either express or implied. See the License for the
  17898. * specific language governing permissions and limitations
  17899. * under the License.
  17900. */
  17901. var boxLayoutMixin = {
  17902. getBoxLayoutParams: function () {
  17903. return {
  17904. left: this.get('left'),
  17905. top: this.get('top'),
  17906. right: this.get('right'),
  17907. bottom: this.get('bottom'),
  17908. width: this.get('width'),
  17909. height: this.get('height')
  17910. };
  17911. }
  17912. };
  17913. /*
  17914. * Licensed to the Apache Software Foundation (ASF) under one
  17915. * or more contributor license agreements. See the NOTICE file
  17916. * distributed with this work for additional information
  17917. * regarding copyright ownership. The ASF licenses this file
  17918. * to you under the Apache License, Version 2.0 (the
  17919. * "License"); you may not use this file except in compliance
  17920. * with the License. You may obtain a copy of the License at
  17921. *
  17922. * http://www.apache.org/licenses/LICENSE-2.0
  17923. *
  17924. * Unless required by applicable law or agreed to in writing,
  17925. * software distributed under the License is distributed on an
  17926. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17927. * KIND, either express or implied. See the License for the
  17928. * specific language governing permissions and limitations
  17929. * under the License.
  17930. */
  17931. /**
  17932. * Component model
  17933. *
  17934. * @module echarts/model/Component
  17935. */
  17936. var inner$1 = makeInner();
  17937. /**
  17938. * @alias module:echarts/model/Component
  17939. * @constructor
  17940. * @param {Object} option
  17941. * @param {module:echarts/model/Model} parentModel
  17942. * @param {module:echarts/model/Model} ecModel
  17943. */
  17944. var ComponentModel = Model.extend({
  17945. type: 'component',
  17946. /**
  17947. * @readOnly
  17948. * @type {string}
  17949. */
  17950. id: '',
  17951. /**
  17952. * Because simplified concept is probably better, series.name (or component.name)
  17953. * has been having too many resposibilities:
  17954. * (1) Generating id (which requires name in option should not be modified).
  17955. * (2) As an index to mapping series when merging option or calling API (a name
  17956. * can refer to more then one components, which is convinient is some case).
  17957. * (3) Display.
  17958. * @readOnly
  17959. */
  17960. name: '',
  17961. /**
  17962. * @readOnly
  17963. * @type {string}
  17964. */
  17965. mainType: '',
  17966. /**
  17967. * @readOnly
  17968. * @type {string}
  17969. */
  17970. subType: '',
  17971. /**
  17972. * @readOnly
  17973. * @type {number}
  17974. */
  17975. componentIndex: 0,
  17976. /**
  17977. * @type {Object}
  17978. * @protected
  17979. */
  17980. defaultOption: null,
  17981. /**
  17982. * @type {module:echarts/model/Global}
  17983. * @readOnly
  17984. */
  17985. ecModel: null,
  17986. /**
  17987. * key: componentType
  17988. * value: Component model list, can not be null.
  17989. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17990. * @readOnly
  17991. */
  17992. dependentModels: [],
  17993. /**
  17994. * @type {string}
  17995. * @readOnly
  17996. */
  17997. uid: null,
  17998. /**
  17999. * Support merge layout params.
  18000. * Only support 'box' now (left/right/top/bottom/width/height).
  18001. * @type {string|Object} Object can be {ignoreSize: true}
  18002. * @readOnly
  18003. */
  18004. layoutMode: null,
  18005. $constructor: function (option, parentModel, ecModel, extraOpt) {
  18006. Model.call(this, option, parentModel, ecModel, extraOpt);
  18007. this.uid = getUID('ec_cpt_model');
  18008. },
  18009. init: function (option, parentModel, ecModel, extraOpt) {
  18010. this.mergeDefaultAndTheme(option, ecModel);
  18011. },
  18012. mergeDefaultAndTheme: function (option, ecModel) {
  18013. var layoutMode = this.layoutMode;
  18014. var inputPositionParams = layoutMode
  18015. ? getLayoutParams(option) : {};
  18016. var themeModel = ecModel.getTheme();
  18017. merge(option, themeModel.get(this.mainType));
  18018. merge(option, this.getDefaultOption());
  18019. if (layoutMode) {
  18020. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18021. }
  18022. },
  18023. mergeOption: function (option, extraOpt) {
  18024. merge(this.option, option, true);
  18025. var layoutMode = this.layoutMode;
  18026. if (layoutMode) {
  18027. mergeLayoutParam(this.option, option, layoutMode);
  18028. }
  18029. },
  18030. // Hooker after init or mergeOption
  18031. optionUpdated: function (newCptOption, isInit) {},
  18032. getDefaultOption: function () {
  18033. var fields = inner$1(this);
  18034. if (!fields.defaultOption) {
  18035. var optList = [];
  18036. var Class = this.constructor;
  18037. while (Class) {
  18038. var opt = Class.prototype.defaultOption;
  18039. opt && optList.push(opt);
  18040. Class = Class.superClass;
  18041. }
  18042. var defaultOption = {};
  18043. for (var i = optList.length - 1; i >= 0; i--) {
  18044. defaultOption = merge(defaultOption, optList[i], true);
  18045. }
  18046. fields.defaultOption = defaultOption;
  18047. }
  18048. return fields.defaultOption;
  18049. },
  18050. getReferringComponents: function (mainType) {
  18051. return this.ecModel.queryComponents({
  18052. mainType: mainType,
  18053. index: this.get(mainType + 'Index', true),
  18054. id: this.get(mainType + 'Id', true)
  18055. });
  18056. }
  18057. });
  18058. // Reset ComponentModel.extend, add preConstruct.
  18059. // clazzUtil.enableClassExtend(
  18060. // ComponentModel,
  18061. // function (option, parentModel, ecModel, extraOpt) {
  18062. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  18063. // zrUtil.extend(this, extraOpt);
  18064. // this.uid = componentUtil.getUID('componentModel');
  18065. // // this.setReadOnly([
  18066. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  18067. // // 'dependentModels', 'componentIndex'
  18068. // // ]);
  18069. // }
  18070. // );
  18071. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18072. enableClassManagement(
  18073. ComponentModel, {registerWhenExtend: true}
  18074. );
  18075. enableSubTypeDefaulter(ComponentModel);
  18076. // Add capability of ComponentModel.topologicalTravel.
  18077. enableTopologicalTravel(ComponentModel, getDependencies);
  18078. function getDependencies(componentType) {
  18079. var deps = [];
  18080. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18081. deps = deps.concat(Clazz.prototype.dependencies || []);
  18082. });
  18083. // Ensure main type.
  18084. deps = map(deps, function (type) {
  18085. return parseClassType$1(type).main;
  18086. });
  18087. // Hack dataset for convenience.
  18088. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18089. deps.unshift('dataset');
  18090. }
  18091. return deps;
  18092. }
  18093. mixin(ComponentModel, boxLayoutMixin);
  18094. /*
  18095. * Licensed to the Apache Software Foundation (ASF) under one
  18096. * or more contributor license agreements. See the NOTICE file
  18097. * distributed with this work for additional information
  18098. * regarding copyright ownership. The ASF licenses this file
  18099. * to you under the Apache License, Version 2.0 (the
  18100. * "License"); you may not use this file except in compliance
  18101. * with the License. You may obtain a copy of the License at
  18102. *
  18103. * http://www.apache.org/licenses/LICENSE-2.0
  18104. *
  18105. * Unless required by applicable law or agreed to in writing,
  18106. * software distributed under the License is distributed on an
  18107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18108. * KIND, either express or implied. See the License for the
  18109. * specific language governing permissions and limitations
  18110. * under the License.
  18111. */
  18112. var platform = '';
  18113. // Navigator not exists in node
  18114. if (typeof navigator !== 'undefined') {
  18115. platform = navigator.platform || '';
  18116. }
  18117. var globalDefault = {
  18118. // backgroundColor: 'rgba(0,0,0,0)',
  18119. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18120. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18121. // Light colors:
  18122. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18123. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18124. // Dark colors:
  18125. color: [
  18126. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18127. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18128. ],
  18129. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18130. // If xAxis and yAxis declared, grid is created by default.
  18131. // grid: {},
  18132. textStyle: {
  18133. // color: '#000',
  18134. // decoration: 'none',
  18135. // PENDING
  18136. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18137. // fontFamily: 'Arial, Verdana, sans-serif',
  18138. fontSize: 12,
  18139. fontStyle: 'normal',
  18140. fontWeight: 'normal'
  18141. },
  18142. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18143. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18144. // Default is source-over
  18145. blendMode: null,
  18146. animation: 'auto',
  18147. animationDuration: 1000,
  18148. animationDurationUpdate: 300,
  18149. animationEasing: 'exponentialOut',
  18150. animationEasingUpdate: 'cubicOut',
  18151. animationThreshold: 2000,
  18152. // Configuration for progressive/incremental rendering
  18153. progressiveThreshold: 3000,
  18154. progressive: 400,
  18155. // Threshold of if use single hover layer to optimize.
  18156. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18157. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18158. // which is unexpected.
  18159. // see example <echarts/test/heatmap-large.html>.
  18160. hoverLayerThreshold: 3000,
  18161. // See: module:echarts/scale/Time
  18162. useUTC: false
  18163. };
  18164. /*
  18165. * Licensed to the Apache Software Foundation (ASF) under one
  18166. * or more contributor license agreements. See the NOTICE file
  18167. * distributed with this work for additional information
  18168. * regarding copyright ownership. The ASF licenses this file
  18169. * to you under the Apache License, Version 2.0 (the
  18170. * "License"); you may not use this file except in compliance
  18171. * with the License. You may obtain a copy of the License at
  18172. *
  18173. * http://www.apache.org/licenses/LICENSE-2.0
  18174. *
  18175. * Unless required by applicable law or agreed to in writing,
  18176. * software distributed under the License is distributed on an
  18177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18178. * KIND, either express or implied. See the License for the
  18179. * specific language governing permissions and limitations
  18180. * under the License.
  18181. */
  18182. var inner$2 = makeInner();
  18183. function getNearestColorPalette(colors, requestColorNum) {
  18184. var paletteNum = colors.length;
  18185. // TODO colors must be in order
  18186. for (var i = 0; i < paletteNum; i++) {
  18187. if (colors[i].length > requestColorNum) {
  18188. return colors[i];
  18189. }
  18190. }
  18191. return colors[paletteNum - 1];
  18192. }
  18193. var colorPaletteMixin = {
  18194. clearColorPalette: function () {
  18195. inner$2(this).colorIdx = 0;
  18196. inner$2(this).colorNameMap = {};
  18197. },
  18198. /**
  18199. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18200. * twise with the same parameters will get different result.
  18201. * @param {Object} [scope=this]
  18202. * @param {Object} [requestColorNum]
  18203. * @return {string} color string.
  18204. */
  18205. getColorFromPalette: function (name, scope, requestColorNum) {
  18206. scope = scope || this;
  18207. var scopeFields = inner$2(scope);
  18208. var colorIdx = scopeFields.colorIdx || 0;
  18209. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18210. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18211. if (colorNameMap.hasOwnProperty(name)) {
  18212. return colorNameMap[name];
  18213. }
  18214. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18215. var layeredColorPalette = this.get('colorLayer', true);
  18216. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18217. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18218. // In case can't find in layered color palette.
  18219. colorPalette = colorPalette || defaultColorPalette;
  18220. if (!colorPalette || !colorPalette.length) {
  18221. return;
  18222. }
  18223. var color = colorPalette[colorIdx];
  18224. if (name) {
  18225. colorNameMap[name] = color;
  18226. }
  18227. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18228. return color;
  18229. }
  18230. };
  18231. /*
  18232. * Licensed to the Apache Software Foundation (ASF) under one
  18233. * or more contributor license agreements. See the NOTICE file
  18234. * distributed with this work for additional information
  18235. * regarding copyright ownership. The ASF licenses this file
  18236. * to you under the Apache License, Version 2.0 (the
  18237. * "License"); you may not use this file except in compliance
  18238. * with the License. You may obtain a copy of the License at
  18239. *
  18240. * http://www.apache.org/licenses/LICENSE-2.0
  18241. *
  18242. * Unless required by applicable law or agreed to in writing,
  18243. * software distributed under the License is distributed on an
  18244. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18245. * KIND, either express or implied. See the License for the
  18246. * specific language governing permissions and limitations
  18247. * under the License.
  18248. */
  18249. // Avoid typo.
  18250. var SOURCE_FORMAT_ORIGINAL = 'original';
  18251. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18252. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18253. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18254. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18255. // ??? CHANGE A NAME
  18256. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18257. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18258. var SERIES_LAYOUT_BY_ROW = 'row';
  18259. /*
  18260. * Licensed to the Apache Software Foundation (ASF) under one
  18261. * or more contributor license agreements. See the NOTICE file
  18262. * distributed with this work for additional information
  18263. * regarding copyright ownership. The ASF licenses this file
  18264. * to you under the Apache License, Version 2.0 (the
  18265. * "License"); you may not use this file except in compliance
  18266. * with the License. You may obtain a copy of the License at
  18267. *
  18268. * http://www.apache.org/licenses/LICENSE-2.0
  18269. *
  18270. * Unless required by applicable law or agreed to in writing,
  18271. * software distributed under the License is distributed on an
  18272. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18273. * KIND, either express or implied. See the License for the
  18274. * specific language governing permissions and limitations
  18275. * under the License.
  18276. */
  18277. /**
  18278. * [sourceFormat]
  18279. *
  18280. * + "original":
  18281. * This format is only used in series.data, where
  18282. * itemStyle can be specified in data item.
  18283. *
  18284. * + "arrayRows":
  18285. * [
  18286. * ['product', 'score', 'amount'],
  18287. * ['Matcha Latte', 89.3, 95.8],
  18288. * ['Milk Tea', 92.1, 89.4],
  18289. * ['Cheese Cocoa', 94.4, 91.2],
  18290. * ['Walnut Brownie', 85.4, 76.9]
  18291. * ]
  18292. *
  18293. * + "objectRows":
  18294. * [
  18295. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18296. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18297. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18298. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18299. * ]
  18300. *
  18301. * + "keyedColumns":
  18302. * {
  18303. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18304. * 'count': [823, 235, 1042, 988],
  18305. * 'score': [95.8, 81.4, 91.2, 76.9]
  18306. * }
  18307. *
  18308. * + "typedArray"
  18309. *
  18310. * + "unknown"
  18311. */
  18312. /**
  18313. * @constructor
  18314. * @param {Object} fields
  18315. * @param {string} fields.sourceFormat
  18316. * @param {Array|Object} fields.fromDataset
  18317. * @param {Array|Object} [fields.data]
  18318. * @param {string} [seriesLayoutBy='column']
  18319. * @param {Array.<Object|string>} [dimensionsDefine]
  18320. * @param {Objet|HashMap} [encodeDefine]
  18321. * @param {number} [startIndex=0]
  18322. * @param {number} [dimensionsDetectCount]
  18323. */
  18324. function Source(fields) {
  18325. /**
  18326. * @type {boolean}
  18327. */
  18328. this.fromDataset = fields.fromDataset;
  18329. /**
  18330. * Not null/undefined.
  18331. * @type {Array|Object}
  18332. */
  18333. this.data = fields.data || (
  18334. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18335. );
  18336. /**
  18337. * See also "detectSourceFormat".
  18338. * Not null/undefined.
  18339. * @type {string}
  18340. */
  18341. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18342. /**
  18343. * 'row' or 'column'
  18344. * Not null/undefined.
  18345. * @type {string} seriesLayoutBy
  18346. */
  18347. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18348. /**
  18349. * dimensions definition in option.
  18350. * can be null/undefined.
  18351. * @type {Array.<Object|string>}
  18352. */
  18353. this.dimensionsDefine = fields.dimensionsDefine;
  18354. /**
  18355. * encode definition in option.
  18356. * can be null/undefined.
  18357. * @type {Objet|HashMap}
  18358. */
  18359. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18360. /**
  18361. * Not null/undefined, uint.
  18362. * @type {number}
  18363. */
  18364. this.startIndex = fields.startIndex || 0;
  18365. /**
  18366. * Can be null/undefined (when unknown), uint.
  18367. * @type {number}
  18368. */
  18369. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18370. }
  18371. /**
  18372. * Wrap original series data for some compatibility cases.
  18373. */
  18374. Source.seriesDataToSource = function (data) {
  18375. return new Source({
  18376. data: data,
  18377. sourceFormat: isTypedArray(data)
  18378. ? SOURCE_FORMAT_TYPED_ARRAY
  18379. : SOURCE_FORMAT_ORIGINAL,
  18380. fromDataset: false
  18381. });
  18382. };
  18383. enableClassCheck(Source);
  18384. /*
  18385. * Licensed to the Apache Software Foundation (ASF) under one
  18386. * or more contributor license agreements. See the NOTICE file
  18387. * distributed with this work for additional information
  18388. * regarding copyright ownership. The ASF licenses this file
  18389. * to you under the Apache License, Version 2.0 (the
  18390. * "License"); you may not use this file except in compliance
  18391. * with the License. You may obtain a copy of the License at
  18392. *
  18393. * http://www.apache.org/licenses/LICENSE-2.0
  18394. *
  18395. * Unless required by applicable law or agreed to in writing,
  18396. * software distributed under the License is distributed on an
  18397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18398. * KIND, either express or implied. See the License for the
  18399. * specific language governing permissions and limitations
  18400. * under the License.
  18401. */
  18402. // The result of `guessOrdinal`.
  18403. var BE_ORDINAL = {
  18404. Must: 1, // Encounter string but not '-' and not number-like.
  18405. Might: 2, // Encounter string but number-like.
  18406. Not: 3 // Other cases
  18407. };
  18408. var inner$3 = makeInner();
  18409. /**
  18410. * @see {module:echarts/data/Source}
  18411. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18412. * @return {string} sourceFormat
  18413. */
  18414. function detectSourceFormat(datasetModel) {
  18415. var data = datasetModel.option.source;
  18416. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18417. if (isTypedArray(data)) {
  18418. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18419. }
  18420. else if (isArray(data)) {
  18421. // FIXME Whether tolerate null in top level array?
  18422. if (data.length === 0) {
  18423. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18424. }
  18425. for (var i = 0, len = data.length; i < len; i++) {
  18426. var item = data[i];
  18427. if (item == null) {
  18428. continue;
  18429. }
  18430. else if (isArray(item)) {
  18431. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18432. break;
  18433. }
  18434. else if (isObject$1(item)) {
  18435. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18436. break;
  18437. }
  18438. }
  18439. }
  18440. else if (isObject$1(data)) {
  18441. for (var key in data) {
  18442. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18443. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18444. break;
  18445. }
  18446. }
  18447. }
  18448. else if (data != null) {
  18449. throw new Error('Invalid data');
  18450. }
  18451. inner$3(datasetModel).sourceFormat = sourceFormat;
  18452. }
  18453. /**
  18454. * [Scenarios]:
  18455. * (1) Provide source data directly:
  18456. * series: {
  18457. * encode: {...},
  18458. * dimensions: [...]
  18459. * seriesLayoutBy: 'row',
  18460. * data: [[...]]
  18461. * }
  18462. * (2) Refer to datasetModel.
  18463. * series: [{
  18464. * encode: {...}
  18465. * // Ignore datasetIndex means `datasetIndex: 0`
  18466. * // and the dimensions defination in dataset is used
  18467. * }, {
  18468. * encode: {...},
  18469. * seriesLayoutBy: 'column',
  18470. * datasetIndex: 1
  18471. * }]
  18472. *
  18473. * Get data from series itself or datset.
  18474. * @return {module:echarts/data/Source} source
  18475. */
  18476. function getSource(seriesModel) {
  18477. return inner$3(seriesModel).source;
  18478. }
  18479. /**
  18480. * MUST be called before mergeOption of all series.
  18481. * @param {module:echarts/model/Global} ecModel
  18482. */
  18483. function resetSourceDefaulter(ecModel) {
  18484. // `datasetMap` is used to make default encode.
  18485. inner$3(ecModel).datasetMap = createHashMap();
  18486. }
  18487. /**
  18488. * [Caution]:
  18489. * MUST be called after series option merged and
  18490. * before "series.getInitailData()" called.
  18491. *
  18492. * [The rule of making default encode]:
  18493. * Category axis (if exists) alway map to the first dimension.
  18494. * Each other axis occupies a subsequent dimension.
  18495. *
  18496. * [Why make default encode]:
  18497. * Simplify the typing of encode in option, avoiding the case like that:
  18498. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18499. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18500. *
  18501. * @param {module:echarts/model/Series} seriesModel
  18502. */
  18503. function prepareSource(seriesModel) {
  18504. var seriesOption = seriesModel.option;
  18505. var data = seriesOption.data;
  18506. var sourceFormat = isTypedArray(data)
  18507. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18508. var fromDataset = false;
  18509. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18510. var sourceHeader = seriesOption.sourceHeader;
  18511. var dimensionsDefine = seriesOption.dimensions;
  18512. var datasetModel = getDatasetModel(seriesModel);
  18513. if (datasetModel) {
  18514. var datasetOption = datasetModel.option;
  18515. data = datasetOption.source;
  18516. sourceFormat = inner$3(datasetModel).sourceFormat;
  18517. fromDataset = true;
  18518. // These settings from series has higher priority.
  18519. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18520. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18521. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18522. }
  18523. var completeResult = completeBySourceData(
  18524. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18525. );
  18526. inner$3(seriesModel).source = new Source({
  18527. data: data,
  18528. fromDataset: fromDataset,
  18529. seriesLayoutBy: seriesLayoutBy,
  18530. sourceFormat: sourceFormat,
  18531. dimensionsDefine: completeResult.dimensionsDefine,
  18532. startIndex: completeResult.startIndex,
  18533. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18534. // Note: dataset option does not have `encode`.
  18535. encodeDefine: seriesOption.encode
  18536. });
  18537. }
  18538. // return {startIndex, dimensionsDefine, dimensionsCount}
  18539. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18540. if (!data) {
  18541. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18542. }
  18543. var dimensionsDetectCount;
  18544. var startIndex;
  18545. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18546. // Rule: Most of the first line are string: it is header.
  18547. // Caution: consider a line with 5 string and 1 number,
  18548. // it still can not be sure it is a head, because the
  18549. // 5 string may be 5 values of category columns.
  18550. if (sourceHeader === 'auto' || sourceHeader == null) {
  18551. arrayRowsTravelFirst(function (val) {
  18552. // '-' is regarded as null/undefined.
  18553. if (val != null && val !== '-') {
  18554. if (isString(val)) {
  18555. startIndex == null && (startIndex = 1);
  18556. }
  18557. else {
  18558. startIndex = 0;
  18559. }
  18560. }
  18561. // 10 is an experience number, avoid long loop.
  18562. }, seriesLayoutBy, data, 10);
  18563. }
  18564. else {
  18565. startIndex = sourceHeader ? 1 : 0;
  18566. }
  18567. if (!dimensionsDefine && startIndex === 1) {
  18568. dimensionsDefine = [];
  18569. arrayRowsTravelFirst(function (val, index) {
  18570. dimensionsDefine[index] = val != null ? val : '';
  18571. }, seriesLayoutBy, data);
  18572. }
  18573. dimensionsDetectCount = dimensionsDefine
  18574. ? dimensionsDefine.length
  18575. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18576. ? data.length
  18577. : data[0]
  18578. ? data[0].length
  18579. : null;
  18580. }
  18581. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18582. if (!dimensionsDefine) {
  18583. dimensionsDefine = objectRowsCollectDimensions(data);
  18584. }
  18585. }
  18586. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18587. if (!dimensionsDefine) {
  18588. dimensionsDefine = [];
  18589. each$1(data, function (colArr, key) {
  18590. dimensionsDefine.push(key);
  18591. });
  18592. }
  18593. }
  18594. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18595. var value0 = getDataItemValue(data[0]);
  18596. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18597. }
  18598. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18599. if (__DEV__) {
  18600. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18601. }
  18602. }
  18603. return {
  18604. startIndex: startIndex,
  18605. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18606. dimensionsDetectCount: dimensionsDetectCount
  18607. };
  18608. }
  18609. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18610. // which is reasonable. But dimension name is duplicated.
  18611. // Returns undefined or an array contains only object without null/undefiend or string.
  18612. function normalizeDimensionsDefine(dimensionsDefine) {
  18613. if (!dimensionsDefine) {
  18614. // The meaning of null/undefined is different from empty array.
  18615. return;
  18616. }
  18617. var nameMap = createHashMap();
  18618. return map(dimensionsDefine, function (item, index) {
  18619. item = extend({}, isObject$1(item) ? item : {name: item});
  18620. // User can set null in dimensions.
  18621. // We dont auto specify name, othewise a given name may
  18622. // cause it be refered unexpectedly.
  18623. if (item.name == null) {
  18624. return item;
  18625. }
  18626. // Also consider number form like 2012.
  18627. item.name += '';
  18628. // User may also specify displayName.
  18629. // displayName will always exists except user not
  18630. // specified or dim name is not specified or detected.
  18631. // (A auto generated dim name will not be used as
  18632. // displayName).
  18633. if (item.displayName == null) {
  18634. item.displayName = item.name;
  18635. }
  18636. var exist = nameMap.get(item.name);
  18637. if (!exist) {
  18638. nameMap.set(item.name, {count: 1});
  18639. }
  18640. else {
  18641. item.name += '-' + exist.count++;
  18642. }
  18643. return item;
  18644. });
  18645. }
  18646. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18647. maxLoop == null && (maxLoop = Infinity);
  18648. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18649. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18650. cb(data[i] ? data[i][0] : null, i);
  18651. }
  18652. }
  18653. else {
  18654. var value0 = data[0] || [];
  18655. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18656. cb(value0[i], i);
  18657. }
  18658. }
  18659. }
  18660. function objectRowsCollectDimensions(data) {
  18661. var firstIndex = 0;
  18662. var obj;
  18663. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18664. if (obj) {
  18665. var dimensions = [];
  18666. each$1(obj, function (value, key) {
  18667. dimensions.push(key);
  18668. });
  18669. return dimensions;
  18670. }
  18671. }
  18672. /**
  18673. * [The strategy of the arrengment of data dimensions for dataset]:
  18674. * "value way": all axes are non-category axes. So series one by one take
  18675. * several (the number is coordSysDims.length) dimensions from dataset.
  18676. * The result of data arrengment of data dimensions like:
  18677. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18678. * "category way": at least one axis is category axis. So the the first data
  18679. * dimension is always mapped to the first category axis and shared by
  18680. * all of the series. The other data dimensions are taken by series like
  18681. * "value way" does.
  18682. * The result of data arrengment of data dimensions like:
  18683. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18684. *
  18685. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18686. * @param {module:model/Series} seriesModel
  18687. * @param {module:data/Source} source
  18688. * @return {Object} encode Never be `null/undefined`.
  18689. */
  18690. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18691. var encode = {};
  18692. var datasetModel = getDatasetModel(seriesModel);
  18693. // Currently only make default when using dataset, util more reqirements occur.
  18694. if (!datasetModel || !coordDimensions) {
  18695. return encode;
  18696. }
  18697. var encodeItemName = [];
  18698. var encodeSeriesName = [];
  18699. var ecModel = seriesModel.ecModel;
  18700. var datasetMap = inner$3(ecModel).datasetMap;
  18701. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18702. var baseCategoryDimIndex;
  18703. var categoryWayValueDimStart;
  18704. coordDimensions = coordDimensions.slice();
  18705. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18706. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18707. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18708. baseCategoryDimIndex = coordDimIdx;
  18709. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18710. }
  18711. encode[coordDimInfo.name] = [];
  18712. });
  18713. var datasetRecord = datasetMap.get(key)
  18714. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18715. // TODO
  18716. // Auto detect first time axis and do arrangement.
  18717. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18718. var coordDimName = coordDimInfo.name;
  18719. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18720. // In value way.
  18721. if (baseCategoryDimIndex == null) {
  18722. var start = datasetRecord.valueWayDim;
  18723. pushDim(encode[coordDimName], start, count);
  18724. pushDim(encodeSeriesName, start, count);
  18725. datasetRecord.valueWayDim += count;
  18726. // ??? TODO give a better default series name rule?
  18727. // especially when encode x y specified.
  18728. // consider: when mutiple series share one dimension
  18729. // category axis, series name should better use
  18730. // the other dimsion name. On the other hand, use
  18731. // both dimensions name.
  18732. }
  18733. // In category way, the first category axis.
  18734. else if (baseCategoryDimIndex === coordDimIdx) {
  18735. pushDim(encode[coordDimName], 0, count);
  18736. pushDim(encodeItemName, 0, count);
  18737. }
  18738. // In category way, the other axis.
  18739. else {
  18740. var start = datasetRecord.categoryWayDim;
  18741. pushDim(encode[coordDimName], start, count);
  18742. pushDim(encodeSeriesName, start, count);
  18743. datasetRecord.categoryWayDim += count;
  18744. }
  18745. });
  18746. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18747. for (var i = 0; i < idxCount; i++) {
  18748. dimIdxArr.push(idxFrom + i);
  18749. }
  18750. }
  18751. function getDataDimCountOnCoordDim(coordDimInfo) {
  18752. var dimsDef = coordDimInfo.dimsDef;
  18753. return dimsDef ? dimsDef.length : 1;
  18754. }
  18755. encodeItemName.length && (encode.itemName = encodeItemName);
  18756. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18757. return encode;
  18758. }
  18759. /**
  18760. * Work for data like [{name: ..., value: ...}, ...].
  18761. *
  18762. * @param {module:model/Series} seriesModel
  18763. * @param {module:data/Source} source
  18764. * @return {Object} encode Never be `null/undefined`.
  18765. */
  18766. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18767. var encode = {};
  18768. var datasetModel = getDatasetModel(seriesModel);
  18769. // Currently only make default when using dataset, util more reqirements occur.
  18770. if (!datasetModel) {
  18771. return encode;
  18772. }
  18773. var sourceFormat = source.sourceFormat;
  18774. var dimensionsDefine = source.dimensionsDefine;
  18775. var potentialNameDimIndex;
  18776. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18777. each$1(dimensionsDefine, function (dim, idx) {
  18778. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18779. potentialNameDimIndex = idx;
  18780. }
  18781. });
  18782. }
  18783. // idxResult: {v, n}.
  18784. var idxResult = (function () {
  18785. var idxRes0 = {};
  18786. var idxRes1 = {};
  18787. var guessRecords = [];
  18788. // 5 is an experience value.
  18789. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18790. var guessResult = doGuessOrdinal(
  18791. source.data, sourceFormat, source.seriesLayoutBy,
  18792. dimensionsDefine, source.startIndex, i
  18793. );
  18794. guessRecords.push(guessResult);
  18795. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18796. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18797. // and then find a name dim with the priority:
  18798. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18799. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18800. idxRes0.v = i;
  18801. }
  18802. if (idxRes0.n == null
  18803. || (idxRes0.n === idxRes0.v)
  18804. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18805. ) {
  18806. idxRes0.n = i;
  18807. }
  18808. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18809. return idxRes0;
  18810. }
  18811. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18812. // find the first BE_ORDINAL.Might as the value dim,
  18813. // and then find a name dim with the priority:
  18814. // "other dim" > "the value dim itself".
  18815. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18816. // treated as number.
  18817. if (!isPureNumber) {
  18818. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18819. idxRes1.v = i;
  18820. }
  18821. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18822. idxRes1.n = i;
  18823. }
  18824. }
  18825. }
  18826. function fulfilled(idxResult) {
  18827. return idxResult.v != null && idxResult.n != null;
  18828. }
  18829. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18830. })();
  18831. if (idxResult) {
  18832. encode.value = idxResult.v;
  18833. // `potentialNameDimIndex` has highest priority.
  18834. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18835. // By default, label use itemName in charts.
  18836. // So we dont set encodeLabel here.
  18837. encode.itemName = [nameDimIndex];
  18838. encode.seriesName = [nameDimIndex];
  18839. }
  18840. return encode;
  18841. }
  18842. /**
  18843. * If return null/undefined, indicate that should not use datasetModel.
  18844. */
  18845. function getDatasetModel(seriesModel) {
  18846. var option = seriesModel.option;
  18847. // Caution: consider the scenario:
  18848. // A dataset is declared and a series is not expected to use the dataset,
  18849. // and at the beginning `setOption({series: { noData })` (just prepare other
  18850. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18851. // the user should set an empty array to avoid that dataset is used by default.
  18852. var thisData = option.data;
  18853. if (!thisData) {
  18854. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18855. }
  18856. }
  18857. /**
  18858. * The rule should not be complex, otherwise user might not
  18859. * be able to known where the data is wrong.
  18860. * The code is ugly, but how to make it neat?
  18861. *
  18862. * @param {module:echars/data/Source} source
  18863. * @param {number} dimIndex
  18864. * @return {BE_ORDINAL} guess result.
  18865. */
  18866. function guessOrdinal(source, dimIndex) {
  18867. return doGuessOrdinal(
  18868. source.data,
  18869. source.sourceFormat,
  18870. source.seriesLayoutBy,
  18871. source.dimensionsDefine,
  18872. source.startIndex,
  18873. dimIndex
  18874. );
  18875. }
  18876. // dimIndex may be overflow source data.
  18877. // return {BE_ORDINAL}
  18878. function doGuessOrdinal(
  18879. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18880. ) {
  18881. var result;
  18882. // Experience value.
  18883. var maxLoop = 5;
  18884. if (isTypedArray(data)) {
  18885. return BE_ORDINAL.Not;
  18886. }
  18887. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18888. // always exists in source.
  18889. var dimName;
  18890. var dimType;
  18891. if (dimensionsDefine) {
  18892. var dimDefItem = dimensionsDefine[dimIndex];
  18893. if (isObject$1(dimDefItem)) {
  18894. dimName = dimDefItem.name;
  18895. dimType = dimDefItem.type;
  18896. }
  18897. else if (isString(dimDefItem)) {
  18898. dimName = dimDefItem;
  18899. }
  18900. }
  18901. if (dimType != null) {
  18902. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18903. }
  18904. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18905. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18906. var sample = data[dimIndex];
  18907. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18908. if ((result = detectValue(sample[startIndex + i])) != null) {
  18909. return result;
  18910. }
  18911. }
  18912. }
  18913. else {
  18914. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18915. var row = data[startIndex + i];
  18916. if (row && (result = detectValue(row[dimIndex])) != null) {
  18917. return result;
  18918. }
  18919. }
  18920. }
  18921. }
  18922. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18923. if (!dimName) {
  18924. return BE_ORDINAL.Not;
  18925. }
  18926. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18927. var item = data[i];
  18928. if (item && (result = detectValue(item[dimName])) != null) {
  18929. return result;
  18930. }
  18931. }
  18932. }
  18933. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18934. if (!dimName) {
  18935. return BE_ORDINAL.Not;
  18936. }
  18937. var sample = data[dimName];
  18938. if (!sample || isTypedArray(sample)) {
  18939. return BE_ORDINAL.Not;
  18940. }
  18941. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18942. if ((result = detectValue(sample[i])) != null) {
  18943. return result;
  18944. }
  18945. }
  18946. }
  18947. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18948. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18949. var item = data[i];
  18950. var val = getDataItemValue(item);
  18951. if (!isArray(val)) {
  18952. return BE_ORDINAL.Not;
  18953. }
  18954. if ((result = detectValue(val[dimIndex])) != null) {
  18955. return result;
  18956. }
  18957. }
  18958. }
  18959. function detectValue(val) {
  18960. var beStr = isString(val);
  18961. // Consider usage convenience, '1', '2' will be treated as "number".
  18962. // `isFinit('')` get `true`.
  18963. if (val != null && isFinite(val) && val !== '') {
  18964. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18965. }
  18966. else if (beStr && val !== '-') {
  18967. return BE_ORDINAL.Must;
  18968. }
  18969. }
  18970. return BE_ORDINAL.Not;
  18971. }
  18972. /*
  18973. * Licensed to the Apache Software Foundation (ASF) under one
  18974. * or more contributor license agreements. See the NOTICE file
  18975. * distributed with this work for additional information
  18976. * regarding copyright ownership. The ASF licenses this file
  18977. * to you under the Apache License, Version 2.0 (the
  18978. * "License"); you may not use this file except in compliance
  18979. * with the License. You may obtain a copy of the License at
  18980. *
  18981. * http://www.apache.org/licenses/LICENSE-2.0
  18982. *
  18983. * Unless required by applicable law or agreed to in writing,
  18984. * software distributed under the License is distributed on an
  18985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18986. * KIND, either express or implied. See the License for the
  18987. * specific language governing permissions and limitations
  18988. * under the License.
  18989. */
  18990. /**
  18991. * ECharts global model
  18992. *
  18993. * @module {echarts/model/Global}
  18994. */
  18995. /**
  18996. * Caution: If the mechanism should be changed some day, these cases
  18997. * should be considered:
  18998. *
  18999. * (1) In `merge option` mode, if using the same option to call `setOption`
  19000. * many times, the result should be the same (try our best to ensure that).
  19001. * (2) In `merge option` mode, if a component has no id/name specified, it
  19002. * will be merged by index, and the result sequence of the components is
  19003. * consistent to the original sequence.
  19004. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  19005. * `mergeOption` in module:echarts/model/OptionManager.
  19006. */
  19007. var OPTION_INNER_KEY = '\0_ec_inner';
  19008. /**
  19009. * @alias module:echarts/model/Global
  19010. *
  19011. * @param {Object} option
  19012. * @param {module:echarts/model/Model} parentModel
  19013. * @param {Object} theme
  19014. */
  19015. var GlobalModel = Model.extend({
  19016. init: function (option, parentModel, theme, optionManager) {
  19017. theme = theme || {};
  19018. this.option = null; // Mark as not initialized.
  19019. /**
  19020. * @type {module:echarts/model/Model}
  19021. * @private
  19022. */
  19023. this._theme = new Model(theme);
  19024. /**
  19025. * @type {module:echarts/model/OptionManager}
  19026. */
  19027. this._optionManager = optionManager;
  19028. },
  19029. setOption: function (option, optionPreprocessorFuncs) {
  19030. assert$1(
  19031. !(OPTION_INNER_KEY in option),
  19032. 'please use chart.getOption()'
  19033. );
  19034. this._optionManager.setOption(option, optionPreprocessorFuncs);
  19035. this.resetOption(null);
  19036. },
  19037. /**
  19038. * @param {string} type null/undefined: reset all.
  19039. * 'recreate': force recreate all.
  19040. * 'timeline': only reset timeline option
  19041. * 'media': only reset media query option
  19042. * @return {boolean} Whether option changed.
  19043. */
  19044. resetOption: function (type) {
  19045. var optionChanged = false;
  19046. var optionManager = this._optionManager;
  19047. if (!type || type === 'recreate') {
  19048. var baseOption = optionManager.mountOption(type === 'recreate');
  19049. if (!this.option || type === 'recreate') {
  19050. initBase.call(this, baseOption);
  19051. }
  19052. else {
  19053. this.restoreData();
  19054. this.mergeOption(baseOption);
  19055. }
  19056. optionChanged = true;
  19057. }
  19058. if (type === 'timeline' || type === 'media') {
  19059. this.restoreData();
  19060. }
  19061. if (!type || type === 'recreate' || type === 'timeline') {
  19062. var timelineOption = optionManager.getTimelineOption(this);
  19063. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  19064. }
  19065. if (!type || type === 'recreate' || type === 'media') {
  19066. var mediaOptions = optionManager.getMediaOption(this, this._api);
  19067. if (mediaOptions.length) {
  19068. each$1(mediaOptions, function (mediaOption) {
  19069. this.mergeOption(mediaOption, optionChanged = true);
  19070. }, this);
  19071. }
  19072. }
  19073. return optionChanged;
  19074. },
  19075. /**
  19076. * @protected
  19077. */
  19078. mergeOption: function (newOption) {
  19079. var option = this.option;
  19080. var componentsMap = this._componentsMap;
  19081. var newCptTypes = [];
  19082. resetSourceDefaulter(this);
  19083. // If no component class, merge directly.
  19084. // For example: color, animaiton options, etc.
  19085. each$1(newOption, function (componentOption, mainType) {
  19086. if (componentOption == null) {
  19087. return;
  19088. }
  19089. if (!ComponentModel.hasClass(mainType)) {
  19090. // globalSettingTask.dirty();
  19091. option[mainType] = option[mainType] == null
  19092. ? clone(componentOption)
  19093. : merge(option[mainType], componentOption, true);
  19094. }
  19095. else if (mainType) {
  19096. newCptTypes.push(mainType);
  19097. }
  19098. });
  19099. ComponentModel.topologicalTravel(
  19100. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19101. );
  19102. function visitComponent(mainType, dependencies) {
  19103. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19104. var mapResult = mappingToExists(
  19105. componentsMap.get(mainType), newCptOptionList
  19106. );
  19107. makeIdAndName(mapResult);
  19108. // Set mainType and complete subType.
  19109. each$1(mapResult, function (item, index) {
  19110. var opt = item.option;
  19111. if (isObject$1(opt)) {
  19112. item.keyInfo.mainType = mainType;
  19113. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19114. }
  19115. });
  19116. var dependentModels = getComponentsByTypes(
  19117. componentsMap, dependencies
  19118. );
  19119. option[mainType] = [];
  19120. componentsMap.set(mainType, []);
  19121. each$1(mapResult, function (resultItem, index) {
  19122. var componentModel = resultItem.exist;
  19123. var newCptOption = resultItem.option;
  19124. assert$1(
  19125. isObject$1(newCptOption) || componentModel,
  19126. 'Empty component definition'
  19127. );
  19128. // Consider where is no new option and should be merged using {},
  19129. // see removeEdgeAndAdd in topologicalTravel and
  19130. // ComponentModel.getAllClassMainTypes.
  19131. if (!newCptOption) {
  19132. componentModel.mergeOption({}, this);
  19133. componentModel.optionUpdated({}, false);
  19134. }
  19135. else {
  19136. var ComponentModelClass = ComponentModel.getClass(
  19137. mainType, resultItem.keyInfo.subType, true
  19138. );
  19139. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19140. componentModel.name = resultItem.keyInfo.name;
  19141. // componentModel.settingTask && componentModel.settingTask.dirty();
  19142. componentModel.mergeOption(newCptOption, this);
  19143. componentModel.optionUpdated(newCptOption, false);
  19144. }
  19145. else {
  19146. // PENDING Global as parent ?
  19147. var extraOpt = extend(
  19148. {
  19149. dependentModels: dependentModels,
  19150. componentIndex: index
  19151. },
  19152. resultItem.keyInfo
  19153. );
  19154. componentModel = new ComponentModelClass(
  19155. newCptOption, this, this, extraOpt
  19156. );
  19157. extend(componentModel, extraOpt);
  19158. componentModel.init(newCptOption, this, this, extraOpt);
  19159. // Call optionUpdated after init.
  19160. // newCptOption has been used as componentModel.option
  19161. // and may be merged with theme and default, so pass null
  19162. // to avoid confusion.
  19163. componentModel.optionUpdated(null, true);
  19164. }
  19165. }
  19166. componentsMap.get(mainType)[index] = componentModel;
  19167. option[mainType][index] = componentModel.option;
  19168. }, this);
  19169. // Backup series for filtering.
  19170. if (mainType === 'series') {
  19171. createSeriesIndices(this, componentsMap.get('series'));
  19172. }
  19173. }
  19174. this._seriesIndicesMap = createHashMap(
  19175. this._seriesIndices = this._seriesIndices || []
  19176. );
  19177. },
  19178. /**
  19179. * Get option for output (cloned option and inner info removed)
  19180. * @public
  19181. * @return {Object}
  19182. */
  19183. getOption: function () {
  19184. var option = clone(this.option);
  19185. each$1(option, function (opts, mainType) {
  19186. if (ComponentModel.hasClass(mainType)) {
  19187. var opts = normalizeToArray(opts);
  19188. for (var i = opts.length - 1; i >= 0; i--) {
  19189. // Remove options with inner id.
  19190. if (isIdInner(opts[i])) {
  19191. opts.splice(i, 1);
  19192. }
  19193. }
  19194. option[mainType] = opts;
  19195. }
  19196. });
  19197. delete option[OPTION_INNER_KEY];
  19198. return option;
  19199. },
  19200. /**
  19201. * @return {module:echarts/model/Model}
  19202. */
  19203. getTheme: function () {
  19204. return this._theme;
  19205. },
  19206. /**
  19207. * @param {string} mainType
  19208. * @param {number} [idx=0]
  19209. * @return {module:echarts/model/Component}
  19210. */
  19211. getComponent: function (mainType, idx) {
  19212. var list = this._componentsMap.get(mainType);
  19213. if (list) {
  19214. return list[idx || 0];
  19215. }
  19216. },
  19217. /**
  19218. * If none of index and id and name used, return all components with mainType.
  19219. * @param {Object} condition
  19220. * @param {string} condition.mainType
  19221. * @param {string} [condition.subType] If ignore, only query by mainType
  19222. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19223. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19224. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19225. * @return {Array.<module:echarts/model/Component>}
  19226. */
  19227. queryComponents: function (condition) {
  19228. var mainType = condition.mainType;
  19229. if (!mainType) {
  19230. return [];
  19231. }
  19232. var index = condition.index;
  19233. var id = condition.id;
  19234. var name = condition.name;
  19235. var cpts = this._componentsMap.get(mainType);
  19236. if (!cpts || !cpts.length) {
  19237. return [];
  19238. }
  19239. var result;
  19240. if (index != null) {
  19241. if (!isArray(index)) {
  19242. index = [index];
  19243. }
  19244. result = filter(map(index, function (idx) {
  19245. return cpts[idx];
  19246. }), function (val) {
  19247. return !!val;
  19248. });
  19249. }
  19250. else if (id != null) {
  19251. var isIdArray = isArray(id);
  19252. result = filter(cpts, function (cpt) {
  19253. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19254. || (!isIdArray && cpt.id === id);
  19255. });
  19256. }
  19257. else if (name != null) {
  19258. var isNameArray = isArray(name);
  19259. result = filter(cpts, function (cpt) {
  19260. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19261. || (!isNameArray && cpt.name === name);
  19262. });
  19263. }
  19264. else {
  19265. // Return all components with mainType
  19266. result = cpts.slice();
  19267. }
  19268. return filterBySubType(result, condition);
  19269. },
  19270. /**
  19271. * The interface is different from queryComponents,
  19272. * which is convenient for inner usage.
  19273. *
  19274. * @usage
  19275. * var result = findComponents(
  19276. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19277. * );
  19278. * var result = findComponents(
  19279. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19280. * );
  19281. * var result = findComponents(
  19282. * {mainType: 'series',
  19283. * filter: function (model, index) {...}}
  19284. * );
  19285. * // result like [component0, componnet1, ...]
  19286. *
  19287. * @param {Object} condition
  19288. * @param {string} condition.mainType Mandatory.
  19289. * @param {string} [condition.subType] Optional.
  19290. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19291. * where xxx is mainType.
  19292. * If query attribute is null/undefined or has no index/id/name,
  19293. * do not filtering by query conditions, which is convenient for
  19294. * no-payload situations or when target of action is global.
  19295. * @param {Function} [condition.filter] parameter: component, return boolean.
  19296. * @return {Array.<module:echarts/model/Component>}
  19297. */
  19298. findComponents: function (condition) {
  19299. var query = condition.query;
  19300. var mainType = condition.mainType;
  19301. var queryCond = getQueryCond(query);
  19302. var result = queryCond
  19303. ? this.queryComponents(queryCond)
  19304. : this._componentsMap.get(mainType);
  19305. return doFilter(filterBySubType(result, condition));
  19306. function getQueryCond(q) {
  19307. var indexAttr = mainType + 'Index';
  19308. var idAttr = mainType + 'Id';
  19309. var nameAttr = mainType + 'Name';
  19310. return q && (
  19311. q[indexAttr] != null
  19312. || q[idAttr] != null
  19313. || q[nameAttr] != null
  19314. )
  19315. ? {
  19316. mainType: mainType,
  19317. // subType will be filtered finally.
  19318. index: q[indexAttr],
  19319. id: q[idAttr],
  19320. name: q[nameAttr]
  19321. }
  19322. : null;
  19323. }
  19324. function doFilter(res) {
  19325. return condition.filter
  19326. ? filter(res, condition.filter)
  19327. : res;
  19328. }
  19329. },
  19330. /**
  19331. * @usage
  19332. * eachComponent('legend', function (legendModel, index) {
  19333. * ...
  19334. * });
  19335. * eachComponent(function (componentType, model, index) {
  19336. * // componentType does not include subType
  19337. * // (componentType is 'xxx' but not 'xxx.aa')
  19338. * });
  19339. * eachComponent(
  19340. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19341. * function (model, index) {...}
  19342. * );
  19343. * eachComponent(
  19344. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19345. * function (model, index) {...}
  19346. * );
  19347. *
  19348. * @param {string|Object=} mainType When mainType is object, the definition
  19349. * is the same as the method 'findComponents'.
  19350. * @param {Function} cb
  19351. * @param {*} context
  19352. */
  19353. eachComponent: function (mainType, cb, context) {
  19354. var componentsMap = this._componentsMap;
  19355. if (typeof mainType === 'function') {
  19356. context = cb;
  19357. cb = mainType;
  19358. componentsMap.each(function (components, componentType) {
  19359. each$1(components, function (component, index) {
  19360. cb.call(context, componentType, component, index);
  19361. });
  19362. });
  19363. }
  19364. else if (isString(mainType)) {
  19365. each$1(componentsMap.get(mainType), cb, context);
  19366. }
  19367. else if (isObject$1(mainType)) {
  19368. var queryResult = this.findComponents(mainType);
  19369. each$1(queryResult, cb, context);
  19370. }
  19371. },
  19372. /**
  19373. * @param {string} name
  19374. * @return {Array.<module:echarts/model/Series>}
  19375. */
  19376. getSeriesByName: function (name) {
  19377. var series = this._componentsMap.get('series');
  19378. return filter(series, function (oneSeries) {
  19379. return oneSeries.name === name;
  19380. });
  19381. },
  19382. /**
  19383. * @param {number} seriesIndex
  19384. * @return {module:echarts/model/Series}
  19385. */
  19386. getSeriesByIndex: function (seriesIndex) {
  19387. return this._componentsMap.get('series')[seriesIndex];
  19388. },
  19389. /**
  19390. * Get series list before filtered by type.
  19391. * FIXME: rename to getRawSeriesByType?
  19392. *
  19393. * @param {string} subType
  19394. * @return {Array.<module:echarts/model/Series>}
  19395. */
  19396. getSeriesByType: function (subType) {
  19397. var series = this._componentsMap.get('series');
  19398. return filter(series, function (oneSeries) {
  19399. return oneSeries.subType === subType;
  19400. });
  19401. },
  19402. /**
  19403. * @return {Array.<module:echarts/model/Series>}
  19404. */
  19405. getSeries: function () {
  19406. return this._componentsMap.get('series').slice();
  19407. },
  19408. /**
  19409. * @return {number}
  19410. */
  19411. getSeriesCount: function () {
  19412. return this._componentsMap.get('series').length;
  19413. },
  19414. /**
  19415. * After filtering, series may be different
  19416. * frome raw series.
  19417. *
  19418. * @param {Function} cb
  19419. * @param {*} context
  19420. */
  19421. eachSeries: function (cb, context) {
  19422. assertSeriesInitialized(this);
  19423. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19424. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19425. cb.call(context, series, rawSeriesIndex);
  19426. }, this);
  19427. },
  19428. /**
  19429. * Iterate raw series before filtered.
  19430. *
  19431. * @param {Function} cb
  19432. * @param {*} context
  19433. */
  19434. eachRawSeries: function (cb, context) {
  19435. each$1(this._componentsMap.get('series'), cb, context);
  19436. },
  19437. /**
  19438. * After filtering, series may be different.
  19439. * frome raw series.
  19440. *
  19441. * @param {string} subType.
  19442. * @param {Function} cb
  19443. * @param {*} context
  19444. */
  19445. eachSeriesByType: function (subType, cb, context) {
  19446. assertSeriesInitialized(this);
  19447. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19448. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19449. if (series.subType === subType) {
  19450. cb.call(context, series, rawSeriesIndex);
  19451. }
  19452. }, this);
  19453. },
  19454. /**
  19455. * Iterate raw series before filtered of given type.
  19456. *
  19457. * @parma {string} subType
  19458. * @param {Function} cb
  19459. * @param {*} context
  19460. */
  19461. eachRawSeriesByType: function (subType, cb, context) {
  19462. return each$1(this.getSeriesByType(subType), cb, context);
  19463. },
  19464. /**
  19465. * @param {module:echarts/model/Series} seriesModel
  19466. */
  19467. isSeriesFiltered: function (seriesModel) {
  19468. assertSeriesInitialized(this);
  19469. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19470. },
  19471. /**
  19472. * @return {Array.<number>}
  19473. */
  19474. getCurrentSeriesIndices: function () {
  19475. return (this._seriesIndices || []).slice();
  19476. },
  19477. /**
  19478. * @param {Function} cb
  19479. * @param {*} context
  19480. */
  19481. filterSeries: function (cb, context) {
  19482. assertSeriesInitialized(this);
  19483. var filteredSeries = filter(
  19484. this._componentsMap.get('series'), cb, context
  19485. );
  19486. createSeriesIndices(this, filteredSeries);
  19487. },
  19488. restoreData: function (payload) {
  19489. var componentsMap = this._componentsMap;
  19490. createSeriesIndices(this, componentsMap.get('series'));
  19491. var componentTypes = [];
  19492. componentsMap.each(function (components, componentType) {
  19493. componentTypes.push(componentType);
  19494. });
  19495. ComponentModel.topologicalTravel(
  19496. componentTypes,
  19497. ComponentModel.getAllClassMainTypes(),
  19498. function (componentType, dependencies) {
  19499. each$1(componentsMap.get(componentType), function (component) {
  19500. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19501. && component.restoreData();
  19502. });
  19503. }
  19504. );
  19505. }
  19506. });
  19507. function isNotTargetSeries(seriesModel, payload) {
  19508. if (payload) {
  19509. var index = payload.seiresIndex;
  19510. var id = payload.seriesId;
  19511. var name = payload.seriesName;
  19512. return (index != null && seriesModel.componentIndex !== index)
  19513. || (id != null && seriesModel.id !== id)
  19514. || (name != null && seriesModel.name !== name);
  19515. }
  19516. }
  19517. /**
  19518. * @inner
  19519. */
  19520. function mergeTheme(option, theme) {
  19521. // PENDING
  19522. // NOT use `colorLayer` in theme if option has `color`
  19523. var notMergeColorLayer = option.color && !option.colorLayer;
  19524. each$1(theme, function (themeItem, name) {
  19525. if (name === 'colorLayer' && notMergeColorLayer) {
  19526. return;
  19527. }
  19528. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19529. if (!ComponentModel.hasClass(name)) {
  19530. if (typeof themeItem === 'object') {
  19531. option[name] = !option[name]
  19532. ? clone(themeItem)
  19533. : merge(option[name], themeItem, false);
  19534. }
  19535. else {
  19536. if (option[name] == null) {
  19537. option[name] = themeItem;
  19538. }
  19539. }
  19540. }
  19541. });
  19542. }
  19543. function initBase(baseOption) {
  19544. baseOption = baseOption;
  19545. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19546. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19547. this.option = {};
  19548. this.option[OPTION_INNER_KEY] = 1;
  19549. /**
  19550. * Init with series: [], in case of calling findSeries method
  19551. * before series initialized.
  19552. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19553. * @private
  19554. */
  19555. this._componentsMap = createHashMap({series: []});
  19556. /**
  19557. * Mapping between filtered series list and raw series list.
  19558. * key: filtered series indices, value: raw series indices.
  19559. * @type {Array.<nubmer>}
  19560. * @private
  19561. */
  19562. this._seriesIndices;
  19563. this._seriesIndicesMap;
  19564. mergeTheme(baseOption, this._theme.option);
  19565. // TODO Needs clone when merging to the unexisted property
  19566. merge(baseOption, globalDefault, false);
  19567. this.mergeOption(baseOption);
  19568. }
  19569. /**
  19570. * @inner
  19571. * @param {Array.<string>|string} types model types
  19572. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19573. */
  19574. function getComponentsByTypes(componentsMap, types) {
  19575. if (!isArray(types)) {
  19576. types = types ? [types] : [];
  19577. }
  19578. var ret = {};
  19579. each$1(types, function (type) {
  19580. ret[type] = (componentsMap.get(type) || []).slice();
  19581. });
  19582. return ret;
  19583. }
  19584. /**
  19585. * @inner
  19586. */
  19587. function determineSubType(mainType, newCptOption, existComponent) {
  19588. var subType = newCptOption.type
  19589. ? newCptOption.type
  19590. : existComponent
  19591. ? existComponent.subType
  19592. // Use determineSubType only when there is no existComponent.
  19593. : ComponentModel.determineSubType(mainType, newCptOption);
  19594. // tooltip, markline, markpoint may always has no subType
  19595. return subType;
  19596. }
  19597. /**
  19598. * @inner
  19599. */
  19600. function createSeriesIndices(ecModel, seriesModels) {
  19601. ecModel._seriesIndicesMap = createHashMap(
  19602. ecModel._seriesIndices = map(seriesModels, function (series) {
  19603. return series.componentIndex;
  19604. }) || []
  19605. );
  19606. }
  19607. /**
  19608. * @inner
  19609. */
  19610. function filterBySubType(components, condition) {
  19611. // Using hasOwnProperty for restrict. Consider
  19612. // subType is undefined in user payload.
  19613. return condition.hasOwnProperty('subType')
  19614. ? filter(components, function (cpt) {
  19615. return cpt.subType === condition.subType;
  19616. })
  19617. : components;
  19618. }
  19619. /**
  19620. * @inner
  19621. */
  19622. function assertSeriesInitialized(ecModel) {
  19623. // Components that use _seriesIndices should depends on series component,
  19624. // which make sure that their initialization is after series.
  19625. if (__DEV__) {
  19626. if (!ecModel._seriesIndices) {
  19627. throw new Error('Option should contains series.');
  19628. }
  19629. }
  19630. }
  19631. mixin(GlobalModel, colorPaletteMixin);
  19632. /*
  19633. * Licensed to the Apache Software Foundation (ASF) under one
  19634. * or more contributor license agreements. See the NOTICE file
  19635. * distributed with this work for additional information
  19636. * regarding copyright ownership. The ASF licenses this file
  19637. * to you under the Apache License, Version 2.0 (the
  19638. * "License"); you may not use this file except in compliance
  19639. * with the License. You may obtain a copy of the License at
  19640. *
  19641. * http://www.apache.org/licenses/LICENSE-2.0
  19642. *
  19643. * Unless required by applicable law or agreed to in writing,
  19644. * software distributed under the License is distributed on an
  19645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19646. * KIND, either express or implied. See the License for the
  19647. * specific language governing permissions and limitations
  19648. * under the License.
  19649. */
  19650. var echartsAPIList = [
  19651. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19652. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19653. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19654. ];
  19655. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19656. function ExtensionAPI(chartInstance) {
  19657. each$1(echartsAPIList, function (name) {
  19658. this[name] = bind(chartInstance[name], chartInstance);
  19659. }, this);
  19660. }
  19661. /*
  19662. * Licensed to the Apache Software Foundation (ASF) under one
  19663. * or more contributor license agreements. See the NOTICE file
  19664. * distributed with this work for additional information
  19665. * regarding copyright ownership. The ASF licenses this file
  19666. * to you under the Apache License, Version 2.0 (the
  19667. * "License"); you may not use this file except in compliance
  19668. * with the License. You may obtain a copy of the License at
  19669. *
  19670. * http://www.apache.org/licenses/LICENSE-2.0
  19671. *
  19672. * Unless required by applicable law or agreed to in writing,
  19673. * software distributed under the License is distributed on an
  19674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19675. * KIND, either express or implied. See the License for the
  19676. * specific language governing permissions and limitations
  19677. * under the License.
  19678. */
  19679. var coordinateSystemCreators = {};
  19680. function CoordinateSystemManager() {
  19681. this._coordinateSystems = [];
  19682. }
  19683. CoordinateSystemManager.prototype = {
  19684. constructor: CoordinateSystemManager,
  19685. create: function (ecModel, api) {
  19686. var coordinateSystems = [];
  19687. each$1(coordinateSystemCreators, function (creater, type) {
  19688. var list = creater.create(ecModel, api);
  19689. coordinateSystems = coordinateSystems.concat(list || []);
  19690. });
  19691. this._coordinateSystems = coordinateSystems;
  19692. },
  19693. update: function (ecModel, api) {
  19694. each$1(this._coordinateSystems, function (coordSys) {
  19695. coordSys.update && coordSys.update(ecModel, api);
  19696. });
  19697. },
  19698. getCoordinateSystems: function () {
  19699. return this._coordinateSystems.slice();
  19700. }
  19701. };
  19702. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19703. coordinateSystemCreators[type] = coordinateSystemCreator;
  19704. };
  19705. CoordinateSystemManager.get = function (type) {
  19706. return coordinateSystemCreators[type];
  19707. };
  19708. /*
  19709. * Licensed to the Apache Software Foundation (ASF) under one
  19710. * or more contributor license agreements. See the NOTICE file
  19711. * distributed with this work for additional information
  19712. * regarding copyright ownership. The ASF licenses this file
  19713. * to you under the Apache License, Version 2.0 (the
  19714. * "License"); you may not use this file except in compliance
  19715. * with the License. You may obtain a copy of the License at
  19716. *
  19717. * http://www.apache.org/licenses/LICENSE-2.0
  19718. *
  19719. * Unless required by applicable law or agreed to in writing,
  19720. * software distributed under the License is distributed on an
  19721. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19722. * KIND, either express or implied. See the License for the
  19723. * specific language governing permissions and limitations
  19724. * under the License.
  19725. */
  19726. /**
  19727. * ECharts option manager
  19728. *
  19729. * @module {echarts/model/OptionManager}
  19730. */
  19731. var each$4 = each$1;
  19732. var clone$3 = clone;
  19733. var map$1 = map;
  19734. var merge$1 = merge;
  19735. var QUERY_REG = /^(min|max)?(.+)$/;
  19736. /**
  19737. * TERM EXPLANATIONS:
  19738. *
  19739. * [option]:
  19740. *
  19741. * An object that contains definitions of components. For example:
  19742. * var option = {
  19743. * title: {...},
  19744. * legend: {...},
  19745. * visualMap: {...},
  19746. * series: [
  19747. * {data: [...]},
  19748. * {data: [...]},
  19749. * ...
  19750. * ]
  19751. * };
  19752. *
  19753. * [rawOption]:
  19754. *
  19755. * An object input to echarts.setOption. 'rawOption' may be an
  19756. * 'option', or may be an object contains multi-options. For example:
  19757. * var option = {
  19758. * baseOption: {
  19759. * title: {...},
  19760. * legend: {...},
  19761. * series: [
  19762. * {data: [...]},
  19763. * {data: [...]},
  19764. * ...
  19765. * ]
  19766. * },
  19767. * timeline: {...},
  19768. * options: [
  19769. * {title: {...}, series: {data: [...]}},
  19770. * {title: {...}, series: {data: [...]}},
  19771. * ...
  19772. * ],
  19773. * media: [
  19774. * {
  19775. * query: {maxWidth: 320},
  19776. * option: {series: {x: 20}, visualMap: {show: false}}
  19777. * },
  19778. * {
  19779. * query: {minWidth: 320, maxWidth: 720},
  19780. * option: {series: {x: 500}, visualMap: {show: true}}
  19781. * },
  19782. * {
  19783. * option: {series: {x: 1200}, visualMap: {show: true}}
  19784. * }
  19785. * ]
  19786. * };
  19787. *
  19788. * @alias module:echarts/model/OptionManager
  19789. * @param {module:echarts/ExtensionAPI} api
  19790. */
  19791. function OptionManager(api) {
  19792. /**
  19793. * @private
  19794. * @type {module:echarts/ExtensionAPI}
  19795. */
  19796. this._api = api;
  19797. /**
  19798. * @private
  19799. * @type {Array.<number>}
  19800. */
  19801. this._timelineOptions = [];
  19802. /**
  19803. * @private
  19804. * @type {Array.<Object>}
  19805. */
  19806. this._mediaList = [];
  19807. /**
  19808. * @private
  19809. * @type {Object}
  19810. */
  19811. this._mediaDefault;
  19812. /**
  19813. * -1, means default.
  19814. * empty means no media.
  19815. * @private
  19816. * @type {Array.<number>}
  19817. */
  19818. this._currentMediaIndices = [];
  19819. /**
  19820. * @private
  19821. * @type {Object}
  19822. */
  19823. this._optionBackup;
  19824. /**
  19825. * @private
  19826. * @type {Object}
  19827. */
  19828. this._newBaseOption;
  19829. }
  19830. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19831. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19832. // rawOption cloned and backuped when timeline changed, which does no
  19833. // good to performance. What's more, that both timeline and setOption
  19834. // method supply 'notMerge' brings complex and some problems.
  19835. // Consider this case:
  19836. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19837. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19838. OptionManager.prototype = {
  19839. constructor: OptionManager,
  19840. /**
  19841. * @public
  19842. * @param {Object} rawOption Raw option.
  19843. * @param {module:echarts/model/Global} ecModel
  19844. * @param {Array.<Function>} optionPreprocessorFuncs
  19845. * @return {Object} Init option
  19846. */
  19847. setOption: function (rawOption, optionPreprocessorFuncs) {
  19848. if (rawOption) {
  19849. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19850. each$1(normalizeToArray(rawOption.series), function (series) {
  19851. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19852. });
  19853. }
  19854. // Caution: some series modify option data, if do not clone,
  19855. // it should ensure that the repeat modify correctly
  19856. // (create a new object when modify itself).
  19857. rawOption = clone$3(rawOption);
  19858. // FIXME
  19859. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19860. var oldOptionBackup = this._optionBackup;
  19861. var newParsedOption = parseRawOption.call(
  19862. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19863. );
  19864. this._newBaseOption = newParsedOption.baseOption;
  19865. // For setOption at second time (using merge mode);
  19866. if (oldOptionBackup) {
  19867. // Only baseOption can be merged.
  19868. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19869. // For simplicity, timeline options and media options do not support merge,
  19870. // that is, if you `setOption` twice and both has timeline options, the latter
  19871. // timeline opitons will not be merged to the formers, but just substitude them.
  19872. if (newParsedOption.timelineOptions.length) {
  19873. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19874. }
  19875. if (newParsedOption.mediaList.length) {
  19876. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19877. }
  19878. if (newParsedOption.mediaDefault) {
  19879. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19880. }
  19881. }
  19882. else {
  19883. this._optionBackup = newParsedOption;
  19884. }
  19885. },
  19886. /**
  19887. * @param {boolean} isRecreate
  19888. * @return {Object}
  19889. */
  19890. mountOption: function (isRecreate) {
  19891. var optionBackup = this._optionBackup;
  19892. // TODO
  19893. // 如果没有reset功能则不clone。
  19894. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19895. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19896. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19897. this._currentMediaIndices = [];
  19898. return clone$3(isRecreate
  19899. // this._optionBackup.baseOption, which is created at the first `setOption`
  19900. // called, and is merged into every new option by inner method `mergeOption`
  19901. // each time `setOption` called, can be only used in `isRecreate`, because
  19902. // its reliability is under suspicion. In other cases option merge is
  19903. // performed by `model.mergeOption`.
  19904. ? optionBackup.baseOption : this._newBaseOption
  19905. );
  19906. },
  19907. /**
  19908. * @param {module:echarts/model/Global} ecModel
  19909. * @return {Object}
  19910. */
  19911. getTimelineOption: function (ecModel) {
  19912. var option;
  19913. var timelineOptions = this._timelineOptions;
  19914. if (timelineOptions.length) {
  19915. // getTimelineOption can only be called after ecModel inited,
  19916. // so we can get currentIndex from timelineModel.
  19917. var timelineModel = ecModel.getComponent('timeline');
  19918. if (timelineModel) {
  19919. option = clone$3(
  19920. timelineOptions[timelineModel.getCurrentIndex()],
  19921. true
  19922. );
  19923. }
  19924. }
  19925. return option;
  19926. },
  19927. /**
  19928. * @param {module:echarts/model/Global} ecModel
  19929. * @return {Array.<Object>}
  19930. */
  19931. getMediaOption: function (ecModel) {
  19932. var ecWidth = this._api.getWidth();
  19933. var ecHeight = this._api.getHeight();
  19934. var mediaList = this._mediaList;
  19935. var mediaDefault = this._mediaDefault;
  19936. var indices = [];
  19937. var result = [];
  19938. // No media defined.
  19939. if (!mediaList.length && !mediaDefault) {
  19940. return result;
  19941. }
  19942. // Multi media may be applied, the latter defined media has higher priority.
  19943. for (var i = 0, len = mediaList.length; i < len; i++) {
  19944. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19945. indices.push(i);
  19946. }
  19947. }
  19948. // FIXME
  19949. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19950. if (!indices.length && mediaDefault) {
  19951. indices = [-1];
  19952. }
  19953. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19954. result = map$1(indices, function (index) {
  19955. return clone$3(
  19956. index === -1 ? mediaDefault.option : mediaList[index].option
  19957. );
  19958. });
  19959. }
  19960. // Otherwise return nothing.
  19961. this._currentMediaIndices = indices;
  19962. return result;
  19963. }
  19964. };
  19965. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19966. var timelineOptions = [];
  19967. var mediaList = [];
  19968. var mediaDefault;
  19969. var baseOption;
  19970. // Compatible with ec2.
  19971. var timelineOpt = rawOption.timeline;
  19972. if (rawOption.baseOption) {
  19973. baseOption = rawOption.baseOption;
  19974. }
  19975. // For timeline
  19976. if (timelineOpt || rawOption.options) {
  19977. baseOption = baseOption || {};
  19978. timelineOptions = (rawOption.options || []).slice();
  19979. }
  19980. // For media query
  19981. if (rawOption.media) {
  19982. baseOption = baseOption || {};
  19983. var media = rawOption.media;
  19984. each$4(media, function (singleMedia) {
  19985. if (singleMedia && singleMedia.option) {
  19986. if (singleMedia.query) {
  19987. mediaList.push(singleMedia);
  19988. }
  19989. else if (!mediaDefault) {
  19990. // Use the first media default.
  19991. mediaDefault = singleMedia;
  19992. }
  19993. }
  19994. });
  19995. }
  19996. // For normal option
  19997. if (!baseOption) {
  19998. baseOption = rawOption;
  19999. }
  20000. // Set timelineOpt to baseOption in ec3,
  20001. // which is convenient for merge option.
  20002. if (!baseOption.timeline) {
  20003. baseOption.timeline = timelineOpt;
  20004. }
  20005. // Preprocess.
  20006. each$4([baseOption].concat(timelineOptions)
  20007. .concat(map(mediaList, function (media) {
  20008. return media.option;
  20009. })),
  20010. function (option) {
  20011. each$4(optionPreprocessorFuncs, function (preProcess) {
  20012. preProcess(option, isNew);
  20013. });
  20014. }
  20015. );
  20016. return {
  20017. baseOption: baseOption,
  20018. timelineOptions: timelineOptions,
  20019. mediaDefault: mediaDefault,
  20020. mediaList: mediaList
  20021. };
  20022. }
  20023. /**
  20024. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  20025. * Support: width, height, aspectRatio
  20026. * Can use max or min as prefix.
  20027. */
  20028. function applyMediaQuery(query, ecWidth, ecHeight) {
  20029. var realMap = {
  20030. width: ecWidth,
  20031. height: ecHeight,
  20032. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  20033. };
  20034. var applicatable = true;
  20035. each$1(query, function (value, attr) {
  20036. var matched = attr.match(QUERY_REG);
  20037. if (!matched || !matched[1] || !matched[2]) {
  20038. return;
  20039. }
  20040. var operator = matched[1];
  20041. var realAttr = matched[2].toLowerCase();
  20042. if (!compare(realMap[realAttr], value, operator)) {
  20043. applicatable = false;
  20044. }
  20045. });
  20046. return applicatable;
  20047. }
  20048. function compare(real, expect, operator) {
  20049. if (operator === 'min') {
  20050. return real >= expect;
  20051. }
  20052. else if (operator === 'max') {
  20053. return real <= expect;
  20054. }
  20055. else { // Equals
  20056. return real === expect;
  20057. }
  20058. }
  20059. function indicesEquals(indices1, indices2) {
  20060. // indices is always order by asc and has only finite number.
  20061. return indices1.join(',') === indices2.join(',');
  20062. }
  20063. /**
  20064. * Consider case:
  20065. * `chart.setOption(opt1);`
  20066. * Then user do some interaction like dataZoom, dataView changing.
  20067. * `chart.setOption(opt2);`
  20068. * Then user press 'reset button' in toolbox.
  20069. *
  20070. * After doing that all of the interaction effects should be reset, the
  20071. * chart should be the same as the result of invoke
  20072. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20073. *
  20074. * Although it is not able ensure that
  20075. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20076. * `chart.setOption(merge(opt1, opt2));` exactly,
  20077. * this might be the only simple way to implement that feature.
  20078. *
  20079. * MEMO: We've considered some other approaches:
  20080. * 1. Each model handle its self restoration but not uniform treatment.
  20081. * (Too complex in logic and error-prone)
  20082. * 2. Use a shadow ecModel. (Performace expensive)
  20083. */
  20084. function mergeOption(oldOption, newOption) {
  20085. newOption = newOption || {};
  20086. each$4(newOption, function (newCptOpt, mainType) {
  20087. if (newCptOpt == null) {
  20088. return;
  20089. }
  20090. var oldCptOpt = oldOption[mainType];
  20091. if (!ComponentModel.hasClass(mainType)) {
  20092. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20093. }
  20094. else {
  20095. newCptOpt = normalizeToArray(newCptOpt);
  20096. oldCptOpt = normalizeToArray(oldCptOpt);
  20097. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20098. oldOption[mainType] = map$1(mapResult, function (item) {
  20099. return (item.option && item.exist)
  20100. ? merge$1(item.exist, item.option, true)
  20101. : (item.exist || item.option);
  20102. });
  20103. }
  20104. });
  20105. }
  20106. /*
  20107. * Licensed to the Apache Software Foundation (ASF) under one
  20108. * or more contributor license agreements. See the NOTICE file
  20109. * distributed with this work for additional information
  20110. * regarding copyright ownership. The ASF licenses this file
  20111. * to you under the Apache License, Version 2.0 (the
  20112. * "License"); you may not use this file except in compliance
  20113. * with the License. You may obtain a copy of the License at
  20114. *
  20115. * http://www.apache.org/licenses/LICENSE-2.0
  20116. *
  20117. * Unless required by applicable law or agreed to in writing,
  20118. * software distributed under the License is distributed on an
  20119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20120. * KIND, either express or implied. See the License for the
  20121. * specific language governing permissions and limitations
  20122. * under the License.
  20123. */
  20124. var each$5 = each$1;
  20125. var isObject$3 = isObject$1;
  20126. var POSSIBLE_STYLES = [
  20127. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20128. 'chordStyle', 'label', 'labelLine'
  20129. ];
  20130. function compatEC2ItemStyle(opt) {
  20131. var itemStyleOpt = opt && opt.itemStyle;
  20132. if (!itemStyleOpt) {
  20133. return;
  20134. }
  20135. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20136. var styleName = POSSIBLE_STYLES[i];
  20137. var normalItemStyleOpt = itemStyleOpt.normal;
  20138. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20139. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20140. opt[styleName] = opt[styleName] || {};
  20141. if (!opt[styleName].normal) {
  20142. opt[styleName].normal = normalItemStyleOpt[styleName];
  20143. }
  20144. else {
  20145. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20146. }
  20147. normalItemStyleOpt[styleName] = null;
  20148. }
  20149. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20150. opt[styleName] = opt[styleName] || {};
  20151. if (!opt[styleName].emphasis) {
  20152. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20153. }
  20154. else {
  20155. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20156. }
  20157. emphasisItemStyleOpt[styleName] = null;
  20158. }
  20159. }
  20160. }
  20161. function convertNormalEmphasis(opt, optType, useExtend) {
  20162. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20163. var normalOpt = opt[optType].normal;
  20164. var emphasisOpt = opt[optType].emphasis;
  20165. if (normalOpt) {
  20166. // Timeline controlStyle has other properties besides normal and emphasis
  20167. if (useExtend) {
  20168. opt[optType].normal = opt[optType].emphasis = null;
  20169. defaults(opt[optType], normalOpt);
  20170. }
  20171. else {
  20172. opt[optType] = normalOpt;
  20173. }
  20174. }
  20175. if (emphasisOpt) {
  20176. opt.emphasis = opt.emphasis || {};
  20177. opt.emphasis[optType] = emphasisOpt;
  20178. }
  20179. }
  20180. }
  20181. function removeEC3NormalStatus(opt) {
  20182. convertNormalEmphasis(opt, 'itemStyle');
  20183. convertNormalEmphasis(opt, 'lineStyle');
  20184. convertNormalEmphasis(opt, 'areaStyle');
  20185. convertNormalEmphasis(opt, 'label');
  20186. convertNormalEmphasis(opt, 'labelLine');
  20187. // treemap
  20188. convertNormalEmphasis(opt, 'upperLabel');
  20189. // graph
  20190. convertNormalEmphasis(opt, 'edgeLabel');
  20191. }
  20192. function compatTextStyle(opt, propName) {
  20193. // Check whether is not object (string\null\undefined ...)
  20194. var labelOptSingle = isObject$3(opt) && opt[propName];
  20195. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20196. if (textStyle) {
  20197. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20198. var propName = TEXT_STYLE_OPTIONS[i];
  20199. if (textStyle.hasOwnProperty(propName)) {
  20200. labelOptSingle[propName] = textStyle[propName];
  20201. }
  20202. }
  20203. }
  20204. }
  20205. function compatEC3CommonStyles(opt) {
  20206. if (opt) {
  20207. removeEC3NormalStatus(opt);
  20208. compatTextStyle(opt, 'label');
  20209. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20210. }
  20211. }
  20212. function processSeries(seriesOpt) {
  20213. if (!isObject$3(seriesOpt)) {
  20214. return;
  20215. }
  20216. compatEC2ItemStyle(seriesOpt);
  20217. removeEC3NormalStatus(seriesOpt);
  20218. compatTextStyle(seriesOpt, 'label');
  20219. // treemap
  20220. compatTextStyle(seriesOpt, 'upperLabel');
  20221. // graph
  20222. compatTextStyle(seriesOpt, 'edgeLabel');
  20223. if (seriesOpt.emphasis) {
  20224. compatTextStyle(seriesOpt.emphasis, 'label');
  20225. // treemap
  20226. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20227. // graph
  20228. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20229. }
  20230. var markPoint = seriesOpt.markPoint;
  20231. if (markPoint) {
  20232. compatEC2ItemStyle(markPoint);
  20233. compatEC3CommonStyles(markPoint);
  20234. }
  20235. var markLine = seriesOpt.markLine;
  20236. if (markLine) {
  20237. compatEC2ItemStyle(markLine);
  20238. compatEC3CommonStyles(markLine);
  20239. }
  20240. var markArea = seriesOpt.markArea;
  20241. if (markArea) {
  20242. compatEC3CommonStyles(markArea);
  20243. }
  20244. var data = seriesOpt.data;
  20245. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20246. // then the backward compat based on option type will not be performed.
  20247. if (seriesOpt.type === 'graph') {
  20248. data = data || seriesOpt.nodes;
  20249. var edgeData = seriesOpt.links || seriesOpt.edges;
  20250. if (edgeData && !isTypedArray(edgeData)) {
  20251. for (var i = 0; i < edgeData.length; i++) {
  20252. compatEC3CommonStyles(edgeData[i]);
  20253. }
  20254. }
  20255. each$1(seriesOpt.categories, function (opt) {
  20256. removeEC3NormalStatus(opt);
  20257. });
  20258. }
  20259. if (data && !isTypedArray(data)) {
  20260. for (var i = 0; i < data.length; i++) {
  20261. compatEC3CommonStyles(data[i]);
  20262. }
  20263. }
  20264. // mark point data
  20265. var markPoint = seriesOpt.markPoint;
  20266. if (markPoint && markPoint.data) {
  20267. var mpData = markPoint.data;
  20268. for (var i = 0; i < mpData.length; i++) {
  20269. compatEC3CommonStyles(mpData[i]);
  20270. }
  20271. }
  20272. // mark line data
  20273. var markLine = seriesOpt.markLine;
  20274. if (markLine && markLine.data) {
  20275. var mlData = markLine.data;
  20276. for (var i = 0; i < mlData.length; i++) {
  20277. if (isArray(mlData[i])) {
  20278. compatEC3CommonStyles(mlData[i][0]);
  20279. compatEC3CommonStyles(mlData[i][1]);
  20280. }
  20281. else {
  20282. compatEC3CommonStyles(mlData[i]);
  20283. }
  20284. }
  20285. }
  20286. // Series
  20287. if (seriesOpt.type === 'gauge') {
  20288. compatTextStyle(seriesOpt, 'axisLabel');
  20289. compatTextStyle(seriesOpt, 'title');
  20290. compatTextStyle(seriesOpt, 'detail');
  20291. }
  20292. else if (seriesOpt.type === 'treemap') {
  20293. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20294. each$1(seriesOpt.levels, function (opt) {
  20295. removeEC3NormalStatus(opt);
  20296. });
  20297. }
  20298. else if (seriesOpt.type === 'tree') {
  20299. removeEC3NormalStatus(seriesOpt.leaves);
  20300. }
  20301. // sunburst starts from ec4, so it does not need to compat levels.
  20302. }
  20303. function toArr(o) {
  20304. return isArray(o) ? o : o ? [o] : [];
  20305. }
  20306. function toObj(o) {
  20307. return (isArray(o) ? o[0] : o) || {};
  20308. }
  20309. var compatStyle = function (option, isTheme) {
  20310. each$5(toArr(option.series), function (seriesOpt) {
  20311. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20312. });
  20313. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20314. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20315. each$5(
  20316. axes,
  20317. function (axisName) {
  20318. each$5(toArr(option[axisName]), function (axisOpt) {
  20319. if (axisOpt) {
  20320. compatTextStyle(axisOpt, 'axisLabel');
  20321. compatTextStyle(axisOpt.axisPointer, 'label');
  20322. }
  20323. });
  20324. }
  20325. );
  20326. each$5(toArr(option.parallel), function (parallelOpt) {
  20327. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20328. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20329. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20330. });
  20331. each$5(toArr(option.calendar), function (calendarOpt) {
  20332. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20333. compatTextStyle(calendarOpt, 'dayLabel');
  20334. compatTextStyle(calendarOpt, 'monthLabel');
  20335. compatTextStyle(calendarOpt, 'yearLabel');
  20336. });
  20337. // radar.name.textStyle
  20338. each$5(toArr(option.radar), function (radarOpt) {
  20339. compatTextStyle(radarOpt, 'name');
  20340. });
  20341. each$5(toArr(option.geo), function (geoOpt) {
  20342. if (isObject$3(geoOpt)) {
  20343. compatEC3CommonStyles(geoOpt);
  20344. each$5(toArr(geoOpt.regions), function (regionObj) {
  20345. compatEC3CommonStyles(regionObj);
  20346. });
  20347. }
  20348. });
  20349. each$5(toArr(option.timeline), function (timelineOpt) {
  20350. compatEC3CommonStyles(timelineOpt);
  20351. convertNormalEmphasis(timelineOpt, 'label');
  20352. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20353. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20354. var data = timelineOpt.data;
  20355. isArray(data) && each$1(data, function (item) {
  20356. if (isObject$1(item)) {
  20357. convertNormalEmphasis(item, 'label');
  20358. convertNormalEmphasis(item, 'itemStyle');
  20359. }
  20360. });
  20361. });
  20362. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20363. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20364. each$5(toolboxOpt.feature, function (featureOpt) {
  20365. convertNormalEmphasis(featureOpt, 'iconStyle');
  20366. });
  20367. });
  20368. compatTextStyle(toObj(option.axisPointer), 'label');
  20369. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20370. };
  20371. /*
  20372. * Licensed to the Apache Software Foundation (ASF) under one
  20373. * or more contributor license agreements. See the NOTICE file
  20374. * distributed with this work for additional information
  20375. * regarding copyright ownership. The ASF licenses this file
  20376. * to you under the Apache License, Version 2.0 (the
  20377. * "License"); you may not use this file except in compliance
  20378. * with the License. You may obtain a copy of the License at
  20379. *
  20380. * http://www.apache.org/licenses/LICENSE-2.0
  20381. *
  20382. * Unless required by applicable law or agreed to in writing,
  20383. * software distributed under the License is distributed on an
  20384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20385. * KIND, either express or implied. See the License for the
  20386. * specific language governing permissions and limitations
  20387. * under the License.
  20388. */
  20389. // Compatitable with 2.0
  20390. function get(opt, path) {
  20391. path = path.split(',');
  20392. var obj = opt;
  20393. for (var i = 0; i < path.length; i++) {
  20394. obj = obj && obj[path[i]];
  20395. if (obj == null) {
  20396. break;
  20397. }
  20398. }
  20399. return obj;
  20400. }
  20401. function set$1(opt, path, val, overwrite) {
  20402. path = path.split(',');
  20403. var obj = opt;
  20404. var key;
  20405. for (var i = 0; i < path.length - 1; i++) {
  20406. key = path[i];
  20407. if (obj[key] == null) {
  20408. obj[key] = {};
  20409. }
  20410. obj = obj[key];
  20411. }
  20412. if (overwrite || obj[path[i]] == null) {
  20413. obj[path[i]] = val;
  20414. }
  20415. }
  20416. function compatLayoutProperties(option) {
  20417. each$1(LAYOUT_PROPERTIES, function (prop) {
  20418. if (prop[0] in option && !(prop[1] in option)) {
  20419. option[prop[1]] = option[prop[0]];
  20420. }
  20421. });
  20422. }
  20423. var LAYOUT_PROPERTIES = [
  20424. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20425. ];
  20426. var COMPATITABLE_COMPONENTS = [
  20427. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20428. ];
  20429. var backwardCompat = function (option, isTheme) {
  20430. compatStyle(option, isTheme);
  20431. // Make sure series array for model initialization.
  20432. option.series = normalizeToArray(option.series);
  20433. each$1(option.series, function (seriesOpt) {
  20434. if (!isObject$1(seriesOpt)) {
  20435. return;
  20436. }
  20437. var seriesType = seriesOpt.type;
  20438. if (seriesType === 'line') {
  20439. if (seriesOpt.clipOverflow != null) {
  20440. seriesOpt.clip = seriesOpt.clipOverflow;
  20441. }
  20442. }
  20443. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20444. if (seriesOpt.clockWise != null) {
  20445. seriesOpt.clockwise = seriesOpt.clockWise;
  20446. }
  20447. }
  20448. else if (seriesType === 'gauge') {
  20449. var pointerColor = get(seriesOpt, 'pointer.color');
  20450. pointerColor != null
  20451. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20452. }
  20453. compatLayoutProperties(seriesOpt);
  20454. });
  20455. // dataRange has changed to visualMap
  20456. if (option.dataRange) {
  20457. option.visualMap = option.dataRange;
  20458. }
  20459. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20460. var options = option[componentName];
  20461. if (options) {
  20462. if (!isArray(options)) {
  20463. options = [options];
  20464. }
  20465. each$1(options, function (option) {
  20466. compatLayoutProperties(option);
  20467. });
  20468. }
  20469. });
  20470. };
  20471. /*
  20472. * Licensed to the Apache Software Foundation (ASF) under one
  20473. * or more contributor license agreements. See the NOTICE file
  20474. * distributed with this work for additional information
  20475. * regarding copyright ownership. The ASF licenses this file
  20476. * to you under the Apache License, Version 2.0 (the
  20477. * "License"); you may not use this file except in compliance
  20478. * with the License. You may obtain a copy of the License at
  20479. *
  20480. * http://www.apache.org/licenses/LICENSE-2.0
  20481. *
  20482. * Unless required by applicable law or agreed to in writing,
  20483. * software distributed under the License is distributed on an
  20484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20485. * KIND, either express or implied. See the License for the
  20486. * specific language governing permissions and limitations
  20487. * under the License.
  20488. */
  20489. // (1) [Caution]: the logic is correct based on the premises:
  20490. // data processing stage is blocked in stream.
  20491. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20492. // (2) Only register once when import repeatly.
  20493. // Should be executed after series filtered and before stack calculation.
  20494. var dataStack = function (ecModel) {
  20495. var stackInfoMap = createHashMap();
  20496. ecModel.eachSeries(function (seriesModel) {
  20497. var stack = seriesModel.get('stack');
  20498. // Compatibal: when `stack` is set as '', do not stack.
  20499. if (stack) {
  20500. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20501. var data = seriesModel.getData();
  20502. var stackInfo = {
  20503. // Used for calculate axis extent automatically.
  20504. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20505. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20506. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20507. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20508. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20509. data: data,
  20510. seriesModel: seriesModel
  20511. };
  20512. // If stacked on axis that do not support data stack.
  20513. if (!stackInfo.stackedDimension
  20514. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20515. ) {
  20516. return;
  20517. }
  20518. stackInfoList.length && data.setCalculationInfo(
  20519. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20520. );
  20521. stackInfoList.push(stackInfo);
  20522. }
  20523. });
  20524. stackInfoMap.each(calculateStack);
  20525. };
  20526. function calculateStack(stackInfoList) {
  20527. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20528. var resultVal = [];
  20529. var resultNaN = [NaN, NaN];
  20530. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20531. var targetData = targetStackInfo.data;
  20532. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20533. // Should not write on raw data, because stack series model list changes
  20534. // depending on legend selection.
  20535. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20536. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20537. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20538. // should also be NaN, to draw a appropriate belt area.
  20539. if (isNaN(sum)) {
  20540. return resultNaN;
  20541. }
  20542. var byValue;
  20543. var stackedDataRawIndex;
  20544. if (isStackedByIndex) {
  20545. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20546. }
  20547. else {
  20548. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20549. }
  20550. // If stackOver is NaN, chart view will render point on value start.
  20551. var stackedOver = NaN;
  20552. for (var j = idxInStack - 1; j >= 0; j--) {
  20553. var stackInfo = stackInfoList[j];
  20554. // Has been optimized by inverted indices on `stackedByDimension`.
  20555. if (!isStackedByIndex) {
  20556. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20557. }
  20558. if (stackedDataRawIndex >= 0) {
  20559. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20560. // Considering positive stack, negative stack and empty data
  20561. if ((sum >= 0 && val > 0) // Positive stack
  20562. || (sum <= 0 && val < 0) // Negative stack
  20563. ) {
  20564. sum += val;
  20565. stackedOver = val;
  20566. break;
  20567. }
  20568. }
  20569. }
  20570. resultVal[0] = sum;
  20571. resultVal[1] = stackedOver;
  20572. return resultVal;
  20573. });
  20574. targetData.hostModel.setData(newData);
  20575. // Update for consequent calculation
  20576. targetStackInfo.data = newData;
  20577. });
  20578. }
  20579. /*
  20580. * Licensed to the Apache Software Foundation (ASF) under one
  20581. * or more contributor license agreements. See the NOTICE file
  20582. * distributed with this work for additional information
  20583. * regarding copyright ownership. The ASF licenses this file
  20584. * to you under the Apache License, Version 2.0 (the
  20585. * "License"); you may not use this file except in compliance
  20586. * with the License. You may obtain a copy of the License at
  20587. *
  20588. * http://www.apache.org/licenses/LICENSE-2.0
  20589. *
  20590. * Unless required by applicable law or agreed to in writing,
  20591. * software distributed under the License is distributed on an
  20592. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20593. * KIND, either express or implied. See the License for the
  20594. * specific language governing permissions and limitations
  20595. * under the License.
  20596. */
  20597. // TODO
  20598. // ??? refactor? check the outer usage of data provider.
  20599. // merge with defaultDimValueGetter?
  20600. /**
  20601. * If normal array used, mutable chunk size is supported.
  20602. * If typed array used, chunk size must be fixed.
  20603. */
  20604. function DefaultDataProvider(source, dimSize) {
  20605. if (!Source.isInstance(source)) {
  20606. source = Source.seriesDataToSource(source);
  20607. }
  20608. this._source = source;
  20609. var data = this._data = source.data;
  20610. var sourceFormat = source.sourceFormat;
  20611. // Typed array. TODO IE10+?
  20612. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20613. if (__DEV__) {
  20614. if (dimSize == null) {
  20615. throw new Error('Typed array data must specify dimension size');
  20616. }
  20617. }
  20618. this._offset = 0;
  20619. this._dimSize = dimSize;
  20620. this._data = data;
  20621. }
  20622. var methods = providerMethods[
  20623. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20624. ? sourceFormat + '_' + source.seriesLayoutBy
  20625. : sourceFormat
  20626. ];
  20627. if (__DEV__) {
  20628. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20629. }
  20630. extend(this, methods);
  20631. }
  20632. var providerProto = DefaultDataProvider.prototype;
  20633. // If data is pure without style configuration
  20634. providerProto.pure = false;
  20635. // If data is persistent and will not be released after use.
  20636. providerProto.persistent = true;
  20637. // ???! FIXME legacy data provider do not has method getSource
  20638. providerProto.getSource = function () {
  20639. return this._source;
  20640. };
  20641. var providerMethods = {
  20642. 'arrayRows_column': {
  20643. pure: true,
  20644. count: function () {
  20645. return Math.max(0, this._data.length - this._source.startIndex);
  20646. },
  20647. getItem: function (idx) {
  20648. return this._data[idx + this._source.startIndex];
  20649. },
  20650. appendData: appendDataSimply
  20651. },
  20652. 'arrayRows_row': {
  20653. pure: true,
  20654. count: function () {
  20655. var row = this._data[0];
  20656. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20657. },
  20658. getItem: function (idx) {
  20659. idx += this._source.startIndex;
  20660. var item = [];
  20661. var data = this._data;
  20662. for (var i = 0; i < data.length; i++) {
  20663. var row = data[i];
  20664. item.push(row ? row[idx] : null);
  20665. }
  20666. return item;
  20667. },
  20668. appendData: function () {
  20669. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20670. }
  20671. },
  20672. 'objectRows': {
  20673. pure: true,
  20674. count: countSimply,
  20675. getItem: getItemSimply,
  20676. appendData: appendDataSimply
  20677. },
  20678. 'keyedColumns': {
  20679. pure: true,
  20680. count: function () {
  20681. var dimName = this._source.dimensionsDefine[0].name;
  20682. var col = this._data[dimName];
  20683. return col ? col.length : 0;
  20684. },
  20685. getItem: function (idx) {
  20686. var item = [];
  20687. var dims = this._source.dimensionsDefine;
  20688. for (var i = 0; i < dims.length; i++) {
  20689. var col = this._data[dims[i].name];
  20690. item.push(col ? col[idx] : null);
  20691. }
  20692. return item;
  20693. },
  20694. appendData: function (newData) {
  20695. var data = this._data;
  20696. each$1(newData, function (newCol, key) {
  20697. var oldCol = data[key] || (data[key] = []);
  20698. for (var i = 0; i < (newCol || []).length; i++) {
  20699. oldCol.push(newCol[i]);
  20700. }
  20701. });
  20702. }
  20703. },
  20704. 'original': {
  20705. count: countSimply,
  20706. getItem: getItemSimply,
  20707. appendData: appendDataSimply
  20708. },
  20709. 'typedArray': {
  20710. persistent: false,
  20711. pure: true,
  20712. count: function () {
  20713. return this._data ? (this._data.length / this._dimSize) : 0;
  20714. },
  20715. getItem: function (idx, out) {
  20716. idx = idx - this._offset;
  20717. out = out || [];
  20718. var offset = this._dimSize * idx;
  20719. for (var i = 0; i < this._dimSize; i++) {
  20720. out[i] = this._data[offset + i];
  20721. }
  20722. return out;
  20723. },
  20724. appendData: function (newData) {
  20725. if (__DEV__) {
  20726. assert$1(
  20727. isTypedArray(newData),
  20728. 'Added data must be TypedArray if data in initialization is TypedArray'
  20729. );
  20730. }
  20731. this._data = newData;
  20732. },
  20733. // Clean self if data is already used.
  20734. clean: function () {
  20735. // PENDING
  20736. this._offset += this.count();
  20737. this._data = null;
  20738. }
  20739. }
  20740. };
  20741. function countSimply() {
  20742. return this._data.length;
  20743. }
  20744. function getItemSimply(idx) {
  20745. return this._data[idx];
  20746. }
  20747. function appendDataSimply(newData) {
  20748. for (var i = 0; i < newData.length; i++) {
  20749. this._data.push(newData[i]);
  20750. }
  20751. }
  20752. var rawValueGetters = {
  20753. arrayRows: getRawValueSimply,
  20754. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20755. return dimIndex != null ? dataItem[dimName] : dataItem;
  20756. },
  20757. keyedColumns: getRawValueSimply,
  20758. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20759. // FIXME
  20760. // In some case (markpoint in geo (geo-map.html)), dataItem
  20761. // is {coord: [...]}
  20762. var value = getDataItemValue(dataItem);
  20763. return (dimIndex == null || !(value instanceof Array))
  20764. ? value
  20765. : value[dimIndex];
  20766. },
  20767. typedArray: getRawValueSimply
  20768. };
  20769. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20770. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20771. }
  20772. var defaultDimValueGetters = {
  20773. arrayRows: getDimValueSimply,
  20774. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20775. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20776. },
  20777. keyedColumns: getDimValueSimply,
  20778. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20779. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20780. // If dataItem is an plain object with no value field, the var `value`
  20781. // will be assigned with the object, but it will be tread correctly
  20782. // in the `convertDataValue`.
  20783. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20784. // If any dataItem is like { value: 10 }
  20785. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20786. this.hasItemOption = true;
  20787. }
  20788. return converDataValue(
  20789. (value instanceof Array)
  20790. ? value[dimIndex]
  20791. // If value is a single number or something else not array.
  20792. : value,
  20793. this._dimensionInfos[dimName]
  20794. );
  20795. },
  20796. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20797. return dataItem[dimIndex];
  20798. }
  20799. };
  20800. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20801. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20802. }
  20803. /**
  20804. * This helper method convert value in data.
  20805. * @param {string|number|Date} value
  20806. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20807. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20808. */
  20809. function converDataValue(value, dimInfo) {
  20810. // Performance sensitive.
  20811. var dimType = dimInfo && dimInfo.type;
  20812. if (dimType === 'ordinal') {
  20813. // If given value is a category string
  20814. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20815. return ordinalMeta
  20816. ? ordinalMeta.parseAndCollect(value)
  20817. : value;
  20818. }
  20819. if (dimType === 'time'
  20820. // spead up when using timestamp
  20821. && typeof value !== 'number'
  20822. && value != null
  20823. && value !== '-'
  20824. ) {
  20825. value = +parseDate(value);
  20826. }
  20827. // dimType defaults 'number'.
  20828. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20829. // parse to NaN.
  20830. return (value == null || value === '')
  20831. ? NaN
  20832. // If string (like '-'), using '+' parse to NaN
  20833. // If object, also parse to NaN
  20834. : +value;
  20835. }
  20836. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20837. // Consider persistent.
  20838. // Caution: why use raw value to display on label or tooltip?
  20839. // A reason is to avoid format. For example time value we do not know
  20840. // how to format is expected. More over, if stack is used, calculated
  20841. // value may be 0.91000000001, which have brings trouble to display.
  20842. // TODO: consider how to treat null/undefined/NaN when display?
  20843. /**
  20844. * @param {module:echarts/data/List} data
  20845. * @param {number} dataIndex
  20846. * @param {string|number} [dim] dimName or dimIndex
  20847. * @return {Array.<number>|string|number} can be null/undefined.
  20848. */
  20849. function retrieveRawValue(data, dataIndex, dim) {
  20850. if (!data) {
  20851. return;
  20852. }
  20853. // Consider data may be not persistent.
  20854. var dataItem = data.getRawDataItem(dataIndex);
  20855. if (dataItem == null) {
  20856. return;
  20857. }
  20858. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20859. var dimName;
  20860. var dimIndex;
  20861. var dimInfo = data.getDimensionInfo(dim);
  20862. if (dimInfo) {
  20863. dimName = dimInfo.name;
  20864. dimIndex = dimInfo.index;
  20865. }
  20866. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20867. }
  20868. /**
  20869. * Compatible with some cases (in pie, map) like:
  20870. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20871. * where only sourceFormat is 'original' and 'objectRows' supported.
  20872. *
  20873. * ??? TODO
  20874. * Supported detail options in data item when using 'arrayRows'.
  20875. *
  20876. * @param {module:echarts/data/List} data
  20877. * @param {number} dataIndex
  20878. * @param {string} attr like 'selected'
  20879. */
  20880. function retrieveRawAttr(data, dataIndex, attr) {
  20881. if (!data) {
  20882. return;
  20883. }
  20884. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20885. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20886. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20887. ) {
  20888. return;
  20889. }
  20890. var dataItem = data.getRawDataItem(dataIndex);
  20891. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20892. dataItem = null;
  20893. }
  20894. if (dataItem) {
  20895. return dataItem[attr];
  20896. }
  20897. }
  20898. /*
  20899. * Licensed to the Apache Software Foundation (ASF) under one
  20900. * or more contributor license agreements. See the NOTICE file
  20901. * distributed with this work for additional information
  20902. * regarding copyright ownership. The ASF licenses this file
  20903. * to you under the Apache License, Version 2.0 (the
  20904. * "License"); you may not use this file except in compliance
  20905. * with the License. You may obtain a copy of the License at
  20906. *
  20907. * http://www.apache.org/licenses/LICENSE-2.0
  20908. *
  20909. * Unless required by applicable law or agreed to in writing,
  20910. * software distributed under the License is distributed on an
  20911. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20912. * KIND, either express or implied. See the License for the
  20913. * specific language governing permissions and limitations
  20914. * under the License.
  20915. */
  20916. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20917. // PENDING A little ugly
  20918. var dataFormatMixin = {
  20919. /**
  20920. * Get params for formatter
  20921. * @param {number} dataIndex
  20922. * @param {string} [dataType]
  20923. * @return {Object}
  20924. */
  20925. getDataParams: function (dataIndex, dataType) {
  20926. var data = this.getData(dataType);
  20927. var rawValue = this.getRawValue(dataIndex, dataType);
  20928. var rawDataIndex = data.getRawIndex(dataIndex);
  20929. var name = data.getName(dataIndex);
  20930. var itemOpt = data.getRawDataItem(dataIndex);
  20931. var color = data.getItemVisual(dataIndex, 'color');
  20932. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20933. var tooltipModel = this.ecModel.getComponent('tooltip');
  20934. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20935. var renderMode = getTooltipRenderMode(renderModeOption);
  20936. var mainType = this.mainType;
  20937. var isSeries = mainType === 'series';
  20938. var userOutput = data.userOutput;
  20939. return {
  20940. componentType: mainType,
  20941. componentSubType: this.subType,
  20942. componentIndex: this.componentIndex,
  20943. seriesType: isSeries ? this.subType : null,
  20944. seriesIndex: this.seriesIndex,
  20945. seriesId: isSeries ? this.id : null,
  20946. seriesName: isSeries ? this.name : null,
  20947. name: name,
  20948. dataIndex: rawDataIndex,
  20949. data: itemOpt,
  20950. dataType: dataType,
  20951. value: rawValue,
  20952. color: color,
  20953. borderColor: borderColor,
  20954. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20955. encode: userOutput ? userOutput.encode : null,
  20956. marker: getTooltipMarker({
  20957. color: color,
  20958. renderMode: renderMode
  20959. }),
  20960. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20961. $vars: ['seriesName', 'name', 'value']
  20962. };
  20963. },
  20964. /**
  20965. * Format label
  20966. * @param {number} dataIndex
  20967. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20968. * @param {string} [dataType]
  20969. * @param {number} [dimIndex] Only used in some chart that
  20970. * use formatter in different dimensions, like radar.
  20971. * @param {string} [labelProp='label']
  20972. * @return {string} If not formatter, return null/undefined
  20973. */
  20974. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20975. status = status || 'normal';
  20976. var data = this.getData(dataType);
  20977. var itemModel = data.getItemModel(dataIndex);
  20978. var params = this.getDataParams(dataIndex, dataType);
  20979. if (dimIndex != null && (params.value instanceof Array)) {
  20980. params.value = params.value[dimIndex];
  20981. }
  20982. var formatter = itemModel.get(
  20983. status === 'normal'
  20984. ? [labelProp || 'label', 'formatter']
  20985. : [status, labelProp || 'label', 'formatter']
  20986. );
  20987. if (typeof formatter === 'function') {
  20988. params.status = status;
  20989. params.dimensionIndex = dimIndex;
  20990. return formatter(params);
  20991. }
  20992. else if (typeof formatter === 'string') {
  20993. var str = formatTpl(formatter, params);
  20994. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20995. // Do not support '}' in dim name util have to.
  20996. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20997. var len = dim.length;
  20998. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20999. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  21000. }
  21001. return retrieveRawValue(data, dataIndex, dim);
  21002. });
  21003. }
  21004. },
  21005. /**
  21006. * Get raw value in option
  21007. * @param {number} idx
  21008. * @param {string} [dataType]
  21009. * @return {Array|number|string}
  21010. */
  21011. getRawValue: function (idx, dataType) {
  21012. return retrieveRawValue(this.getData(dataType), idx);
  21013. },
  21014. /**
  21015. * Should be implemented.
  21016. * @param {number} dataIndex
  21017. * @param {boolean} [multipleSeries=false]
  21018. * @param {number} [dataType]
  21019. * @return {string} tooltip string
  21020. */
  21021. formatTooltip: function () {
  21022. // Empty function
  21023. }
  21024. };
  21025. /*
  21026. * Licensed to the Apache Software Foundation (ASF) under one
  21027. * or more contributor license agreements. See the NOTICE file
  21028. * distributed with this work for additional information
  21029. * regarding copyright ownership. The ASF licenses this file
  21030. * to you under the Apache License, Version 2.0 (the
  21031. * "License"); you may not use this file except in compliance
  21032. * with the License. You may obtain a copy of the License at
  21033. *
  21034. * http://www.apache.org/licenses/LICENSE-2.0
  21035. *
  21036. * Unless required by applicable law or agreed to in writing,
  21037. * software distributed under the License is distributed on an
  21038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21039. * KIND, either express or implied. See the License for the
  21040. * specific language governing permissions and limitations
  21041. * under the License.
  21042. */
  21043. /**
  21044. * @param {Object} define
  21045. * @return See the return of `createTask`.
  21046. */
  21047. function createTask(define) {
  21048. return new Task(define);
  21049. }
  21050. /**
  21051. * @constructor
  21052. * @param {Object} define
  21053. * @param {Function} define.reset Custom reset
  21054. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  21055. * @param {Function} [define.count] count is used to determin data task.
  21056. * @param {Function} [define.onDirty] count is used to determin data task.
  21057. */
  21058. function Task(define) {
  21059. define = define || {};
  21060. this._reset = define.reset;
  21061. this._plan = define.plan;
  21062. this._count = define.count;
  21063. this._onDirty = define.onDirty;
  21064. this._dirty = true;
  21065. // Context must be specified implicitly, to
  21066. // avoid miss update context when model changed.
  21067. this.context;
  21068. }
  21069. var taskProto = Task.prototype;
  21070. /**
  21071. * @param {Object} performArgs
  21072. * @param {number} [performArgs.step] Specified step.
  21073. * @param {number} [performArgs.skip] Skip customer perform call.
  21074. * @param {number} [performArgs.modBy] Sampling window size.
  21075. * @param {number} [performArgs.modDataCount] Sampling count.
  21076. */
  21077. taskProto.perform = function (performArgs) {
  21078. var upTask = this._upstream;
  21079. var skip = performArgs && performArgs.skip;
  21080. // TODO some refactor.
  21081. // Pull data. Must pull data each time, because context.data
  21082. // may be updated by Series.setData.
  21083. if (this._dirty && upTask) {
  21084. var context = this.context;
  21085. context.data = context.outputData = upTask.context.outputData;
  21086. }
  21087. if (this.__pipeline) {
  21088. this.__pipeline.currentTask = this;
  21089. }
  21090. var planResult;
  21091. if (this._plan && !skip) {
  21092. planResult = this._plan(this.context);
  21093. }
  21094. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21095. // elements uniformed distributed when progress, especially when moving or zooming.
  21096. var lastModBy = normalizeModBy(this._modBy);
  21097. var lastModDataCount = this._modDataCount || 0;
  21098. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21099. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21100. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21101. planResult = 'reset';
  21102. }
  21103. function normalizeModBy(val) {
  21104. !(val >= 1) && (val = 1); // jshint ignore:line
  21105. return val;
  21106. }
  21107. var forceFirstProgress;
  21108. if (this._dirty || planResult === 'reset') {
  21109. this._dirty = false;
  21110. forceFirstProgress = reset(this, skip);
  21111. }
  21112. this._modBy = modBy;
  21113. this._modDataCount = modDataCount;
  21114. var step = performArgs && performArgs.step;
  21115. if (upTask) {
  21116. if (__DEV__) {
  21117. assert$1(upTask._outputDueEnd != null);
  21118. }
  21119. this._dueEnd = upTask._outputDueEnd;
  21120. }
  21121. // DataTask or overallTask
  21122. else {
  21123. if (__DEV__) {
  21124. assert$1(!this._progress || this._count);
  21125. }
  21126. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21127. }
  21128. // Note: Stubs, that its host overall task let it has progress, has progress.
  21129. // If no progress, pass index from upstream to downstream each time plan called.
  21130. if (this._progress) {
  21131. var start = this._dueIndex;
  21132. var end = Math.min(
  21133. step != null ? this._dueIndex + step : Infinity,
  21134. this._dueEnd
  21135. );
  21136. if (!skip && (forceFirstProgress || start < end)) {
  21137. var progress = this._progress;
  21138. if (isArray(progress)) {
  21139. for (var i = 0; i < progress.length; i++) {
  21140. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21141. }
  21142. }
  21143. else {
  21144. doProgress(this, progress, start, end, modBy, modDataCount);
  21145. }
  21146. }
  21147. this._dueIndex = end;
  21148. // If no `outputDueEnd`, assume that output data and
  21149. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21150. var outputDueEnd = this._settedOutputEnd != null
  21151. ? this._settedOutputEnd : end;
  21152. if (__DEV__) {
  21153. // ??? Can not rollback.
  21154. assert$1(outputDueEnd >= this._outputDueEnd);
  21155. }
  21156. this._outputDueEnd = outputDueEnd;
  21157. }
  21158. else {
  21159. // (1) Some overall task has no progress.
  21160. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21161. // This should always be performed so it can be passed to downstream.
  21162. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21163. ? this._settedOutputEnd : this._dueEnd;
  21164. }
  21165. return this.unfinished();
  21166. };
  21167. var iterator = (function () {
  21168. var end;
  21169. var current;
  21170. var modBy;
  21171. var modDataCount;
  21172. var winCount;
  21173. var it = {
  21174. reset: function (s, e, sStep, sCount) {
  21175. current = s;
  21176. end = e;
  21177. modBy = sStep;
  21178. modDataCount = sCount;
  21179. winCount = Math.ceil(modDataCount / modBy);
  21180. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21181. }
  21182. };
  21183. return it;
  21184. function sequentialNext() {
  21185. return current < end ? current++ : null;
  21186. }
  21187. function modNext() {
  21188. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21189. var result = current >= end
  21190. ? null
  21191. : dataIndex < modDataCount
  21192. ? dataIndex
  21193. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21194. // Use normal linear rendering mode.
  21195. : current;
  21196. current++;
  21197. return result;
  21198. }
  21199. })();
  21200. taskProto.dirty = function () {
  21201. this._dirty = true;
  21202. this._onDirty && this._onDirty(this.context);
  21203. };
  21204. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21205. iterator.reset(start, end, modBy, modDataCount);
  21206. taskIns._callingProgress = progress;
  21207. taskIns._callingProgress({
  21208. start: start, end: end, count: end - start, next: iterator.next
  21209. }, taskIns.context);
  21210. }
  21211. function reset(taskIns, skip) {
  21212. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21213. taskIns._settedOutputEnd = null;
  21214. var progress;
  21215. var forceFirstProgress;
  21216. if (!skip && taskIns._reset) {
  21217. progress = taskIns._reset(taskIns.context);
  21218. if (progress && progress.progress) {
  21219. forceFirstProgress = progress.forceFirstProgress;
  21220. progress = progress.progress;
  21221. }
  21222. // To simplify no progress checking, array must has item.
  21223. if (isArray(progress) && !progress.length) {
  21224. progress = null;
  21225. }
  21226. }
  21227. taskIns._progress = progress;
  21228. taskIns._modBy = taskIns._modDataCount = null;
  21229. var downstream = taskIns._downstream;
  21230. downstream && downstream.dirty();
  21231. return forceFirstProgress;
  21232. }
  21233. /**
  21234. * @return {boolean}
  21235. */
  21236. taskProto.unfinished = function () {
  21237. return this._progress && this._dueIndex < this._dueEnd;
  21238. };
  21239. /**
  21240. * @param {Object} downTask The downstream task.
  21241. * @return {Object} The downstream task.
  21242. */
  21243. taskProto.pipe = function (downTask) {
  21244. if (__DEV__) {
  21245. assert$1(downTask && !downTask._disposed && downTask !== this);
  21246. }
  21247. // If already downstream, do not dirty downTask.
  21248. if (this._downstream !== downTask || this._dirty) {
  21249. this._downstream = downTask;
  21250. downTask._upstream = this;
  21251. downTask.dirty();
  21252. }
  21253. };
  21254. taskProto.dispose = function () {
  21255. if (this._disposed) {
  21256. return;
  21257. }
  21258. this._upstream && (this._upstream._downstream = null);
  21259. this._downstream && (this._downstream._upstream = null);
  21260. this._dirty = false;
  21261. this._disposed = true;
  21262. };
  21263. taskProto.getUpstream = function () {
  21264. return this._upstream;
  21265. };
  21266. taskProto.getDownstream = function () {
  21267. return this._downstream;
  21268. };
  21269. taskProto.setOutputEnd = function (end) {
  21270. // This only happend in dataTask, dataZoom, map, currently.
  21271. // where dataZoom do not set end each time, but only set
  21272. // when reset. So we should record the setted end, in case
  21273. // that the stub of dataZoom perform again and earse the
  21274. // setted end by upstream.
  21275. this._outputDueEnd = this._settedOutputEnd = end;
  21276. };
  21277. ///////////////////////////////////////////////////////////
  21278. // For stream debug (Should be commented out after used!)
  21279. // Usage: printTask(this, 'begin');
  21280. // Usage: printTask(this, null, {someExtraProp});
  21281. // function printTask(task, prefix, extra) {
  21282. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21283. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21284. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21285. // var props = [];
  21286. // if (task.__pipeline) {
  21287. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21288. // props.push({text: 'idx', value: val});
  21289. // } else {
  21290. // var stubCount = 0;
  21291. // task.agentStubMap.each(() => stubCount++);
  21292. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21293. // }
  21294. // props.push({text: 'uid', value: task.uidDebug});
  21295. // if (task.__pipeline) {
  21296. // props.push({text: 'pid', value: task.__pipeline.id});
  21297. // task.agent && props.push(
  21298. // {text: 'stubFor', value: task.agent.uidDebug}
  21299. // );
  21300. // }
  21301. // props.push(
  21302. // {text: 'dirty', value: task._dirty},
  21303. // {text: 'dueIndex', value: task._dueIndex},
  21304. // {text: 'dueEnd', value: task._dueEnd},
  21305. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21306. // );
  21307. // if (extra) {
  21308. // Object.keys(extra).forEach(key => {
  21309. // props.push({text: key, value: extra[key]});
  21310. // });
  21311. // }
  21312. // var args = ['color: blue'];
  21313. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21314. // args.push('color: black', 'color: red'),
  21315. // `${item.text}: %c${item.value}`
  21316. // )).join('%c, ');
  21317. // console.log.apply(console, [msg].concat(args));
  21318. // // console.log(this);
  21319. // }
  21320. /*
  21321. * Licensed to the Apache Software Foundation (ASF) under one
  21322. * or more contributor license agreements. See the NOTICE file
  21323. * distributed with this work for additional information
  21324. * regarding copyright ownership. The ASF licenses this file
  21325. * to you under the Apache License, Version 2.0 (the
  21326. * "License"); you may not use this file except in compliance
  21327. * with the License. You may obtain a copy of the License at
  21328. *
  21329. * http://www.apache.org/licenses/LICENSE-2.0
  21330. *
  21331. * Unless required by applicable law or agreed to in writing,
  21332. * software distributed under the License is distributed on an
  21333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21334. * KIND, either express or implied. See the License for the
  21335. * specific language governing permissions and limitations
  21336. * under the License.
  21337. */
  21338. var inner$4 = makeInner();
  21339. var SeriesModel = ComponentModel.extend({
  21340. type: 'series.__base__',
  21341. /**
  21342. * @readOnly
  21343. */
  21344. seriesIndex: 0,
  21345. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21346. coordinateSystem: null,
  21347. /**
  21348. * @type {Object}
  21349. * @protected
  21350. */
  21351. defaultOption: null,
  21352. /**
  21353. * legend visual provider to the legend component
  21354. * @type {Object}
  21355. */
  21356. // PENDING
  21357. legendVisualProvider: null,
  21358. /**
  21359. * Access path of color for visual
  21360. */
  21361. visualColorAccessPath: 'itemStyle.color',
  21362. /**
  21363. * Access path of borderColor for visual
  21364. */
  21365. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21366. /**
  21367. * Support merge layout params.
  21368. * Only support 'box' now (left/right/top/bottom/width/height).
  21369. * @type {string|Object} Object can be {ignoreSize: true}
  21370. * @readOnly
  21371. */
  21372. layoutMode: null,
  21373. init: function (option, parentModel, ecModel, extraOpt) {
  21374. /**
  21375. * @type {number}
  21376. * @readOnly
  21377. */
  21378. this.seriesIndex = this.componentIndex;
  21379. this.dataTask = createTask({
  21380. count: dataTaskCount,
  21381. reset: dataTaskReset
  21382. });
  21383. this.dataTask.context = {model: this};
  21384. this.mergeDefaultAndTheme(option, ecModel);
  21385. prepareSource(this);
  21386. var data = this.getInitialData(option, ecModel);
  21387. wrapData(data, this);
  21388. this.dataTask.context.data = data;
  21389. if (__DEV__) {
  21390. assert$1(data, 'getInitialData returned invalid data.');
  21391. }
  21392. /**
  21393. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21394. * @private
  21395. */
  21396. inner$4(this).dataBeforeProcessed = data;
  21397. // If we reverse the order (make data firstly, and then make
  21398. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21399. // cause data.graph.data !== data when using
  21400. // module:echarts/data/Graph or module:echarts/data/Tree.
  21401. // See module:echarts/data/helper/linkList
  21402. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21403. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21404. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21405. // Call `seriesModel.getRawData()` instead.
  21406. // this.restoreData();
  21407. autoSeriesName(this);
  21408. },
  21409. /**
  21410. * Util for merge default and theme to option
  21411. * @param {Object} option
  21412. * @param {module:echarts/model/Global} ecModel
  21413. */
  21414. mergeDefaultAndTheme: function (option, ecModel) {
  21415. var layoutMode = this.layoutMode;
  21416. var inputPositionParams = layoutMode
  21417. ? getLayoutParams(option) : {};
  21418. // Backward compat: using subType on theme.
  21419. // But if name duplicate between series subType
  21420. // (for example: parallel) add component mainType,
  21421. // add suffix 'Series'.
  21422. var themeSubType = this.subType;
  21423. if (ComponentModel.hasClass(themeSubType)) {
  21424. themeSubType += 'Series';
  21425. }
  21426. merge(
  21427. option,
  21428. ecModel.getTheme().get(this.subType)
  21429. );
  21430. merge(option, this.getDefaultOption());
  21431. // Default label emphasis `show`
  21432. defaultEmphasis(option, 'label', ['show']);
  21433. this.fillDataTextStyle(option.data);
  21434. if (layoutMode) {
  21435. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21436. }
  21437. },
  21438. mergeOption: function (newSeriesOption, ecModel) {
  21439. // this.settingTask.dirty();
  21440. newSeriesOption = merge(this.option, newSeriesOption, true);
  21441. this.fillDataTextStyle(newSeriesOption.data);
  21442. var layoutMode = this.layoutMode;
  21443. if (layoutMode) {
  21444. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21445. }
  21446. prepareSource(this);
  21447. var data = this.getInitialData(newSeriesOption, ecModel);
  21448. wrapData(data, this);
  21449. this.dataTask.dirty();
  21450. this.dataTask.context.data = data;
  21451. inner$4(this).dataBeforeProcessed = data;
  21452. autoSeriesName(this);
  21453. },
  21454. fillDataTextStyle: function (data) {
  21455. // Default data label emphasis `show`
  21456. // FIXME Tree structure data ?
  21457. // FIXME Performance ?
  21458. if (data && !isTypedArray(data)) {
  21459. var props = ['show'];
  21460. for (var i = 0; i < data.length; i++) {
  21461. if (data[i] && data[i].label) {
  21462. defaultEmphasis(data[i], 'label', props);
  21463. }
  21464. }
  21465. }
  21466. },
  21467. /**
  21468. * Init a data structure from data related option in series
  21469. * Must be overwritten
  21470. */
  21471. getInitialData: function () {},
  21472. /**
  21473. * Append data to list
  21474. * @param {Object} params
  21475. * @param {Array|TypedArray} params.data
  21476. */
  21477. appendData: function (params) {
  21478. // FIXME ???
  21479. // (1) If data from dataset, forbidden append.
  21480. // (2) support append data of dataset.
  21481. var data = this.getRawData();
  21482. data.appendData(params.data);
  21483. },
  21484. /**
  21485. * Consider some method like `filter`, `map` need make new data,
  21486. * We should make sure that `seriesModel.getData()` get correct
  21487. * data in the stream procedure. So we fetch data from upstream
  21488. * each time `task.perform` called.
  21489. * @param {string} [dataType]
  21490. * @return {module:echarts/data/List}
  21491. */
  21492. getData: function (dataType) {
  21493. var task = getCurrentTask(this);
  21494. if (task) {
  21495. var data = task.context.data;
  21496. return dataType == null ? data : data.getLinkedData(dataType);
  21497. }
  21498. else {
  21499. // When series is not alive (that may happen when click toolbox
  21500. // restore or setOption with not merge mode), series data may
  21501. // be still need to judge animation or something when graphic
  21502. // elements want to know whether fade out.
  21503. return inner$4(this).data;
  21504. }
  21505. },
  21506. /**
  21507. * @param {module:echarts/data/List} data
  21508. */
  21509. setData: function (data) {
  21510. var task = getCurrentTask(this);
  21511. if (task) {
  21512. var context = task.context;
  21513. // Consider case: filter, data sample.
  21514. if (context.data !== data && task.modifyOutputEnd) {
  21515. task.setOutputEnd(data.count());
  21516. }
  21517. context.outputData = data;
  21518. // Caution: setData should update context.data,
  21519. // Because getData may be called multiply in a
  21520. // single stage and expect to get the data just
  21521. // set. (For example, AxisProxy, x y both call
  21522. // getData and setDate sequentially).
  21523. // So the context.data should be fetched from
  21524. // upstream each time when a stage starts to be
  21525. // performed.
  21526. if (task !== this.dataTask) {
  21527. context.data = data;
  21528. }
  21529. }
  21530. inner$4(this).data = data;
  21531. },
  21532. /**
  21533. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21534. * @return {module:echarts/data/Source} source
  21535. */
  21536. getSource: function () {
  21537. return getSource(this);
  21538. },
  21539. /**
  21540. * Get data before processed
  21541. * @return {module:echarts/data/List}
  21542. */
  21543. getRawData: function () {
  21544. return inner$4(this).dataBeforeProcessed;
  21545. },
  21546. /**
  21547. * Get base axis if has coordinate system and has axis.
  21548. * By default use coordSys.getBaseAxis();
  21549. * Can be overrided for some chart.
  21550. * @return {type} description
  21551. */
  21552. getBaseAxis: function () {
  21553. var coordSys = this.coordinateSystem;
  21554. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21555. },
  21556. // FIXME
  21557. /**
  21558. * Default tooltip formatter
  21559. *
  21560. * @param {number} dataIndex
  21561. * @param {boolean} [multipleSeries=false]
  21562. * @param {number} [dataType]
  21563. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21564. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21565. * string is used as DOM HTML content.
  21566. * 'richText' is used for rendering tooltip in rich text form, for those where
  21567. * DOM operation is not supported.
  21568. * @return {Object} formatted tooltip with `html` and `markers`
  21569. */
  21570. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21571. var series = this;
  21572. renderMode = renderMode || 'html';
  21573. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21574. var isRichText = renderMode === 'richText';
  21575. var markers = {};
  21576. var markerId = 0;
  21577. function formatArrayValue(value) {
  21578. // ??? TODO refactor these logic.
  21579. // check: category-no-encode-has-axis-data in dataset.html
  21580. var vertially = reduce(value, function (vertially, val, idx) {
  21581. var dimItem = data.getDimensionInfo(idx);
  21582. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21583. }, 0);
  21584. var result = [];
  21585. tooltipDims.length
  21586. ? each$1(tooltipDims, function (dim) {
  21587. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21588. })
  21589. // By default, all dims is used on tooltip.
  21590. : each$1(value, setEachItem);
  21591. function setEachItem(val, dim) {
  21592. var dimInfo = data.getDimensionInfo(dim);
  21593. // If `dimInfo.tooltip` is not set, show tooltip.
  21594. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21595. return;
  21596. }
  21597. var dimType = dimInfo.type;
  21598. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21599. var dimHead = getTooltipMarker({
  21600. color: color,
  21601. type: 'subItem',
  21602. renderMode: renderMode,
  21603. markerId: markName
  21604. });
  21605. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21606. var valStr = (vertially
  21607. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21608. : ''
  21609. )
  21610. // FIXME should not format time for raw data?
  21611. + encodeHTML(dimType === 'ordinal'
  21612. ? val + ''
  21613. : dimType === 'time'
  21614. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21615. : addCommas(val)
  21616. );
  21617. valStr && result.push(valStr);
  21618. if (isRichText) {
  21619. markers[markName] = color;
  21620. ++markerId;
  21621. }
  21622. }
  21623. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21624. var content = newLine + result.join(newLine || ', ');
  21625. return {
  21626. renderMode: renderMode,
  21627. content: content,
  21628. style: markers
  21629. };
  21630. }
  21631. function formatSingleValue(val) {
  21632. // return encodeHTML(addCommas(val));
  21633. return {
  21634. renderMode: renderMode,
  21635. content: encodeHTML(addCommas(val)),
  21636. style: markers
  21637. };
  21638. }
  21639. var data = this.getData();
  21640. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21641. var tooltipDimLen = tooltipDims.length;
  21642. var value = this.getRawValue(dataIndex);
  21643. var isValueArr = isArray(value);
  21644. var color = data.getItemVisual(dataIndex, 'color');
  21645. if (isObject$1(color) && color.colorStops) {
  21646. color = (color.colorStops[0] || {}).color;
  21647. }
  21648. color = color || 'transparent';
  21649. // Complicated rule for pretty tooltip.
  21650. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21651. ? formatArrayValue(value)
  21652. : tooltipDimLen
  21653. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21654. : formatSingleValue(isValueArr ? value[0] : value);
  21655. var content = formattedValue.content;
  21656. var markName = series.seriesIndex + 'at' + markerId;
  21657. var colorEl = getTooltipMarker({
  21658. color: color,
  21659. type: 'item',
  21660. renderMode: renderMode,
  21661. markerId: markName
  21662. });
  21663. markers[markName] = color;
  21664. ++markerId;
  21665. var name = data.getName(dataIndex);
  21666. var seriesName = this.name;
  21667. if (!isNameSpecified(this)) {
  21668. seriesName = '';
  21669. }
  21670. seriesName = seriesName
  21671. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21672. : '';
  21673. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21674. var html = !multipleSeries
  21675. ? seriesName + colorStr
  21676. + (name
  21677. ? encodeHTML(name) + ': ' + content
  21678. : content
  21679. )
  21680. : colorStr + seriesName + content;
  21681. return {
  21682. html: html,
  21683. markers: markers
  21684. };
  21685. },
  21686. /**
  21687. * @return {boolean}
  21688. */
  21689. isAnimationEnabled: function () {
  21690. if (env$1.node) {
  21691. return false;
  21692. }
  21693. var animationEnabled = this.getShallow('animation');
  21694. if (animationEnabled) {
  21695. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21696. animationEnabled = false;
  21697. }
  21698. }
  21699. return animationEnabled;
  21700. },
  21701. restoreData: function () {
  21702. this.dataTask.dirty();
  21703. },
  21704. getColorFromPalette: function (name, scope, requestColorNum) {
  21705. var ecModel = this.ecModel;
  21706. // PENDING
  21707. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21708. if (!color) {
  21709. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21710. }
  21711. return color;
  21712. },
  21713. /**
  21714. * Use `data.mapDimension(coordDim, true)` instead.
  21715. * @deprecated
  21716. */
  21717. coordDimToDataDim: function (coordDim) {
  21718. return this.getRawData().mapDimension(coordDim, true);
  21719. },
  21720. /**
  21721. * Get progressive rendering count each step
  21722. * @return {number}
  21723. */
  21724. getProgressive: function () {
  21725. return this.get('progressive');
  21726. },
  21727. /**
  21728. * Get progressive rendering count each step
  21729. * @return {number}
  21730. */
  21731. getProgressiveThreshold: function () {
  21732. return this.get('progressiveThreshold');
  21733. },
  21734. /**
  21735. * Get data indices for show tooltip content. See tooltip.
  21736. * @abstract
  21737. * @param {Array.<string>|string} dim
  21738. * @param {Array.<number>} value
  21739. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21740. * @return {Object} {dataIndices, nestestValue}.
  21741. */
  21742. getAxisTooltipData: null,
  21743. /**
  21744. * See tooltip.
  21745. * @abstract
  21746. * @param {number} dataIndex
  21747. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21748. */
  21749. getTooltipPosition: null,
  21750. /**
  21751. * @see {module:echarts/stream/Scheduler}
  21752. */
  21753. pipeTask: null,
  21754. /**
  21755. * Convinient for override in extended class.
  21756. * @protected
  21757. * @type {Function}
  21758. */
  21759. preventIncremental: null,
  21760. /**
  21761. * @public
  21762. * @readOnly
  21763. * @type {Object}
  21764. */
  21765. pipelineContext: null
  21766. });
  21767. mixin(SeriesModel, dataFormatMixin);
  21768. mixin(SeriesModel, colorPaletteMixin);
  21769. /**
  21770. * MUST be called after `prepareSource` called
  21771. * Here we need to make auto series, especially for auto legend. But we
  21772. * do not modify series.name in option to avoid side effects.
  21773. */
  21774. function autoSeriesName(seriesModel) {
  21775. // User specified name has higher priority, otherwise it may cause
  21776. // series can not be queried unexpectedly.
  21777. var name = seriesModel.name;
  21778. if (!isNameSpecified(seriesModel)) {
  21779. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21780. }
  21781. }
  21782. function getSeriesAutoName(seriesModel) {
  21783. var data = seriesModel.getRawData();
  21784. var dataDims = data.mapDimension('seriesName', true);
  21785. var nameArr = [];
  21786. each$1(dataDims, function (dataDim) {
  21787. var dimInfo = data.getDimensionInfo(dataDim);
  21788. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21789. });
  21790. return nameArr.join(' ');
  21791. }
  21792. function dataTaskCount(context) {
  21793. return context.model.getRawData().count();
  21794. }
  21795. function dataTaskReset(context) {
  21796. var seriesModel = context.model;
  21797. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21798. return dataTaskProgress;
  21799. }
  21800. function dataTaskProgress(param, context) {
  21801. // Avoid repead cloneShallow when data just created in reset.
  21802. if (param.end > context.outputData.count()) {
  21803. context.model.getRawData().cloneShallow(context.outputData);
  21804. }
  21805. }
  21806. // TODO refactor
  21807. function wrapData(data, seriesModel) {
  21808. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21809. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21810. });
  21811. }
  21812. function onDataSelfChange(seriesModel) {
  21813. var task = getCurrentTask(seriesModel);
  21814. if (task) {
  21815. // Consider case: filter, selectRange
  21816. task.setOutputEnd(this.count());
  21817. }
  21818. }
  21819. function getCurrentTask(seriesModel) {
  21820. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21821. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21822. if (pipeline) {
  21823. // When pipline finished, the currrentTask keep the last
  21824. // task (renderTask).
  21825. var task = pipeline.currentTask;
  21826. if (task) {
  21827. var agentStubMap = task.agentStubMap;
  21828. if (agentStubMap) {
  21829. task = agentStubMap.get(seriesModel.uid);
  21830. }
  21831. }
  21832. return task;
  21833. }
  21834. }
  21835. /*
  21836. * Licensed to the Apache Software Foundation (ASF) under one
  21837. * or more contributor license agreements. See the NOTICE file
  21838. * distributed with this work for additional information
  21839. * regarding copyright ownership. The ASF licenses this file
  21840. * to you under the Apache License, Version 2.0 (the
  21841. * "License"); you may not use this file except in compliance
  21842. * with the License. You may obtain a copy of the License at
  21843. *
  21844. * http://www.apache.org/licenses/LICENSE-2.0
  21845. *
  21846. * Unless required by applicable law or agreed to in writing,
  21847. * software distributed under the License is distributed on an
  21848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21849. * KIND, either express or implied. See the License for the
  21850. * specific language governing permissions and limitations
  21851. * under the License.
  21852. */
  21853. var Component$1 = function () {
  21854. /**
  21855. * @type {module:zrender/container/Group}
  21856. * @readOnly
  21857. */
  21858. this.group = new Group();
  21859. /**
  21860. * @type {string}
  21861. * @readOnly
  21862. */
  21863. this.uid = getUID('viewComponent');
  21864. };
  21865. Component$1.prototype = {
  21866. constructor: Component$1,
  21867. init: function (ecModel, api) {},
  21868. render: function (componentModel, ecModel, api, payload) {},
  21869. dispose: function () {},
  21870. /**
  21871. * @param {string} eventType
  21872. * @param {Object} query
  21873. * @param {module:zrender/Element} targetEl
  21874. * @param {Object} packedEvent
  21875. * @return {boolen} Pass only when return `true`.
  21876. */
  21877. filterForExposedEvent: null
  21878. };
  21879. var componentProto = Component$1.prototype;
  21880. componentProto.updateView =
  21881. componentProto.updateLayout =
  21882. componentProto.updateVisual =
  21883. function (seriesModel, ecModel, api, payload) {
  21884. // Do nothing;
  21885. };
  21886. // Enable Component.extend.
  21887. enableClassExtend(Component$1);
  21888. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21889. enableClassManagement(Component$1, {registerWhenExtend: true});
  21890. /*
  21891. * Licensed to the Apache Software Foundation (ASF) under one
  21892. * or more contributor license agreements. See the NOTICE file
  21893. * distributed with this work for additional information
  21894. * regarding copyright ownership. The ASF licenses this file
  21895. * to you under the Apache License, Version 2.0 (the
  21896. * "License"); you may not use this file except in compliance
  21897. * with the License. You may obtain a copy of the License at
  21898. *
  21899. * http://www.apache.org/licenses/LICENSE-2.0
  21900. *
  21901. * Unless required by applicable law or agreed to in writing,
  21902. * software distributed under the License is distributed on an
  21903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21904. * KIND, either express or implied. See the License for the
  21905. * specific language governing permissions and limitations
  21906. * under the License.
  21907. */
  21908. /**
  21909. * @return {string} If large mode changed, return string 'reset';
  21910. */
  21911. var createRenderPlanner = function () {
  21912. var inner = makeInner();
  21913. return function (seriesModel) {
  21914. var fields = inner(seriesModel);
  21915. var pipelineContext = seriesModel.pipelineContext;
  21916. var originalLarge = fields.large;
  21917. var originalProgressive = fields.progressiveRender;
  21918. var large = fields.large = pipelineContext.large;
  21919. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21920. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21921. };
  21922. };
  21923. /*
  21924. * Licensed to the Apache Software Foundation (ASF) under one
  21925. * or more contributor license agreements. See the NOTICE file
  21926. * distributed with this work for additional information
  21927. * regarding copyright ownership. The ASF licenses this file
  21928. * to you under the Apache License, Version 2.0 (the
  21929. * "License"); you may not use this file except in compliance
  21930. * with the License. You may obtain a copy of the License at
  21931. *
  21932. * http://www.apache.org/licenses/LICENSE-2.0
  21933. *
  21934. * Unless required by applicable law or agreed to in writing,
  21935. * software distributed under the License is distributed on an
  21936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21937. * KIND, either express or implied. See the License for the
  21938. * specific language governing permissions and limitations
  21939. * under the License.
  21940. */
  21941. var inner$5 = makeInner();
  21942. var renderPlanner = createRenderPlanner();
  21943. function Chart() {
  21944. /**
  21945. * @type {module:zrender/container/Group}
  21946. * @readOnly
  21947. */
  21948. this.group = new Group();
  21949. /**
  21950. * @type {string}
  21951. * @readOnly
  21952. */
  21953. this.uid = getUID('viewChart');
  21954. this.renderTask = createTask({
  21955. plan: renderTaskPlan,
  21956. reset: renderTaskReset
  21957. });
  21958. this.renderTask.context = {view: this};
  21959. }
  21960. Chart.prototype = {
  21961. type: 'chart',
  21962. /**
  21963. * Init the chart.
  21964. * @param {module:echarts/model/Global} ecModel
  21965. * @param {module:echarts/ExtensionAPI} api
  21966. */
  21967. init: function (ecModel, api) {},
  21968. /**
  21969. * Render the chart.
  21970. * @param {module:echarts/model/Series} seriesModel
  21971. * @param {module:echarts/model/Global} ecModel
  21972. * @param {module:echarts/ExtensionAPI} api
  21973. * @param {Object} payload
  21974. */
  21975. render: function (seriesModel, ecModel, api, payload) {},
  21976. /**
  21977. * Highlight series or specified data item.
  21978. * @param {module:echarts/model/Series} seriesModel
  21979. * @param {module:echarts/model/Global} ecModel
  21980. * @param {module:echarts/ExtensionAPI} api
  21981. * @param {Object} payload
  21982. */
  21983. highlight: function (seriesModel, ecModel, api, payload) {
  21984. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21985. },
  21986. /**
  21987. * Downplay series or specified data item.
  21988. * @param {module:echarts/model/Series} seriesModel
  21989. * @param {module:echarts/model/Global} ecModel
  21990. * @param {module:echarts/ExtensionAPI} api
  21991. * @param {Object} payload
  21992. */
  21993. downplay: function (seriesModel, ecModel, api, payload) {
  21994. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21995. },
  21996. /**
  21997. * Remove self.
  21998. * @param {module:echarts/model/Global} ecModel
  21999. * @param {module:echarts/ExtensionAPI} api
  22000. */
  22001. remove: function (ecModel, api) {
  22002. this.group.removeAll();
  22003. },
  22004. /**
  22005. * Dispose self.
  22006. * @param {module:echarts/model/Global} ecModel
  22007. * @param {module:echarts/ExtensionAPI} api
  22008. */
  22009. dispose: function () {},
  22010. /**
  22011. * Rendering preparation in progressive mode.
  22012. * @param {module:echarts/model/Series} seriesModel
  22013. * @param {module:echarts/model/Global} ecModel
  22014. * @param {module:echarts/ExtensionAPI} api
  22015. * @param {Object} payload
  22016. */
  22017. incrementalPrepareRender: null,
  22018. /**
  22019. * Render in progressive mode.
  22020. * @param {Object} params See taskParams in `stream/task.js`
  22021. * @param {module:echarts/model/Series} seriesModel
  22022. * @param {module:echarts/model/Global} ecModel
  22023. * @param {module:echarts/ExtensionAPI} api
  22024. * @param {Object} payload
  22025. */
  22026. incrementalRender: null,
  22027. /**
  22028. * Update transform directly.
  22029. * @param {module:echarts/model/Series} seriesModel
  22030. * @param {module:echarts/model/Global} ecModel
  22031. * @param {module:echarts/ExtensionAPI} api
  22032. * @param {Object} payload
  22033. * @return {Object} {update: true}
  22034. */
  22035. updateTransform: null,
  22036. /**
  22037. * The view contains the given point.
  22038. * @interface
  22039. * @param {Array.<number>} point
  22040. * @return {boolean}
  22041. */
  22042. // containPoint: function () {}
  22043. /**
  22044. * @param {string} eventType
  22045. * @param {Object} query
  22046. * @param {module:zrender/Element} targetEl
  22047. * @param {Object} packedEvent
  22048. * @return {boolen} Pass only when return `true`.
  22049. */
  22050. filterForExposedEvent: null
  22051. };
  22052. var chartProto = Chart.prototype;
  22053. chartProto.updateView =
  22054. chartProto.updateLayout =
  22055. chartProto.updateVisual =
  22056. function (seriesModel, ecModel, api, payload) {
  22057. this.render(seriesModel, ecModel, api, payload);
  22058. };
  22059. /**
  22060. * Set state of single element
  22061. * @param {module:zrender/Element} el
  22062. * @param {string} state 'normal'|'emphasis'
  22063. * @param {number} highlightDigit
  22064. */
  22065. function elSetState(el, state, highlightDigit) {
  22066. if (el) {
  22067. el.trigger(state, highlightDigit);
  22068. if (el.isGroup
  22069. // Simple optimize.
  22070. && !isHighDownDispatcher(el)
  22071. ) {
  22072. for (var i = 0, len = el.childCount(); i < len; i++) {
  22073. elSetState(el.childAt(i), state, highlightDigit);
  22074. }
  22075. }
  22076. }
  22077. }
  22078. /**
  22079. * @param {module:echarts/data/List} data
  22080. * @param {Object} payload
  22081. * @param {string} state 'normal'|'emphasis'
  22082. */
  22083. function toggleHighlight(data, payload, state) {
  22084. var dataIndex = queryDataIndex(data, payload);
  22085. var highlightDigit = (payload && payload.highlightKey != null)
  22086. ? getHighlightDigit(payload.highlightKey)
  22087. : null;
  22088. if (dataIndex != null) {
  22089. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22090. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22091. });
  22092. }
  22093. else {
  22094. data.eachItemGraphicEl(function (el) {
  22095. elSetState(el, state, highlightDigit);
  22096. });
  22097. }
  22098. }
  22099. // Enable Chart.extend.
  22100. enableClassExtend(Chart, ['dispose']);
  22101. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22102. enableClassManagement(Chart, {registerWhenExtend: true});
  22103. Chart.markUpdateMethod = function (payload, methodName) {
  22104. inner$5(payload).updateMethod = methodName;
  22105. };
  22106. function renderTaskPlan(context) {
  22107. return renderPlanner(context.model);
  22108. }
  22109. function renderTaskReset(context) {
  22110. var seriesModel = context.model;
  22111. var ecModel = context.ecModel;
  22112. var api = context.api;
  22113. var payload = context.payload;
  22114. // ???! remove updateView updateVisual
  22115. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22116. var view = context.view;
  22117. var updateMethod = payload && inner$5(payload).updateMethod;
  22118. var methodName = progressiveRender
  22119. ? 'incrementalPrepareRender'
  22120. : (updateMethod && view[updateMethod])
  22121. ? updateMethod
  22122. // `appendData` is also supported when data amount
  22123. // is less than progressive threshold.
  22124. : 'render';
  22125. if (methodName !== 'render') {
  22126. view[methodName](seriesModel, ecModel, api, payload);
  22127. }
  22128. return progressMethodMap[methodName];
  22129. }
  22130. var progressMethodMap = {
  22131. incrementalPrepareRender: {
  22132. progress: function (params, context) {
  22133. context.view.incrementalRender(
  22134. params, context.model, context.ecModel, context.api, context.payload
  22135. );
  22136. }
  22137. },
  22138. render: {
  22139. // Put view.render in `progress` to support appendData. But in this case
  22140. // view.render should not be called in reset, otherwise it will be called
  22141. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22142. // in any cases.
  22143. forceFirstProgress: true,
  22144. progress: function (params, context) {
  22145. context.view.render(
  22146. context.model, context.ecModel, context.api, context.payload
  22147. );
  22148. }
  22149. }
  22150. };
  22151. /*
  22152. * Licensed to the Apache Software Foundation (ASF) under one
  22153. * or more contributor license agreements. See the NOTICE file
  22154. * distributed with this work for additional information
  22155. * regarding copyright ownership. The ASF licenses this file
  22156. * to you under the Apache License, Version 2.0 (the
  22157. * "License"); you may not use this file except in compliance
  22158. * with the License. You may obtain a copy of the License at
  22159. *
  22160. * http://www.apache.org/licenses/LICENSE-2.0
  22161. *
  22162. * Unless required by applicable law or agreed to in writing,
  22163. * software distributed under the License is distributed on an
  22164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22165. * KIND, either express or implied. See the License for the
  22166. * specific language governing permissions and limitations
  22167. * under the License.
  22168. */
  22169. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22170. var RATE = '\0__throttleRate';
  22171. var THROTTLE_TYPE = '\0__throttleType';
  22172. /**
  22173. * @public
  22174. * @param {(Function)} fn
  22175. * @param {number} [delay=0] Unit: ms.
  22176. * @param {boolean} [debounce=false]
  22177. * true: If call interval less than `delay`, only the last call works.
  22178. * false: If call interval less than `delay, call works on fixed rate.
  22179. * @return {(Function)} throttled fn.
  22180. */
  22181. function throttle(fn, delay, debounce) {
  22182. var currCall;
  22183. var lastCall = 0;
  22184. var lastExec = 0;
  22185. var timer = null;
  22186. var diff;
  22187. var scope;
  22188. var args;
  22189. var debounceNextCall;
  22190. delay = delay || 0;
  22191. function exec() {
  22192. lastExec = (new Date()).getTime();
  22193. timer = null;
  22194. fn.apply(scope, args || []);
  22195. }
  22196. var cb = function () {
  22197. currCall = (new Date()).getTime();
  22198. scope = this;
  22199. args = arguments;
  22200. var thisDelay = debounceNextCall || delay;
  22201. var thisDebounce = debounceNextCall || debounce;
  22202. debounceNextCall = null;
  22203. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22204. clearTimeout(timer);
  22205. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22206. // than a new call of `cb`, that is, preserving the command order. Consider
  22207. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22208. // happens, either the `exec` is called dierectly, or the call is delayed.
  22209. // But the delayed call should never be later than next call of `cb`. Under
  22210. // this assurance, we can simply update view state each time `dispatchAction`
  22211. // triggered by user roaming, but not need to add extra code to avoid the
  22212. // state being "rolled-back".
  22213. if (thisDebounce) {
  22214. timer = setTimeout(exec, thisDelay);
  22215. }
  22216. else {
  22217. if (diff >= 0) {
  22218. exec();
  22219. }
  22220. else {
  22221. timer = setTimeout(exec, -diff);
  22222. }
  22223. }
  22224. lastCall = currCall;
  22225. };
  22226. /**
  22227. * Clear throttle.
  22228. * @public
  22229. */
  22230. cb.clear = function () {
  22231. if (timer) {
  22232. clearTimeout(timer);
  22233. timer = null;
  22234. }
  22235. };
  22236. /**
  22237. * Enable debounce once.
  22238. */
  22239. cb.debounceNextCall = function (debounceDelay) {
  22240. debounceNextCall = debounceDelay;
  22241. };
  22242. return cb;
  22243. }
  22244. /**
  22245. * Create throttle method or update throttle rate.
  22246. *
  22247. * @example
  22248. * ComponentView.prototype.render = function () {
  22249. * ...
  22250. * throttle.createOrUpdate(
  22251. * this,
  22252. * '_dispatchAction',
  22253. * this.model.get('throttle'),
  22254. * 'fixRate'
  22255. * );
  22256. * };
  22257. * ComponentView.prototype.remove = function () {
  22258. * throttle.clear(this, '_dispatchAction');
  22259. * };
  22260. * ComponentView.prototype.dispose = function () {
  22261. * throttle.clear(this, '_dispatchAction');
  22262. * };
  22263. *
  22264. * @public
  22265. * @param {Object} obj
  22266. * @param {string} fnAttr
  22267. * @param {number} [rate]
  22268. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22269. * @return {Function} throttled function.
  22270. */
  22271. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22272. var fn = obj[fnAttr];
  22273. if (!fn) {
  22274. return;
  22275. }
  22276. var originFn = fn[ORIGIN_METHOD] || fn;
  22277. var lastThrottleType = fn[THROTTLE_TYPE];
  22278. var lastRate = fn[RATE];
  22279. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22280. if (rate == null || !throttleType) {
  22281. return (obj[fnAttr] = originFn);
  22282. }
  22283. fn = obj[fnAttr] = throttle(
  22284. originFn, rate, throttleType === 'debounce'
  22285. );
  22286. fn[ORIGIN_METHOD] = originFn;
  22287. fn[THROTTLE_TYPE] = throttleType;
  22288. fn[RATE] = rate;
  22289. }
  22290. return fn;
  22291. }
  22292. /**
  22293. * Clear throttle. Example see throttle.createOrUpdate.
  22294. *
  22295. * @public
  22296. * @param {Object} obj
  22297. * @param {string} fnAttr
  22298. */
  22299. function clear(obj, fnAttr) {
  22300. var fn = obj[fnAttr];
  22301. if (fn && fn[ORIGIN_METHOD]) {
  22302. obj[fnAttr] = fn[ORIGIN_METHOD];
  22303. }
  22304. }
  22305. /*
  22306. * Licensed to the Apache Software Foundation (ASF) under one
  22307. * or more contributor license agreements. See the NOTICE file
  22308. * distributed with this work for additional information
  22309. * regarding copyright ownership. The ASF licenses this file
  22310. * to you under the Apache License, Version 2.0 (the
  22311. * "License"); you may not use this file except in compliance
  22312. * with the License. You may obtain a copy of the License at
  22313. *
  22314. * http://www.apache.org/licenses/LICENSE-2.0
  22315. *
  22316. * Unless required by applicable law or agreed to in writing,
  22317. * software distributed under the License is distributed on an
  22318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22319. * KIND, either express or implied. See the License for the
  22320. * specific language governing permissions and limitations
  22321. * under the License.
  22322. */
  22323. var seriesColor = {
  22324. createOnAllSeries: true,
  22325. performRawSeries: true,
  22326. reset: function (seriesModel, ecModel) {
  22327. var data = seriesModel.getData();
  22328. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22329. // Set in itemStyle
  22330. var color = seriesModel.get(colorAccessPath);
  22331. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22332. ? color : null;
  22333. // Default color
  22334. if (!color || colorCallback) {
  22335. color = seriesModel.getColorFromPalette(
  22336. // TODO series count changed.
  22337. seriesModel.name, null, ecModel.getSeriesCount()
  22338. );
  22339. }
  22340. data.setVisual('color', color);
  22341. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22342. var borderColor = seriesModel.get(borderColorAccessPath);
  22343. data.setVisual('borderColor', borderColor);
  22344. // Only visible series has each data be visual encoded
  22345. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22346. if (colorCallback) {
  22347. data.each(function (idx) {
  22348. data.setItemVisual(
  22349. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22350. );
  22351. });
  22352. }
  22353. // itemStyle in each data item
  22354. var dataEach = function (data, idx) {
  22355. var itemModel = data.getItemModel(idx);
  22356. var color = itemModel.get(colorAccessPath, true);
  22357. var borderColor = itemModel.get(borderColorAccessPath, true);
  22358. if (color != null) {
  22359. data.setItemVisual(idx, 'color', color);
  22360. }
  22361. if (borderColor != null) {
  22362. data.setItemVisual(idx, 'borderColor', borderColor);
  22363. }
  22364. };
  22365. return { dataEach: data.hasItemOption ? dataEach : null };
  22366. }
  22367. }
  22368. };
  22369. /*
  22370. * Licensed to the Apache Software Foundation (ASF) under one
  22371. * or more contributor license agreements. See the NOTICE file
  22372. * distributed with this work for additional information
  22373. * regarding copyright ownership. The ASF licenses this file
  22374. * to you under the Apache License, Version 2.0 (the
  22375. * "License"); you may not use this file except in compliance
  22376. * with the License. You may obtain a copy of the License at
  22377. *
  22378. * http://www.apache.org/licenses/LICENSE-2.0
  22379. *
  22380. * Unless required by applicable law or agreed to in writing,
  22381. * software distributed under the License is distributed on an
  22382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22383. * KIND, either express or implied. See the License for the
  22384. * specific language governing permissions and limitations
  22385. * under the License.
  22386. */
  22387. /**
  22388. * Language: (Simplified) Chinese.
  22389. */
  22390. var lang = {
  22391. legend: {
  22392. selector: {
  22393. all: '全选',
  22394. inverse: '反选'
  22395. }
  22396. },
  22397. toolbox: {
  22398. brush: {
  22399. title: {
  22400. rect: '矩形选择',
  22401. polygon: '圈选',
  22402. lineX: '横向选择',
  22403. lineY: '纵向选择',
  22404. keep: '保持选择',
  22405. clear: '清除选择'
  22406. }
  22407. },
  22408. dataView: {
  22409. title: '数据视图',
  22410. lang: ['数据视图', '关闭', '刷新']
  22411. },
  22412. dataZoom: {
  22413. title: {
  22414. zoom: '区域缩放',
  22415. back: '区域缩放还原'
  22416. }
  22417. },
  22418. magicType: {
  22419. title: {
  22420. line: '切换为折线图',
  22421. bar: '切换为柱状图',
  22422. stack: '切换为堆叠',
  22423. tiled: '切换为平铺'
  22424. }
  22425. },
  22426. restore: {
  22427. title: '还原'
  22428. },
  22429. saveAsImage: {
  22430. title: '保存为图片',
  22431. lang: ['右键另存为图片']
  22432. }
  22433. },
  22434. series: {
  22435. typeNames: {
  22436. pie: '饼图',
  22437. bar: '柱状图',
  22438. line: '折线图',
  22439. scatter: '散点图',
  22440. effectScatter: '涟漪散点图',
  22441. radar: '雷达图',
  22442. tree: '树图',
  22443. treemap: '矩形树图',
  22444. boxplot: '箱型图',
  22445. candlestick: 'K线图',
  22446. k: 'K线图',
  22447. heatmap: '热力图',
  22448. map: '地图',
  22449. parallel: '平行坐标图',
  22450. lines: '线图',
  22451. graph: '关系图',
  22452. sankey: '桑基图',
  22453. funnel: '漏斗图',
  22454. gauge: '仪表盘图',
  22455. pictorialBar: '象形柱图',
  22456. themeRiver: '主题河流图',
  22457. sunburst: '旭日图'
  22458. }
  22459. },
  22460. aria: {
  22461. general: {
  22462. withTitle: '这是一个关于“{title}”的图表。',
  22463. withoutTitle: '这是一个图表,'
  22464. },
  22465. series: {
  22466. single: {
  22467. prefix: '',
  22468. withName: '图表类型是{seriesType},表示{seriesName}。',
  22469. withoutName: '图表类型是{seriesType}。'
  22470. },
  22471. multiple: {
  22472. prefix: '它由{seriesCount}个图表系列组成。',
  22473. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  22474. withoutName: '第{seriesId}个系列是一个{seriesType},',
  22475. separator: {
  22476. middle: ';',
  22477. end: '。'
  22478. }
  22479. }
  22480. },
  22481. data: {
  22482. allData: '其数据是——',
  22483. partialData: '其中,前{displayCnt}项是——',
  22484. withName: '{name}的数据是{value}',
  22485. withoutName: '{value}',
  22486. separator: {
  22487. middle: ',',
  22488. end: ''
  22489. }
  22490. }
  22491. }
  22492. };
  22493. /*
  22494. * Licensed to the Apache Software Foundation (ASF) under one
  22495. * or more contributor license agreements. See the NOTICE file
  22496. * distributed with this work for additional information
  22497. * regarding copyright ownership. The ASF licenses this file
  22498. * to you under the Apache License, Version 2.0 (the
  22499. * "License"); you may not use this file except in compliance
  22500. * with the License. You may obtain a copy of the License at
  22501. *
  22502. * http://www.apache.org/licenses/LICENSE-2.0
  22503. *
  22504. * Unless required by applicable law or agreed to in writing,
  22505. * software distributed under the License is distributed on an
  22506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22507. * KIND, either express or implied. See the License for the
  22508. * specific language governing permissions and limitations
  22509. * under the License.
  22510. */
  22511. var aria = function (dom, ecModel) {
  22512. var ariaModel = ecModel.getModel('aria');
  22513. if (!ariaModel.get('show')) {
  22514. return;
  22515. }
  22516. else if (ariaModel.get('description')) {
  22517. dom.setAttribute('aria-label', ariaModel.get('description'));
  22518. return;
  22519. }
  22520. var seriesCnt = 0;
  22521. ecModel.eachSeries(function (seriesModel, idx) {
  22522. ++seriesCnt;
  22523. }, this);
  22524. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22525. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22526. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22527. var ariaLabel;
  22528. if (seriesCnt < 1) {
  22529. // No series, no aria label
  22530. return;
  22531. }
  22532. else {
  22533. var title = getTitle();
  22534. if (title) {
  22535. ariaLabel = replace(getConfig('general.withTitle'), {
  22536. title: title
  22537. });
  22538. }
  22539. else {
  22540. ariaLabel = getConfig('general.withoutTitle');
  22541. }
  22542. var seriesLabels = [];
  22543. var prefix = seriesCnt > 1
  22544. ? 'series.multiple.prefix'
  22545. : 'series.single.prefix';
  22546. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22547. ecModel.eachSeries(function (seriesModel, idx) {
  22548. if (idx < displaySeriesCnt) {
  22549. var seriesLabel;
  22550. var seriesName = seriesModel.get('name');
  22551. var seriesTpl = 'series.'
  22552. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22553. seriesLabel = getConfig(seriesName
  22554. ? seriesTpl + 'withName'
  22555. : seriesTpl + 'withoutName');
  22556. seriesLabel = replace(seriesLabel, {
  22557. seriesId: seriesModel.seriesIndex,
  22558. seriesName: seriesModel.get('name'),
  22559. seriesType: getSeriesTypeName(seriesModel.subType)
  22560. });
  22561. var data = seriesModel.getData();
  22562. window.data = data;
  22563. if (data.count() > maxDataCnt) {
  22564. // Show part of data
  22565. seriesLabel += replace(getConfig('data.partialData'), {
  22566. displayCnt: maxDataCnt
  22567. });
  22568. }
  22569. else {
  22570. seriesLabel += getConfig('data.allData');
  22571. }
  22572. var dataLabels = [];
  22573. for (var i = 0; i < data.count(); i++) {
  22574. if (i < maxDataCnt) {
  22575. var name = data.getName(i);
  22576. var value = retrieveRawValue(data, i);
  22577. dataLabels.push(
  22578. replace(
  22579. name
  22580. ? getConfig('data.withName')
  22581. : getConfig('data.withoutName'),
  22582. {
  22583. name: name,
  22584. value: value
  22585. }
  22586. )
  22587. );
  22588. }
  22589. }
  22590. seriesLabel += dataLabels
  22591. .join(getConfig('data.separator.middle'))
  22592. + getConfig('data.separator.end');
  22593. seriesLabels.push(seriesLabel);
  22594. }
  22595. });
  22596. ariaLabel += seriesLabels
  22597. .join(getConfig('series.multiple.separator.middle'))
  22598. + getConfig('series.multiple.separator.end');
  22599. dom.setAttribute('aria-label', ariaLabel);
  22600. }
  22601. function replace(str, keyValues) {
  22602. if (typeof str !== 'string') {
  22603. return str;
  22604. }
  22605. var result = str;
  22606. each$1(keyValues, function (value, key) {
  22607. result = result.replace(
  22608. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22609. value
  22610. );
  22611. });
  22612. return result;
  22613. }
  22614. function getConfig(path) {
  22615. var userConfig = ariaModel.get(path);
  22616. if (userConfig == null) {
  22617. var pathArr = path.split('.');
  22618. var result = lang.aria;
  22619. for (var i = 0; i < pathArr.length; ++i) {
  22620. result = result[pathArr[i]];
  22621. }
  22622. return result;
  22623. }
  22624. else {
  22625. return userConfig;
  22626. }
  22627. }
  22628. function getTitle() {
  22629. var title = ecModel.getModel('title').option;
  22630. if (title && title.length) {
  22631. title = title[0];
  22632. }
  22633. return title && title.text;
  22634. }
  22635. function getSeriesTypeName(type) {
  22636. return lang.series.typeNames[type] || '自定义图';
  22637. }
  22638. };
  22639. /*
  22640. * Licensed to the Apache Software Foundation (ASF) under one
  22641. * or more contributor license agreements. See the NOTICE file
  22642. * distributed with this work for additional information
  22643. * regarding copyright ownership. The ASF licenses this file
  22644. * to you under the Apache License, Version 2.0 (the
  22645. * "License"); you may not use this file except in compliance
  22646. * with the License. You may obtain a copy of the License at
  22647. *
  22648. * http://www.apache.org/licenses/LICENSE-2.0
  22649. *
  22650. * Unless required by applicable law or agreed to in writing,
  22651. * software distributed under the License is distributed on an
  22652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22653. * KIND, either express or implied. See the License for the
  22654. * specific language governing permissions and limitations
  22655. * under the License.
  22656. */
  22657. var PI$1 = Math.PI;
  22658. /**
  22659. * @param {module:echarts/ExtensionAPI} api
  22660. * @param {Object} [opts]
  22661. * @param {string} [opts.text]
  22662. * @param {string} [opts.color]
  22663. * @param {string} [opts.textColor]
  22664. * @return {module:zrender/Element}
  22665. */
  22666. var loadingDefault = function (api, opts) {
  22667. opts = opts || {};
  22668. defaults(opts, {
  22669. text: 'loading',
  22670. color: '#c23531',
  22671. textColor: '#000',
  22672. maskColor: 'rgba(255, 255, 255, 0.8)',
  22673. zlevel: 0
  22674. });
  22675. var mask = new Rect({
  22676. style: {
  22677. fill: opts.maskColor
  22678. },
  22679. zlevel: opts.zlevel,
  22680. z: 10000
  22681. });
  22682. var arc = new Arc({
  22683. shape: {
  22684. startAngle: -PI$1 / 2,
  22685. endAngle: -PI$1 / 2 + 0.1,
  22686. r: 10
  22687. },
  22688. style: {
  22689. stroke: opts.color,
  22690. lineCap: 'round',
  22691. lineWidth: 5
  22692. },
  22693. zlevel: opts.zlevel,
  22694. z: 10001
  22695. });
  22696. var labelRect = new Rect({
  22697. style: {
  22698. fill: 'none',
  22699. text: opts.text,
  22700. textPosition: 'right',
  22701. textDistance: 10,
  22702. textFill: opts.textColor
  22703. },
  22704. zlevel: opts.zlevel,
  22705. z: 10001
  22706. });
  22707. arc.animateShape(true)
  22708. .when(1000, {
  22709. endAngle: PI$1 * 3 / 2
  22710. })
  22711. .start('circularInOut');
  22712. arc.animateShape(true)
  22713. .when(1000, {
  22714. startAngle: PI$1 * 3 / 2
  22715. })
  22716. .delay(300)
  22717. .start('circularInOut');
  22718. var group = new Group();
  22719. group.add(arc);
  22720. group.add(labelRect);
  22721. group.add(mask);
  22722. // Inject resize
  22723. group.resize = function () {
  22724. var cx = api.getWidth() / 2;
  22725. var cy = api.getHeight() / 2;
  22726. arc.setShape({
  22727. cx: cx,
  22728. cy: cy
  22729. });
  22730. var r = arc.shape.r;
  22731. labelRect.setShape({
  22732. x: cx - r,
  22733. y: cy - r,
  22734. width: r * 2,
  22735. height: r * 2
  22736. });
  22737. mask.setShape({
  22738. x: 0,
  22739. y: 0,
  22740. width: api.getWidth(),
  22741. height: api.getHeight()
  22742. });
  22743. };
  22744. group.resize();
  22745. return group;
  22746. };
  22747. /*
  22748. * Licensed to the Apache Software Foundation (ASF) under one
  22749. * or more contributor license agreements. See the NOTICE file
  22750. * distributed with this work for additional information
  22751. * regarding copyright ownership. The ASF licenses this file
  22752. * to you under the Apache License, Version 2.0 (the
  22753. * "License"); you may not use this file except in compliance
  22754. * with the License. You may obtain a copy of the License at
  22755. *
  22756. * http://www.apache.org/licenses/LICENSE-2.0
  22757. *
  22758. * Unless required by applicable law or agreed to in writing,
  22759. * software distributed under the License is distributed on an
  22760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22761. * KIND, either express or implied. See the License for the
  22762. * specific language governing permissions and limitations
  22763. * under the License.
  22764. */
  22765. /**
  22766. * @module echarts/stream/Scheduler
  22767. */
  22768. /**
  22769. * @constructor
  22770. */
  22771. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22772. this.ecInstance = ecInstance;
  22773. this.api = api;
  22774. this.unfinished;
  22775. // Fix current processors in case that in some rear cases that
  22776. // processors might be registered after echarts instance created.
  22777. // Register processors incrementally for a echarts instance is
  22778. // not supported by this stream architecture.
  22779. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22780. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22781. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22782. /**
  22783. * @private
  22784. * @type {
  22785. * [handlerUID: string]: {
  22786. * seriesTaskMap?: {
  22787. * [seriesUID: string]: Task
  22788. * },
  22789. * overallTask?: Task
  22790. * }
  22791. * }
  22792. */
  22793. this._stageTaskMap = createHashMap();
  22794. }
  22795. var proto = Scheduler.prototype;
  22796. /**
  22797. * @param {module:echarts/model/Global} ecModel
  22798. * @param {Object} payload
  22799. */
  22800. proto.restoreData = function (ecModel, payload) {
  22801. // TODO: Only restroe needed series and components, but not all components.
  22802. // Currently `restoreData` of all of the series and component will be called.
  22803. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22804. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22805. // and some components like coordinate system, axes, dataZoom, visualMap only
  22806. // need their target series refresh.
  22807. // (1) If we are implementing this feature some day, we should consider these cases:
  22808. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22809. // on the settings of `dataZoom`), it should be re-performed if the component
  22810. // is modified by `setOption`.
  22811. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22812. // it should be re-performed when the result array of `getTargetSeries` changed.
  22813. // We use `dependencies` to cover these issues.
  22814. // (3) How to update target series when coordinate system related components modified.
  22815. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22816. // and this case all of the tasks will be set as dirty.
  22817. ecModel.restoreData(payload);
  22818. // Theoretically an overall task not only depends on each of its target series, but also
  22819. // depends on all of the series.
  22820. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22821. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22822. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22823. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22824. // probably cause state chaos (consider `dataZoomProcessor`).
  22825. this._stageTaskMap.each(function (taskRecord) {
  22826. var overallTask = taskRecord.overallTask;
  22827. overallTask && overallTask.dirty();
  22828. });
  22829. };
  22830. // If seriesModel provided, incremental threshold is check by series data.
  22831. proto.getPerformArgs = function (task, isBlock) {
  22832. // For overall task
  22833. if (!task.__pipeline) {
  22834. return;
  22835. }
  22836. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22837. var pCtx = pipeline.context;
  22838. var incremental = !isBlock
  22839. && pipeline.progressiveEnabled
  22840. && (!pCtx || pCtx.progressiveRender)
  22841. && task.__idxInPipeline > pipeline.blockIndex;
  22842. var step = incremental ? pipeline.step : null;
  22843. var modDataCount = pCtx && pCtx.modDataCount;
  22844. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22845. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22846. };
  22847. proto.getPipeline = function (pipelineId) {
  22848. return this._pipelineMap.get(pipelineId);
  22849. };
  22850. /**
  22851. * Current, progressive rendering starts from visual and layout.
  22852. * Always detect render mode in the same stage, avoiding that incorrect
  22853. * detection caused by data filtering.
  22854. * Caution:
  22855. * `updateStreamModes` use `seriesModel.getData()`.
  22856. */
  22857. proto.updateStreamModes = function (seriesModel, view) {
  22858. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22859. var data = seriesModel.getData();
  22860. var dataLen = data.count();
  22861. // `progressiveRender` means that can render progressively in each
  22862. // animation frame. Note that some types of series do not provide
  22863. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22864. // use the term `incremental` but not `progressive` to describe the
  22865. // case that `chart.appendData`.
  22866. var progressiveRender = pipeline.progressiveEnabled
  22867. && view.incrementalPrepareRender
  22868. && dataLen >= pipeline.threshold;
  22869. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22870. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22871. // see `test/candlestick-large3.html`
  22872. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22873. seriesModel.pipelineContext = pipeline.context = {
  22874. progressiveRender: progressiveRender,
  22875. modDataCount: modDataCount,
  22876. large: large
  22877. };
  22878. };
  22879. proto.restorePipelines = function (ecModel) {
  22880. var scheduler = this;
  22881. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22882. ecModel.eachSeries(function (seriesModel) {
  22883. var progressive = seriesModel.getProgressive();
  22884. var pipelineId = seriesModel.uid;
  22885. pipelineMap.set(pipelineId, {
  22886. id: pipelineId,
  22887. head: null,
  22888. tail: null,
  22889. threshold: seriesModel.getProgressiveThreshold(),
  22890. progressiveEnabled: progressive
  22891. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22892. blockIndex: -1,
  22893. step: Math.round(progressive || 700),
  22894. count: 0
  22895. });
  22896. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22897. });
  22898. };
  22899. proto.prepareStageTasks = function () {
  22900. var stageTaskMap = this._stageTaskMap;
  22901. var ecModel = this.ecInstance.getModel();
  22902. var api = this.api;
  22903. each$1(this._allHandlers, function (handler) {
  22904. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22905. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22906. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22907. }, this);
  22908. };
  22909. proto.prepareView = function (view, model, ecModel, api) {
  22910. var renderTask = view.renderTask;
  22911. var context = renderTask.context;
  22912. context.model = model;
  22913. context.ecModel = ecModel;
  22914. context.api = api;
  22915. renderTask.__block = !view.incrementalPrepareRender;
  22916. pipe(this, model, renderTask);
  22917. };
  22918. proto.performDataProcessorTasks = function (ecModel, payload) {
  22919. // If we do not use `block` here, it should be considered when to update modes.
  22920. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22921. };
  22922. // opt
  22923. // opt.visualType: 'visual' or 'layout'
  22924. // opt.setDirty
  22925. proto.performVisualTasks = function (ecModel, payload, opt) {
  22926. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22927. };
  22928. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22929. opt = opt || {};
  22930. var unfinished;
  22931. each$1(stageHandlers, function (stageHandler, idx) {
  22932. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22933. return;
  22934. }
  22935. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22936. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22937. var overallTask = stageHandlerRecord.overallTask;
  22938. if (overallTask) {
  22939. var overallNeedDirty;
  22940. var agentStubMap = overallTask.agentStubMap;
  22941. agentStubMap.each(function (stub) {
  22942. if (needSetDirty(opt, stub)) {
  22943. stub.dirty();
  22944. overallNeedDirty = true;
  22945. }
  22946. });
  22947. overallNeedDirty && overallTask.dirty();
  22948. updatePayload(overallTask, payload);
  22949. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22950. // Execute stubs firstly, which may set the overall task dirty,
  22951. // then execute the overall task. And stub will call seriesModel.setData,
  22952. // which ensures that in the overallTask seriesModel.getData() will not
  22953. // return incorrect data.
  22954. agentStubMap.each(function (stub) {
  22955. stub.perform(performArgs);
  22956. });
  22957. unfinished |= overallTask.perform(performArgs);
  22958. }
  22959. else if (seriesTaskMap) {
  22960. seriesTaskMap.each(function (task, pipelineId) {
  22961. if (needSetDirty(opt, task)) {
  22962. task.dirty();
  22963. }
  22964. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22965. performArgs.skip = !stageHandler.performRawSeries
  22966. && ecModel.isSeriesFiltered(task.context.model);
  22967. updatePayload(task, payload);
  22968. unfinished |= task.perform(performArgs);
  22969. });
  22970. }
  22971. });
  22972. function needSetDirty(opt, task) {
  22973. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22974. }
  22975. scheduler.unfinished |= unfinished;
  22976. }
  22977. proto.performSeriesTasks = function (ecModel) {
  22978. var unfinished;
  22979. ecModel.eachSeries(function (seriesModel) {
  22980. // Progress to the end for dataInit and dataRestore.
  22981. unfinished |= seriesModel.dataTask.perform();
  22982. });
  22983. this.unfinished |= unfinished;
  22984. };
  22985. proto.plan = function () {
  22986. // Travel pipelines, check block.
  22987. this._pipelineMap.each(function (pipeline) {
  22988. var task = pipeline.tail;
  22989. do {
  22990. if (task.__block) {
  22991. pipeline.blockIndex = task.__idxInPipeline;
  22992. break;
  22993. }
  22994. task = task.getUpstream();
  22995. }
  22996. while (task);
  22997. });
  22998. };
  22999. var updatePayload = proto.updatePayload = function (task, payload) {
  23000. payload !== 'remain' && (task.context.payload = payload);
  23001. };
  23002. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23003. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  23004. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  23005. var seriesType = stageHandler.seriesType;
  23006. var getTargetSeries = stageHandler.getTargetSeries;
  23007. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23008. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23009. // it works but it may cause other irrelevant charts blocked.
  23010. if (stageHandler.createOnAllSeries) {
  23011. ecModel.eachRawSeries(create);
  23012. }
  23013. else if (seriesType) {
  23014. ecModel.eachRawSeriesByType(seriesType, create);
  23015. }
  23016. else if (getTargetSeries) {
  23017. getTargetSeries(ecModel, api).each(create);
  23018. }
  23019. function create(seriesModel) {
  23020. var pipelineId = seriesModel.uid;
  23021. // Init tasks for each seriesModel only once.
  23022. // Reuse original task instance.
  23023. var task = seriesTaskMap.get(pipelineId)
  23024. || seriesTaskMap.set(pipelineId, createTask({
  23025. plan: seriesTaskPlan,
  23026. reset: seriesTaskReset,
  23027. count: seriesTaskCount
  23028. }));
  23029. task.context = {
  23030. model: seriesModel,
  23031. ecModel: ecModel,
  23032. api: api,
  23033. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23034. plan: stageHandler.plan,
  23035. reset: stageHandler.reset,
  23036. scheduler: scheduler
  23037. };
  23038. pipe(scheduler, seriesModel, task);
  23039. }
  23040. // Clear unused series tasks.
  23041. var pipelineMap = scheduler._pipelineMap;
  23042. seriesTaskMap.each(function (task, pipelineId) {
  23043. if (!pipelineMap.get(pipelineId)) {
  23044. task.dispose();
  23045. seriesTaskMap.removeKey(pipelineId);
  23046. }
  23047. });
  23048. }
  23049. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23050. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23051. // For overall task, the function only be called on reset stage.
  23052. || createTask({reset: overallTaskReset});
  23053. overallTask.context = {
  23054. ecModel: ecModel,
  23055. api: api,
  23056. overallReset: stageHandler.overallReset,
  23057. scheduler: scheduler
  23058. };
  23059. // Reuse orignal stubs.
  23060. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  23061. var seriesType = stageHandler.seriesType;
  23062. var getTargetSeries = stageHandler.getTargetSeries;
  23063. var overallProgress = true;
  23064. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  23065. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23066. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23067. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23068. // we set the pipeline block.
  23069. if (seriesType) {
  23070. ecModel.eachRawSeriesByType(seriesType, createStub);
  23071. }
  23072. else if (getTargetSeries) {
  23073. getTargetSeries(ecModel, api).each(createStub);
  23074. }
  23075. // Otherwise, (usually it is legancy case), the overall task will only be
  23076. // executed when upstream dirty. Otherwise the progressive rendering of all
  23077. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23078. // dirty info from upsteam.
  23079. else {
  23080. overallProgress = false;
  23081. each$1(ecModel.getSeries(), createStub);
  23082. }
  23083. function createStub(seriesModel) {
  23084. var pipelineId = seriesModel.uid;
  23085. var stub = agentStubMap.get(pipelineId);
  23086. if (!stub) {
  23087. stub = agentStubMap.set(pipelineId, createTask(
  23088. {reset: stubReset, onDirty: stubOnDirty}
  23089. ));
  23090. // When the result of `getTargetSeries` changed, the overallTask
  23091. // should be set as dirty and re-performed.
  23092. overallTask.dirty();
  23093. }
  23094. stub.context = {
  23095. model: seriesModel,
  23096. overallProgress: overallProgress,
  23097. modifyOutputEnd: modifyOutputEnd
  23098. };
  23099. stub.agent = overallTask;
  23100. stub.__block = overallProgress;
  23101. pipe(scheduler, seriesModel, stub);
  23102. }
  23103. // Clear unused stubs.
  23104. var pipelineMap = scheduler._pipelineMap;
  23105. agentStubMap.each(function (stub, pipelineId) {
  23106. if (!pipelineMap.get(pipelineId)) {
  23107. stub.dispose();
  23108. // When the result of `getTargetSeries` changed, the overallTask
  23109. // should be set as dirty and re-performed.
  23110. overallTask.dirty();
  23111. agentStubMap.removeKey(pipelineId);
  23112. }
  23113. });
  23114. }
  23115. function overallTaskReset(context) {
  23116. context.overallReset(
  23117. context.ecModel, context.api, context.payload
  23118. );
  23119. }
  23120. function stubReset(context, upstreamContext) {
  23121. return context.overallProgress && stubProgress;
  23122. }
  23123. function stubProgress() {
  23124. this.agent.dirty();
  23125. this.getDownstream().dirty();
  23126. }
  23127. function stubOnDirty() {
  23128. this.agent && this.agent.dirty();
  23129. }
  23130. function seriesTaskPlan(context) {
  23131. return context.plan && context.plan(
  23132. context.model, context.ecModel, context.api, context.payload
  23133. );
  23134. }
  23135. function seriesTaskReset(context) {
  23136. if (context.useClearVisual) {
  23137. context.data.clearAllVisual();
  23138. }
  23139. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23140. context.model, context.ecModel, context.api, context.payload
  23141. ));
  23142. return resetDefines.length > 1
  23143. ? map(resetDefines, function (v, idx) {
  23144. return makeSeriesTaskProgress(idx);
  23145. })
  23146. : singleSeriesTaskProgress;
  23147. }
  23148. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23149. function makeSeriesTaskProgress(resetDefineIdx) {
  23150. return function (params, context) {
  23151. var data = context.data;
  23152. var resetDefine = context.resetDefines[resetDefineIdx];
  23153. if (resetDefine && resetDefine.dataEach) {
  23154. for (var i = params.start; i < params.end; i++) {
  23155. resetDefine.dataEach(data, i);
  23156. }
  23157. }
  23158. else if (resetDefine && resetDefine.progress) {
  23159. resetDefine.progress(params, data);
  23160. }
  23161. };
  23162. }
  23163. function seriesTaskCount(context) {
  23164. return context.data.count();
  23165. }
  23166. function pipe(scheduler, seriesModel, task) {
  23167. var pipelineId = seriesModel.uid;
  23168. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23169. !pipeline.head && (pipeline.head = task);
  23170. pipeline.tail && pipeline.tail.pipe(task);
  23171. pipeline.tail = task;
  23172. task.__idxInPipeline = pipeline.count++;
  23173. task.__pipeline = pipeline;
  23174. }
  23175. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23176. if (isFunction$1(stageHandler)) {
  23177. stageHandler = {
  23178. overallReset: stageHandler,
  23179. seriesType: detectSeriseType(stageHandler)
  23180. };
  23181. }
  23182. stageHandler.uid = getUID('stageHandler');
  23183. visualType && (stageHandler.visualType = visualType);
  23184. return stageHandler;
  23185. };
  23186. /**
  23187. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23188. * To ensure that they can work normally, they should work in block mode, that is,
  23189. * they should not be started util the previous tasks finished. So they cause the
  23190. * progressive rendering disabled. We try to detect the series type, to narrow down
  23191. * the block range to only the series type they concern, but not all series.
  23192. */
  23193. function detectSeriseType(legacyFunc) {
  23194. seriesType = null;
  23195. try {
  23196. // Assume there is no async when calling `eachSeriesByType`.
  23197. legacyFunc(ecModelMock, apiMock);
  23198. }
  23199. catch (e) {
  23200. }
  23201. return seriesType;
  23202. }
  23203. var ecModelMock = {};
  23204. var apiMock = {};
  23205. var seriesType;
  23206. mockMethods(ecModelMock, GlobalModel);
  23207. mockMethods(apiMock, ExtensionAPI);
  23208. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23209. seriesType = type;
  23210. };
  23211. ecModelMock.eachComponent = function (cond) {
  23212. if (cond.mainType === 'series' && cond.subType) {
  23213. seriesType = cond.subType;
  23214. }
  23215. };
  23216. function mockMethods(target, Clz) {
  23217. /* eslint-disable */
  23218. for (var name in Clz.prototype) {
  23219. // Do not use hasOwnProperty
  23220. target[name] = noop;
  23221. }
  23222. /* eslint-enable */
  23223. }
  23224. /*
  23225. * Licensed to the Apache Software Foundation (ASF) under one
  23226. * or more contributor license agreements. See the NOTICE file
  23227. * distributed with this work for additional information
  23228. * regarding copyright ownership. The ASF licenses this file
  23229. * to you under the Apache License, Version 2.0 (the
  23230. * "License"); you may not use this file except in compliance
  23231. * with the License. You may obtain a copy of the License at
  23232. *
  23233. * http://www.apache.org/licenses/LICENSE-2.0
  23234. *
  23235. * Unless required by applicable law or agreed to in writing,
  23236. * software distributed under the License is distributed on an
  23237. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23238. * KIND, either express or implied. See the License for the
  23239. * specific language governing permissions and limitations
  23240. * under the License.
  23241. */
  23242. var colorAll = [
  23243. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23244. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23245. ];
  23246. var lightTheme = {
  23247. color: colorAll,
  23248. colorLayer: [
  23249. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23250. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23251. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23252. colorAll
  23253. ]
  23254. };
  23255. /*
  23256. * Licensed to the Apache Software Foundation (ASF) under one
  23257. * or more contributor license agreements. See the NOTICE file
  23258. * distributed with this work for additional information
  23259. * regarding copyright ownership. The ASF licenses this file
  23260. * to you under the Apache License, Version 2.0 (the
  23261. * "License"); you may not use this file except in compliance
  23262. * with the License. You may obtain a copy of the License at
  23263. *
  23264. * http://www.apache.org/licenses/LICENSE-2.0
  23265. *
  23266. * Unless required by applicable law or agreed to in writing,
  23267. * software distributed under the License is distributed on an
  23268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23269. * KIND, either express or implied. See the License for the
  23270. * specific language governing permissions and limitations
  23271. * under the License.
  23272. */
  23273. var contrastColor = '#eee';
  23274. var axisCommon = function () {
  23275. return {
  23276. axisLine: {
  23277. lineStyle: {
  23278. color: contrastColor
  23279. }
  23280. },
  23281. axisTick: {
  23282. lineStyle: {
  23283. color: contrastColor
  23284. }
  23285. },
  23286. axisLabel: {
  23287. textStyle: {
  23288. color: contrastColor
  23289. }
  23290. },
  23291. splitLine: {
  23292. lineStyle: {
  23293. type: 'dashed',
  23294. color: '#aaa'
  23295. }
  23296. },
  23297. splitArea: {
  23298. areaStyle: {
  23299. color: contrastColor
  23300. }
  23301. }
  23302. };
  23303. };
  23304. var colorPalette = [
  23305. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23306. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23307. ];
  23308. var theme = {
  23309. color: colorPalette,
  23310. backgroundColor: '#333',
  23311. tooltip: {
  23312. axisPointer: {
  23313. lineStyle: {
  23314. color: contrastColor
  23315. },
  23316. crossStyle: {
  23317. color: contrastColor
  23318. },
  23319. label: {
  23320. color: '#000'
  23321. }
  23322. }
  23323. },
  23324. legend: {
  23325. textStyle: {
  23326. color: contrastColor
  23327. }
  23328. },
  23329. textStyle: {
  23330. color: contrastColor
  23331. },
  23332. title: {
  23333. textStyle: {
  23334. color: contrastColor
  23335. }
  23336. },
  23337. toolbox: {
  23338. iconStyle: {
  23339. normal: {
  23340. borderColor: contrastColor
  23341. }
  23342. }
  23343. },
  23344. dataZoom: {
  23345. textStyle: {
  23346. color: contrastColor
  23347. }
  23348. },
  23349. visualMap: {
  23350. textStyle: {
  23351. color: contrastColor
  23352. }
  23353. },
  23354. timeline: {
  23355. lineStyle: {
  23356. color: contrastColor
  23357. },
  23358. itemStyle: {
  23359. normal: {
  23360. color: colorPalette[1]
  23361. }
  23362. },
  23363. label: {
  23364. normal: {
  23365. textStyle: {
  23366. color: contrastColor
  23367. }
  23368. }
  23369. },
  23370. controlStyle: {
  23371. normal: {
  23372. color: contrastColor,
  23373. borderColor: contrastColor
  23374. }
  23375. }
  23376. },
  23377. timeAxis: axisCommon(),
  23378. logAxis: axisCommon(),
  23379. valueAxis: axisCommon(),
  23380. categoryAxis: axisCommon(),
  23381. line: {
  23382. symbol: 'circle'
  23383. },
  23384. graph: {
  23385. color: colorPalette
  23386. },
  23387. gauge: {
  23388. title: {
  23389. textStyle: {
  23390. color: contrastColor
  23391. }
  23392. }
  23393. },
  23394. candlestick: {
  23395. itemStyle: {
  23396. normal: {
  23397. color: '#FD1050',
  23398. color0: '#0CF49B',
  23399. borderColor: '#FD1050',
  23400. borderColor0: '#0CF49B'
  23401. }
  23402. }
  23403. }
  23404. };
  23405. theme.categoryAxis.splitLine.show = false;
  23406. /*
  23407. * Licensed to the Apache Software Foundation (ASF) under one
  23408. * or more contributor license agreements. See the NOTICE file
  23409. * distributed with this work for additional information
  23410. * regarding copyright ownership. The ASF licenses this file
  23411. * to you under the Apache License, Version 2.0 (the
  23412. * "License"); you may not use this file except in compliance
  23413. * with the License. You may obtain a copy of the License at
  23414. *
  23415. * http://www.apache.org/licenses/LICENSE-2.0
  23416. *
  23417. * Unless required by applicable law or agreed to in writing,
  23418. * software distributed under the License is distributed on an
  23419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23420. * KIND, either express or implied. See the License for the
  23421. * specific language governing permissions and limitations
  23422. * under the License.
  23423. */
  23424. /**
  23425. * This module is imported by echarts directly.
  23426. *
  23427. * Notice:
  23428. * Always keep this file exists for backward compatibility.
  23429. * Because before 4.1.0, dataset is an optional component,
  23430. * some users may import this module manually.
  23431. */
  23432. ComponentModel.extend({
  23433. type: 'dataset',
  23434. /**
  23435. * @protected
  23436. */
  23437. defaultOption: {
  23438. // 'row', 'column'
  23439. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23440. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23441. sourceHeader: null,
  23442. dimensions: null,
  23443. source: null
  23444. },
  23445. optionUpdated: function () {
  23446. detectSourceFormat(this);
  23447. }
  23448. });
  23449. Component$1.extend({
  23450. type: 'dataset'
  23451. });
  23452. /**
  23453. * 椭圆形状
  23454. * @module zrender/graphic/shape/Ellipse
  23455. */
  23456. var Ellipse = Path.extend({
  23457. type: 'ellipse',
  23458. shape: {
  23459. cx: 0, cy: 0,
  23460. rx: 0, ry: 0
  23461. },
  23462. buildPath: function (ctx, shape) {
  23463. var k = 0.5522848;
  23464. var x = shape.cx;
  23465. var y = shape.cy;
  23466. var a = shape.rx;
  23467. var b = shape.ry;
  23468. var ox = a * k; // 水平控制点偏移量
  23469. var oy = b * k; // 垂直控制点偏移量
  23470. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23471. ctx.moveTo(x - a, y);
  23472. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23473. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23474. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23475. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23476. ctx.closePath();
  23477. }
  23478. });
  23479. // import RadialGradient from '../graphic/RadialGradient';
  23480. // import Pattern from '../graphic/Pattern';
  23481. // import * as vector from '../core/vector';
  23482. // Most of the values can be separated by comma and/or white space.
  23483. var DILIMITER_REG = /[\s,]+/;
  23484. /**
  23485. * For big svg string, this method might be time consuming.
  23486. *
  23487. * @param {string} svg xml string
  23488. * @return {Object} xml root.
  23489. */
  23490. function parseXML(svg) {
  23491. if (isString(svg)) {
  23492. var parser = new DOMParser();
  23493. svg = parser.parseFromString(svg, 'text/xml');
  23494. }
  23495. // Document node. If using $.get, doc node may be input.
  23496. if (svg.nodeType === 9) {
  23497. svg = svg.firstChild;
  23498. }
  23499. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23500. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23501. svg = svg.nextSibling;
  23502. }
  23503. return svg;
  23504. }
  23505. function SVGParser() {
  23506. this._defs = {};
  23507. this._root = null;
  23508. this._isDefine = false;
  23509. this._isText = false;
  23510. }
  23511. SVGParser.prototype.parse = function (xml, opt) {
  23512. opt = opt || {};
  23513. var svg = parseXML(xml);
  23514. if (!svg) {
  23515. throw new Error('Illegal svg');
  23516. }
  23517. var root = new Group();
  23518. this._root = root;
  23519. // parse view port
  23520. var viewBox = svg.getAttribute('viewBox') || '';
  23521. // If width/height not specified, means "100%" of `opt.width/height`.
  23522. // TODO: Other percent value not supported yet.
  23523. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23524. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23525. // If width/height not specified, set as null for output.
  23526. isNaN(width) && (width = null);
  23527. isNaN(height) && (height = null);
  23528. // Apply inline style on svg element.
  23529. parseAttributes(svg, root, null, true);
  23530. var child = svg.firstChild;
  23531. while (child) {
  23532. this._parseNode(child, root);
  23533. child = child.nextSibling;
  23534. }
  23535. var viewBoxRect;
  23536. var viewBoxTransform;
  23537. if (viewBox) {
  23538. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23539. // Some invalid case like viewBox: 'none'.
  23540. if (viewBoxArr.length >= 4) {
  23541. viewBoxRect = {
  23542. x: parseFloat(viewBoxArr[0] || 0),
  23543. y: parseFloat(viewBoxArr[1] || 0),
  23544. width: parseFloat(viewBoxArr[2]),
  23545. height: parseFloat(viewBoxArr[3])
  23546. };
  23547. }
  23548. }
  23549. if (viewBoxRect && width != null && height != null) {
  23550. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23551. if (!opt.ignoreViewBox) {
  23552. // If set transform on the output group, it probably bring trouble when
  23553. // some users only intend to show the clipped content inside the viewBox,
  23554. // but not intend to transform the output group. So we keep the output
  23555. // group no transform. If the user intend to use the viewBox as a
  23556. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23557. // manually according to the viewBox info in the output of this method.
  23558. var elRoot = root;
  23559. root = new Group();
  23560. root.add(elRoot);
  23561. elRoot.scale = viewBoxTransform.scale.slice();
  23562. elRoot.position = viewBoxTransform.position.slice();
  23563. }
  23564. }
  23565. // Some shapes might be overflow the viewport, which should be
  23566. // clipped despite whether the viewBox is used, as the SVG does.
  23567. if (!opt.ignoreRootClip && width != null && height != null) {
  23568. root.setClipPath(new Rect({
  23569. shape: {x: 0, y: 0, width: width, height: height}
  23570. }));
  23571. }
  23572. // Set width/height on group just for output the viewport size.
  23573. return {
  23574. root: root,
  23575. width: width,
  23576. height: height,
  23577. viewBoxRect: viewBoxRect,
  23578. viewBoxTransform: viewBoxTransform
  23579. };
  23580. };
  23581. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23582. var nodeName = xmlNode.nodeName.toLowerCase();
  23583. // TODO
  23584. // support <style>...</style> in svg, where nodeName is 'style',
  23585. // CSS classes is defined globally wherever the style tags are declared.
  23586. if (nodeName === 'defs') {
  23587. // define flag
  23588. this._isDefine = true;
  23589. }
  23590. else if (nodeName === 'text') {
  23591. this._isText = true;
  23592. }
  23593. var el;
  23594. if (this._isDefine) {
  23595. var parser = defineParsers[nodeName];
  23596. if (parser) {
  23597. var def = parser.call(this, xmlNode);
  23598. var id = xmlNode.getAttribute('id');
  23599. if (id) {
  23600. this._defs[id] = def;
  23601. }
  23602. }
  23603. }
  23604. else {
  23605. var parser = nodeParsers[nodeName];
  23606. if (parser) {
  23607. el = parser.call(this, xmlNode, parentGroup);
  23608. parentGroup.add(el);
  23609. }
  23610. }
  23611. var child = xmlNode.firstChild;
  23612. while (child) {
  23613. if (child.nodeType === 1) {
  23614. this._parseNode(child, el);
  23615. }
  23616. // Is text
  23617. if (child.nodeType === 3 && this._isText) {
  23618. this._parseText(child, el);
  23619. }
  23620. child = child.nextSibling;
  23621. }
  23622. // Quit define
  23623. if (nodeName === 'defs') {
  23624. this._isDefine = false;
  23625. }
  23626. else if (nodeName === 'text') {
  23627. this._isText = false;
  23628. }
  23629. };
  23630. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23631. if (xmlNode.nodeType === 1) {
  23632. var dx = xmlNode.getAttribute('dx') || 0;
  23633. var dy = xmlNode.getAttribute('dy') || 0;
  23634. this._textX += parseFloat(dx);
  23635. this._textY += parseFloat(dy);
  23636. }
  23637. var text = new Text({
  23638. style: {
  23639. text: xmlNode.textContent,
  23640. transformText: true
  23641. },
  23642. position: [this._textX || 0, this._textY || 0]
  23643. });
  23644. inheritStyle(parentGroup, text);
  23645. parseAttributes(xmlNode, text, this._defs);
  23646. var fontSize = text.style.fontSize;
  23647. if (fontSize && fontSize < 9) {
  23648. // PENDING
  23649. text.style.fontSize = 9;
  23650. text.scale = text.scale || [1, 1];
  23651. text.scale[0] *= fontSize / 9;
  23652. text.scale[1] *= fontSize / 9;
  23653. }
  23654. var rect = text.getBoundingRect();
  23655. this._textX += rect.width;
  23656. parentGroup.add(text);
  23657. return text;
  23658. };
  23659. var nodeParsers = {
  23660. 'g': function (xmlNode, parentGroup) {
  23661. var g = new Group();
  23662. inheritStyle(parentGroup, g);
  23663. parseAttributes(xmlNode, g, this._defs);
  23664. return g;
  23665. },
  23666. 'rect': function (xmlNode, parentGroup) {
  23667. var rect = new Rect();
  23668. inheritStyle(parentGroup, rect);
  23669. parseAttributes(xmlNode, rect, this._defs);
  23670. rect.setShape({
  23671. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23672. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23673. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23674. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23675. });
  23676. // console.log(xmlNode.getAttribute('transform'));
  23677. // console.log(rect.transform);
  23678. return rect;
  23679. },
  23680. 'circle': function (xmlNode, parentGroup) {
  23681. var circle = new Circle();
  23682. inheritStyle(parentGroup, circle);
  23683. parseAttributes(xmlNode, circle, this._defs);
  23684. circle.setShape({
  23685. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23686. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23687. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23688. });
  23689. return circle;
  23690. },
  23691. 'line': function (xmlNode, parentGroup) {
  23692. var line = new Line();
  23693. inheritStyle(parentGroup, line);
  23694. parseAttributes(xmlNode, line, this._defs);
  23695. line.setShape({
  23696. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23697. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23698. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23699. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23700. });
  23701. return line;
  23702. },
  23703. 'ellipse': function (xmlNode, parentGroup) {
  23704. var ellipse = new Ellipse();
  23705. inheritStyle(parentGroup, ellipse);
  23706. parseAttributes(xmlNode, ellipse, this._defs);
  23707. ellipse.setShape({
  23708. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23709. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23710. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23711. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23712. });
  23713. return ellipse;
  23714. },
  23715. 'polygon': function (xmlNode, parentGroup) {
  23716. var points = xmlNode.getAttribute('points');
  23717. if (points) {
  23718. points = parsePoints(points);
  23719. }
  23720. var polygon = new Polygon({
  23721. shape: {
  23722. points: points || []
  23723. }
  23724. });
  23725. inheritStyle(parentGroup, polygon);
  23726. parseAttributes(xmlNode, polygon, this._defs);
  23727. return polygon;
  23728. },
  23729. 'polyline': function (xmlNode, parentGroup) {
  23730. var path = new Path();
  23731. inheritStyle(parentGroup, path);
  23732. parseAttributes(xmlNode, path, this._defs);
  23733. var points = xmlNode.getAttribute('points');
  23734. if (points) {
  23735. points = parsePoints(points);
  23736. }
  23737. var polyline = new Polyline({
  23738. shape: {
  23739. points: points || []
  23740. }
  23741. });
  23742. return polyline;
  23743. },
  23744. 'image': function (xmlNode, parentGroup) {
  23745. var img = new ZImage();
  23746. inheritStyle(parentGroup, img);
  23747. parseAttributes(xmlNode, img, this._defs);
  23748. img.setStyle({
  23749. image: xmlNode.getAttribute('xlink:href'),
  23750. x: xmlNode.getAttribute('x'),
  23751. y: xmlNode.getAttribute('y'),
  23752. width: xmlNode.getAttribute('width'),
  23753. height: xmlNode.getAttribute('height')
  23754. });
  23755. return img;
  23756. },
  23757. 'text': function (xmlNode, parentGroup) {
  23758. var x = xmlNode.getAttribute('x') || 0;
  23759. var y = xmlNode.getAttribute('y') || 0;
  23760. var dx = xmlNode.getAttribute('dx') || 0;
  23761. var dy = xmlNode.getAttribute('dy') || 0;
  23762. this._textX = parseFloat(x) + parseFloat(dx);
  23763. this._textY = parseFloat(y) + parseFloat(dy);
  23764. var g = new Group();
  23765. inheritStyle(parentGroup, g);
  23766. parseAttributes(xmlNode, g, this._defs);
  23767. return g;
  23768. },
  23769. 'tspan': function (xmlNode, parentGroup) {
  23770. var x = xmlNode.getAttribute('x');
  23771. var y = xmlNode.getAttribute('y');
  23772. if (x != null) {
  23773. // new offset x
  23774. this._textX = parseFloat(x);
  23775. }
  23776. if (y != null) {
  23777. // new offset y
  23778. this._textY = parseFloat(y);
  23779. }
  23780. var dx = xmlNode.getAttribute('dx') || 0;
  23781. var dy = xmlNode.getAttribute('dy') || 0;
  23782. var g = new Group();
  23783. inheritStyle(parentGroup, g);
  23784. parseAttributes(xmlNode, g, this._defs);
  23785. this._textX += dx;
  23786. this._textY += dy;
  23787. return g;
  23788. },
  23789. 'path': function (xmlNode, parentGroup) {
  23790. // TODO svg fill rule
  23791. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23792. // path.style.globalCompositeOperation = 'xor';
  23793. var d = xmlNode.getAttribute('d') || '';
  23794. // Performance sensitive.
  23795. var path = createFromString(d);
  23796. inheritStyle(parentGroup, path);
  23797. parseAttributes(xmlNode, path, this._defs);
  23798. return path;
  23799. }
  23800. };
  23801. var defineParsers = {
  23802. 'lineargradient': function (xmlNode) {
  23803. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23804. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23805. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23806. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23807. var gradient = new LinearGradient(x1, y1, x2, y2);
  23808. _parseGradientColorStops(xmlNode, gradient);
  23809. return gradient;
  23810. },
  23811. 'radialgradient': function (xmlNode) {
  23812. }
  23813. };
  23814. function _parseGradientColorStops(xmlNode, gradient) {
  23815. var stop = xmlNode.firstChild;
  23816. while (stop) {
  23817. if (stop.nodeType === 1) {
  23818. var offset = stop.getAttribute('offset');
  23819. if (offset.indexOf('%') > 0) { // percentage
  23820. offset = parseInt(offset, 10) / 100;
  23821. }
  23822. else if (offset) { // number from 0 to 1
  23823. offset = parseFloat(offset);
  23824. }
  23825. else {
  23826. offset = 0;
  23827. }
  23828. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23829. gradient.addColorStop(offset, stopColor);
  23830. }
  23831. stop = stop.nextSibling;
  23832. }
  23833. }
  23834. function inheritStyle(parent, child) {
  23835. if (parent && parent.__inheritedStyle) {
  23836. if (!child.__inheritedStyle) {
  23837. child.__inheritedStyle = {};
  23838. }
  23839. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23840. }
  23841. }
  23842. function parsePoints(pointsString) {
  23843. var list = trim(pointsString).split(DILIMITER_REG);
  23844. var points = [];
  23845. for (var i = 0; i < list.length; i += 2) {
  23846. var x = parseFloat(list[i]);
  23847. var y = parseFloat(list[i + 1]);
  23848. points.push([x, y]);
  23849. }
  23850. return points;
  23851. }
  23852. var attributesMap = {
  23853. 'fill': 'fill',
  23854. 'stroke': 'stroke',
  23855. 'stroke-width': 'lineWidth',
  23856. 'opacity': 'opacity',
  23857. 'fill-opacity': 'fillOpacity',
  23858. 'stroke-opacity': 'strokeOpacity',
  23859. 'stroke-dasharray': 'lineDash',
  23860. 'stroke-dashoffset': 'lineDashOffset',
  23861. 'stroke-linecap': 'lineCap',
  23862. 'stroke-linejoin': 'lineJoin',
  23863. 'stroke-miterlimit': 'miterLimit',
  23864. 'font-family': 'fontFamily',
  23865. 'font-size': 'fontSize',
  23866. 'font-style': 'fontStyle',
  23867. 'font-weight': 'fontWeight',
  23868. 'text-align': 'textAlign',
  23869. 'alignment-baseline': 'textBaseline'
  23870. };
  23871. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23872. var zrStyle = el.__inheritedStyle || {};
  23873. var isTextEl = el.type === 'text';
  23874. // TODO Shadow
  23875. if (xmlNode.nodeType === 1) {
  23876. parseTransformAttribute(xmlNode, el);
  23877. extend(zrStyle, parseStyleAttribute(xmlNode));
  23878. if (!onlyInlineStyle) {
  23879. for (var svgAttrName in attributesMap) {
  23880. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23881. var attrValue = xmlNode.getAttribute(svgAttrName);
  23882. if (attrValue != null) {
  23883. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23884. }
  23885. }
  23886. }
  23887. }
  23888. }
  23889. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23890. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23891. el.style = el.style || new Style();
  23892. var elStyle = el.style;
  23893. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23894. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23895. each$1([
  23896. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23897. ], function (propName) {
  23898. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23899. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23900. });
  23901. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23902. zrStyle.textBaseline = 'alphabetic';
  23903. }
  23904. if (zrStyle.textBaseline === 'alphabetic') {
  23905. zrStyle.textBaseline = 'bottom';
  23906. }
  23907. if (zrStyle.textAlign === 'start') {
  23908. zrStyle.textAlign = 'left';
  23909. }
  23910. if (zrStyle.textAlign === 'end') {
  23911. zrStyle.textAlign = 'right';
  23912. }
  23913. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23914. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23915. ], function (propName) {
  23916. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23917. });
  23918. if (zrStyle.lineDash) {
  23919. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23920. }
  23921. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23922. // enable stroke
  23923. el[elStrokeProp] = true;
  23924. }
  23925. el.__inheritedStyle = zrStyle;
  23926. }
  23927. var urlRegex = /url\(\s*#(.*?)\)/;
  23928. function getPaint(str, defs) {
  23929. // if (str === 'none') {
  23930. // return;
  23931. // }
  23932. var urlMatch = defs && str && str.match(urlRegex);
  23933. if (urlMatch) {
  23934. var url = trim(urlMatch[1]);
  23935. var def = defs[url];
  23936. return def;
  23937. }
  23938. return str;
  23939. }
  23940. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23941. function parseTransformAttribute(xmlNode, node) {
  23942. var transform = xmlNode.getAttribute('transform');
  23943. if (transform) {
  23944. transform = transform.replace(/,/g, ' ');
  23945. var m = null;
  23946. var transformOps = [];
  23947. transform.replace(transformRegex, function (str, type, value) {
  23948. transformOps.push(type, value);
  23949. });
  23950. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23951. var value = transformOps[i];
  23952. var type = transformOps[i - 1];
  23953. m = m || create$1();
  23954. switch (type) {
  23955. case 'translate':
  23956. value = trim(value).split(DILIMITER_REG);
  23957. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23958. break;
  23959. case 'scale':
  23960. value = trim(value).split(DILIMITER_REG);
  23961. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23962. break;
  23963. case 'rotate':
  23964. value = trim(value).split(DILIMITER_REG);
  23965. rotate(m, m, parseFloat(value[0]));
  23966. break;
  23967. case 'skew':
  23968. value = trim(value).split(DILIMITER_REG);
  23969. console.warn('Skew transform is not supported yet');
  23970. break;
  23971. case 'matrix':
  23972. var value = trim(value).split(DILIMITER_REG);
  23973. m[0] = parseFloat(value[0]);
  23974. m[1] = parseFloat(value[1]);
  23975. m[2] = parseFloat(value[2]);
  23976. m[3] = parseFloat(value[3]);
  23977. m[4] = parseFloat(value[4]);
  23978. m[5] = parseFloat(value[5]);
  23979. break;
  23980. }
  23981. }
  23982. node.setLocalTransform(m);
  23983. }
  23984. }
  23985. // Value may contain space.
  23986. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23987. function parseStyleAttribute(xmlNode) {
  23988. var style = xmlNode.getAttribute('style');
  23989. var result = {};
  23990. if (!style) {
  23991. return result;
  23992. }
  23993. var styleList = {};
  23994. styleRegex.lastIndex = 0;
  23995. var styleRegResult;
  23996. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23997. styleList[styleRegResult[1]] = styleRegResult[2];
  23998. }
  23999. for (var svgAttrName in attributesMap) {
  24000. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  24001. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  24002. }
  24003. }
  24004. return result;
  24005. }
  24006. /**
  24007. * @param {Array.<number>} viewBoxRect
  24008. * @param {number} width
  24009. * @param {number} height
  24010. * @return {Object} {scale, position}
  24011. */
  24012. function makeViewBoxTransform(viewBoxRect, width, height) {
  24013. var scaleX = width / viewBoxRect.width;
  24014. var scaleY = height / viewBoxRect.height;
  24015. var scale = Math.min(scaleX, scaleY);
  24016. // preserveAspectRatio 'xMidYMid'
  24017. var viewBoxScale = [scale, scale];
  24018. var viewBoxPosition = [
  24019. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  24020. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  24021. ];
  24022. return {
  24023. scale: viewBoxScale,
  24024. position: viewBoxPosition
  24025. };
  24026. }
  24027. /**
  24028. * @param {string|XMLElement} xml
  24029. * @param {Object} [opt]
  24030. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  24031. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  24032. * @param {boolean} [opt.ignoreViewBox]
  24033. * @param {boolean} [opt.ignoreRootClip]
  24034. * @return {Object} result:
  24035. * {
  24036. * root: Group, The root of the the result tree of zrender shapes,
  24037. * width: number, the viewport width of the SVG,
  24038. * height: number, the viewport height of the SVG,
  24039. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  24040. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  24041. * }
  24042. */
  24043. function parseSVG(xml, opt) {
  24044. var parser = new SVGParser();
  24045. return parser.parse(xml, opt);
  24046. }
  24047. /*
  24048. * Licensed to the Apache Software Foundation (ASF) under one
  24049. * or more contributor license agreements. See the NOTICE file
  24050. * distributed with this work for additional information
  24051. * regarding copyright ownership. The ASF licenses this file
  24052. * to you under the Apache License, Version 2.0 (the
  24053. * "License"); you may not use this file except in compliance
  24054. * with the License. You may obtain a copy of the License at
  24055. *
  24056. * http://www.apache.org/licenses/LICENSE-2.0
  24057. *
  24058. * Unless required by applicable law or agreed to in writing,
  24059. * software distributed under the License is distributed on an
  24060. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24061. * KIND, either express or implied. See the License for the
  24062. * specific language governing permissions and limitations
  24063. * under the License.
  24064. */
  24065. var storage = createHashMap();
  24066. // For minimize the code size of common echarts package,
  24067. // do not put too much logic in this module.
  24068. var mapDataStorage = {
  24069. // The format of record: see `echarts.registerMap`.
  24070. // Compatible with previous `echarts.registerMap`.
  24071. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  24072. var records;
  24073. if (isArray(rawGeoJson)) {
  24074. records = rawGeoJson;
  24075. }
  24076. else if (rawGeoJson.svg) {
  24077. records = [{
  24078. type: 'svg',
  24079. source: rawGeoJson.svg,
  24080. specialAreas: rawGeoJson.specialAreas
  24081. }];
  24082. }
  24083. else {
  24084. // Backward compatibility.
  24085. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24086. rawSpecialAreas = rawGeoJson.specialAreas;
  24087. rawGeoJson = rawGeoJson.geoJson;
  24088. }
  24089. records = [{
  24090. type: 'geoJSON',
  24091. source: rawGeoJson,
  24092. specialAreas: rawSpecialAreas
  24093. }];
  24094. }
  24095. each$1(records, function (record) {
  24096. var type = record.type;
  24097. type === 'geoJson' && (type = record.type = 'geoJSON');
  24098. var parse = parsers[type];
  24099. if (__DEV__) {
  24100. assert$1(parse, 'Illegal map type: ' + type);
  24101. }
  24102. parse(record);
  24103. });
  24104. return storage.set(mapName, records);
  24105. },
  24106. retrieveMap: function (mapName) {
  24107. return storage.get(mapName);
  24108. }
  24109. };
  24110. var parsers = {
  24111. geoJSON: function (record) {
  24112. var source = record.source;
  24113. record.geoJSON = !isString(source)
  24114. ? source
  24115. : (typeof JSON !== 'undefined' && JSON.parse)
  24116. ? JSON.parse(source)
  24117. : (new Function('return (' + source + ');'))();
  24118. },
  24119. // Only perform parse to XML object here, which might be time
  24120. // consiming for large SVG.
  24121. // Although convert XML to zrender element is also time consiming,
  24122. // if we do it here, the clone of zrender elements has to be
  24123. // required. So we do it once for each geo instance, util real
  24124. // performance issues call for optimizing it.
  24125. svg: function (record) {
  24126. record.svgXML = parseXML(record.source);
  24127. }
  24128. };
  24129. /*
  24130. * Licensed to the Apache Software Foundation (ASF) under one
  24131. * or more contributor license agreements. See the NOTICE file
  24132. * distributed with this work for additional information
  24133. * regarding copyright ownership. The ASF licenses this file
  24134. * to you under the Apache License, Version 2.0 (the
  24135. * "License"); you may not use this file except in compliance
  24136. * with the License. You may obtain a copy of the License at
  24137. *
  24138. * http://www.apache.org/licenses/LICENSE-2.0
  24139. *
  24140. * Unless required by applicable law or agreed to in writing,
  24141. * software distributed under the License is distributed on an
  24142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24143. * KIND, either express or implied. See the License for the
  24144. * specific language governing permissions and limitations
  24145. * under the License.
  24146. */
  24147. var assert = assert$1;
  24148. var each = each$1;
  24149. var isFunction = isFunction$1;
  24150. var isObject = isObject$1;
  24151. var parseClassType = ComponentModel.parseClassType;
  24152. var version = '4.6.0';
  24153. var dependencies = {
  24154. zrender: '4.2.0'
  24155. };
  24156. var TEST_FRAME_REMAIN_TIME = 1;
  24157. var PRIORITY_PROCESSOR_FILTER = 1000;
  24158. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24159. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24160. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24161. var PRIORITY_VISUAL_LAYOUT = 1000;
  24162. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24163. var PRIORITY_VISUAL_GLOBAL = 2000;
  24164. var PRIORITY_VISUAL_CHART = 3000;
  24165. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24166. var PRIORITY_VISUAL_COMPONENT = 4000;
  24167. // FIXME
  24168. // necessary?
  24169. var PRIORITY_VISUAL_BRUSH = 5000;
  24170. var PRIORITY = {
  24171. PROCESSOR: {
  24172. FILTER: PRIORITY_PROCESSOR_FILTER,
  24173. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24174. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24175. },
  24176. VISUAL: {
  24177. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24178. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24179. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24180. CHART: PRIORITY_VISUAL_CHART,
  24181. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24182. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24183. BRUSH: PRIORITY_VISUAL_BRUSH
  24184. }
  24185. };
  24186. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24187. // where they must not be invoked nestedly, except the only case: invoke
  24188. // dispatchAction with updateMethod "none" in main process.
  24189. // This flag is used to carry out this rule.
  24190. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24191. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24192. var OPTION_UPDATED = '__optionUpdated';
  24193. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24194. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24195. return function (eventName, handler, context) {
  24196. if (!ignoreDisposed && this._disposed) {
  24197. disposedWarning(this.id);
  24198. return;
  24199. }
  24200. // Event name is all lowercase
  24201. eventName = eventName && eventName.toLowerCase();
  24202. Eventful.prototype[method].call(this, eventName, handler, context);
  24203. };
  24204. }
  24205. /**
  24206. * @module echarts~MessageCenter
  24207. */
  24208. function MessageCenter() {
  24209. Eventful.call(this);
  24210. }
  24211. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24212. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24213. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24214. mixin(MessageCenter, Eventful);
  24215. /**
  24216. * @module echarts~ECharts
  24217. */
  24218. function ECharts(dom, theme$$1, opts) {
  24219. opts = opts || {};
  24220. // Get theme by name
  24221. if (typeof theme$$1 === 'string') {
  24222. theme$$1 = themeStorage[theme$$1];
  24223. }
  24224. /**
  24225. * @type {string}
  24226. */
  24227. this.id;
  24228. /**
  24229. * Group id
  24230. * @type {string}
  24231. */
  24232. this.group;
  24233. /**
  24234. * @type {HTMLElement}
  24235. * @private
  24236. */
  24237. this._dom = dom;
  24238. var defaultRenderer = 'canvas';
  24239. if (__DEV__) {
  24240. defaultRenderer = (
  24241. typeof window === 'undefined' ? global : window
  24242. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24243. }
  24244. /**
  24245. * @type {module:zrender/ZRender}
  24246. * @private
  24247. */
  24248. var zr = this._zr = init$1(dom, {
  24249. renderer: opts.renderer || defaultRenderer,
  24250. devicePixelRatio: opts.devicePixelRatio,
  24251. width: opts.width,
  24252. height: opts.height
  24253. });
  24254. /**
  24255. * Expect 60 fps.
  24256. * @type {Function}
  24257. * @private
  24258. */
  24259. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24260. var theme$$1 = clone(theme$$1);
  24261. theme$$1 && backwardCompat(theme$$1, true);
  24262. /**
  24263. * @type {Object}
  24264. * @private
  24265. */
  24266. this._theme = theme$$1;
  24267. /**
  24268. * @type {Array.<module:echarts/view/Chart>}
  24269. * @private
  24270. */
  24271. this._chartsViews = [];
  24272. /**
  24273. * @type {Object.<string, module:echarts/view/Chart>}
  24274. * @private
  24275. */
  24276. this._chartsMap = {};
  24277. /**
  24278. * @type {Array.<module:echarts/view/Component>}
  24279. * @private
  24280. */
  24281. this._componentsViews = [];
  24282. /**
  24283. * @type {Object.<string, module:echarts/view/Component>}
  24284. * @private
  24285. */
  24286. this._componentsMap = {};
  24287. /**
  24288. * @type {module:echarts/CoordinateSystem}
  24289. * @private
  24290. */
  24291. this._coordSysMgr = new CoordinateSystemManager();
  24292. /**
  24293. * @type {module:echarts/ExtensionAPI}
  24294. * @private
  24295. */
  24296. var api = this._api = createExtensionAPI(this);
  24297. // Sort on demand
  24298. function prioritySortFunc(a, b) {
  24299. return a.__prio - b.__prio;
  24300. }
  24301. sort(visualFuncs, prioritySortFunc);
  24302. sort(dataProcessorFuncs, prioritySortFunc);
  24303. /**
  24304. * @type {module:echarts/stream/Scheduler}
  24305. */
  24306. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24307. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24308. /**
  24309. * @type {module:echarts~MessageCenter}
  24310. * @private
  24311. */
  24312. this._messageCenter = new MessageCenter();
  24313. // Init mouse events
  24314. this._initEvents();
  24315. // In case some people write `window.onresize = chart.resize`
  24316. this.resize = bind(this.resize, this);
  24317. // Can't dispatch action during rendering procedure
  24318. this._pendingActions = [];
  24319. zr.animation.on('frame', this._onframe, this);
  24320. bindRenderedEvent(zr, this);
  24321. // ECharts instance can be used as value.
  24322. setAsPrimitive(this);
  24323. }
  24324. var echartsProto = ECharts.prototype;
  24325. echartsProto._onframe = function () {
  24326. if (this._disposed) {
  24327. return;
  24328. }
  24329. var scheduler = this._scheduler;
  24330. // Lazy update
  24331. if (this[OPTION_UPDATED]) {
  24332. var silent = this[OPTION_UPDATED].silent;
  24333. this[IN_MAIN_PROCESS] = true;
  24334. prepare(this);
  24335. updateMethods.update.call(this);
  24336. this[IN_MAIN_PROCESS] = false;
  24337. this[OPTION_UPDATED] = false;
  24338. flushPendingActions.call(this, silent);
  24339. triggerUpdatedEvent.call(this, silent);
  24340. }
  24341. // Avoid do both lazy update and progress in one frame.
  24342. else if (scheduler.unfinished) {
  24343. // Stream progress.
  24344. var remainTime = TEST_FRAME_REMAIN_TIME;
  24345. var ecModel = this._model;
  24346. var api = this._api;
  24347. scheduler.unfinished = false;
  24348. do {
  24349. var startTime = +new Date();
  24350. scheduler.performSeriesTasks(ecModel);
  24351. // Currently dataProcessorFuncs do not check threshold.
  24352. scheduler.performDataProcessorTasks(ecModel);
  24353. updateStreamModes(this, ecModel);
  24354. // Do not update coordinate system here. Because that coord system update in
  24355. // each frame is not a good user experience. So we follow the rule that
  24356. // the extent of the coordinate system is determin in the first frame (the
  24357. // frame is executed immedietely after task reset.
  24358. // this._coordSysMgr.update(ecModel, api);
  24359. // console.log('--- ec frame visual ---', remainTime);
  24360. scheduler.performVisualTasks(ecModel);
  24361. renderSeries(this, this._model, api, 'remain');
  24362. remainTime -= (+new Date() - startTime);
  24363. }
  24364. while (remainTime > 0 && scheduler.unfinished);
  24365. // Call flush explicitly for trigger finished event.
  24366. if (!scheduler.unfinished) {
  24367. this._zr.flush();
  24368. }
  24369. // Else, zr flushing be ensue within the same frame,
  24370. // because zr flushing is after onframe event.
  24371. }
  24372. };
  24373. /**
  24374. * @return {HTMLElement}
  24375. */
  24376. echartsProto.getDom = function () {
  24377. return this._dom;
  24378. };
  24379. /**
  24380. * @return {module:zrender~ZRender}
  24381. */
  24382. echartsProto.getZr = function () {
  24383. return this._zr;
  24384. };
  24385. /**
  24386. * Usage:
  24387. * chart.setOption(option, notMerge, lazyUpdate);
  24388. * chart.setOption(option, {
  24389. * notMerge: ...,
  24390. * lazyUpdate: ...,
  24391. * silent: ...
  24392. * });
  24393. *
  24394. * @param {Object} option
  24395. * @param {Object|boolean} [opts] opts or notMerge.
  24396. * @param {boolean} [opts.notMerge=false]
  24397. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24398. */
  24399. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24400. if (__DEV__) {
  24401. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24402. }
  24403. if (this._disposed) {
  24404. disposedWarning(this.id);
  24405. return;
  24406. }
  24407. var silent;
  24408. if (isObject(notMerge)) {
  24409. lazyUpdate = notMerge.lazyUpdate;
  24410. silent = notMerge.silent;
  24411. notMerge = notMerge.notMerge;
  24412. }
  24413. this[IN_MAIN_PROCESS] = true;
  24414. if (!this._model || notMerge) {
  24415. var optionManager = new OptionManager(this._api);
  24416. var theme$$1 = this._theme;
  24417. var ecModel = this._model = new GlobalModel();
  24418. ecModel.scheduler = this._scheduler;
  24419. ecModel.init(null, null, theme$$1, optionManager);
  24420. }
  24421. this._model.setOption(option, optionPreprocessorFuncs);
  24422. if (lazyUpdate) {
  24423. this[OPTION_UPDATED] = {silent: silent};
  24424. this[IN_MAIN_PROCESS] = false;
  24425. }
  24426. else {
  24427. prepare(this);
  24428. updateMethods.update.call(this);
  24429. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24430. // fetched after `setOption`.
  24431. this._zr.flush();
  24432. this[OPTION_UPDATED] = false;
  24433. this[IN_MAIN_PROCESS] = false;
  24434. flushPendingActions.call(this, silent);
  24435. triggerUpdatedEvent.call(this, silent);
  24436. }
  24437. };
  24438. /**
  24439. * @DEPRECATED
  24440. */
  24441. echartsProto.setTheme = function () {
  24442. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24443. };
  24444. /**
  24445. * @return {module:echarts/model/Global}
  24446. */
  24447. echartsProto.getModel = function () {
  24448. return this._model;
  24449. };
  24450. /**
  24451. * @return {Object}
  24452. */
  24453. echartsProto.getOption = function () {
  24454. return this._model && this._model.getOption();
  24455. };
  24456. /**
  24457. * @return {number}
  24458. */
  24459. echartsProto.getWidth = function () {
  24460. return this._zr.getWidth();
  24461. };
  24462. /**
  24463. * @return {number}
  24464. */
  24465. echartsProto.getHeight = function () {
  24466. return this._zr.getHeight();
  24467. };
  24468. /**
  24469. * @return {number}
  24470. */
  24471. echartsProto.getDevicePixelRatio = function () {
  24472. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24473. };
  24474. /**
  24475. * Get canvas which has all thing rendered
  24476. * @param {Object} opts
  24477. * @param {string} [opts.backgroundColor]
  24478. * @return {string}
  24479. */
  24480. echartsProto.getRenderedCanvas = function (opts) {
  24481. if (!env$1.canvasSupported) {
  24482. return;
  24483. }
  24484. opts = opts || {};
  24485. opts.pixelRatio = opts.pixelRatio || 1;
  24486. opts.backgroundColor = opts.backgroundColor
  24487. || this._model.get('backgroundColor');
  24488. var zr = this._zr;
  24489. // var list = zr.storage.getDisplayList();
  24490. // Stop animations
  24491. // Never works before in init animation, so remove it.
  24492. // zrUtil.each(list, function (el) {
  24493. // el.stopAnimation(true);
  24494. // });
  24495. return zr.painter.getRenderedCanvas(opts);
  24496. };
  24497. /**
  24498. * Get svg data url
  24499. * @return {string}
  24500. */
  24501. echartsProto.getSvgDataUrl = function () {
  24502. if (!env$1.svgSupported) {
  24503. return;
  24504. }
  24505. var zr = this._zr;
  24506. var list = zr.storage.getDisplayList();
  24507. // Stop animations
  24508. each$1(list, function (el) {
  24509. el.stopAnimation(true);
  24510. });
  24511. return zr.painter.pathToDataUrl();
  24512. };
  24513. /**
  24514. * @return {string}
  24515. * @param {Object} opts
  24516. * @param {string} [opts.type='png']
  24517. * @param {string} [opts.pixelRatio=1]
  24518. * @param {string} [opts.backgroundColor]
  24519. * @param {string} [opts.excludeComponents]
  24520. */
  24521. echartsProto.getDataURL = function (opts) {
  24522. if (this._disposed) {
  24523. disposedWarning(this.id);
  24524. return;
  24525. }
  24526. opts = opts || {};
  24527. var excludeComponents = opts.excludeComponents;
  24528. var ecModel = this._model;
  24529. var excludesComponentViews = [];
  24530. var self = this;
  24531. each(excludeComponents, function (componentType) {
  24532. ecModel.eachComponent({
  24533. mainType: componentType
  24534. }, function (component) {
  24535. var view = self._componentsMap[component.__viewId];
  24536. if (!view.group.ignore) {
  24537. excludesComponentViews.push(view);
  24538. view.group.ignore = true;
  24539. }
  24540. });
  24541. });
  24542. var url = this._zr.painter.getType() === 'svg'
  24543. ? this.getSvgDataUrl()
  24544. : this.getRenderedCanvas(opts).toDataURL(
  24545. 'image/' + (opts && opts.type || 'png')
  24546. );
  24547. each(excludesComponentViews, function (view) {
  24548. view.group.ignore = false;
  24549. });
  24550. return url;
  24551. };
  24552. /**
  24553. * @return {string}
  24554. * @param {Object} opts
  24555. * @param {string} [opts.type='png']
  24556. * @param {string} [opts.pixelRatio=1]
  24557. * @param {string} [opts.backgroundColor]
  24558. */
  24559. echartsProto.getConnectedDataURL = function (opts) {
  24560. if (this._disposed) {
  24561. disposedWarning(this.id);
  24562. return;
  24563. }
  24564. if (!env$1.canvasSupported) {
  24565. return;
  24566. }
  24567. var groupId = this.group;
  24568. var mathMin = Math.min;
  24569. var mathMax = Math.max;
  24570. var MAX_NUMBER = Infinity;
  24571. if (connectedGroups[groupId]) {
  24572. var left = MAX_NUMBER;
  24573. var top = MAX_NUMBER;
  24574. var right = -MAX_NUMBER;
  24575. var bottom = -MAX_NUMBER;
  24576. var canvasList = [];
  24577. var dpr = (opts && opts.pixelRatio) || 1;
  24578. each$1(instances, function (chart, id) {
  24579. if (chart.group === groupId) {
  24580. var canvas = chart.getRenderedCanvas(
  24581. clone(opts)
  24582. );
  24583. var boundingRect = chart.getDom().getBoundingClientRect();
  24584. left = mathMin(boundingRect.left, left);
  24585. top = mathMin(boundingRect.top, top);
  24586. right = mathMax(boundingRect.right, right);
  24587. bottom = mathMax(boundingRect.bottom, bottom);
  24588. canvasList.push({
  24589. dom: canvas,
  24590. left: boundingRect.left,
  24591. top: boundingRect.top
  24592. });
  24593. }
  24594. });
  24595. left *= dpr;
  24596. top *= dpr;
  24597. right *= dpr;
  24598. bottom *= dpr;
  24599. var width = right - left;
  24600. var height = bottom - top;
  24601. var targetCanvas = createCanvas();
  24602. targetCanvas.width = width;
  24603. targetCanvas.height = height;
  24604. var zr = init$1(targetCanvas);
  24605. // Background between the charts
  24606. if (opts.connectedBackgroundColor) {
  24607. zr.add(new Rect({
  24608. shape: {
  24609. x: 0,
  24610. y: 0,
  24611. width: width,
  24612. height: height
  24613. },
  24614. style: {
  24615. fill: opts.connectedBackgroundColor
  24616. }
  24617. }));
  24618. }
  24619. each(canvasList, function (item) {
  24620. var img = new ZImage({
  24621. style: {
  24622. x: item.left * dpr - left,
  24623. y: item.top * dpr - top,
  24624. image: item.dom
  24625. }
  24626. });
  24627. zr.add(img);
  24628. });
  24629. zr.refreshImmediately();
  24630. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24631. }
  24632. else {
  24633. return this.getDataURL(opts);
  24634. }
  24635. };
  24636. /**
  24637. * Convert from logical coordinate system to pixel coordinate system.
  24638. * See CoordinateSystem#convertToPixel.
  24639. * @param {string|Object} finder
  24640. * If string, e.g., 'geo', means {geoIndex: 0}.
  24641. * If Object, could contain some of these properties below:
  24642. * {
  24643. * seriesIndex / seriesId / seriesName,
  24644. * geoIndex / geoId, geoName,
  24645. * bmapIndex / bmapId / bmapName,
  24646. * xAxisIndex / xAxisId / xAxisName,
  24647. * yAxisIndex / yAxisId / yAxisName,
  24648. * gridIndex / gridId / gridName,
  24649. * ... (can be extended)
  24650. * }
  24651. * @param {Array|number} value
  24652. * @return {Array|number} result
  24653. */
  24654. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24655. /**
  24656. * Convert from pixel coordinate system to logical coordinate system.
  24657. * See CoordinateSystem#convertFromPixel.
  24658. * @param {string|Object} finder
  24659. * If string, e.g., 'geo', means {geoIndex: 0}.
  24660. * If Object, could contain some of these properties below:
  24661. * {
  24662. * seriesIndex / seriesId / seriesName,
  24663. * geoIndex / geoId / geoName,
  24664. * bmapIndex / bmapId / bmapName,
  24665. * xAxisIndex / xAxisId / xAxisName,
  24666. * yAxisIndex / yAxisId / yAxisName
  24667. * gridIndex / gridId / gridName,
  24668. * ... (can be extended)
  24669. * }
  24670. * @param {Array|number} value
  24671. * @return {Array|number} result
  24672. */
  24673. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24674. function doConvertPixel(methodName, finder, value) {
  24675. if (this._disposed) {
  24676. disposedWarning(this.id);
  24677. return;
  24678. }
  24679. var ecModel = this._model;
  24680. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24681. var result;
  24682. finder = parseFinder(ecModel, finder);
  24683. for (var i = 0; i < coordSysList.length; i++) {
  24684. var coordSys = coordSysList[i];
  24685. if (coordSys[methodName]
  24686. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24687. ) {
  24688. return result;
  24689. }
  24690. }
  24691. if (__DEV__) {
  24692. console.warn(
  24693. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24694. );
  24695. }
  24696. }
  24697. /**
  24698. * Is the specified coordinate systems or components contain the given pixel point.
  24699. * @param {string|Object} finder
  24700. * If string, e.g., 'geo', means {geoIndex: 0}.
  24701. * If Object, could contain some of these properties below:
  24702. * {
  24703. * seriesIndex / seriesId / seriesName,
  24704. * geoIndex / geoId / geoName,
  24705. * bmapIndex / bmapId / bmapName,
  24706. * xAxisIndex / xAxisId / xAxisName,
  24707. * yAxisIndex / yAxisId / yAxisName,
  24708. * gridIndex / gridId / gridName,
  24709. * ... (can be extended)
  24710. * }
  24711. * @param {Array|number} value
  24712. * @return {boolean} result
  24713. */
  24714. echartsProto.containPixel = function (finder, value) {
  24715. if (this._disposed) {
  24716. disposedWarning(this.id);
  24717. return;
  24718. }
  24719. var ecModel = this._model;
  24720. var result;
  24721. finder = parseFinder(ecModel, finder);
  24722. each$1(finder, function (models, key) {
  24723. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24724. var coordSys = model.coordinateSystem;
  24725. if (coordSys && coordSys.containPoint) {
  24726. result |= !!coordSys.containPoint(value);
  24727. }
  24728. else if (key === 'seriesModels') {
  24729. var view = this._chartsMap[model.__viewId];
  24730. if (view && view.containPoint) {
  24731. result |= view.containPoint(value, model);
  24732. }
  24733. else {
  24734. if (__DEV__) {
  24735. console.warn(key + ': ' + (view
  24736. ? 'The found component do not support containPoint.'
  24737. : 'No view mapping to the found component.'
  24738. ));
  24739. }
  24740. }
  24741. }
  24742. else {
  24743. if (__DEV__) {
  24744. console.warn(key + ': containPoint is not supported');
  24745. }
  24746. }
  24747. }, this);
  24748. }, this);
  24749. return !!result;
  24750. };
  24751. /**
  24752. * Get visual from series or data.
  24753. * @param {string|Object} finder
  24754. * If string, e.g., 'series', means {seriesIndex: 0}.
  24755. * If Object, could contain some of these properties below:
  24756. * {
  24757. * seriesIndex / seriesId / seriesName,
  24758. * dataIndex / dataIndexInside
  24759. * }
  24760. * If dataIndex is not specified, series visual will be fetched,
  24761. * but not data item visual.
  24762. * If all of seriesIndex, seriesId, seriesName are not specified,
  24763. * visual will be fetched from first series.
  24764. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24765. */
  24766. echartsProto.getVisual = function (finder, visualType) {
  24767. var ecModel = this._model;
  24768. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24769. var seriesModel = finder.seriesModel;
  24770. if (__DEV__) {
  24771. if (!seriesModel) {
  24772. console.warn('There is no specified seires model');
  24773. }
  24774. }
  24775. var data = seriesModel.getData();
  24776. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24777. ? finder.dataIndexInside
  24778. : finder.hasOwnProperty('dataIndex')
  24779. ? data.indexOfRawIndex(finder.dataIndex)
  24780. : null;
  24781. return dataIndexInside != null
  24782. ? data.getItemVisual(dataIndexInside, visualType)
  24783. : data.getVisual(visualType);
  24784. };
  24785. /**
  24786. * Get view of corresponding component model
  24787. * @param {module:echarts/model/Component} componentModel
  24788. * @return {module:echarts/view/Component}
  24789. */
  24790. echartsProto.getViewOfComponentModel = function (componentModel) {
  24791. return this._componentsMap[componentModel.__viewId];
  24792. };
  24793. /**
  24794. * Get view of corresponding series model
  24795. * @param {module:echarts/model/Series} seriesModel
  24796. * @return {module:echarts/view/Chart}
  24797. */
  24798. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24799. return this._chartsMap[seriesModel.__viewId];
  24800. };
  24801. var updateMethods = {
  24802. prepareAndUpdate: function (payload) {
  24803. prepare(this);
  24804. updateMethods.update.call(this, payload);
  24805. },
  24806. /**
  24807. * @param {Object} payload
  24808. * @private
  24809. */
  24810. update: function (payload) {
  24811. // console.profile && console.profile('update');
  24812. var ecModel = this._model;
  24813. var api = this._api;
  24814. var zr = this._zr;
  24815. var coordSysMgr = this._coordSysMgr;
  24816. var scheduler = this._scheduler;
  24817. // update before setOption
  24818. if (!ecModel) {
  24819. return;
  24820. }
  24821. scheduler.restoreData(ecModel, payload);
  24822. scheduler.performSeriesTasks(ecModel);
  24823. // TODO
  24824. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24825. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24826. // Create new coordinate system each update
  24827. // In LineView may save the old coordinate system and use it to get the orignal point
  24828. coordSysMgr.create(ecModel, api);
  24829. scheduler.performDataProcessorTasks(ecModel, payload);
  24830. // Current stream render is not supported in data process. So we can update
  24831. // stream modes after data processing, where the filtered data is used to
  24832. // deteming whether use progressive rendering.
  24833. updateStreamModes(this, ecModel);
  24834. // We update stream modes before coordinate system updated, then the modes info
  24835. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24836. // the drawback is the full coord info can not be fetched. Fortunately this full
  24837. // coord is not requied in stream mode updater currently.
  24838. coordSysMgr.update(ecModel, api);
  24839. clearColorPalette(ecModel);
  24840. scheduler.performVisualTasks(ecModel, payload);
  24841. render(this, ecModel, api, payload);
  24842. // Set background
  24843. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24844. // In IE8
  24845. if (!env$1.canvasSupported) {
  24846. var colorArr = parse(backgroundColor);
  24847. backgroundColor = stringify(colorArr, 'rgb');
  24848. if (colorArr[3] === 0) {
  24849. backgroundColor = 'transparent';
  24850. }
  24851. }
  24852. else {
  24853. zr.setBackgroundColor(backgroundColor);
  24854. }
  24855. performPostUpdateFuncs(ecModel, api);
  24856. // console.profile && console.profileEnd('update');
  24857. },
  24858. /**
  24859. * @param {Object} payload
  24860. * @private
  24861. */
  24862. updateTransform: function (payload) {
  24863. var ecModel = this._model;
  24864. var ecIns = this;
  24865. var api = this._api;
  24866. // update before setOption
  24867. if (!ecModel) {
  24868. return;
  24869. }
  24870. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24871. var componentDirtyList = [];
  24872. ecModel.eachComponent(function (componentType, componentModel) {
  24873. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24874. if (componentView && componentView.__alive) {
  24875. if (componentView.updateTransform) {
  24876. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24877. result && result.update && componentDirtyList.push(componentView);
  24878. }
  24879. else {
  24880. componentDirtyList.push(componentView);
  24881. }
  24882. }
  24883. });
  24884. var seriesDirtyMap = createHashMap();
  24885. ecModel.eachSeries(function (seriesModel) {
  24886. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24887. if (chartView.updateTransform) {
  24888. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24889. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24890. }
  24891. else {
  24892. seriesDirtyMap.set(seriesModel.uid, 1);
  24893. }
  24894. });
  24895. clearColorPalette(ecModel);
  24896. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24897. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24898. this._scheduler.performVisualTasks(
  24899. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24900. );
  24901. // Currently, not call render of components. Geo render cost a lot.
  24902. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24903. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24904. performPostUpdateFuncs(ecModel, this._api);
  24905. },
  24906. /**
  24907. * @param {Object} payload
  24908. * @private
  24909. */
  24910. updateView: function (payload) {
  24911. var ecModel = this._model;
  24912. // update before setOption
  24913. if (!ecModel) {
  24914. return;
  24915. }
  24916. Chart.markUpdateMethod(payload, 'updateView');
  24917. clearColorPalette(ecModel);
  24918. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24919. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24920. render(this, this._model, this._api, payload);
  24921. performPostUpdateFuncs(ecModel, this._api);
  24922. },
  24923. /**
  24924. * @param {Object} payload
  24925. * @private
  24926. */
  24927. updateVisual: function (payload) {
  24928. updateMethods.update.call(this, payload);
  24929. // var ecModel = this._model;
  24930. // // update before setOption
  24931. // if (!ecModel) {
  24932. // return;
  24933. // }
  24934. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24935. // clearColorPalette(ecModel);
  24936. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24937. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24938. // render(this, this._model, this._api, payload);
  24939. // performPostUpdateFuncs(ecModel, this._api);
  24940. },
  24941. /**
  24942. * @param {Object} payload
  24943. * @private
  24944. */
  24945. updateLayout: function (payload) {
  24946. updateMethods.update.call(this, payload);
  24947. // var ecModel = this._model;
  24948. // // update before setOption
  24949. // if (!ecModel) {
  24950. // return;
  24951. // }
  24952. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24953. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24954. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24955. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24956. // render(this, this._model, this._api, payload);
  24957. // performPostUpdateFuncs(ecModel, this._api);
  24958. }
  24959. };
  24960. function prepare(ecIns) {
  24961. var ecModel = ecIns._model;
  24962. var scheduler = ecIns._scheduler;
  24963. scheduler.restorePipelines(ecModel);
  24964. scheduler.prepareStageTasks();
  24965. prepareView(ecIns, 'component', ecModel, scheduler);
  24966. prepareView(ecIns, 'chart', ecModel, scheduler);
  24967. scheduler.plan();
  24968. }
  24969. /**
  24970. * @private
  24971. */
  24972. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24973. var ecModel = ecIns._model;
  24974. // broadcast
  24975. if (!mainType) {
  24976. // FIXME
  24977. // Chart will not be update directly here, except set dirty.
  24978. // But there is no such scenario now.
  24979. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24980. return;
  24981. }
  24982. var query = {};
  24983. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24984. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24985. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24986. var condition = {mainType: mainType, query: query};
  24987. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24988. var excludeSeriesId = payload.excludeSeriesId;
  24989. if (excludeSeriesId != null) {
  24990. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24991. }
  24992. // If dispatchAction before setOption, do nothing.
  24993. ecModel && ecModel.eachComponent(condition, function (model) {
  24994. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24995. callView(ecIns[
  24996. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24997. ][model.__viewId]);
  24998. }
  24999. }, ecIns);
  25000. function callView(view) {
  25001. view && view.__alive && view[method] && view[method](
  25002. view.__model, ecModel, ecIns._api, payload
  25003. );
  25004. }
  25005. }
  25006. /**
  25007. * Resize the chart
  25008. * @param {Object} opts
  25009. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  25010. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  25011. * @param {boolean} [opts.silent=false]
  25012. */
  25013. echartsProto.resize = function (opts) {
  25014. if (__DEV__) {
  25015. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  25016. }
  25017. if (this._disposed) {
  25018. disposedWarning(this.id);
  25019. return;
  25020. }
  25021. this._zr.resize(opts);
  25022. var ecModel = this._model;
  25023. // Resize loading effect
  25024. this._loadingFX && this._loadingFX.resize();
  25025. if (!ecModel) {
  25026. return;
  25027. }
  25028. var optionChanged = ecModel.resetOption('media');
  25029. var silent = opts && opts.silent;
  25030. this[IN_MAIN_PROCESS] = true;
  25031. optionChanged && prepare(this);
  25032. updateMethods.update.call(this);
  25033. this[IN_MAIN_PROCESS] = false;
  25034. flushPendingActions.call(this, silent);
  25035. triggerUpdatedEvent.call(this, silent);
  25036. };
  25037. function updateStreamModes(ecIns, ecModel) {
  25038. var chartsMap = ecIns._chartsMap;
  25039. var scheduler = ecIns._scheduler;
  25040. ecModel.eachSeries(function (seriesModel) {
  25041. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25042. });
  25043. }
  25044. /**
  25045. * Show loading effect
  25046. * @param {string} [name='default']
  25047. * @param {Object} [cfg]
  25048. */
  25049. echartsProto.showLoading = function (name, cfg) {
  25050. if (this._disposed) {
  25051. disposedWarning(this.id);
  25052. return;
  25053. }
  25054. if (isObject(name)) {
  25055. cfg = name;
  25056. name = '';
  25057. }
  25058. name = name || 'default';
  25059. this.hideLoading();
  25060. if (!loadingEffects[name]) {
  25061. if (__DEV__) {
  25062. console.warn('Loading effects ' + name + ' not exists.');
  25063. }
  25064. return;
  25065. }
  25066. var el = loadingEffects[name](this._api, cfg);
  25067. var zr = this._zr;
  25068. this._loadingFX = el;
  25069. zr.add(el);
  25070. };
  25071. /**
  25072. * Hide loading effect
  25073. */
  25074. echartsProto.hideLoading = function () {
  25075. if (this._disposed) {
  25076. disposedWarning(this.id);
  25077. return;
  25078. }
  25079. this._loadingFX && this._zr.remove(this._loadingFX);
  25080. this._loadingFX = null;
  25081. };
  25082. /**
  25083. * @param {Object} eventObj
  25084. * @return {Object}
  25085. */
  25086. echartsProto.makeActionFromEvent = function (eventObj) {
  25087. var payload = extend({}, eventObj);
  25088. payload.type = eventActionMap[eventObj.type];
  25089. return payload;
  25090. };
  25091. /**
  25092. * @pubilc
  25093. * @param {Object} payload
  25094. * @param {string} [payload.type] Action type
  25095. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25096. * @param {boolean} [opt.silent=false] Whether trigger events.
  25097. * @param {boolean} [opt.flush=undefined]
  25098. * true: Flush immediately, and then pixel in canvas can be fetched
  25099. * immediately. Caution: it might affect performance.
  25100. * false: Not flush.
  25101. * undefined: Auto decide whether perform flush.
  25102. */
  25103. echartsProto.dispatchAction = function (payload, opt) {
  25104. if (this._disposed) {
  25105. disposedWarning(this.id);
  25106. return;
  25107. }
  25108. if (!isObject(opt)) {
  25109. opt = {silent: !!opt};
  25110. }
  25111. if (!actions[payload.type]) {
  25112. return;
  25113. }
  25114. // Avoid dispatch action before setOption. Especially in `connect`.
  25115. if (!this._model) {
  25116. return;
  25117. }
  25118. // May dispatchAction in rendering procedure
  25119. if (this[IN_MAIN_PROCESS]) {
  25120. this._pendingActions.push(payload);
  25121. return;
  25122. }
  25123. doDispatchAction.call(this, payload, opt.silent);
  25124. if (opt.flush) {
  25125. this._zr.flush(true);
  25126. }
  25127. else if (opt.flush !== false && env$1.browser.weChat) {
  25128. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25129. // hang when sliding page (on touch event), which cause that zr does not
  25130. // refresh util user interaction finished, which is not expected.
  25131. // But `dispatchAction` may be called too frequently when pan on touch
  25132. // screen, which impacts performance if do not throttle them.
  25133. this._throttledZrFlush();
  25134. }
  25135. flushPendingActions.call(this, opt.silent);
  25136. triggerUpdatedEvent.call(this, opt.silent);
  25137. };
  25138. function doDispatchAction(payload, silent) {
  25139. var payloadType = payload.type;
  25140. var escapeConnect = payload.escapeConnect;
  25141. var actionWrap = actions[payloadType];
  25142. var actionInfo = actionWrap.actionInfo;
  25143. var cptType = (actionInfo.update || 'update').split(':');
  25144. var updateMethod = cptType.pop();
  25145. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25146. this[IN_MAIN_PROCESS] = true;
  25147. var payloads = [payload];
  25148. var batched = false;
  25149. // Batch action
  25150. if (payload.batch) {
  25151. batched = true;
  25152. payloads = map(payload.batch, function (item) {
  25153. item = defaults(extend({}, item), payload);
  25154. item.batch = null;
  25155. return item;
  25156. });
  25157. }
  25158. var eventObjBatch = [];
  25159. var eventObj;
  25160. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25161. each(payloads, function (batchItem) {
  25162. // Action can specify the event by return it.
  25163. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25164. // Emit event outside
  25165. eventObj = eventObj || extend({}, batchItem);
  25166. // Convert type to eventType
  25167. eventObj.type = actionInfo.event || eventObj.type;
  25168. eventObjBatch.push(eventObj);
  25169. // light update does not perform data process, layout and visual.
  25170. if (isHighDown) {
  25171. // method, payload, mainType, subType
  25172. updateDirectly(this, updateMethod, batchItem, 'series');
  25173. }
  25174. else if (cptType) {
  25175. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25176. }
  25177. }, this);
  25178. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25179. // Still dirty
  25180. if (this[OPTION_UPDATED]) {
  25181. // FIXME Pass payload ?
  25182. prepare(this);
  25183. updateMethods.update.call(this, payload);
  25184. this[OPTION_UPDATED] = false;
  25185. }
  25186. else {
  25187. updateMethods[updateMethod].call(this, payload);
  25188. }
  25189. }
  25190. // Follow the rule of action batch
  25191. if (batched) {
  25192. eventObj = {
  25193. type: actionInfo.event || payloadType,
  25194. escapeConnect: escapeConnect,
  25195. batch: eventObjBatch
  25196. };
  25197. }
  25198. else {
  25199. eventObj = eventObjBatch[0];
  25200. }
  25201. this[IN_MAIN_PROCESS] = false;
  25202. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25203. }
  25204. function flushPendingActions(silent) {
  25205. var pendingActions = this._pendingActions;
  25206. while (pendingActions.length) {
  25207. var payload = pendingActions.shift();
  25208. doDispatchAction.call(this, payload, silent);
  25209. }
  25210. }
  25211. function triggerUpdatedEvent(silent) {
  25212. !silent && this.trigger('updated');
  25213. }
  25214. /**
  25215. * Event `rendered` is triggered when zr
  25216. * rendered. It is useful for realtime
  25217. * snapshot (reflect animation).
  25218. *
  25219. * Event `finished` is triggered when:
  25220. * (1) zrender rendering finished.
  25221. * (2) initial animation finished.
  25222. * (3) progressive rendering finished.
  25223. * (4) no pending action.
  25224. * (5) no delayed setOption needs to be processed.
  25225. */
  25226. function bindRenderedEvent(zr, ecIns) {
  25227. zr.on('rendered', function () {
  25228. ecIns.trigger('rendered');
  25229. // The `finished` event should not be triggered repeatly,
  25230. // so it should only be triggered when rendering indeed happend
  25231. // in zrender. (Consider the case that dipatchAction is keep
  25232. // triggering when mouse move).
  25233. if (
  25234. // Although zr is dirty if initial animation is not finished
  25235. // and this checking is called on frame, we also check
  25236. // animation finished for robustness.
  25237. zr.animation.isFinished()
  25238. && !ecIns[OPTION_UPDATED]
  25239. && !ecIns._scheduler.unfinished
  25240. && !ecIns._pendingActions.length
  25241. ) {
  25242. ecIns.trigger('finished');
  25243. }
  25244. });
  25245. }
  25246. /**
  25247. * @param {Object} params
  25248. * @param {number} params.seriesIndex
  25249. * @param {Array|TypedArray} params.data
  25250. */
  25251. echartsProto.appendData = function (params) {
  25252. if (this._disposed) {
  25253. disposedWarning(this.id);
  25254. return;
  25255. }
  25256. var seriesIndex = params.seriesIndex;
  25257. var ecModel = this.getModel();
  25258. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25259. if (__DEV__) {
  25260. assert(params.data && seriesModel);
  25261. }
  25262. seriesModel.appendData(params);
  25263. // Note: `appendData` does not support that update extent of coordinate
  25264. // system, util some scenario require that. In the expected usage of
  25265. // `appendData`, the initial extent of coordinate system should better
  25266. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25267. // the extent changed while `appendData`, the location of the painted
  25268. // graphic elements have to be changed, which make the usage of
  25269. // `appendData` meaningless.
  25270. this._scheduler.unfinished = true;
  25271. };
  25272. /**
  25273. * Register event
  25274. * @method
  25275. */
  25276. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25277. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25278. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25279. /**
  25280. * Prepare view instances of charts and components
  25281. * @param {module:echarts/model/Global} ecModel
  25282. * @private
  25283. */
  25284. function prepareView(ecIns, type, ecModel, scheduler) {
  25285. var isComponent = type === 'component';
  25286. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25287. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25288. var zr = ecIns._zr;
  25289. var api = ecIns._api;
  25290. for (var i = 0; i < viewList.length; i++) {
  25291. viewList[i].__alive = false;
  25292. }
  25293. isComponent
  25294. ? ecModel.eachComponent(function (componentType, model) {
  25295. componentType !== 'series' && doPrepare(model);
  25296. })
  25297. : ecModel.eachSeries(doPrepare);
  25298. function doPrepare(model) {
  25299. // Consider: id same and type changed.
  25300. var viewId = '_ec_' + model.id + '_' + model.type;
  25301. var view = viewMap[viewId];
  25302. if (!view) {
  25303. var classType = parseClassType(model.type);
  25304. var Clazz = isComponent
  25305. ? Component$1.getClass(classType.main, classType.sub)
  25306. : Chart.getClass(classType.sub);
  25307. if (__DEV__) {
  25308. assert(Clazz, classType.sub + ' does not exist.');
  25309. }
  25310. view = new Clazz();
  25311. view.init(ecModel, api);
  25312. viewMap[viewId] = view;
  25313. viewList.push(view);
  25314. zr.add(view.group);
  25315. }
  25316. model.__viewId = view.__id = viewId;
  25317. view.__alive = true;
  25318. view.__model = model;
  25319. view.group.__ecComponentInfo = {
  25320. mainType: model.mainType,
  25321. index: model.componentIndex
  25322. };
  25323. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25324. }
  25325. for (var i = 0; i < viewList.length;) {
  25326. var view = viewList[i];
  25327. if (!view.__alive) {
  25328. !isComponent && view.renderTask.dispose();
  25329. zr.remove(view.group);
  25330. view.dispose(ecModel, api);
  25331. viewList.splice(i, 1);
  25332. delete viewMap[view.__id];
  25333. view.__id = view.group.__ecComponentInfo = null;
  25334. }
  25335. else {
  25336. i++;
  25337. }
  25338. }
  25339. }
  25340. // /**
  25341. // * Encode visual infomation from data after data processing
  25342. // *
  25343. // * @param {module:echarts/model/Global} ecModel
  25344. // * @param {object} layout
  25345. // * @param {boolean} [layoutFilter] `true`: only layout,
  25346. // * `false`: only not layout,
  25347. // * `null`/`undefined`: all.
  25348. // * @param {string} taskBaseTag
  25349. // * @private
  25350. // */
  25351. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25352. // each(visualFuncs, function (visual, index) {
  25353. // var isLayout = visual.isLayout;
  25354. // if (layoutFilter == null
  25355. // || (layoutFilter === false && !isLayout)
  25356. // || (layoutFilter === true && isLayout)
  25357. // ) {
  25358. // visual.func(ecModel, api, payload);
  25359. // }
  25360. // });
  25361. // }
  25362. function clearColorPalette(ecModel) {
  25363. ecModel.clearColorPalette();
  25364. ecModel.eachSeries(function (seriesModel) {
  25365. seriesModel.clearColorPalette();
  25366. });
  25367. }
  25368. function render(ecIns, ecModel, api, payload) {
  25369. renderComponents(ecIns, ecModel, api, payload);
  25370. each(ecIns._chartsViews, function (chart) {
  25371. chart.__alive = false;
  25372. });
  25373. renderSeries(ecIns, ecModel, api, payload);
  25374. // Remove groups of unrendered charts
  25375. each(ecIns._chartsViews, function (chart) {
  25376. if (!chart.__alive) {
  25377. chart.remove(ecModel, api);
  25378. }
  25379. });
  25380. }
  25381. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25382. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25383. var componentModel = componentView.__model;
  25384. componentView.render(componentModel, ecModel, api, payload);
  25385. updateZ(componentModel, componentView);
  25386. });
  25387. }
  25388. /**
  25389. * Render each chart and component
  25390. * @private
  25391. */
  25392. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25393. // Render all charts
  25394. var scheduler = ecIns._scheduler;
  25395. var unfinished;
  25396. ecModel.eachSeries(function (seriesModel) {
  25397. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25398. chartView.__alive = true;
  25399. var renderTask = chartView.renderTask;
  25400. scheduler.updatePayload(renderTask, payload);
  25401. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25402. renderTask.dirty();
  25403. }
  25404. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25405. chartView.group.silent = !!seriesModel.get('silent');
  25406. updateZ(seriesModel, chartView);
  25407. updateBlend(seriesModel, chartView);
  25408. });
  25409. scheduler.unfinished |= unfinished;
  25410. // If use hover layer
  25411. updateHoverLayerStatus(ecIns, ecModel);
  25412. // Add aria
  25413. aria(ecIns._zr.dom, ecModel);
  25414. }
  25415. function performPostUpdateFuncs(ecModel, api) {
  25416. each(postUpdateFuncs, function (func) {
  25417. func(ecModel, api);
  25418. });
  25419. }
  25420. var MOUSE_EVENT_NAMES = [
  25421. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25422. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25423. ];
  25424. /**
  25425. * @private
  25426. */
  25427. echartsProto._initEvents = function () {
  25428. each(MOUSE_EVENT_NAMES, function (eveName) {
  25429. var handler = function (e) {
  25430. var ecModel = this.getModel();
  25431. var el = e.target;
  25432. var params;
  25433. var isGlobalOut = eveName === 'globalout';
  25434. // no e.target when 'globalout'.
  25435. if (isGlobalOut) {
  25436. params = {};
  25437. }
  25438. else if (el && el.dataIndex != null) {
  25439. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25440. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25441. }
  25442. // If element has custom eventData of components
  25443. else if (el && el.eventData) {
  25444. params = extend({}, el.eventData);
  25445. }
  25446. // Contract: if params prepared in mouse event,
  25447. // these properties must be specified:
  25448. // {
  25449. // componentType: string (component main type)
  25450. // componentIndex: number
  25451. // }
  25452. // Otherwise event query can not work.
  25453. if (params) {
  25454. var componentType = params.componentType;
  25455. var componentIndex = params.componentIndex;
  25456. // Special handling for historic reason: when trigger by
  25457. // markLine/markPoint/markArea, the componentType is
  25458. // 'markLine'/'markPoint'/'markArea', but we should better
  25459. // enable them to be queried by seriesIndex, since their
  25460. // option is set in each series.
  25461. if (componentType === 'markLine'
  25462. || componentType === 'markPoint'
  25463. || componentType === 'markArea'
  25464. ) {
  25465. componentType = 'series';
  25466. componentIndex = params.seriesIndex;
  25467. }
  25468. var model = componentType && componentIndex != null
  25469. && ecModel.getComponent(componentType, componentIndex);
  25470. var view = model && this[
  25471. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25472. ][model.__viewId];
  25473. if (__DEV__) {
  25474. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25475. // be missed, otherwise there is no way to distinguish source component.
  25476. // See `dataFormat.getDataParams`.
  25477. if (!isGlobalOut && !(model && view)) {
  25478. console.warn('model or view can not be found by params');
  25479. }
  25480. }
  25481. params.event = e;
  25482. params.type = eveName;
  25483. this._ecEventProcessor.eventInfo = {
  25484. targetEl: el,
  25485. packedEvent: params,
  25486. model: model,
  25487. view: view
  25488. };
  25489. this.trigger(eveName, params);
  25490. }
  25491. };
  25492. // Consider that some component (like tooltip, brush, ...)
  25493. // register zr event handler, but user event handler might
  25494. // do anything, such as call `setOption` or `dispatchAction`,
  25495. // which probably update any of the content and probably
  25496. // cause problem if it is called previous other inner handlers.
  25497. handler.zrEventfulCallAtLast = true;
  25498. this._zr.on(eveName, handler, this);
  25499. }, this);
  25500. each(eventActionMap, function (actionType, eventType) {
  25501. this._messageCenter.on(eventType, function (event) {
  25502. this.trigger(eventType, event);
  25503. }, this);
  25504. }, this);
  25505. };
  25506. /**
  25507. * @return {boolean}
  25508. */
  25509. echartsProto.isDisposed = function () {
  25510. return this._disposed;
  25511. };
  25512. /**
  25513. * Clear
  25514. */
  25515. echartsProto.clear = function () {
  25516. if (this._disposed) {
  25517. disposedWarning(this.id);
  25518. return;
  25519. }
  25520. this.setOption({ series: [] }, true);
  25521. };
  25522. /**
  25523. * Dispose instance
  25524. */
  25525. echartsProto.dispose = function () {
  25526. if (this._disposed) {
  25527. disposedWarning(this.id);
  25528. return;
  25529. }
  25530. this._disposed = true;
  25531. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25532. var api = this._api;
  25533. var ecModel = this._model;
  25534. each(this._componentsViews, function (component) {
  25535. component.dispose(ecModel, api);
  25536. });
  25537. each(this._chartsViews, function (chart) {
  25538. chart.dispose(ecModel, api);
  25539. });
  25540. // Dispose after all views disposed
  25541. this._zr.dispose();
  25542. delete instances[this.id];
  25543. };
  25544. mixin(ECharts, Eventful);
  25545. function disposedWarning(id) {
  25546. if (__DEV__) {
  25547. console.warn('Instance ' + id + ' has been disposed');
  25548. }
  25549. }
  25550. function updateHoverLayerStatus(ecIns, ecModel) {
  25551. var zr = ecIns._zr;
  25552. var storage = zr.storage;
  25553. var elCount = 0;
  25554. storage.traverse(function (el) {
  25555. elCount++;
  25556. });
  25557. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25558. ecModel.eachSeries(function (seriesModel) {
  25559. if (seriesModel.preventUsingHoverLayer) {
  25560. return;
  25561. }
  25562. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25563. if (chartView.__alive) {
  25564. chartView.group.traverse(function (el) {
  25565. // Don't switch back.
  25566. el.useHoverLayer = true;
  25567. });
  25568. }
  25569. });
  25570. }
  25571. }
  25572. /**
  25573. * Update chart progressive and blend.
  25574. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25575. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25576. */
  25577. function updateBlend(seriesModel, chartView) {
  25578. var blendMode = seriesModel.get('blendMode') || null;
  25579. if (__DEV__) {
  25580. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25581. console.warn('Only canvas support blendMode');
  25582. }
  25583. }
  25584. chartView.group.traverse(function (el) {
  25585. // FIXME marker and other components
  25586. if (!el.isGroup) {
  25587. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25588. if (el.style.blend !== blendMode) {
  25589. el.setStyle('blend', blendMode);
  25590. }
  25591. }
  25592. if (el.eachPendingDisplayable) {
  25593. el.eachPendingDisplayable(function (displayable) {
  25594. displayable.setStyle('blend', blendMode);
  25595. });
  25596. }
  25597. });
  25598. }
  25599. /**
  25600. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25601. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25602. */
  25603. function updateZ(model, view) {
  25604. var z = model.get('z');
  25605. var zlevel = model.get('zlevel');
  25606. // Set z and zlevel
  25607. view.group.traverse(function (el) {
  25608. if (el.type !== 'group') {
  25609. z != null && (el.z = z);
  25610. zlevel != null && (el.zlevel = zlevel);
  25611. }
  25612. });
  25613. }
  25614. function createExtensionAPI(ecInstance) {
  25615. var coordSysMgr = ecInstance._coordSysMgr;
  25616. return extend(new ExtensionAPI(ecInstance), {
  25617. // Inject methods
  25618. getCoordinateSystems: bind(
  25619. coordSysMgr.getCoordinateSystems, coordSysMgr
  25620. ),
  25621. getComponentByElement: function (el) {
  25622. while (el) {
  25623. var modelInfo = el.__ecComponentInfo;
  25624. if (modelInfo != null) {
  25625. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25626. }
  25627. el = el.parent;
  25628. }
  25629. }
  25630. });
  25631. }
  25632. /**
  25633. * @class
  25634. * Usage of query:
  25635. * `chart.on('click', query, handler);`
  25636. * The `query` can be:
  25637. * + The component type query string, only `mainType` or `mainType.subType`,
  25638. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25639. * + The component query object, like:
  25640. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25641. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25642. * + The data query object, like:
  25643. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25644. * + The other query object (cmponent customized query), like:
  25645. * `{element: 'some'}` (only available in custom series).
  25646. *
  25647. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25648. * same as there is no such prop in the `query` object.
  25649. */
  25650. function EventProcessor() {
  25651. // These info required: targetEl, packedEvent, model, view
  25652. this.eventInfo;
  25653. }
  25654. EventProcessor.prototype = {
  25655. constructor: EventProcessor,
  25656. normalizeQuery: function (query) {
  25657. var cptQuery = {};
  25658. var dataQuery = {};
  25659. var otherQuery = {};
  25660. // `query` is `mainType` or `mainType.subType` of component.
  25661. if (isString(query)) {
  25662. var condCptType = parseClassType(query);
  25663. // `.main` and `.sub` may be ''.
  25664. cptQuery.mainType = condCptType.main || null;
  25665. cptQuery.subType = condCptType.sub || null;
  25666. }
  25667. // `query` is an object, convert to {mainType, index, name, id}.
  25668. else {
  25669. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25670. // can not be used in `compomentModel.filterForExposedEvent`.
  25671. var suffixes = ['Index', 'Name', 'Id'];
  25672. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25673. each$1(query, function (val, key) {
  25674. var reserved = false;
  25675. for (var i = 0; i < suffixes.length; i++) {
  25676. var propSuffix = suffixes[i];
  25677. var suffixPos = key.lastIndexOf(propSuffix);
  25678. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25679. var mainType = key.slice(0, suffixPos);
  25680. // Consider `dataIndex`.
  25681. if (mainType !== 'data') {
  25682. cptQuery.mainType = mainType;
  25683. cptQuery[propSuffix.toLowerCase()] = val;
  25684. reserved = true;
  25685. }
  25686. }
  25687. }
  25688. if (dataKeys.hasOwnProperty(key)) {
  25689. dataQuery[key] = val;
  25690. reserved = true;
  25691. }
  25692. if (!reserved) {
  25693. otherQuery[key] = val;
  25694. }
  25695. });
  25696. }
  25697. return {
  25698. cptQuery: cptQuery,
  25699. dataQuery: dataQuery,
  25700. otherQuery: otherQuery
  25701. };
  25702. },
  25703. filter: function (eventType, query, args) {
  25704. // They should be assigned before each trigger call.
  25705. var eventInfo = this.eventInfo;
  25706. if (!eventInfo) {
  25707. return true;
  25708. }
  25709. var targetEl = eventInfo.targetEl;
  25710. var packedEvent = eventInfo.packedEvent;
  25711. var model = eventInfo.model;
  25712. var view = eventInfo.view;
  25713. // For event like 'globalout'.
  25714. if (!model || !view) {
  25715. return true;
  25716. }
  25717. var cptQuery = query.cptQuery;
  25718. var dataQuery = query.dataQuery;
  25719. return check(cptQuery, model, 'mainType')
  25720. && check(cptQuery, model, 'subType')
  25721. && check(cptQuery, model, 'index', 'componentIndex')
  25722. && check(cptQuery, model, 'name')
  25723. && check(cptQuery, model, 'id')
  25724. && check(dataQuery, packedEvent, 'name')
  25725. && check(dataQuery, packedEvent, 'dataIndex')
  25726. && check(dataQuery, packedEvent, 'dataType')
  25727. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25728. eventType, query.otherQuery, targetEl, packedEvent
  25729. ));
  25730. function check(query, host, prop, propOnHost) {
  25731. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25732. }
  25733. },
  25734. afterTrigger: function () {
  25735. // Make sure the eventInfo wont be used in next trigger.
  25736. this.eventInfo = null;
  25737. }
  25738. };
  25739. /**
  25740. * @type {Object} key: actionType.
  25741. * @inner
  25742. */
  25743. var actions = {};
  25744. /**
  25745. * Map eventType to actionType
  25746. * @type {Object}
  25747. */
  25748. var eventActionMap = {};
  25749. /**
  25750. * Data processor functions of each stage
  25751. * @type {Array.<Object.<string, Function>>}
  25752. * @inner
  25753. */
  25754. var dataProcessorFuncs = [];
  25755. /**
  25756. * @type {Array.<Function>}
  25757. * @inner
  25758. */
  25759. var optionPreprocessorFuncs = [];
  25760. /**
  25761. * @type {Array.<Function>}
  25762. * @inner
  25763. */
  25764. var postUpdateFuncs = [];
  25765. /**
  25766. * Visual encoding functions of each stage
  25767. * @type {Array.<Object.<string, Function>>}
  25768. */
  25769. var visualFuncs = [];
  25770. /**
  25771. * Theme storage
  25772. * @type {Object.<key, Object>}
  25773. */
  25774. var themeStorage = {};
  25775. /**
  25776. * Loading effects
  25777. */
  25778. var loadingEffects = {};
  25779. var instances = {};
  25780. var connectedGroups = {};
  25781. var idBase = new Date() - 0;
  25782. var groupIdBase = new Date() - 0;
  25783. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25784. function enableConnect(chart) {
  25785. var STATUS_PENDING = 0;
  25786. var STATUS_UPDATING = 1;
  25787. var STATUS_UPDATED = 2;
  25788. var STATUS_KEY = '__connectUpdateStatus';
  25789. function updateConnectedChartsStatus(charts, status) {
  25790. for (var i = 0; i < charts.length; i++) {
  25791. var otherChart = charts[i];
  25792. otherChart[STATUS_KEY] = status;
  25793. }
  25794. }
  25795. each(eventActionMap, function (actionType, eventType) {
  25796. chart._messageCenter.on(eventType, function (event) {
  25797. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25798. if (event && event.escapeConnect) {
  25799. return;
  25800. }
  25801. var action = chart.makeActionFromEvent(event);
  25802. var otherCharts = [];
  25803. each(instances, function (otherChart) {
  25804. if (otherChart !== chart && otherChart.group === chart.group) {
  25805. otherCharts.push(otherChart);
  25806. }
  25807. });
  25808. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25809. each(otherCharts, function (otherChart) {
  25810. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25811. otherChart.dispatchAction(action);
  25812. }
  25813. });
  25814. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25815. }
  25816. });
  25817. });
  25818. }
  25819. /**
  25820. * @param {HTMLElement} dom
  25821. * @param {Object} [theme]
  25822. * @param {Object} opts
  25823. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25824. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25825. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25826. * Can be 'auto' (the same as null/undefined)
  25827. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25828. * Can be 'auto' (the same as null/undefined)
  25829. */
  25830. function init(dom, theme$$1, opts) {
  25831. if (__DEV__) {
  25832. // Check version
  25833. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25834. throw new Error(
  25835. 'zrender/src ' + version$1
  25836. + ' is too old for ECharts ' + version
  25837. + '. Current version need ZRender '
  25838. + dependencies.zrender + '+'
  25839. );
  25840. }
  25841. if (!dom) {
  25842. throw new Error('Initialize failed: invalid dom.');
  25843. }
  25844. }
  25845. var existInstance = getInstanceByDom(dom);
  25846. if (existInstance) {
  25847. if (__DEV__) {
  25848. console.warn('There is a chart instance already initialized on the dom.');
  25849. }
  25850. return existInstance;
  25851. }
  25852. if (__DEV__) {
  25853. if (isDom(dom)
  25854. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25855. && (
  25856. (!dom.clientWidth && (!opts || opts.width == null))
  25857. || (!dom.clientHeight && (!opts || opts.height == null))
  25858. )
  25859. ) {
  25860. console.warn('Can\'t get DOM width or height. Please check '
  25861. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25862. + 'For example, you may need to call this in the callback '
  25863. + 'of window.onload.');
  25864. }
  25865. }
  25866. var chart = new ECharts(dom, theme$$1, opts);
  25867. chart.id = 'ec_' + idBase++;
  25868. instances[chart.id] = chart;
  25869. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25870. enableConnect(chart);
  25871. return chart;
  25872. }
  25873. /**
  25874. * @return {string|Array.<module:echarts~ECharts>} groupId
  25875. */
  25876. function connect(groupId) {
  25877. // Is array of charts
  25878. if (isArray(groupId)) {
  25879. var charts = groupId;
  25880. groupId = null;
  25881. // If any chart has group
  25882. each(charts, function (chart) {
  25883. if (chart.group != null) {
  25884. groupId = chart.group;
  25885. }
  25886. });
  25887. groupId = groupId || ('g_' + groupIdBase++);
  25888. each(charts, function (chart) {
  25889. chart.group = groupId;
  25890. });
  25891. }
  25892. connectedGroups[groupId] = true;
  25893. return groupId;
  25894. }
  25895. /**
  25896. * @DEPRECATED
  25897. * @return {string} groupId
  25898. */
  25899. function disConnect(groupId) {
  25900. connectedGroups[groupId] = false;
  25901. }
  25902. /**
  25903. * @return {string} groupId
  25904. */
  25905. var disconnect = disConnect;
  25906. /**
  25907. * Dispose a chart instance
  25908. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25909. */
  25910. function dispose(chart) {
  25911. if (typeof chart === 'string') {
  25912. chart = instances[chart];
  25913. }
  25914. else if (!(chart instanceof ECharts)) {
  25915. // Try to treat as dom
  25916. chart = getInstanceByDom(chart);
  25917. }
  25918. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25919. chart.dispose();
  25920. }
  25921. }
  25922. /**
  25923. * @param {HTMLElement} dom
  25924. * @return {echarts~ECharts}
  25925. */
  25926. function getInstanceByDom(dom) {
  25927. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25928. }
  25929. /**
  25930. * @param {string} key
  25931. * @return {echarts~ECharts}
  25932. */
  25933. function getInstanceById(key) {
  25934. return instances[key];
  25935. }
  25936. /**
  25937. * Register theme
  25938. */
  25939. function registerTheme(name, theme$$1) {
  25940. themeStorage[name] = theme$$1;
  25941. }
  25942. /**
  25943. * Register option preprocessor
  25944. * @param {Function} preprocessorFunc
  25945. */
  25946. function registerPreprocessor(preprocessorFunc) {
  25947. optionPreprocessorFuncs.push(preprocessorFunc);
  25948. }
  25949. /**
  25950. * @param {number} [priority=1000]
  25951. * @param {Object|Function} processor
  25952. */
  25953. function registerProcessor(priority, processor) {
  25954. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25955. }
  25956. /**
  25957. * Register postUpdater
  25958. * @param {Function} postUpdateFunc
  25959. */
  25960. function registerPostUpdate(postUpdateFunc) {
  25961. postUpdateFuncs.push(postUpdateFunc);
  25962. }
  25963. /**
  25964. * Usage:
  25965. * registerAction('someAction', 'someEvent', function () { ... });
  25966. * registerAction('someAction', function () { ... });
  25967. * registerAction(
  25968. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25969. * function () { ... }
  25970. * );
  25971. *
  25972. * @param {(string|Object)} actionInfo
  25973. * @param {string} actionInfo.type
  25974. * @param {string} [actionInfo.event]
  25975. * @param {string} [actionInfo.update]
  25976. * @param {string} [eventName]
  25977. * @param {Function} action
  25978. */
  25979. function registerAction(actionInfo, eventName, action) {
  25980. if (typeof eventName === 'function') {
  25981. action = eventName;
  25982. eventName = '';
  25983. }
  25984. var actionType = isObject(actionInfo)
  25985. ? actionInfo.type
  25986. : ([actionInfo, actionInfo = {
  25987. event: eventName
  25988. }][0]);
  25989. // Event name is all lowercase
  25990. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25991. eventName = actionInfo.event;
  25992. // Validate action type and event name.
  25993. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25994. if (!actions[actionType]) {
  25995. actions[actionType] = {action: action, actionInfo: actionInfo};
  25996. }
  25997. eventActionMap[eventName] = actionType;
  25998. }
  25999. /**
  26000. * @param {string} type
  26001. * @param {*} CoordinateSystem
  26002. */
  26003. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  26004. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  26005. }
  26006. /**
  26007. * Get dimensions of specified coordinate system.
  26008. * @param {string} type
  26009. * @return {Array.<string|Object>}
  26010. */
  26011. function getCoordinateSystemDimensions(type) {
  26012. var coordSysCreator = CoordinateSystemManager.get(type);
  26013. if (coordSysCreator) {
  26014. return coordSysCreator.getDimensionsInfo
  26015. ? coordSysCreator.getDimensionsInfo()
  26016. : coordSysCreator.dimensions.slice();
  26017. }
  26018. }
  26019. /**
  26020. * Layout is a special stage of visual encoding
  26021. * Most visual encoding like color are common for different chart
  26022. * But each chart has it's own layout algorithm
  26023. *
  26024. * @param {number} [priority=1000]
  26025. * @param {Function} layoutTask
  26026. */
  26027. function registerLayout(priority, layoutTask) {
  26028. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26029. }
  26030. /**
  26031. * @param {number} [priority=3000]
  26032. * @param {module:echarts/stream/Task} visualTask
  26033. */
  26034. function registerVisual(priority, visualTask) {
  26035. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26036. }
  26037. /**
  26038. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  26039. */
  26040. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26041. if (isFunction(priority) || isObject(priority)) {
  26042. fn = priority;
  26043. priority = defaultPriority;
  26044. }
  26045. if (__DEV__) {
  26046. if (isNaN(priority) || priority == null) {
  26047. throw new Error('Illegal priority');
  26048. }
  26049. // Check duplicate
  26050. each(targetList, function (wrap) {
  26051. assert(wrap.__raw !== fn);
  26052. });
  26053. }
  26054. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26055. stageHandler.__prio = priority;
  26056. stageHandler.__raw = fn;
  26057. targetList.push(stageHandler);
  26058. return stageHandler;
  26059. }
  26060. /**
  26061. * @param {string} name
  26062. */
  26063. function registerLoading(name, loadingFx) {
  26064. loadingEffects[name] = loadingFx;
  26065. }
  26066. /**
  26067. * @param {Object} opts
  26068. * @param {string} [superClass]
  26069. */
  26070. function extendComponentModel(opts/*, superClass*/) {
  26071. // var Clazz = ComponentModel;
  26072. // if (superClass) {
  26073. // var classType = parseClassType(superClass);
  26074. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26075. // }
  26076. return ComponentModel.extend(opts);
  26077. }
  26078. /**
  26079. * @param {Object} opts
  26080. * @param {string} [superClass]
  26081. */
  26082. function extendComponentView(opts/*, superClass*/) {
  26083. // var Clazz = ComponentView;
  26084. // if (superClass) {
  26085. // var classType = parseClassType(superClass);
  26086. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26087. // }
  26088. return Component$1.extend(opts);
  26089. }
  26090. /**
  26091. * @param {Object} opts
  26092. * @param {string} [superClass]
  26093. */
  26094. function extendSeriesModel(opts/*, superClass*/) {
  26095. // var Clazz = SeriesModel;
  26096. // if (superClass) {
  26097. // superClass = 'series.' + superClass.replace('series.', '');
  26098. // var classType = parseClassType(superClass);
  26099. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26100. // }
  26101. return SeriesModel.extend(opts);
  26102. }
  26103. /**
  26104. * @param {Object} opts
  26105. * @param {string} [superClass]
  26106. */
  26107. function extendChartView(opts/*, superClass*/) {
  26108. // var Clazz = ChartView;
  26109. // if (superClass) {
  26110. // superClass = superClass.replace('series.', '');
  26111. // var classType = parseClassType(superClass);
  26112. // Clazz = ChartView.getClass(classType.main, true);
  26113. // }
  26114. return Chart.extend(opts);
  26115. }
  26116. /**
  26117. * ZRender need a canvas context to do measureText.
  26118. * But in node environment canvas may be created by node-canvas.
  26119. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26120. *
  26121. * Be careful of using it in the browser.
  26122. *
  26123. * @param {Function} creator
  26124. * @example
  26125. * var Canvas = require('canvas');
  26126. * var echarts = require('echarts');
  26127. * echarts.setCanvasCreator(function () {
  26128. * // Small size is enough.
  26129. * return new Canvas(32, 32);
  26130. * });
  26131. */
  26132. function setCanvasCreator(creator) {
  26133. $override('createCanvas', creator);
  26134. }
  26135. /**
  26136. * @param {string} mapName
  26137. * @param {Array.<Object>|Object|string} geoJson
  26138. * @param {Object} [specialAreas]
  26139. *
  26140. * @example GeoJSON
  26141. * $.get('USA.json', function (geoJson) {
  26142. * echarts.registerMap('USA', geoJson);
  26143. * // Or
  26144. * echarts.registerMap('USA', {
  26145. * geoJson: geoJson,
  26146. * specialAreas: {}
  26147. * })
  26148. * });
  26149. *
  26150. * $.get('airport.svg', function (svg) {
  26151. * echarts.registerMap('airport', {
  26152. * svg: svg
  26153. * }
  26154. * });
  26155. *
  26156. * echarts.registerMap('eu', [
  26157. * {svg: eu-topographic.svg},
  26158. * {geoJSON: eu.json}
  26159. * ])
  26160. */
  26161. function registerMap(mapName, geoJson, specialAreas) {
  26162. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26163. }
  26164. /**
  26165. * @param {string} mapName
  26166. * @return {Object}
  26167. */
  26168. function getMap(mapName) {
  26169. // For backward compatibility, only return the first one.
  26170. var records = mapDataStorage.retrieveMap(mapName);
  26171. return records && records[0] && {
  26172. geoJson: records[0].geoJSON,
  26173. specialAreas: records[0].specialAreas
  26174. };
  26175. }
  26176. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26177. registerPreprocessor(backwardCompat);
  26178. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26179. registerLoading('default', loadingDefault);
  26180. // Default actions
  26181. registerAction({
  26182. type: 'highlight',
  26183. event: 'highlight',
  26184. update: 'highlight'
  26185. }, noop);
  26186. registerAction({
  26187. type: 'downplay',
  26188. event: 'downplay',
  26189. update: 'downplay'
  26190. }, noop);
  26191. // Default theme
  26192. registerTheme('light', lightTheme);
  26193. registerTheme('dark', theme);
  26194. // For backward compatibility, where the namespace `dataTool` will
  26195. // be mounted on `echarts` is the extension `dataTool` is imported.
  26196. var dataTool = {};
  26197. /*
  26198. * Licensed to the Apache Software Foundation (ASF) under one
  26199. * or more contributor license agreements. See the NOTICE file
  26200. * distributed with this work for additional information
  26201. * regarding copyright ownership. The ASF licenses this file
  26202. * to you under the Apache License, Version 2.0 (the
  26203. * "License"); you may not use this file except in compliance
  26204. * with the License. You may obtain a copy of the License at
  26205. *
  26206. * http://www.apache.org/licenses/LICENSE-2.0
  26207. *
  26208. * Unless required by applicable law or agreed to in writing,
  26209. * software distributed under the License is distributed on an
  26210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26211. * KIND, either express or implied. See the License for the
  26212. * specific language governing permissions and limitations
  26213. * under the License.
  26214. */
  26215. function defaultKeyGetter(item) {
  26216. return item;
  26217. }
  26218. /**
  26219. * @param {Array} oldArr
  26220. * @param {Array} newArr
  26221. * @param {Function} oldKeyGetter
  26222. * @param {Function} newKeyGetter
  26223. * @param {Object} [context] Can be visited by this.context in callback.
  26224. */
  26225. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26226. this._old = oldArr;
  26227. this._new = newArr;
  26228. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26229. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26230. this.context = context;
  26231. }
  26232. DataDiffer.prototype = {
  26233. constructor: DataDiffer,
  26234. /**
  26235. * Callback function when add a data
  26236. */
  26237. add: function (func) {
  26238. this._add = func;
  26239. return this;
  26240. },
  26241. /**
  26242. * Callback function when update a data
  26243. */
  26244. update: function (func) {
  26245. this._update = func;
  26246. return this;
  26247. },
  26248. /**
  26249. * Callback function when remove a data
  26250. */
  26251. remove: function (func) {
  26252. this._remove = func;
  26253. return this;
  26254. },
  26255. execute: function () {
  26256. var oldArr = this._old;
  26257. var newArr = this._new;
  26258. var oldDataIndexMap = {};
  26259. var newDataIndexMap = {};
  26260. var oldDataKeyArr = [];
  26261. var newDataKeyArr = [];
  26262. var i;
  26263. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26264. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26265. for (i = 0; i < oldArr.length; i++) {
  26266. var key = oldDataKeyArr[i];
  26267. var idx = newDataIndexMap[key];
  26268. // idx can never be empty array here. see 'set null' logic below.
  26269. if (idx != null) {
  26270. // Consider there is duplicate key (for example, use dataItem.name as key).
  26271. // We should make sure every item in newArr and oldArr can be visited.
  26272. var len = idx.length;
  26273. if (len) {
  26274. len === 1 && (newDataIndexMap[key] = null);
  26275. idx = idx.shift();
  26276. }
  26277. else {
  26278. newDataIndexMap[key] = null;
  26279. }
  26280. this._update && this._update(idx, i);
  26281. }
  26282. else {
  26283. this._remove && this._remove(i);
  26284. }
  26285. }
  26286. for (var i = 0; i < newDataKeyArr.length; i++) {
  26287. var key = newDataKeyArr[i];
  26288. if (newDataIndexMap.hasOwnProperty(key)) {
  26289. var idx = newDataIndexMap[key];
  26290. if (idx == null) {
  26291. continue;
  26292. }
  26293. // idx can never be empty array here. see 'set null' logic above.
  26294. if (!idx.length) {
  26295. this._add && this._add(idx);
  26296. }
  26297. else {
  26298. for (var j = 0, len = idx.length; j < len; j++) {
  26299. this._add && this._add(idx[j]);
  26300. }
  26301. }
  26302. }
  26303. }
  26304. }
  26305. };
  26306. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26307. for (var i = 0; i < arr.length; i++) {
  26308. // Add prefix to avoid conflict with Object.prototype.
  26309. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26310. var existence = map[key];
  26311. if (existence == null) {
  26312. keyArr.push(key);
  26313. map[key] = i;
  26314. }
  26315. else {
  26316. if (!existence.length) {
  26317. map[key] = existence = [existence];
  26318. }
  26319. existence.push(i);
  26320. }
  26321. }
  26322. }
  26323. /*
  26324. * Licensed to the Apache Software Foundation (ASF) under one
  26325. * or more contributor license agreements. See the NOTICE file
  26326. * distributed with this work for additional information
  26327. * regarding copyright ownership. The ASF licenses this file
  26328. * to you under the Apache License, Version 2.0 (the
  26329. * "License"); you may not use this file except in compliance
  26330. * with the License. You may obtain a copy of the License at
  26331. *
  26332. * http://www.apache.org/licenses/LICENSE-2.0
  26333. *
  26334. * Unless required by applicable law or agreed to in writing,
  26335. * software distributed under the License is distributed on an
  26336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26337. * KIND, either express or implied. See the License for the
  26338. * specific language governing permissions and limitations
  26339. * under the License.
  26340. */
  26341. var OTHER_DIMENSIONS = createHashMap([
  26342. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26343. ]);
  26344. function summarizeDimensions(data) {
  26345. var summary = {};
  26346. var encode = summary.encode = {};
  26347. var notExtraCoordDimMap = createHashMap();
  26348. var defaultedLabel = [];
  26349. var defaultedTooltip = [];
  26350. // See the comment of `List.js#userOutput`.
  26351. var userOutput = summary.userOutput = {
  26352. dimensionNames: data.dimensions.slice(),
  26353. encode: {}
  26354. };
  26355. each$1(data.dimensions, function (dimName) {
  26356. var dimItem = data.getDimensionInfo(dimName);
  26357. var coordDim = dimItem.coordDim;
  26358. if (coordDim) {
  26359. if (__DEV__) {
  26360. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26361. }
  26362. var coordDimIndex = dimItem.coordDimIndex;
  26363. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26364. if (!dimItem.isExtraCoord) {
  26365. notExtraCoordDimMap.set(coordDim, 1);
  26366. // Use the last coord dim (and label friendly) as default label,
  26367. // because when dataset is used, it is hard to guess which dimension
  26368. // can be value dimension. If both show x, y on label is not look good,
  26369. // and conventionally y axis is focused more.
  26370. if (mayLabelDimType(dimItem.type)) {
  26371. defaultedLabel[0] = dimName;
  26372. }
  26373. // User output encode do not contain generated coords.
  26374. // And it only has index. User can use index to retrieve value from the raw item array.
  26375. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26376. }
  26377. if (dimItem.defaultTooltip) {
  26378. defaultedTooltip.push(dimName);
  26379. }
  26380. }
  26381. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26382. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26383. var dimIndex = dimItem.otherDims[otherDim];
  26384. if (dimIndex != null && dimIndex !== false) {
  26385. encodeArr[dimIndex] = dimItem.name;
  26386. }
  26387. });
  26388. });
  26389. var dataDimsOnCoord = [];
  26390. var encodeFirstDimNotExtra = {};
  26391. notExtraCoordDimMap.each(function (v, coordDim) {
  26392. var dimArr = encode[coordDim];
  26393. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26394. // But should fix the case that radar axes: simplify the logic
  26395. // of `completeDimension`, remove `extraPrefix`.
  26396. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26397. // Not necessary to remove duplicate, because a data
  26398. // dim canot on more than one coordDim.
  26399. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26400. });
  26401. summary.dataDimsOnCoord = dataDimsOnCoord;
  26402. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26403. var encodeLabel = encode.label;
  26404. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26405. // in this way. Use label.formatter instead. May be remove this approach someday.
  26406. if (encodeLabel && encodeLabel.length) {
  26407. defaultedLabel = encodeLabel.slice();
  26408. }
  26409. var encodeTooltip = encode.tooltip;
  26410. if (encodeTooltip && encodeTooltip.length) {
  26411. defaultedTooltip = encodeTooltip.slice();
  26412. }
  26413. else if (!defaultedTooltip.length) {
  26414. defaultedTooltip = defaultedLabel.slice();
  26415. }
  26416. encode.defaultedLabel = defaultedLabel;
  26417. encode.defaultedTooltip = defaultedTooltip;
  26418. return summary;
  26419. }
  26420. function getOrCreateEncodeArr(encode, dim) {
  26421. if (!encode.hasOwnProperty(dim)) {
  26422. encode[dim] = [];
  26423. }
  26424. return encode[dim];
  26425. }
  26426. function getDimensionTypeByAxis(axisType) {
  26427. return axisType === 'category'
  26428. ? 'ordinal'
  26429. : axisType === 'time'
  26430. ? 'time'
  26431. : 'float';
  26432. }
  26433. function mayLabelDimType(dimType) {
  26434. // In most cases, ordinal and time do not suitable for label.
  26435. // Ordinal info can be displayed on axis. Time is too long.
  26436. return !(dimType === 'ordinal' || dimType === 'time');
  26437. }
  26438. // function findTheLastDimMayLabel(data) {
  26439. // // Get last value dim
  26440. // var dimensions = data.dimensions.slice();
  26441. // var valueType;
  26442. // var valueDim;
  26443. // while (dimensions.length && (
  26444. // valueDim = dimensions.pop(),
  26445. // valueType = data.getDimensionInfo(valueDim).type,
  26446. // valueType === 'ordinal' || valueType === 'time'
  26447. // )) {} // jshint ignore:line
  26448. // return valueDim;
  26449. // }
  26450. /*
  26451. * Licensed to the Apache Software Foundation (ASF) under one
  26452. * or more contributor license agreements. See the NOTICE file
  26453. * distributed with this work for additional information
  26454. * regarding copyright ownership. The ASF licenses this file
  26455. * to you under the Apache License, Version 2.0 (the
  26456. * "License"); you may not use this file except in compliance
  26457. * with the License. You may obtain a copy of the License at
  26458. *
  26459. * http://www.apache.org/licenses/LICENSE-2.0
  26460. *
  26461. * Unless required by applicable law or agreed to in writing,
  26462. * software distributed under the License is distributed on an
  26463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26464. * KIND, either express or implied. See the License for the
  26465. * specific language governing permissions and limitations
  26466. * under the License.
  26467. */
  26468. /**
  26469. * @class
  26470. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26471. */
  26472. function DataDimensionInfo(opt) {
  26473. if (opt != null) {
  26474. extend(this, opt);
  26475. }
  26476. /**
  26477. * Dimension name.
  26478. * Mandatory.
  26479. * @type {string}
  26480. */
  26481. // this.name;
  26482. /**
  26483. * The origin name in dimsDef, see source helper.
  26484. * If displayName given, the tooltip will displayed vertically.
  26485. * Optional.
  26486. * @type {string}
  26487. */
  26488. // this.displayName;
  26489. /**
  26490. * Which coordSys dimension this dimension mapped to.
  26491. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26492. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26493. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26494. * (That is determined by whether `isExtraCoord` is `true`).
  26495. * Mandatory.
  26496. * @type {string}
  26497. */
  26498. // this.coordDim;
  26499. /**
  26500. * The index of this dimension in `series.encode[coordDim]`.
  26501. * Mandatory.
  26502. * @type {number}
  26503. */
  26504. // this.coordDimIndex;
  26505. /**
  26506. * Dimension type. The enumerable values are the key of
  26507. * `dataCtors` of `data/List`.
  26508. * Optional.
  26509. * @type {string}
  26510. */
  26511. // this.type;
  26512. /**
  26513. * This index of this dimension info in `data/List#_dimensionInfos`.
  26514. * Mandatory after added to `data/List`.
  26515. * @type {number}
  26516. */
  26517. // this.index;
  26518. /**
  26519. * The format of `otherDims` is:
  26520. * ```js
  26521. * {
  26522. * tooltip: number optional,
  26523. * label: number optional,
  26524. * itemName: number optional,
  26525. * seriesName: number optional,
  26526. * }
  26527. * ```
  26528. *
  26529. * A `series.encode` can specified these fields:
  26530. * ```js
  26531. * encode: {
  26532. * // "3, 1, 5" is the index of data dimension.
  26533. * tooltip: [3, 1, 5],
  26534. * label: [0, 3],
  26535. * ...
  26536. * }
  26537. * ```
  26538. * `otherDims` is the parse result of the `series.encode` above, like:
  26539. * ```js
  26540. * // Suppose the index of this data dimension is `3`.
  26541. * this.otherDims = {
  26542. * // `3` is at the index `0` of the `encode.tooltip`
  26543. * tooltip: 0,
  26544. * // `3` is at the index `1` of the `encode.tooltip`
  26545. * label: 1
  26546. * };
  26547. * ```
  26548. *
  26549. * This prop should never be `null`/`undefined` after initialized.
  26550. * @type {Object}
  26551. */
  26552. this.otherDims = {};
  26553. /**
  26554. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26555. * "coordSys" required.
  26556. * Mandatory.
  26557. * @type {boolean}
  26558. */
  26559. // this.isExtraCoord;
  26560. /**
  26561. * @type {module:data/OrdinalMeta}
  26562. */
  26563. // this.ordinalMeta;
  26564. /**
  26565. * Whether to create inverted indices.
  26566. * @type {boolean}
  26567. */
  26568. // this.createInvertedIndices;
  26569. }
  26570. /*
  26571. * Licensed to the Apache Software Foundation (ASF) under one
  26572. * or more contributor license agreements. See the NOTICE file
  26573. * distributed with this work for additional information
  26574. * regarding copyright ownership. The ASF licenses this file
  26575. * to you under the Apache License, Version 2.0 (the
  26576. * "License"); you may not use this file except in compliance
  26577. * with the License. You may obtain a copy of the License at
  26578. *
  26579. * http://www.apache.org/licenses/LICENSE-2.0
  26580. *
  26581. * Unless required by applicable law or agreed to in writing,
  26582. * software distributed under the License is distributed on an
  26583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26584. * KIND, either express or implied. See the License for the
  26585. * specific language governing permissions and limitations
  26586. * under the License.
  26587. */
  26588. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26589. /**
  26590. * List for data storage
  26591. * @module echarts/data/List
  26592. */
  26593. var isObject$4 = isObject$1;
  26594. var UNDEFINED = 'undefined';
  26595. var INDEX_NOT_FOUND = -1;
  26596. // Use prefix to avoid index to be the same as otherIdList[idx],
  26597. // which will cause weird udpate animation.
  26598. var ID_PREFIX = 'e\0\0';
  26599. var dataCtors = {
  26600. 'float': typeof Float64Array === UNDEFINED
  26601. ? Array : Float64Array,
  26602. 'int': typeof Int32Array === UNDEFINED
  26603. ? Array : Int32Array,
  26604. // Ordinal data type can be string or int
  26605. 'ordinal': Array,
  26606. 'number': Array,
  26607. 'time': Array
  26608. };
  26609. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26610. // different from the Ctor of typed array.
  26611. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26612. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26613. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26614. function getIndicesCtor(list) {
  26615. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26616. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26617. }
  26618. function cloneChunk(originalChunk) {
  26619. var Ctor = originalChunk.constructor;
  26620. // Only shallow clone is enough when Array.
  26621. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26622. }
  26623. var TRANSFERABLE_PROPERTIES = [
  26624. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26625. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26626. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26627. ];
  26628. var CLONE_PROPERTIES = [
  26629. '_extent', '_approximateExtent', '_rawExtent'
  26630. ];
  26631. function transferProperties(target, source) {
  26632. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26633. if (source.hasOwnProperty(propName)) {
  26634. target[propName] = source[propName];
  26635. }
  26636. });
  26637. target.__wrappedMethods = source.__wrappedMethods;
  26638. each$1(CLONE_PROPERTIES, function (propName) {
  26639. target[propName] = clone(source[propName]);
  26640. });
  26641. target._calculationInfo = extend(source._calculationInfo);
  26642. }
  26643. /**
  26644. * @constructor
  26645. * @alias module:echarts/data/List
  26646. *
  26647. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26648. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26649. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26650. * @param {module:echarts/model/Model} hostModel
  26651. */
  26652. var List = function (dimensions, hostModel) {
  26653. dimensions = dimensions || ['x', 'y'];
  26654. var dimensionInfos = {};
  26655. var dimensionNames = [];
  26656. var invertedIndicesMap = {};
  26657. for (var i = 0; i < dimensions.length; i++) {
  26658. // Use the original dimensions[i], where other flag props may exists.
  26659. var dimensionInfo = dimensions[i];
  26660. if (isString(dimensionInfo)) {
  26661. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26662. }
  26663. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26664. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26665. }
  26666. var dimensionName = dimensionInfo.name;
  26667. dimensionInfo.type = dimensionInfo.type || 'float';
  26668. if (!dimensionInfo.coordDim) {
  26669. dimensionInfo.coordDim = dimensionName;
  26670. dimensionInfo.coordDimIndex = 0;
  26671. }
  26672. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26673. dimensionNames.push(dimensionName);
  26674. dimensionInfos[dimensionName] = dimensionInfo;
  26675. dimensionInfo.index = i;
  26676. if (dimensionInfo.createInvertedIndices) {
  26677. invertedIndicesMap[dimensionName] = [];
  26678. }
  26679. }
  26680. /**
  26681. * @readOnly
  26682. * @type {Array.<string>}
  26683. */
  26684. this.dimensions = dimensionNames;
  26685. /**
  26686. * Infomation of each data dimension, like data type.
  26687. * @type {Object}
  26688. */
  26689. this._dimensionInfos = dimensionInfos;
  26690. /**
  26691. * @type {module:echarts/model/Model}
  26692. */
  26693. this.hostModel = hostModel;
  26694. /**
  26695. * @type {module:echarts/model/Model}
  26696. */
  26697. this.dataType;
  26698. /**
  26699. * Indices stores the indices of data subset after filtered.
  26700. * This data subset will be used in chart.
  26701. * @type {Array.<number>}
  26702. * @readOnly
  26703. */
  26704. this._indices = null;
  26705. this._count = 0;
  26706. this._rawCount = 0;
  26707. /**
  26708. * Data storage
  26709. * @type {Object.<key, Array.<TypedArray|Array>>}
  26710. * @private
  26711. */
  26712. this._storage = {};
  26713. /**
  26714. * @type {Array.<string>}
  26715. */
  26716. this._nameList = [];
  26717. /**
  26718. * @type {Array.<string>}
  26719. */
  26720. this._idList = [];
  26721. /**
  26722. * Models of data option is stored sparse for optimizing memory cost
  26723. * @type {Array.<module:echarts/model/Model>}
  26724. * @private
  26725. */
  26726. this._optionModels = [];
  26727. /**
  26728. * Global visual properties after visual coding
  26729. * @type {Object}
  26730. * @private
  26731. */
  26732. this._visual = {};
  26733. /**
  26734. * Globel layout properties.
  26735. * @type {Object}
  26736. * @private
  26737. */
  26738. this._layout = {};
  26739. /**
  26740. * Item visual properties after visual coding
  26741. * @type {Array.<Object>}
  26742. * @private
  26743. */
  26744. this._itemVisuals = [];
  26745. /**
  26746. * Key: visual type, Value: boolean
  26747. * @type {Object}
  26748. * @readOnly
  26749. */
  26750. this.hasItemVisual = {};
  26751. /**
  26752. * Item layout properties after layout
  26753. * @type {Array.<Object>}
  26754. * @private
  26755. */
  26756. this._itemLayouts = [];
  26757. /**
  26758. * Graphic elemnents
  26759. * @type {Array.<module:zrender/Element>}
  26760. * @private
  26761. */
  26762. this._graphicEls = [];
  26763. /**
  26764. * Max size of each chunk.
  26765. * @type {number}
  26766. * @private
  26767. */
  26768. this._chunkSize = 1e5;
  26769. /**
  26770. * @type {number}
  26771. * @private
  26772. */
  26773. this._chunkCount = 0;
  26774. /**
  26775. * @type {Array.<Array|Object>}
  26776. * @private
  26777. */
  26778. this._rawData;
  26779. /**
  26780. * Raw extent will not be cloned, but only transfered.
  26781. * It will not be calculated util needed.
  26782. * key: dim,
  26783. * value: {end: number, extent: Array.<number>}
  26784. * @type {Object}
  26785. * @private
  26786. */
  26787. this._rawExtent = {};
  26788. /**
  26789. * @type {Object}
  26790. * @private
  26791. */
  26792. this._extent = {};
  26793. /**
  26794. * key: dim
  26795. * value: extent
  26796. * @type {Object}
  26797. * @private
  26798. */
  26799. this._approximateExtent = {};
  26800. /**
  26801. * Cache summary info for fast visit. See "dimensionHelper".
  26802. * @type {Object}
  26803. * @private
  26804. */
  26805. this._dimensionsSummary = summarizeDimensions(this);
  26806. /**
  26807. * @type {Object.<Array|TypedArray>}
  26808. * @private
  26809. */
  26810. this._invertedIndicesMap = invertedIndicesMap;
  26811. /**
  26812. * @type {Object}
  26813. * @private
  26814. */
  26815. this._calculationInfo = {};
  26816. /**
  26817. * User output info of this data.
  26818. * DO NOT use it in other places!
  26819. *
  26820. * When preparing user params for user callbacks, we have
  26821. * to clone these inner data structures to prevent users
  26822. * from modifying them to effect built-in logic. And for
  26823. * performance consideration we make this `userOutput` to
  26824. * avoid clone them too many times.
  26825. *
  26826. * @type {Object}
  26827. * @readOnly
  26828. */
  26829. this.userOutput = this._dimensionsSummary.userOutput;
  26830. };
  26831. var listProto = List.prototype;
  26832. listProto.type = 'list';
  26833. /**
  26834. * If each data item has it's own option
  26835. * @type {boolean}
  26836. */
  26837. listProto.hasItemOption = true;
  26838. /**
  26839. * The meanings of the input parameter `dim`:
  26840. *
  26841. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26842. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26843. * + If dim is a number-like string (e.g., `"1"`):
  26844. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26845. * + If not, it will be converted to a number, which means the index of the dimension.
  26846. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26847. * dimension setting, although now it seems that it is not a good idea.)
  26848. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26849. * if no dimension name is defined as `"1"`.
  26850. * + If dim is a not-number-like string, it means the concrete dim name.
  26851. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26852. * or customized in `dimensions` property of option like `"age"`.
  26853. *
  26854. * Get dimension name
  26855. * @param {string|number} dim See above.
  26856. * @return {string} Concrete dim name.
  26857. */
  26858. listProto.getDimension = function (dim) {
  26859. if (typeof dim === 'number'
  26860. // If being a number-like string but not being defined a dimension name.
  26861. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26862. ) {
  26863. dim = this.dimensions[dim];
  26864. }
  26865. return dim;
  26866. };
  26867. /**
  26868. * Get type and calculation info of particular dimension
  26869. * @param {string|number} dim
  26870. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26871. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26872. */
  26873. listProto.getDimensionInfo = function (dim) {
  26874. // Do not clone, because there may be categories in dimInfo.
  26875. return this._dimensionInfos[this.getDimension(dim)];
  26876. };
  26877. /**
  26878. * @return {Array.<string>} concrete dimension name list on coord.
  26879. */
  26880. listProto.getDimensionsOnCoord = function () {
  26881. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26882. };
  26883. /**
  26884. * @param {string} coordDim
  26885. * @param {number} [idx] A coordDim may map to more than one data dim.
  26886. * If idx is `true`, return a array of all mapped dims.
  26887. * If idx is not specified, return the first dim not extra.
  26888. * @return {string|Array.<string>} concrete data dim.
  26889. * If idx is number, and not found, return null/undefined.
  26890. * If idx is `true`, and not found, return empty array (always return array).
  26891. */
  26892. listProto.mapDimension = function (coordDim, idx) {
  26893. var dimensionsSummary = this._dimensionsSummary;
  26894. if (idx == null) {
  26895. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26896. }
  26897. var dims = dimensionsSummary.encode[coordDim];
  26898. return idx === true
  26899. // always return array if idx is `true`
  26900. ? (dims || []).slice()
  26901. : (dims && dims[idx]);
  26902. };
  26903. /**
  26904. * Initialize from data
  26905. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26906. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26907. * defualt label/tooltip.
  26908. * A name can be specified in encode.itemName,
  26909. * or dataItem.name (only for series option data),
  26910. * or provided in nameList from outside.
  26911. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26912. */
  26913. listProto.initData = function (data, nameList, dimValueGetter) {
  26914. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26915. if (notProvider) {
  26916. data = new DefaultDataProvider(data, this.dimensions.length);
  26917. }
  26918. if (__DEV__) {
  26919. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26920. throw new Error('Inavlid data provider.');
  26921. }
  26922. }
  26923. this._rawData = data;
  26924. // Clear
  26925. this._storage = {};
  26926. this._indices = null;
  26927. this._nameList = nameList || [];
  26928. this._idList = [];
  26929. this._nameRepeatCount = {};
  26930. if (!dimValueGetter) {
  26931. this.hasItemOption = false;
  26932. }
  26933. /**
  26934. * @readOnly
  26935. */
  26936. this.defaultDimValueGetter = defaultDimValueGetters[
  26937. this._rawData.getSource().sourceFormat
  26938. ];
  26939. // Default dim value getter
  26940. this._dimValueGetter = dimValueGetter = dimValueGetter
  26941. || this.defaultDimValueGetter;
  26942. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26943. // Reset raw extent.
  26944. this._rawExtent = {};
  26945. this._initDataFromProvider(0, data.count());
  26946. // If data has no item option.
  26947. if (data.pure) {
  26948. this.hasItemOption = false;
  26949. }
  26950. };
  26951. listProto.getProvider = function () {
  26952. return this._rawData;
  26953. };
  26954. /**
  26955. * Caution: Can be only called on raw data (before `this._indices` created).
  26956. */
  26957. listProto.appendData = function (data) {
  26958. if (__DEV__) {
  26959. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26960. }
  26961. var rawData = this._rawData;
  26962. var start = this.count();
  26963. rawData.appendData(data);
  26964. var end = rawData.count();
  26965. if (!rawData.persistent) {
  26966. end += start;
  26967. }
  26968. this._initDataFromProvider(start, end);
  26969. };
  26970. /**
  26971. * Caution: Can be only called on raw data (before `this._indices` created).
  26972. * This method does not modify `rawData` (`dataProvider`), but only
  26973. * add values to storage.
  26974. *
  26975. * The final count will be increased by `Math.max(values.length, names.length)`.
  26976. *
  26977. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26978. * [
  26979. * [12, 33, 44],
  26980. * [NaN, 43, 1],
  26981. * ['-', 'asdf', 0]
  26982. * ]
  26983. * Each item is exaclty cooresponding to a dimension.
  26984. * @param {Array.<string>} [names]
  26985. */
  26986. listProto.appendValues = function (values, names) {
  26987. var chunkSize = this._chunkSize;
  26988. var storage = this._storage;
  26989. var dimensions = this.dimensions;
  26990. var dimLen = dimensions.length;
  26991. var rawExtent = this._rawExtent;
  26992. var start = this.count();
  26993. var end = start + Math.max(values.length, names ? names.length : 0);
  26994. var originalChunkCount = this._chunkCount;
  26995. for (var i = 0; i < dimLen; i++) {
  26996. var dim = dimensions[i];
  26997. if (!rawExtent[dim]) {
  26998. rawExtent[dim] = getInitialExtent();
  26999. }
  27000. if (!storage[dim]) {
  27001. storage[dim] = [];
  27002. }
  27003. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  27004. this._chunkCount = storage[dim].length;
  27005. }
  27006. var emptyDataItem = new Array(dimLen);
  27007. for (var idx = start; idx < end; idx++) {
  27008. var sourceIdx = idx - start;
  27009. var chunkIndex = Math.floor(idx / chunkSize);
  27010. var chunkOffset = idx % chunkSize;
  27011. // Store the data by dimensions
  27012. for (var k = 0; k < dimLen; k++) {
  27013. var dim = dimensions[k];
  27014. var val = this._dimValueGetterArrayRows(
  27015. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  27016. );
  27017. storage[dim][chunkIndex][chunkOffset] = val;
  27018. var dimRawExtent = rawExtent[dim];
  27019. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27020. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27021. }
  27022. if (names) {
  27023. this._nameList[idx] = names[sourceIdx];
  27024. }
  27025. }
  27026. this._rawCount = this._count = end;
  27027. // Reset data extent
  27028. this._extent = {};
  27029. prepareInvertedIndex(this);
  27030. };
  27031. listProto._initDataFromProvider = function (start, end) {
  27032. // Optimize.
  27033. if (start >= end) {
  27034. return;
  27035. }
  27036. var chunkSize = this._chunkSize;
  27037. var rawData = this._rawData;
  27038. var storage = this._storage;
  27039. var dimensions = this.dimensions;
  27040. var dimLen = dimensions.length;
  27041. var dimensionInfoMap = this._dimensionInfos;
  27042. var nameList = this._nameList;
  27043. var idList = this._idList;
  27044. var rawExtent = this._rawExtent;
  27045. var nameRepeatCount = this._nameRepeatCount = {};
  27046. var nameDimIdx;
  27047. var originalChunkCount = this._chunkCount;
  27048. for (var i = 0; i < dimLen; i++) {
  27049. var dim = dimensions[i];
  27050. if (!rawExtent[dim]) {
  27051. rawExtent[dim] = getInitialExtent();
  27052. }
  27053. var dimInfo = dimensionInfoMap[dim];
  27054. if (dimInfo.otherDims.itemName === 0) {
  27055. nameDimIdx = this._nameDimIdx = i;
  27056. }
  27057. if (dimInfo.otherDims.itemId === 0) {
  27058. this._idDimIdx = i;
  27059. }
  27060. if (!storage[dim]) {
  27061. storage[dim] = [];
  27062. }
  27063. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  27064. this._chunkCount = storage[dim].length;
  27065. }
  27066. var dataItem = new Array(dimLen);
  27067. for (var idx = start; idx < end; idx++) {
  27068. // NOTICE: Try not to write things into dataItem
  27069. dataItem = rawData.getItem(idx, dataItem);
  27070. // Each data item is value
  27071. // [1, 2]
  27072. // 2
  27073. // Bar chart, line chart which uses category axis
  27074. // only gives the 'y' value. 'x' value is the indices of category
  27075. // Use a tempValue to normalize the value to be a (x, y) value
  27076. var chunkIndex = Math.floor(idx / chunkSize);
  27077. var chunkOffset = idx % chunkSize;
  27078. // Store the data by dimensions
  27079. for (var k = 0; k < dimLen; k++) {
  27080. var dim = dimensions[k];
  27081. var dimStorage = storage[dim][chunkIndex];
  27082. // PENDING NULL is empty or zero
  27083. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27084. dimStorage[chunkOffset] = val;
  27085. var dimRawExtent = rawExtent[dim];
  27086. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27087. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27088. }
  27089. // ??? FIXME not check by pure but sourceFormat?
  27090. // TODO refactor these logic.
  27091. if (!rawData.pure) {
  27092. var name = nameList[idx];
  27093. if (dataItem && name == null) {
  27094. // If dataItem is {name: ...}, it has highest priority.
  27095. // That is appropriate for many common cases.
  27096. if (dataItem.name != null) {
  27097. // There is no other place to persistent dataItem.name,
  27098. // so save it to nameList.
  27099. nameList[idx] = name = dataItem.name;
  27100. }
  27101. else if (nameDimIdx != null) {
  27102. var nameDim = dimensions[nameDimIdx];
  27103. var nameDimChunk = storage[nameDim][chunkIndex];
  27104. if (nameDimChunk) {
  27105. name = nameDimChunk[chunkOffset];
  27106. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27107. if (ordinalMeta && ordinalMeta.categories.length) {
  27108. name = ordinalMeta.categories[name];
  27109. }
  27110. }
  27111. }
  27112. }
  27113. // Try using the id in option
  27114. // id or name is used on dynamical data, mapping old and new items.
  27115. var id = dataItem == null ? null : dataItem.id;
  27116. if (id == null && name != null) {
  27117. // Use name as id and add counter to avoid same name
  27118. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27119. id = name;
  27120. if (nameRepeatCount[name] > 0) {
  27121. id += '__ec__' + nameRepeatCount[name];
  27122. }
  27123. nameRepeatCount[name]++;
  27124. }
  27125. id != null && (idList[idx] = id);
  27126. }
  27127. }
  27128. if (!rawData.persistent && rawData.clean) {
  27129. // Clean unused data if data source is typed array.
  27130. rawData.clean();
  27131. }
  27132. this._rawCount = this._count = end;
  27133. // Reset data extent
  27134. this._extent = {};
  27135. prepareInvertedIndex(this);
  27136. };
  27137. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27138. var DataCtor = dataCtors[dimInfo.type];
  27139. var lastChunkIndex = chunkCount - 1;
  27140. var dim = dimInfo.name;
  27141. var resizeChunkArray = storage[dim][lastChunkIndex];
  27142. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27143. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27144. // The cost of the copy is probably inconsiderable
  27145. // within the initial chunkSize.
  27146. for (var j = 0; j < resizeChunkArray.length; j++) {
  27147. newStore[j] = resizeChunkArray[j];
  27148. }
  27149. storage[dim][lastChunkIndex] = newStore;
  27150. }
  27151. // Create new chunks.
  27152. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27153. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27154. }
  27155. }
  27156. function prepareInvertedIndex(list) {
  27157. var invertedIndicesMap = list._invertedIndicesMap;
  27158. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27159. var dimInfo = list._dimensionInfos[dim];
  27160. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27161. var ordinalMeta = dimInfo.ordinalMeta;
  27162. if (ordinalMeta) {
  27163. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27164. ordinalMeta.categories.length
  27165. );
  27166. // The default value of TypedArray is 0. To avoid miss
  27167. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27168. for (var i = 0; i < invertedIndices.length; i++) {
  27169. invertedIndices[i] = INDEX_NOT_FOUND;
  27170. }
  27171. for (var i = 0; i < list._count; i++) {
  27172. // Only support the case that all values are distinct.
  27173. invertedIndices[list.get(dim, i)] = i;
  27174. }
  27175. }
  27176. });
  27177. }
  27178. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27179. var val;
  27180. if (dimIndex != null) {
  27181. var chunkSize = list._chunkSize;
  27182. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27183. var chunkOffset = rawIndex % chunkSize;
  27184. var dim = list.dimensions[dimIndex];
  27185. var chunk = list._storage[dim][chunkIndex];
  27186. if (chunk) {
  27187. val = chunk[chunkOffset];
  27188. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27189. if (ordinalMeta && ordinalMeta.categories.length) {
  27190. val = ordinalMeta.categories[val];
  27191. }
  27192. }
  27193. }
  27194. return val;
  27195. }
  27196. /**
  27197. * @return {number}
  27198. */
  27199. listProto.count = function () {
  27200. return this._count;
  27201. };
  27202. listProto.getIndices = function () {
  27203. var newIndices;
  27204. var indices = this._indices;
  27205. if (indices) {
  27206. var Ctor = indices.constructor;
  27207. var thisCount = this._count;
  27208. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27209. if (Ctor === Array) {
  27210. newIndices = new Ctor(thisCount);
  27211. for (var i = 0; i < thisCount; i++) {
  27212. newIndices[i] = indices[i];
  27213. }
  27214. }
  27215. else {
  27216. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27217. }
  27218. }
  27219. else {
  27220. var Ctor = getIndicesCtor(this);
  27221. var newIndices = new Ctor(this.count());
  27222. for (var i = 0; i < newIndices.length; i++) {
  27223. newIndices[i] = i;
  27224. }
  27225. }
  27226. return newIndices;
  27227. };
  27228. /**
  27229. * Get value. Return NaN if idx is out of range.
  27230. * @param {string} dim Dim must be concrete name.
  27231. * @param {number} idx
  27232. * @param {boolean} stack
  27233. * @return {number}
  27234. */
  27235. listProto.get = function (dim, idx /*, stack */) {
  27236. if (!(idx >= 0 && idx < this._count)) {
  27237. return NaN;
  27238. }
  27239. var storage = this._storage;
  27240. if (!storage[dim]) {
  27241. // TODO Warn ?
  27242. return NaN;
  27243. }
  27244. idx = this.getRawIndex(idx);
  27245. var chunkIndex = Math.floor(idx / this._chunkSize);
  27246. var chunkOffset = idx % this._chunkSize;
  27247. var chunkStore = storage[dim][chunkIndex];
  27248. var value = chunkStore[chunkOffset];
  27249. // FIXME ordinal data type is not stackable
  27250. // if (stack) {
  27251. // var dimensionInfo = this._dimensionInfos[dim];
  27252. // if (dimensionInfo && dimensionInfo.stackable) {
  27253. // var stackedOn = this.stackedOn;
  27254. // while (stackedOn) {
  27255. // // Get no stacked data of stacked on
  27256. // var stackedValue = stackedOn.get(dim, idx);
  27257. // // Considering positive stack, negative stack and empty data
  27258. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27259. // || (value <= 0 && stackedValue < 0) // Negative stack
  27260. // ) {
  27261. // value += stackedValue;
  27262. // }
  27263. // stackedOn = stackedOn.stackedOn;
  27264. // }
  27265. // }
  27266. // }
  27267. return value;
  27268. };
  27269. /**
  27270. * @param {string} dim concrete dim
  27271. * @param {number} rawIndex
  27272. * @return {number|string}
  27273. */
  27274. listProto.getByRawIndex = function (dim, rawIdx) {
  27275. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27276. return NaN;
  27277. }
  27278. var dimStore = this._storage[dim];
  27279. if (!dimStore) {
  27280. // TODO Warn ?
  27281. return NaN;
  27282. }
  27283. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27284. var chunkOffset = rawIdx % this._chunkSize;
  27285. var chunkStore = dimStore[chunkIndex];
  27286. return chunkStore[chunkOffset];
  27287. };
  27288. /**
  27289. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27290. * Hack a much simpler _getFast
  27291. * @private
  27292. */
  27293. listProto._getFast = function (dim, rawIdx) {
  27294. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27295. var chunkOffset = rawIdx % this._chunkSize;
  27296. var chunkStore = this._storage[dim][chunkIndex];
  27297. return chunkStore[chunkOffset];
  27298. };
  27299. /**
  27300. * Get value for multi dimensions.
  27301. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27302. * @param {number} idx
  27303. * @return {number}
  27304. */
  27305. listProto.getValues = function (dimensions, idx /*, stack */) {
  27306. var values = [];
  27307. if (!isArray(dimensions)) {
  27308. // stack = idx;
  27309. idx = dimensions;
  27310. dimensions = this.dimensions;
  27311. }
  27312. for (var i = 0, len = dimensions.length; i < len; i++) {
  27313. values.push(this.get(dimensions[i], idx /*, stack */));
  27314. }
  27315. return values;
  27316. };
  27317. /**
  27318. * If value is NaN. Inlcuding '-'
  27319. * Only check the coord dimensions.
  27320. * @param {string} dim
  27321. * @param {number} idx
  27322. * @return {number}
  27323. */
  27324. listProto.hasValue = function (idx) {
  27325. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27326. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27327. // Ordinal type originally can be string or number.
  27328. // But when an ordinal type is used on coord, it can
  27329. // not be string but only number. So we can also use isNaN.
  27330. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27331. return false;
  27332. }
  27333. }
  27334. return true;
  27335. };
  27336. /**
  27337. * Get extent of data in one dimension
  27338. * @param {string} dim
  27339. * @param {boolean} stack
  27340. */
  27341. listProto.getDataExtent = function (dim /*, stack */) {
  27342. // Make sure use concrete dim as cache name.
  27343. dim = this.getDimension(dim);
  27344. var dimData = this._storage[dim];
  27345. var initialExtent = getInitialExtent();
  27346. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27347. if (!dimData) {
  27348. return initialExtent;
  27349. }
  27350. // Make more strict checkings to ensure hitting cache.
  27351. var currEnd = this.count();
  27352. // var cacheName = [dim, !!stack].join('_');
  27353. // var cacheName = dim;
  27354. // Consider the most cases when using data zoom, `getDataExtent`
  27355. // happened before filtering. We cache raw extent, which is not
  27356. // necessary to be cleared and recalculated when restore data.
  27357. var useRaw = !this._indices; // && !stack;
  27358. var dimExtent;
  27359. if (useRaw) {
  27360. return this._rawExtent[dim].slice();
  27361. }
  27362. dimExtent = this._extent[dim];
  27363. if (dimExtent) {
  27364. return dimExtent.slice();
  27365. }
  27366. dimExtent = initialExtent;
  27367. var min = dimExtent[0];
  27368. var max = dimExtent[1];
  27369. for (var i = 0; i < currEnd; i++) {
  27370. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27371. var value = this._getFast(dim, this.getRawIndex(i));
  27372. value < min && (min = value);
  27373. value > max && (max = value);
  27374. }
  27375. dimExtent = [min, max];
  27376. this._extent[dim] = dimExtent;
  27377. return dimExtent;
  27378. };
  27379. /**
  27380. * Optimize for the scenario that data is filtered by a given extent.
  27381. * Consider that if data amount is more than hundreds of thousand,
  27382. * extent calculation will cost more than 10ms and the cache will
  27383. * be erased because of the filtering.
  27384. */
  27385. listProto.getApproximateExtent = function (dim /*, stack */) {
  27386. dim = this.getDimension(dim);
  27387. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27388. };
  27389. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27390. dim = this.getDimension(dim);
  27391. this._approximateExtent[dim] = extent.slice();
  27392. };
  27393. /**
  27394. * @param {string} key
  27395. * @return {*}
  27396. */
  27397. listProto.getCalculationInfo = function (key) {
  27398. return this._calculationInfo[key];
  27399. };
  27400. /**
  27401. * @param {string|Object} key or k-v object
  27402. * @param {*} [value]
  27403. */
  27404. listProto.setCalculationInfo = function (key, value) {
  27405. isObject$4(key)
  27406. ? extend(this._calculationInfo, key)
  27407. : (this._calculationInfo[key] = value);
  27408. };
  27409. /**
  27410. * Get sum of data in one dimension
  27411. * @param {string} dim
  27412. */
  27413. listProto.getSum = function (dim /*, stack */) {
  27414. var dimData = this._storage[dim];
  27415. var sum = 0;
  27416. if (dimData) {
  27417. for (var i = 0, len = this.count(); i < len; i++) {
  27418. var value = this.get(dim, i /*, stack */);
  27419. if (!isNaN(value)) {
  27420. sum += value;
  27421. }
  27422. }
  27423. }
  27424. return sum;
  27425. };
  27426. /**
  27427. * Get median of data in one dimension
  27428. * @param {string} dim
  27429. */
  27430. listProto.getMedian = function (dim /*, stack */) {
  27431. var dimDataArray = [];
  27432. // map all data of one dimension
  27433. this.each(dim, function (val, idx) {
  27434. if (!isNaN(val)) {
  27435. dimDataArray.push(val);
  27436. }
  27437. });
  27438. // TODO
  27439. // Use quick select?
  27440. // immutability & sort
  27441. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27442. return a - b;
  27443. });
  27444. var len = this.count();
  27445. // calculate median
  27446. return len === 0
  27447. ? 0
  27448. : len % 2 === 1
  27449. ? sortedDimDataArray[(len - 1) / 2]
  27450. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27451. };
  27452. // /**
  27453. // * Retreive the index with given value
  27454. // * @param {string} dim Concrete dimension.
  27455. // * @param {number} value
  27456. // * @return {number}
  27457. // */
  27458. // Currently incorrect: should return dataIndex but not rawIndex.
  27459. // Do not fix it until this method is to be used somewhere.
  27460. // FIXME Precision of float value
  27461. // listProto.indexOf = function (dim, value) {
  27462. // var storage = this._storage;
  27463. // var dimData = storage[dim];
  27464. // var chunkSize = this._chunkSize;
  27465. // if (dimData) {
  27466. // for (var i = 0, len = this.count(); i < len; i++) {
  27467. // var chunkIndex = Math.floor(i / chunkSize);
  27468. // var chunkOffset = i % chunkSize;
  27469. // if (dimData[chunkIndex][chunkOffset] === value) {
  27470. // return i;
  27471. // }
  27472. // }
  27473. // }
  27474. // return -1;
  27475. // };
  27476. /**
  27477. * Only support the dimension which inverted index created.
  27478. * Do not support other cases until required.
  27479. * @param {string} concrete dim
  27480. * @param {number|string} value
  27481. * @return {number} rawIndex
  27482. */
  27483. listProto.rawIndexOf = function (dim, value) {
  27484. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27485. if (__DEV__) {
  27486. if (!invertedIndices) {
  27487. throw new Error('Do not supported yet');
  27488. }
  27489. }
  27490. var rawIndex = invertedIndices[value];
  27491. if (rawIndex == null || isNaN(rawIndex)) {
  27492. return INDEX_NOT_FOUND;
  27493. }
  27494. return rawIndex;
  27495. };
  27496. /**
  27497. * Retreive the index with given name
  27498. * @param {number} idx
  27499. * @param {number} name
  27500. * @return {number}
  27501. */
  27502. listProto.indexOfName = function (name) {
  27503. for (var i = 0, len = this.count(); i < len; i++) {
  27504. if (this.getName(i) === name) {
  27505. return i;
  27506. }
  27507. }
  27508. return -1;
  27509. };
  27510. /**
  27511. * Retreive the index with given raw data index
  27512. * @param {number} idx
  27513. * @param {number} name
  27514. * @return {number}
  27515. */
  27516. listProto.indexOfRawIndex = function (rawIndex) {
  27517. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27518. return -1;
  27519. }
  27520. if (!this._indices) {
  27521. return rawIndex;
  27522. }
  27523. // Indices are ascending
  27524. var indices = this._indices;
  27525. // If rawIndex === dataIndex
  27526. var rawDataIndex = indices[rawIndex];
  27527. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27528. return rawIndex;
  27529. }
  27530. var left = 0;
  27531. var right = this._count - 1;
  27532. while (left <= right) {
  27533. var mid = (left + right) / 2 | 0;
  27534. if (indices[mid] < rawIndex) {
  27535. left = mid + 1;
  27536. }
  27537. else if (indices[mid] > rawIndex) {
  27538. right = mid - 1;
  27539. }
  27540. else {
  27541. return mid;
  27542. }
  27543. }
  27544. return -1;
  27545. };
  27546. /**
  27547. * Retreive the index of nearest value
  27548. * @param {string} dim
  27549. * @param {number} value
  27550. * @param {number} [maxDistance=Infinity]
  27551. * @return {Array.<number>} If and only if multiple indices has
  27552. * the same value, they are put to the result.
  27553. */
  27554. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27555. var storage = this._storage;
  27556. var dimData = storage[dim];
  27557. var nearestIndices = [];
  27558. if (!dimData) {
  27559. return nearestIndices;
  27560. }
  27561. if (maxDistance == null) {
  27562. maxDistance = Infinity;
  27563. }
  27564. var minDist = Infinity;
  27565. var minDiff = -1;
  27566. var nearestIndicesLen = 0;
  27567. // Check the test case of `test/ut/spec/data/List.js`.
  27568. for (var i = 0, len = this.count(); i < len; i++) {
  27569. var diff = value - this.get(dim, i);
  27570. var dist = Math.abs(diff);
  27571. if (dist <= maxDistance) {
  27572. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27573. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27574. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27575. // So we chose the one that `diff >= 0` in this csae.
  27576. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27577. // should be push to `nearestIndices`.
  27578. if (dist < minDist
  27579. || (dist === minDist && diff >= 0 && minDiff < 0)
  27580. ) {
  27581. minDist = dist;
  27582. minDiff = diff;
  27583. nearestIndicesLen = 0;
  27584. }
  27585. if (diff === minDiff) {
  27586. nearestIndices[nearestIndicesLen++] = i;
  27587. }
  27588. }
  27589. }
  27590. nearestIndices.length = nearestIndicesLen;
  27591. return nearestIndices;
  27592. };
  27593. /**
  27594. * Get raw data index
  27595. * @param {number} idx
  27596. * @return {number}
  27597. */
  27598. listProto.getRawIndex = getRawIndexWithoutIndices;
  27599. function getRawIndexWithoutIndices(idx) {
  27600. return idx;
  27601. }
  27602. function getRawIndexWithIndices(idx) {
  27603. if (idx < this._count && idx >= 0) {
  27604. return this._indices[idx];
  27605. }
  27606. return -1;
  27607. }
  27608. /**
  27609. * Get raw data item
  27610. * @param {number} idx
  27611. * @return {number}
  27612. */
  27613. listProto.getRawDataItem = function (idx) {
  27614. if (!this._rawData.persistent) {
  27615. var val = [];
  27616. for (var i = 0; i < this.dimensions.length; i++) {
  27617. var dim = this.dimensions[i];
  27618. val.push(this.get(dim, idx));
  27619. }
  27620. return val;
  27621. }
  27622. else {
  27623. return this._rawData.getItem(this.getRawIndex(idx));
  27624. }
  27625. };
  27626. /**
  27627. * @param {number} idx
  27628. * @param {boolean} [notDefaultIdx=false]
  27629. * @return {string}
  27630. */
  27631. listProto.getName = function (idx) {
  27632. var rawIndex = this.getRawIndex(idx);
  27633. return this._nameList[rawIndex]
  27634. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27635. || '';
  27636. };
  27637. /**
  27638. * @param {number} idx
  27639. * @param {boolean} [notDefaultIdx=false]
  27640. * @return {string}
  27641. */
  27642. listProto.getId = function (idx) {
  27643. return getId(this, this.getRawIndex(idx));
  27644. };
  27645. function getId(list, rawIndex) {
  27646. var id = list._idList[rawIndex];
  27647. if (id == null) {
  27648. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27649. }
  27650. if (id == null) {
  27651. // FIXME Check the usage in graph, should not use prefix.
  27652. id = ID_PREFIX + rawIndex;
  27653. }
  27654. return id;
  27655. }
  27656. function normalizeDimensions(dimensions) {
  27657. if (!isArray(dimensions)) {
  27658. dimensions = [dimensions];
  27659. }
  27660. return dimensions;
  27661. }
  27662. function validateDimensions(list, dims) {
  27663. for (var i = 0; i < dims.length; i++) {
  27664. // stroage may be empty when no data, so use
  27665. // dimensionInfos to check.
  27666. if (!list._dimensionInfos[dims[i]]) {
  27667. console.error('Unkown dimension ' + dims[i]);
  27668. }
  27669. }
  27670. }
  27671. /**
  27672. * Data iteration
  27673. * @param {string|Array.<string>}
  27674. * @param {Function} cb
  27675. * @param {*} [context=this]
  27676. *
  27677. * @example
  27678. * list.each('x', function (x, idx) {});
  27679. * list.each(['x', 'y'], function (x, y, idx) {});
  27680. * list.each(function (idx) {})
  27681. */
  27682. listProto.each = function (dims, cb, context, contextCompat) {
  27683. 'use strict';
  27684. if (!this._count) {
  27685. return;
  27686. }
  27687. if (typeof dims === 'function') {
  27688. contextCompat = context;
  27689. context = cb;
  27690. cb = dims;
  27691. dims = [];
  27692. }
  27693. // contextCompat just for compat echarts3
  27694. context = context || contextCompat || this;
  27695. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27696. if (__DEV__) {
  27697. validateDimensions(this, dims);
  27698. }
  27699. var dimSize = dims.length;
  27700. for (var i = 0; i < this.count(); i++) {
  27701. // Simple optimization
  27702. switch (dimSize) {
  27703. case 0:
  27704. cb.call(context, i);
  27705. break;
  27706. case 1:
  27707. cb.call(context, this.get(dims[0], i), i);
  27708. break;
  27709. case 2:
  27710. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27711. break;
  27712. default:
  27713. var k = 0;
  27714. var value = [];
  27715. for (; k < dimSize; k++) {
  27716. value[k] = this.get(dims[k], i);
  27717. }
  27718. // Index
  27719. value[k] = i;
  27720. cb.apply(context, value);
  27721. }
  27722. }
  27723. };
  27724. /**
  27725. * Data filter
  27726. * @param {string|Array.<string>}
  27727. * @param {Function} cb
  27728. * @param {*} [context=this]
  27729. */
  27730. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27731. 'use strict';
  27732. if (!this._count) {
  27733. return;
  27734. }
  27735. if (typeof dimensions === 'function') {
  27736. contextCompat = context;
  27737. context = cb;
  27738. cb = dimensions;
  27739. dimensions = [];
  27740. }
  27741. // contextCompat just for compat echarts3
  27742. context = context || contextCompat || this;
  27743. dimensions = map(
  27744. normalizeDimensions(dimensions), this.getDimension, this
  27745. );
  27746. if (__DEV__) {
  27747. validateDimensions(this, dimensions);
  27748. }
  27749. var count = this.count();
  27750. var Ctor = getIndicesCtor(this);
  27751. var newIndices = new Ctor(count);
  27752. var value = [];
  27753. var dimSize = dimensions.length;
  27754. var offset = 0;
  27755. var dim0 = dimensions[0];
  27756. for (var i = 0; i < count; i++) {
  27757. var keep;
  27758. var rawIdx = this.getRawIndex(i);
  27759. // Simple optimization
  27760. if (dimSize === 0) {
  27761. keep = cb.call(context, i);
  27762. }
  27763. else if (dimSize === 1) {
  27764. var val = this._getFast(dim0, rawIdx);
  27765. keep = cb.call(context, val, i);
  27766. }
  27767. else {
  27768. for (var k = 0; k < dimSize; k++) {
  27769. value[k] = this._getFast(dim0, rawIdx);
  27770. }
  27771. value[k] = i;
  27772. keep = cb.apply(context, value);
  27773. }
  27774. if (keep) {
  27775. newIndices[offset++] = rawIdx;
  27776. }
  27777. }
  27778. // Set indices after filtered.
  27779. if (offset < count) {
  27780. this._indices = newIndices;
  27781. }
  27782. this._count = offset;
  27783. // Reset data extent
  27784. this._extent = {};
  27785. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27786. return this;
  27787. };
  27788. /**
  27789. * Select data in range. (For optimization of filter)
  27790. * (Manually inline code, support 5 million data filtering in data zoom.)
  27791. */
  27792. listProto.selectRange = function (range) {
  27793. 'use strict';
  27794. if (!this._count) {
  27795. return;
  27796. }
  27797. var dimensions = [];
  27798. for (var dim in range) {
  27799. if (range.hasOwnProperty(dim)) {
  27800. dimensions.push(dim);
  27801. }
  27802. }
  27803. if (__DEV__) {
  27804. validateDimensions(this, dimensions);
  27805. }
  27806. var dimSize = dimensions.length;
  27807. if (!dimSize) {
  27808. return;
  27809. }
  27810. var originalCount = this.count();
  27811. var Ctor = getIndicesCtor(this);
  27812. var newIndices = new Ctor(originalCount);
  27813. var offset = 0;
  27814. var dim0 = dimensions[0];
  27815. var min = range[dim0][0];
  27816. var max = range[dim0][1];
  27817. var quickFinished = false;
  27818. if (!this._indices) {
  27819. // Extreme optimization for common case. About 2x faster in chrome.
  27820. var idx = 0;
  27821. if (dimSize === 1) {
  27822. var dimStorage = this._storage[dimensions[0]];
  27823. for (var k = 0; k < this._chunkCount; k++) {
  27824. var chunkStorage = dimStorage[k];
  27825. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27826. for (var i = 0; i < len; i++) {
  27827. var val = chunkStorage[i];
  27828. // NaN will not be filtered. Consider the case, in line chart, empty
  27829. // value indicates the line should be broken. But for the case like
  27830. // scatter plot, a data item with empty value will not be rendered,
  27831. // but the axis extent may be effected if some other dim of the data
  27832. // item has value. Fortunately it is not a significant negative effect.
  27833. if (
  27834. (val >= min && val <= max) || isNaN(val)
  27835. ) {
  27836. newIndices[offset++] = idx;
  27837. }
  27838. idx++;
  27839. }
  27840. }
  27841. quickFinished = true;
  27842. }
  27843. else if (dimSize === 2) {
  27844. var dimStorage = this._storage[dim0];
  27845. var dimStorage2 = this._storage[dimensions[1]];
  27846. var min2 = range[dimensions[1]][0];
  27847. var max2 = range[dimensions[1]][1];
  27848. for (var k = 0; k < this._chunkCount; k++) {
  27849. var chunkStorage = dimStorage[k];
  27850. var chunkStorage2 = dimStorage2[k];
  27851. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27852. for (var i = 0; i < len; i++) {
  27853. var val = chunkStorage[i];
  27854. var val2 = chunkStorage2[i];
  27855. // Do not filter NaN, see comment above.
  27856. if ((
  27857. (val >= min && val <= max) || isNaN(val)
  27858. )
  27859. && (
  27860. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27861. )
  27862. ) {
  27863. newIndices[offset++] = idx;
  27864. }
  27865. idx++;
  27866. }
  27867. }
  27868. quickFinished = true;
  27869. }
  27870. }
  27871. if (!quickFinished) {
  27872. if (dimSize === 1) {
  27873. for (var i = 0; i < originalCount; i++) {
  27874. var rawIndex = this.getRawIndex(i);
  27875. var val = this._getFast(dim0, rawIndex);
  27876. // Do not filter NaN, see comment above.
  27877. if (
  27878. (val >= min && val <= max) || isNaN(val)
  27879. ) {
  27880. newIndices[offset++] = rawIndex;
  27881. }
  27882. }
  27883. }
  27884. else {
  27885. for (var i = 0; i < originalCount; i++) {
  27886. var keep = true;
  27887. var rawIndex = this.getRawIndex(i);
  27888. for (var k = 0; k < dimSize; k++) {
  27889. var dimk = dimensions[k];
  27890. var val = this._getFast(dim, rawIndex);
  27891. // Do not filter NaN, see comment above.
  27892. if (val < range[dimk][0] || val > range[dimk][1]) {
  27893. keep = false;
  27894. }
  27895. }
  27896. if (keep) {
  27897. newIndices[offset++] = this.getRawIndex(i);
  27898. }
  27899. }
  27900. }
  27901. }
  27902. // Set indices after filtered.
  27903. if (offset < originalCount) {
  27904. this._indices = newIndices;
  27905. }
  27906. this._count = offset;
  27907. // Reset data extent
  27908. this._extent = {};
  27909. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27910. return this;
  27911. };
  27912. /**
  27913. * Data mapping to a plain array
  27914. * @param {string|Array.<string>} [dimensions]
  27915. * @param {Function} cb
  27916. * @param {*} [context=this]
  27917. * @return {Array}
  27918. */
  27919. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27920. 'use strict';
  27921. if (typeof dimensions === 'function') {
  27922. contextCompat = context;
  27923. context = cb;
  27924. cb = dimensions;
  27925. dimensions = [];
  27926. }
  27927. // contextCompat just for compat echarts3
  27928. context = context || contextCompat || this;
  27929. var result = [];
  27930. this.each(dimensions, function () {
  27931. result.push(cb && cb.apply(this, arguments));
  27932. }, context);
  27933. return result;
  27934. };
  27935. // Data in excludeDimensions is copied, otherwise transfered.
  27936. function cloneListForMapAndSample(original, excludeDimensions) {
  27937. var allDimensions = original.dimensions;
  27938. var list = new List(
  27939. map(allDimensions, original.getDimensionInfo, original),
  27940. original.hostModel
  27941. );
  27942. // FIXME If needs stackedOn, value may already been stacked
  27943. transferProperties(list, original);
  27944. var storage = list._storage = {};
  27945. var originalStorage = original._storage;
  27946. // Init storage
  27947. for (var i = 0; i < allDimensions.length; i++) {
  27948. var dim = allDimensions[i];
  27949. if (originalStorage[dim]) {
  27950. // Notice that we do not reset invertedIndicesMap here, becuase
  27951. // there is no scenario of mapping or sampling ordinal dimension.
  27952. if (indexOf(excludeDimensions, dim) >= 0) {
  27953. storage[dim] = cloneDimStore(originalStorage[dim]);
  27954. list._rawExtent[dim] = getInitialExtent();
  27955. list._extent[dim] = null;
  27956. }
  27957. else {
  27958. // Direct reference for other dimensions
  27959. storage[dim] = originalStorage[dim];
  27960. }
  27961. }
  27962. }
  27963. return list;
  27964. }
  27965. function cloneDimStore(originalDimStore) {
  27966. var newDimStore = new Array(originalDimStore.length);
  27967. for (var j = 0; j < originalDimStore.length; j++) {
  27968. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27969. }
  27970. return newDimStore;
  27971. }
  27972. function getInitialExtent() {
  27973. return [Infinity, -Infinity];
  27974. }
  27975. /**
  27976. * Data mapping to a new List with given dimensions
  27977. * @param {string|Array.<string>} dimensions
  27978. * @param {Function} cb
  27979. * @param {*} [context=this]
  27980. * @return {Array}
  27981. */
  27982. listProto.map = function (dimensions, cb, context, contextCompat) {
  27983. 'use strict';
  27984. // contextCompat just for compat echarts3
  27985. context = context || contextCompat || this;
  27986. dimensions = map(
  27987. normalizeDimensions(dimensions), this.getDimension, this
  27988. );
  27989. if (__DEV__) {
  27990. validateDimensions(this, dimensions);
  27991. }
  27992. var list = cloneListForMapAndSample(this, dimensions);
  27993. // Following properties are all immutable.
  27994. // So we can reference to the same value
  27995. list._indices = this._indices;
  27996. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27997. var storage = list._storage;
  27998. var tmpRetValue = [];
  27999. var chunkSize = this._chunkSize;
  28000. var dimSize = dimensions.length;
  28001. var dataCount = this.count();
  28002. var values = [];
  28003. var rawExtent = list._rawExtent;
  28004. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28005. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28006. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  28007. }
  28008. values[dimSize] = dataIndex;
  28009. var retValue = cb && cb.apply(context, values);
  28010. if (retValue != null) {
  28011. // a number or string (in oridinal dimension)?
  28012. if (typeof retValue !== 'object') {
  28013. tmpRetValue[0] = retValue;
  28014. retValue = tmpRetValue;
  28015. }
  28016. var rawIndex = this.getRawIndex(dataIndex);
  28017. var chunkIndex = Math.floor(rawIndex / chunkSize);
  28018. var chunkOffset = rawIndex % chunkSize;
  28019. for (var i = 0; i < retValue.length; i++) {
  28020. var dim = dimensions[i];
  28021. var val = retValue[i];
  28022. var rawExtentOnDim = rawExtent[dim];
  28023. var dimStore = storage[dim];
  28024. if (dimStore) {
  28025. dimStore[chunkIndex][chunkOffset] = val;
  28026. }
  28027. if (val < rawExtentOnDim[0]) {
  28028. rawExtentOnDim[0] = val;
  28029. }
  28030. if (val > rawExtentOnDim[1]) {
  28031. rawExtentOnDim[1] = val;
  28032. }
  28033. }
  28034. }
  28035. }
  28036. return list;
  28037. };
  28038. /**
  28039. * Large data down sampling on given dimension
  28040. * @param {string} dimension
  28041. * @param {number} rate
  28042. * @param {Function} sampleValue
  28043. * @param {Function} sampleIndex Sample index for name and id
  28044. */
  28045. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28046. var list = cloneListForMapAndSample(this, [dimension]);
  28047. var targetStorage = list._storage;
  28048. var frameValues = [];
  28049. var frameSize = Math.floor(1 / rate);
  28050. var dimStore = targetStorage[dimension];
  28051. var len = this.count();
  28052. var chunkSize = this._chunkSize;
  28053. var rawExtentOnDim = list._rawExtent[dimension];
  28054. var newIndices = new (getIndicesCtor(this))(len);
  28055. var offset = 0;
  28056. for (var i = 0; i < len; i += frameSize) {
  28057. // Last frame
  28058. if (frameSize > len - i) {
  28059. frameSize = len - i;
  28060. frameValues.length = frameSize;
  28061. }
  28062. for (var k = 0; k < frameSize; k++) {
  28063. var dataIdx = this.getRawIndex(i + k);
  28064. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  28065. var originalChunkOffset = dataIdx % chunkSize;
  28066. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  28067. }
  28068. var value = sampleValue(frameValues);
  28069. var sampleFrameIdx = this.getRawIndex(
  28070. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  28071. );
  28072. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  28073. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28074. // Only write value on the filtered data
  28075. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28076. if (value < rawExtentOnDim[0]) {
  28077. rawExtentOnDim[0] = value;
  28078. }
  28079. if (value > rawExtentOnDim[1]) {
  28080. rawExtentOnDim[1] = value;
  28081. }
  28082. newIndices[offset++] = sampleFrameIdx;
  28083. }
  28084. list._count = offset;
  28085. list._indices = newIndices;
  28086. list.getRawIndex = getRawIndexWithIndices;
  28087. return list;
  28088. };
  28089. /**
  28090. * Get model of one data item.
  28091. *
  28092. * @param {number} idx
  28093. */
  28094. // FIXME Model proxy ?
  28095. listProto.getItemModel = function (idx) {
  28096. var hostModel = this.hostModel;
  28097. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28098. };
  28099. /**
  28100. * Create a data differ
  28101. * @param {module:echarts/data/List} otherList
  28102. * @return {module:echarts/data/DataDiffer}
  28103. */
  28104. listProto.diff = function (otherList) {
  28105. var thisList = this;
  28106. return new DataDiffer(
  28107. otherList ? otherList.getIndices() : [],
  28108. this.getIndices(),
  28109. function (idx) {
  28110. return getId(otherList, idx);
  28111. },
  28112. function (idx) {
  28113. return getId(thisList, idx);
  28114. }
  28115. );
  28116. };
  28117. /**
  28118. * Get visual property.
  28119. * @param {string} key
  28120. */
  28121. listProto.getVisual = function (key) {
  28122. var visual = this._visual;
  28123. return visual && visual[key];
  28124. };
  28125. /**
  28126. * Set visual property
  28127. * @param {string|Object} key
  28128. * @param {*} [value]
  28129. *
  28130. * @example
  28131. * setVisual('color', color);
  28132. * setVisual({
  28133. * 'color': color
  28134. * });
  28135. */
  28136. listProto.setVisual = function (key, val) {
  28137. if (isObject$4(key)) {
  28138. for (var name in key) {
  28139. if (key.hasOwnProperty(name)) {
  28140. this.setVisual(name, key[name]);
  28141. }
  28142. }
  28143. return;
  28144. }
  28145. this._visual = this._visual || {};
  28146. this._visual[key] = val;
  28147. };
  28148. /**
  28149. * Set layout property.
  28150. * @param {string|Object} key
  28151. * @param {*} [val]
  28152. */
  28153. listProto.setLayout = function (key, val) {
  28154. if (isObject$4(key)) {
  28155. for (var name in key) {
  28156. if (key.hasOwnProperty(name)) {
  28157. this.setLayout(name, key[name]);
  28158. }
  28159. }
  28160. return;
  28161. }
  28162. this._layout[key] = val;
  28163. };
  28164. /**
  28165. * Get layout property.
  28166. * @param {string} key.
  28167. * @return {*}
  28168. */
  28169. listProto.getLayout = function (key) {
  28170. return this._layout[key];
  28171. };
  28172. /**
  28173. * Get layout of single data item
  28174. * @param {number} idx
  28175. */
  28176. listProto.getItemLayout = function (idx) {
  28177. return this._itemLayouts[idx];
  28178. };
  28179. /**
  28180. * Set layout of single data item
  28181. * @param {number} idx
  28182. * @param {Object} layout
  28183. * @param {boolean=} [merge=false]
  28184. */
  28185. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28186. this._itemLayouts[idx] = merge$$1
  28187. ? extend(this._itemLayouts[idx] || {}, layout)
  28188. : layout;
  28189. };
  28190. /**
  28191. * Clear all layout of single data item
  28192. */
  28193. listProto.clearItemLayouts = function () {
  28194. this._itemLayouts.length = 0;
  28195. };
  28196. /**
  28197. * Get visual property of single data item
  28198. * @param {number} idx
  28199. * @param {string} key
  28200. * @param {boolean} [ignoreParent=false]
  28201. */
  28202. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28203. var itemVisual = this._itemVisuals[idx];
  28204. var val = itemVisual && itemVisual[key];
  28205. if (val == null && !ignoreParent) {
  28206. // Use global visual property
  28207. return this.getVisual(key);
  28208. }
  28209. return val;
  28210. };
  28211. /**
  28212. * Set visual property of single data item
  28213. *
  28214. * @param {number} idx
  28215. * @param {string|Object} key
  28216. * @param {*} [value]
  28217. *
  28218. * @example
  28219. * setItemVisual(0, 'color', color);
  28220. * setItemVisual(0, {
  28221. * 'color': color
  28222. * });
  28223. */
  28224. listProto.setItemVisual = function (idx, key, value) {
  28225. var itemVisual = this._itemVisuals[idx] || {};
  28226. var hasItemVisual = this.hasItemVisual;
  28227. this._itemVisuals[idx] = itemVisual;
  28228. if (isObject$4(key)) {
  28229. for (var name in key) {
  28230. if (key.hasOwnProperty(name)) {
  28231. itemVisual[name] = key[name];
  28232. hasItemVisual[name] = true;
  28233. }
  28234. }
  28235. return;
  28236. }
  28237. itemVisual[key] = value;
  28238. hasItemVisual[key] = true;
  28239. };
  28240. /**
  28241. * Clear itemVisuals and list visual.
  28242. */
  28243. listProto.clearAllVisual = function () {
  28244. this._visual = {};
  28245. this._itemVisuals = [];
  28246. this.hasItemVisual = {};
  28247. };
  28248. var setItemDataAndSeriesIndex = function (child) {
  28249. child.seriesIndex = this.seriesIndex;
  28250. child.dataIndex = this.dataIndex;
  28251. child.dataType = this.dataType;
  28252. };
  28253. /**
  28254. * Set graphic element relative to data. It can be set as null
  28255. * @param {number} idx
  28256. * @param {module:zrender/Element} [el]
  28257. */
  28258. listProto.setItemGraphicEl = function (idx, el) {
  28259. var hostModel = this.hostModel;
  28260. if (el) {
  28261. // Add data index and series index for indexing the data by element
  28262. // Useful in tooltip
  28263. el.dataIndex = idx;
  28264. el.dataType = this.dataType;
  28265. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28266. if (el.type === 'group') {
  28267. el.traverse(setItemDataAndSeriesIndex, el);
  28268. }
  28269. }
  28270. this._graphicEls[idx] = el;
  28271. };
  28272. /**
  28273. * @param {number} idx
  28274. * @return {module:zrender/Element}
  28275. */
  28276. listProto.getItemGraphicEl = function (idx) {
  28277. return this._graphicEls[idx];
  28278. };
  28279. /**
  28280. * @param {Function} cb
  28281. * @param {*} context
  28282. */
  28283. listProto.eachItemGraphicEl = function (cb, context) {
  28284. each$1(this._graphicEls, function (el, idx) {
  28285. if (el) {
  28286. cb && cb.call(context, el, idx);
  28287. }
  28288. });
  28289. };
  28290. /**
  28291. * Shallow clone a new list except visual and layout properties, and graph elements.
  28292. * New list only change the indices.
  28293. */
  28294. listProto.cloneShallow = function (list) {
  28295. if (!list) {
  28296. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28297. list = new List(dimensionInfoList, this.hostModel);
  28298. }
  28299. // FIXME
  28300. list._storage = this._storage;
  28301. transferProperties(list, this);
  28302. // Clone will not change the data extent and indices
  28303. if (this._indices) {
  28304. var Ctor = this._indices.constructor;
  28305. list._indices = new Ctor(this._indices);
  28306. }
  28307. else {
  28308. list._indices = null;
  28309. }
  28310. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28311. return list;
  28312. };
  28313. /**
  28314. * Wrap some method to add more feature
  28315. * @param {string} methodName
  28316. * @param {Function} injectFunction
  28317. */
  28318. listProto.wrapMethod = function (methodName, injectFunction) {
  28319. var originalMethod = this[methodName];
  28320. if (typeof originalMethod !== 'function') {
  28321. return;
  28322. }
  28323. this.__wrappedMethods = this.__wrappedMethods || [];
  28324. this.__wrappedMethods.push(methodName);
  28325. this[methodName] = function () {
  28326. var res = originalMethod.apply(this, arguments);
  28327. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28328. };
  28329. };
  28330. // Methods that create a new list based on this list should be listed here.
  28331. // Notice that those method should `RETURN` the new list.
  28332. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28333. // Methods that change indices of this list should be listed here.
  28334. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28335. /*
  28336. * Licensed to the Apache Software Foundation (ASF) under one
  28337. * or more contributor license agreements. See the NOTICE file
  28338. * distributed with this work for additional information
  28339. * regarding copyright ownership. The ASF licenses this file
  28340. * to you under the Apache License, Version 2.0 (the
  28341. * "License"); you may not use this file except in compliance
  28342. * with the License. You may obtain a copy of the License at
  28343. *
  28344. * http://www.apache.org/licenses/LICENSE-2.0
  28345. *
  28346. * Unless required by applicable law or agreed to in writing,
  28347. * software distributed under the License is distributed on an
  28348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28349. * KIND, either express or implied. See the License for the
  28350. * specific language governing permissions and limitations
  28351. * under the License.
  28352. */
  28353. /**
  28354. * @deprecated
  28355. * Use `echarts/data/helper/createDimensions` instead.
  28356. */
  28357. /**
  28358. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28359. *
  28360. * This method builds the relationship between:
  28361. * + "what the coord sys or series requires (see `sysDims`)",
  28362. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28363. * + "what the data source provids (see `source`)".
  28364. *
  28365. * Some guess strategy will be adapted if user does not define something.
  28366. * If no 'value' dimension specified, the first no-named dimension will be
  28367. * named as 'value'.
  28368. *
  28369. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28370. * provides not only dim template, but also default order.
  28371. * properties: 'name', 'type', 'displayName'.
  28372. * `name` of each item provides default coord name.
  28373. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28374. * provide dims count that the sysDim required.
  28375. * [{ordinalMeta}] can be specified.
  28376. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28377. * @param {Object} [opt]
  28378. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28379. * For example: ['asdf', {name, type}, ...].
  28380. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28381. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28382. * If not specified, auto find the next available data dim.
  28383. * param source {module:data/Source}
  28384. * param dimCount {number}
  28385. * return {Object} encode Never be `null/undefined`.
  28386. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28387. * If not specified, extra dim names will be:
  28388. * 'value', 'value0', 'value1', ...
  28389. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28390. * If `generateCoordCount` specified, the generated dim names will be:
  28391. * `generateCoord` + 0, `generateCoord` + 1, ...
  28392. * can be Infinity, indicate that use all of the remain columns.
  28393. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28394. * @return {Array.<module:data/DataDimensionInfo>}
  28395. */
  28396. function completeDimensions(sysDims, source, opt) {
  28397. if (!Source.isInstance(source)) {
  28398. source = Source.seriesDataToSource(source);
  28399. }
  28400. opt = opt || {};
  28401. sysDims = (sysDims || []).slice();
  28402. var dimsDef = (opt.dimsDef || []).slice();
  28403. var dataDimNameMap = createHashMap();
  28404. var coordDimNameMap = createHashMap();
  28405. // var valueCandidate;
  28406. var result = [];
  28407. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28408. // Apply user defined dims (`name` and `type`) and init result.
  28409. for (var i = 0; i < dimCount; i++) {
  28410. var dimDefItem = dimsDef[i] = extend(
  28411. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28412. );
  28413. var userDimName = dimDefItem.name;
  28414. var resultItem = result[i] = new DataDimensionInfo();
  28415. // Name will be applied later for avoiding duplication.
  28416. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28417. // Only if `series.dimensions` is defined in option
  28418. // displayName, will be set, and dimension will be diplayed vertically in
  28419. // tooltip by default.
  28420. resultItem.name = resultItem.displayName = userDimName;
  28421. dataDimNameMap.set(userDimName, i);
  28422. }
  28423. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28424. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28425. }
  28426. var encodeDef = opt.encodeDef;
  28427. if (!encodeDef && opt.encodeDefaulter) {
  28428. encodeDef = opt.encodeDefaulter(source, dimCount);
  28429. }
  28430. encodeDef = createHashMap(encodeDef);
  28431. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28432. encodeDef.each(function (dataDims, coordDim) {
  28433. dataDims = normalizeToArray(dataDims).slice();
  28434. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28435. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28436. // this case.
  28437. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28438. encodeDef.set(coordDim, false);
  28439. return;
  28440. }
  28441. var validDataDims = encodeDef.set(coordDim, []);
  28442. each$1(dataDims, function (resultDimIdx, idx) {
  28443. // The input resultDimIdx can be dim name or index.
  28444. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28445. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28446. validDataDims[idx] = resultDimIdx;
  28447. applyDim(result[resultDimIdx], coordDim, idx);
  28448. }
  28449. });
  28450. });
  28451. // Apply templetes and default order from `sysDims`.
  28452. var availDimIdx = 0;
  28453. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28454. var coordDim;
  28455. var sysDimItem;
  28456. var sysDimItemDimsDef;
  28457. var sysDimItemOtherDims;
  28458. if (isString(sysDimItem)) {
  28459. coordDim = sysDimItem;
  28460. sysDimItem = {};
  28461. }
  28462. else {
  28463. coordDim = sysDimItem.name;
  28464. var ordinalMeta = sysDimItem.ordinalMeta;
  28465. sysDimItem.ordinalMeta = null;
  28466. sysDimItem = clone(sysDimItem);
  28467. sysDimItem.ordinalMeta = ordinalMeta;
  28468. // `coordDimIndex` should not be set directly.
  28469. sysDimItemDimsDef = sysDimItem.dimsDef;
  28470. sysDimItemOtherDims = sysDimItem.otherDims;
  28471. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28472. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28473. }
  28474. var dataDims = encodeDef.get(coordDim);
  28475. // negative resultDimIdx means no need to mapping.
  28476. if (dataDims === false) {
  28477. return;
  28478. }
  28479. var dataDims = normalizeToArray(dataDims);
  28480. // dimensions provides default dim sequences.
  28481. if (!dataDims.length) {
  28482. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28483. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28484. availDimIdx++;
  28485. }
  28486. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28487. }
  28488. }
  28489. // Apply templates.
  28490. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28491. var resultItem = result[resultDimIdx];
  28492. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28493. if (resultItem.name == null && sysDimItemDimsDef) {
  28494. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28495. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28496. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28497. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28498. }
  28499. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28500. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28501. });
  28502. });
  28503. function applyDim(resultItem, coordDim, coordDimIndex) {
  28504. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28505. resultItem.otherDims[coordDim] = coordDimIndex;
  28506. }
  28507. else {
  28508. resultItem.coordDim = coordDim;
  28509. resultItem.coordDimIndex = coordDimIndex;
  28510. coordDimNameMap.set(coordDim, true);
  28511. }
  28512. }
  28513. // Make sure the first extra dim is 'value'.
  28514. var generateCoord = opt.generateCoord;
  28515. var generateCoordCount = opt.generateCoordCount;
  28516. var fromZero = generateCoordCount != null;
  28517. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28518. var extra = generateCoord || 'value';
  28519. // Set dim `name` and other `coordDim` and other props.
  28520. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28521. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28522. var coordDim = resultItem.coordDim;
  28523. if (coordDim == null) {
  28524. resultItem.coordDim = genName(
  28525. extra, coordDimNameMap, fromZero
  28526. );
  28527. resultItem.coordDimIndex = 0;
  28528. if (!generateCoord || generateCoordCount <= 0) {
  28529. resultItem.isExtraCoord = true;
  28530. }
  28531. generateCoordCount--;
  28532. }
  28533. resultItem.name == null && (resultItem.name = genName(
  28534. resultItem.coordDim,
  28535. dataDimNameMap
  28536. ));
  28537. if (resultItem.type == null
  28538. && (
  28539. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28540. // Consider the case:
  28541. // {
  28542. // dataset: {source: [
  28543. // ['2001', 123],
  28544. // ['2002', 456],
  28545. // ...
  28546. // ['The others', 987],
  28547. // ]},
  28548. // series: {type: 'pie'}
  28549. // }
  28550. // The first colum should better be treated as a "ordinal" although it
  28551. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28552. || (resultItem.isExtraCoord
  28553. && (resultItem.otherDims.itemName != null
  28554. || resultItem.otherDims.seriesName != null
  28555. )
  28556. )
  28557. )
  28558. ) {
  28559. resultItem.type = 'ordinal';
  28560. }
  28561. }
  28562. return result;
  28563. }
  28564. // ??? TODO
  28565. // Originally detect dimCount by data[0]. Should we
  28566. // optimize it to only by sysDims and dimensions and encode.
  28567. // So only necessary dims will be initialized.
  28568. // But
  28569. // (1) custom series should be considered. where other dims
  28570. // may be visited.
  28571. // (2) sometimes user need to calcualte bubble size or use visualMap
  28572. // on other dimensions besides coordSys needed.
  28573. // So, dims that is not used by system, should be shared in storage?
  28574. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28575. // Note that the result dimCount should not small than columns count
  28576. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28577. var dimCount = Math.max(
  28578. source.dimensionsDetectCount || 1,
  28579. sysDims.length,
  28580. dimsDef.length,
  28581. optDimCount || 0
  28582. );
  28583. each$1(sysDims, function (sysDimItem) {
  28584. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28585. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28586. });
  28587. return dimCount;
  28588. }
  28589. function genName(name, map$$1, fromZero) {
  28590. if (fromZero || map$$1.get(name) != null) {
  28591. var i = 0;
  28592. while (map$$1.get(name + i) != null) {
  28593. i++;
  28594. }
  28595. name += i;
  28596. }
  28597. map$$1.set(name, true);
  28598. return name;
  28599. }
  28600. /*
  28601. * Licensed to the Apache Software Foundation (ASF) under one
  28602. * or more contributor license agreements. See the NOTICE file
  28603. * distributed with this work for additional information
  28604. * regarding copyright ownership. The ASF licenses this file
  28605. * to you under the Apache License, Version 2.0 (the
  28606. * "License"); you may not use this file except in compliance
  28607. * with the License. You may obtain a copy of the License at
  28608. *
  28609. * http://www.apache.org/licenses/LICENSE-2.0
  28610. *
  28611. * Unless required by applicable law or agreed to in writing,
  28612. * software distributed under the License is distributed on an
  28613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28614. * KIND, either express or implied. See the License for the
  28615. * specific language governing permissions and limitations
  28616. * under the License.
  28617. */
  28618. /**
  28619. * Substitute `completeDimensions`.
  28620. * `completeDimensions` is to be deprecated.
  28621. */
  28622. /**
  28623. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28624. * @param {Object|Array} [opt]
  28625. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28626. * @param {number} [opt.dimensionsCount]
  28627. * @param {string} [opt.generateCoord]
  28628. * @param {string} [opt.generateCoordCount]
  28629. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28630. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28631. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28632. * @return {Array.<Object>} dimensionsInfo
  28633. */
  28634. var createDimensions = function (source, opt) {
  28635. opt = opt || {};
  28636. return completeDimensions(opt.coordDimensions || [], source, {
  28637. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28638. encodeDef: opt.encodeDefine || source.encodeDefine,
  28639. dimCount: opt.dimensionsCount,
  28640. encodeDefaulter: opt.encodeDefaulter,
  28641. generateCoord: opt.generateCoord,
  28642. generateCoordCount: opt.generateCoordCount
  28643. });
  28644. };
  28645. /*
  28646. * Licensed to the Apache Software Foundation (ASF) under one
  28647. * or more contributor license agreements. See the NOTICE file
  28648. * distributed with this work for additional information
  28649. * regarding copyright ownership. The ASF licenses this file
  28650. * to you under the Apache License, Version 2.0 (the
  28651. * "License"); you may not use this file except in compliance
  28652. * with the License. You may obtain a copy of the License at
  28653. *
  28654. * http://www.apache.org/licenses/LICENSE-2.0
  28655. *
  28656. * Unless required by applicable law or agreed to in writing,
  28657. * software distributed under the License is distributed on an
  28658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28659. * KIND, either express or implied. See the License for the
  28660. * specific language governing permissions and limitations
  28661. * under the License.
  28662. */
  28663. /**
  28664. * Helper for model references.
  28665. * There are many manners to refer axis/coordSys.
  28666. */
  28667. // TODO
  28668. // merge relevant logic to this file?
  28669. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28670. /**
  28671. * @class
  28672. * For example:
  28673. * {
  28674. * coordSysName: 'cartesian2d',
  28675. * coordSysDims: ['x', 'y', ...],
  28676. * axisMap: HashMap({
  28677. * x: xAxisModel,
  28678. * y: yAxisModel
  28679. * }),
  28680. * categoryAxisMap: HashMap({
  28681. * x: xAxisModel,
  28682. * y: undefined
  28683. * }),
  28684. * // The index of the first category axis in `coordSysDims`.
  28685. * // `null/undefined` means no category axis exists.
  28686. * firstCategoryDimIndex: 1,
  28687. * // To replace user specified encode.
  28688. * }
  28689. */
  28690. function CoordSysInfo(coordSysName) {
  28691. /**
  28692. * @type {string}
  28693. */
  28694. this.coordSysName = coordSysName;
  28695. /**
  28696. * @type {Array.<string>}
  28697. */
  28698. this.coordSysDims = [];
  28699. /**
  28700. * @type {module:zrender/core/util#HashMap}
  28701. */
  28702. this.axisMap = createHashMap();
  28703. /**
  28704. * @type {module:zrender/core/util#HashMap}
  28705. */
  28706. this.categoryAxisMap = createHashMap();
  28707. /**
  28708. * @type {number}
  28709. */
  28710. this.firstCategoryDimIndex = null;
  28711. }
  28712. /**
  28713. * @return {module:model/referHelper#CoordSysInfo}
  28714. */
  28715. function getCoordSysInfoBySeries(seriesModel) {
  28716. var coordSysName = seriesModel.get('coordinateSystem');
  28717. var result = new CoordSysInfo(coordSysName);
  28718. var fetch = fetchers[coordSysName];
  28719. if (fetch) {
  28720. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28721. return result;
  28722. }
  28723. }
  28724. var fetchers = {
  28725. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28726. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28727. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28728. if (__DEV__) {
  28729. if (!xAxisModel) {
  28730. throw new Error('xAxis "' + retrieve(
  28731. seriesModel.get('xAxisIndex'),
  28732. seriesModel.get('xAxisId'),
  28733. 0
  28734. ) + '" not found');
  28735. }
  28736. if (!yAxisModel) {
  28737. throw new Error('yAxis "' + retrieve(
  28738. seriesModel.get('xAxisIndex'),
  28739. seriesModel.get('yAxisId'),
  28740. 0
  28741. ) + '" not found');
  28742. }
  28743. }
  28744. result.coordSysDims = ['x', 'y'];
  28745. axisMap.set('x', xAxisModel);
  28746. axisMap.set('y', yAxisModel);
  28747. if (isCategory(xAxisModel)) {
  28748. categoryAxisMap.set('x', xAxisModel);
  28749. result.firstCategoryDimIndex = 0;
  28750. }
  28751. if (isCategory(yAxisModel)) {
  28752. categoryAxisMap.set('y', yAxisModel);
  28753. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28754. }
  28755. },
  28756. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28757. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28758. if (__DEV__) {
  28759. if (!singleAxisModel) {
  28760. throw new Error('singleAxis should be specified.');
  28761. }
  28762. }
  28763. result.coordSysDims = ['single'];
  28764. axisMap.set('single', singleAxisModel);
  28765. if (isCategory(singleAxisModel)) {
  28766. categoryAxisMap.set('single', singleAxisModel);
  28767. result.firstCategoryDimIndex = 0;
  28768. }
  28769. },
  28770. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28771. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28772. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28773. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28774. if (__DEV__) {
  28775. if (!angleAxisModel) {
  28776. throw new Error('angleAxis option not found');
  28777. }
  28778. if (!radiusAxisModel) {
  28779. throw new Error('radiusAxis option not found');
  28780. }
  28781. }
  28782. result.coordSysDims = ['radius', 'angle'];
  28783. axisMap.set('radius', radiusAxisModel);
  28784. axisMap.set('angle', angleAxisModel);
  28785. if (isCategory(radiusAxisModel)) {
  28786. categoryAxisMap.set('radius', radiusAxisModel);
  28787. result.firstCategoryDimIndex = 0;
  28788. }
  28789. if (isCategory(angleAxisModel)) {
  28790. categoryAxisMap.set('angle', angleAxisModel);
  28791. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28792. }
  28793. },
  28794. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28795. result.coordSysDims = ['lng', 'lat'];
  28796. },
  28797. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28798. var ecModel = seriesModel.ecModel;
  28799. var parallelModel = ecModel.getComponent(
  28800. 'parallel', seriesModel.get('parallelIndex')
  28801. );
  28802. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28803. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28804. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28805. var axisDim = coordSysDims[index];
  28806. axisMap.set(axisDim, axisModel);
  28807. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28808. categoryAxisMap.set(axisDim, axisModel);
  28809. result.firstCategoryDimIndex = index;
  28810. }
  28811. });
  28812. }
  28813. };
  28814. function isCategory(axisModel) {
  28815. return axisModel.get('type') === 'category';
  28816. }
  28817. /*
  28818. * Licensed to the Apache Software Foundation (ASF) under one
  28819. * or more contributor license agreements. See the NOTICE file
  28820. * distributed with this work for additional information
  28821. * regarding copyright ownership. The ASF licenses this file
  28822. * to you under the Apache License, Version 2.0 (the
  28823. * "License"); you may not use this file except in compliance
  28824. * with the License. You may obtain a copy of the License at
  28825. *
  28826. * http://www.apache.org/licenses/LICENSE-2.0
  28827. *
  28828. * Unless required by applicable law or agreed to in writing,
  28829. * software distributed under the License is distributed on an
  28830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28831. * KIND, either express or implied. See the License for the
  28832. * specific language governing permissions and limitations
  28833. * under the License.
  28834. */
  28835. /**
  28836. * Note that it is too complicated to support 3d stack by value
  28837. * (have to create two-dimension inverted index), so in 3d case
  28838. * we just support that stacked by index.
  28839. *
  28840. * @param {module:echarts/model/Series} seriesModel
  28841. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28842. * The input dimensionInfoList will be modified.
  28843. * @param {Object} [opt]
  28844. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28845. * @param {boolean} [opt.byIndex=false]
  28846. * @return {Object} calculationInfo
  28847. * {
  28848. * stackedDimension: string
  28849. * stackedByDimension: string
  28850. * isStackedByIndex: boolean
  28851. * stackedOverDimension: string
  28852. * stackResultDimension: string
  28853. * }
  28854. */
  28855. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28856. opt = opt || {};
  28857. var byIndex = opt.byIndex;
  28858. var stackedCoordDimension = opt.stackedCoordDimension;
  28859. // Compatibal: when `stack` is set as '', do not stack.
  28860. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28861. var stackedByDimInfo;
  28862. var stackedDimInfo;
  28863. var stackResultDimension;
  28864. var stackedOverDimension;
  28865. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28866. if (isString(dimensionInfo)) {
  28867. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28868. }
  28869. if (mayStack && !dimensionInfo.isExtraCoord) {
  28870. // Find the first ordinal dimension as the stackedByDimInfo.
  28871. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28872. stackedByDimInfo = dimensionInfo;
  28873. }
  28874. // Find the first stackable dimension as the stackedDimInfo.
  28875. if (!stackedDimInfo
  28876. && dimensionInfo.type !== 'ordinal'
  28877. && dimensionInfo.type !== 'time'
  28878. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28879. ) {
  28880. stackedDimInfo = dimensionInfo;
  28881. }
  28882. }
  28883. });
  28884. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28885. // Compatible with previous design, value axis (time axis) only stack by index.
  28886. // It may make sense if the user provides elaborately constructed data.
  28887. byIndex = true;
  28888. }
  28889. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28890. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28891. // might not be a good way.
  28892. if (stackedDimInfo) {
  28893. // Use a weird name that not duplicated with other names.
  28894. stackResultDimension = '__\0ecstackresult';
  28895. stackedOverDimension = '__\0ecstackedover';
  28896. // Create inverted index to fast query index by value.
  28897. if (stackedByDimInfo) {
  28898. stackedByDimInfo.createInvertedIndices = true;
  28899. }
  28900. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28901. var stackedDimType = stackedDimInfo.type;
  28902. var stackedDimCoordIndex = 0;
  28903. each$1(dimensionInfoList, function (dimensionInfo) {
  28904. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28905. stackedDimCoordIndex++;
  28906. }
  28907. });
  28908. dimensionInfoList.push({
  28909. name: stackResultDimension,
  28910. coordDim: stackedDimCoordDim,
  28911. coordDimIndex: stackedDimCoordIndex,
  28912. type: stackedDimType,
  28913. isExtraCoord: true,
  28914. isCalculationCoord: true
  28915. });
  28916. stackedDimCoordIndex++;
  28917. dimensionInfoList.push({
  28918. name: stackedOverDimension,
  28919. // This dimension contains stack base (generally, 0), so do not set it as
  28920. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28921. coordDim: stackedOverDimension,
  28922. coordDimIndex: stackedDimCoordIndex,
  28923. type: stackedDimType,
  28924. isExtraCoord: true,
  28925. isCalculationCoord: true
  28926. });
  28927. }
  28928. return {
  28929. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28930. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28931. isStackedByIndex: byIndex,
  28932. stackedOverDimension: stackedOverDimension,
  28933. stackResultDimension: stackResultDimension
  28934. };
  28935. }
  28936. /**
  28937. * @param {module:echarts/data/List} data
  28938. * @param {string} stackedDim
  28939. */
  28940. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28941. // Each single series only maps to one pair of axis. So we do not need to
  28942. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28943. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28944. // && (
  28945. // stackedByDim != null
  28946. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28947. // : data.getCalculationInfo('isStackedByIndex')
  28948. // );
  28949. }
  28950. /**
  28951. * @param {module:echarts/data/List} data
  28952. * @param {string} targetDim
  28953. * @param {string} [stackedByDim] If not input this parameter, check whether
  28954. * stacked by index.
  28955. * @return {string} dimension
  28956. */
  28957. function getStackedDimension(data, targetDim) {
  28958. return isDimensionStacked(data, targetDim)
  28959. ? data.getCalculationInfo('stackResultDimension')
  28960. : targetDim;
  28961. }
  28962. /*
  28963. * Licensed to the Apache Software Foundation (ASF) under one
  28964. * or more contributor license agreements. See the NOTICE file
  28965. * distributed with this work for additional information
  28966. * regarding copyright ownership. The ASF licenses this file
  28967. * to you under the Apache License, Version 2.0 (the
  28968. * "License"); you may not use this file except in compliance
  28969. * with the License. You may obtain a copy of the License at
  28970. *
  28971. * http://www.apache.org/licenses/LICENSE-2.0
  28972. *
  28973. * Unless required by applicable law or agreed to in writing,
  28974. * software distributed under the License is distributed on an
  28975. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28976. * KIND, either express or implied. See the License for the
  28977. * specific language governing permissions and limitations
  28978. * under the License.
  28979. */
  28980. /**
  28981. * @param {module:echarts/data/Source|Array} source Or raw data.
  28982. * @param {module:echarts/model/Series} seriesModel
  28983. * @param {Object} [opt]
  28984. * @param {string} [opt.generateCoord]
  28985. * @param {boolean} [opt.useEncodeDefaulter]
  28986. */
  28987. function createListFromArray(source, seriesModel, opt) {
  28988. opt = opt || {};
  28989. if (!Source.isInstance(source)) {
  28990. source = Source.seriesDataToSource(source);
  28991. }
  28992. var coordSysName = seriesModel.get('coordinateSystem');
  28993. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28994. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28995. var coordSysDimDefs;
  28996. if (coordSysInfo) {
  28997. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28998. var dimInfo = {name: dim};
  28999. var axisModel = coordSysInfo.axisMap.get(dim);
  29000. if (axisModel) {
  29001. var axisType = axisModel.get('type');
  29002. dimInfo.type = getDimensionTypeByAxis(axisType);
  29003. // dimInfo.stackable = isStackable(axisType);
  29004. }
  29005. return dimInfo;
  29006. });
  29007. }
  29008. if (!coordSysDimDefs) {
  29009. // Get dimensions from registered coordinate system
  29010. coordSysDimDefs = (registeredCoordSys && (
  29011. registeredCoordSys.getDimensionsInfo
  29012. ? registeredCoordSys.getDimensionsInfo()
  29013. : registeredCoordSys.dimensions.slice()
  29014. )) || ['x', 'y'];
  29015. }
  29016. var dimInfoList = createDimensions(source, {
  29017. coordDimensions: coordSysDimDefs,
  29018. generateCoord: opt.generateCoord,
  29019. encodeDefaulter: opt.useEncodeDefaulter
  29020. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  29021. : null
  29022. });
  29023. var firstCategoryDimIndex;
  29024. var hasNameEncode;
  29025. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  29026. var coordDim = dimInfo.coordDim;
  29027. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29028. if (categoryAxisModel) {
  29029. if (firstCategoryDimIndex == null) {
  29030. firstCategoryDimIndex = dimIndex;
  29031. }
  29032. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29033. }
  29034. if (dimInfo.otherDims.itemName != null) {
  29035. hasNameEncode = true;
  29036. }
  29037. });
  29038. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29039. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29040. }
  29041. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29042. var list = new List(dimInfoList, seriesModel);
  29043. list.setCalculationInfo(stackCalculationInfo);
  29044. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  29045. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29046. // Use dataIndex as ordinal value in categoryAxis
  29047. return dimIndex === firstCategoryDimIndex
  29048. ? dataIndex
  29049. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29050. }
  29051. : null;
  29052. list.hasItemOption = false;
  29053. list.initData(source, null, dimValueGetter);
  29054. return list;
  29055. }
  29056. function isNeedCompleteOrdinalData(source) {
  29057. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29058. var sampleItem = firstDataNotNull(source.data || []);
  29059. return sampleItem != null
  29060. && !isArray(getDataItemValue(sampleItem));
  29061. }
  29062. }
  29063. function firstDataNotNull(data) {
  29064. var i = 0;
  29065. while (i < data.length && data[i] == null) {
  29066. i++;
  29067. }
  29068. return data[i];
  29069. }
  29070. /*
  29071. * Licensed to the Apache Software Foundation (ASF) under one
  29072. * or more contributor license agreements. See the NOTICE file
  29073. * distributed with this work for additional information
  29074. * regarding copyright ownership. The ASF licenses this file
  29075. * to you under the Apache License, Version 2.0 (the
  29076. * "License"); you may not use this file except in compliance
  29077. * with the License. You may obtain a copy of the License at
  29078. *
  29079. * http://www.apache.org/licenses/LICENSE-2.0
  29080. *
  29081. * Unless required by applicable law or agreed to in writing,
  29082. * software distributed under the License is distributed on an
  29083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29084. * KIND, either express or implied. See the License for the
  29085. * specific language governing permissions and limitations
  29086. * under the License.
  29087. */
  29088. /**
  29089. * // Scale class management
  29090. * @module echarts/scale/Scale
  29091. */
  29092. /**
  29093. * @param {Object} [setting]
  29094. */
  29095. function Scale(setting) {
  29096. this._setting = setting || {};
  29097. /**
  29098. * Extent
  29099. * @type {Array.<number>}
  29100. * @protected
  29101. */
  29102. this._extent = [Infinity, -Infinity];
  29103. /**
  29104. * Step is calculated in adjustExtent
  29105. * @type {Array.<number>}
  29106. * @protected
  29107. */
  29108. this._interval = 0;
  29109. this.init && this.init.apply(this, arguments);
  29110. }
  29111. /**
  29112. * Parse input val to valid inner number.
  29113. * @param {*} val
  29114. * @return {number}
  29115. */
  29116. Scale.prototype.parse = function (val) {
  29117. // Notice: This would be a trap here, If the implementation
  29118. // of this method depends on extent, and this method is used
  29119. // before extent set (like in dataZoom), it would be wrong.
  29120. // Nevertheless, parse does not depend on extent generally.
  29121. return val;
  29122. };
  29123. Scale.prototype.getSetting = function (name) {
  29124. return this._setting[name];
  29125. };
  29126. Scale.prototype.contain = function (val) {
  29127. var extent = this._extent;
  29128. return val >= extent[0] && val <= extent[1];
  29129. };
  29130. /**
  29131. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29132. * @param {number} val
  29133. * @return {number}
  29134. */
  29135. Scale.prototype.normalize = function (val) {
  29136. var extent = this._extent;
  29137. if (extent[1] === extent[0]) {
  29138. return 0.5;
  29139. }
  29140. return (val - extent[0]) / (extent[1] - extent[0]);
  29141. };
  29142. /**
  29143. * Scale normalized value
  29144. * @param {number} val
  29145. * @return {number}
  29146. */
  29147. Scale.prototype.scale = function (val) {
  29148. var extent = this._extent;
  29149. return val * (extent[1] - extent[0]) + extent[0];
  29150. };
  29151. /**
  29152. * Set extent from data
  29153. * @param {Array.<number>} other
  29154. */
  29155. Scale.prototype.unionExtent = function (other) {
  29156. var extent = this._extent;
  29157. other[0] < extent[0] && (extent[0] = other[0]);
  29158. other[1] > extent[1] && (extent[1] = other[1]);
  29159. // not setExtent because in log axis it may transformed to power
  29160. // this.setExtent(extent[0], extent[1]);
  29161. };
  29162. /**
  29163. * Set extent from data
  29164. * @param {module:echarts/data/List} data
  29165. * @param {string} dim
  29166. */
  29167. Scale.prototype.unionExtentFromData = function (data, dim) {
  29168. this.unionExtent(data.getApproximateExtent(dim));
  29169. };
  29170. /**
  29171. * Get extent
  29172. * @return {Array.<number>}
  29173. */
  29174. Scale.prototype.getExtent = function () {
  29175. return this._extent.slice();
  29176. };
  29177. /**
  29178. * Set extent
  29179. * @param {number} start
  29180. * @param {number} end
  29181. */
  29182. Scale.prototype.setExtent = function (start, end) {
  29183. var thisExtent = this._extent;
  29184. if (!isNaN(start)) {
  29185. thisExtent[0] = start;
  29186. }
  29187. if (!isNaN(end)) {
  29188. thisExtent[1] = end;
  29189. }
  29190. };
  29191. /**
  29192. * When axis extent depends on data and no data exists,
  29193. * axis ticks should not be drawn, which is named 'blank'.
  29194. */
  29195. Scale.prototype.isBlank = function () {
  29196. return this._isBlank;
  29197. },
  29198. /**
  29199. * When axis extent depends on data and no data exists,
  29200. * axis ticks should not be drawn, which is named 'blank'.
  29201. */
  29202. Scale.prototype.setBlank = function (isBlank) {
  29203. this._isBlank = isBlank;
  29204. };
  29205. /**
  29206. * @abstract
  29207. * @param {*} tick
  29208. * @return {string} label of the tick.
  29209. */
  29210. Scale.prototype.getLabel = null;
  29211. enableClassExtend(Scale);
  29212. enableClassManagement(Scale, {
  29213. registerWhenExtend: true
  29214. });
  29215. /*
  29216. * Licensed to the Apache Software Foundation (ASF) under one
  29217. * or more contributor license agreements. See the NOTICE file
  29218. * distributed with this work for additional information
  29219. * regarding copyright ownership. The ASF licenses this file
  29220. * to you under the Apache License, Version 2.0 (the
  29221. * "License"); you may not use this file except in compliance
  29222. * with the License. You may obtain a copy of the License at
  29223. *
  29224. * http://www.apache.org/licenses/LICENSE-2.0
  29225. *
  29226. * Unless required by applicable law or agreed to in writing,
  29227. * software distributed under the License is distributed on an
  29228. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29229. * KIND, either express or implied. See the License for the
  29230. * specific language governing permissions and limitations
  29231. * under the License.
  29232. */
  29233. /**
  29234. * @constructor
  29235. * @param {Object} [opt]
  29236. * @param {Object} [opt.categories=[]]
  29237. * @param {Object} [opt.needCollect=false]
  29238. * @param {Object} [opt.deduplication=false]
  29239. */
  29240. function OrdinalMeta(opt) {
  29241. /**
  29242. * @readOnly
  29243. * @type {Array.<string>}
  29244. */
  29245. this.categories = opt.categories || [];
  29246. /**
  29247. * @private
  29248. * @type {boolean}
  29249. */
  29250. this._needCollect = opt.needCollect;
  29251. /**
  29252. * @private
  29253. * @type {boolean}
  29254. */
  29255. this._deduplication = opt.deduplication;
  29256. /**
  29257. * @private
  29258. * @type {boolean}
  29259. */
  29260. this._map;
  29261. }
  29262. /**
  29263. * @param {module:echarts/model/Model} axisModel
  29264. * @return {module:echarts/data/OrdinalMeta}
  29265. */
  29266. OrdinalMeta.createByAxisModel = function (axisModel) {
  29267. var option = axisModel.option;
  29268. var data = option.data;
  29269. var categories = data && map(data, getName);
  29270. return new OrdinalMeta({
  29271. categories: categories,
  29272. needCollect: !categories,
  29273. // deduplication is default in axis.
  29274. deduplication: option.dedplication !== false
  29275. });
  29276. };
  29277. var proto$1 = OrdinalMeta.prototype;
  29278. /**
  29279. * @param {string} category
  29280. * @return {number} ordinal
  29281. */
  29282. proto$1.getOrdinal = function (category) {
  29283. return getOrCreateMap(this).get(category);
  29284. };
  29285. /**
  29286. * @param {*} category
  29287. * @return {number} The ordinal. If not found, return NaN.
  29288. */
  29289. proto$1.parseAndCollect = function (category) {
  29290. var index;
  29291. var needCollect = this._needCollect;
  29292. // The value of category dim can be the index of the given category set.
  29293. // This feature is only supported when !needCollect, because we should
  29294. // consider a common case: a value is 2017, which is a number but is
  29295. // expected to be tread as a category. This case usually happen in dataset,
  29296. // where it happent to be no need of the index feature.
  29297. if (typeof category !== 'string' && !needCollect) {
  29298. return category;
  29299. }
  29300. // Optimize for the scenario:
  29301. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29302. // data has been ensured not duplicate and is large data.
  29303. // Notice, if a dataset dimension provide categroies, usually echarts
  29304. // should remove duplication except user tell echarts dont do that
  29305. // (set axis.deduplication = false), because echarts do not know whether
  29306. // the values in the category dimension has duplication (consider the
  29307. // parallel-aqi example)
  29308. if (needCollect && !this._deduplication) {
  29309. index = this.categories.length;
  29310. this.categories[index] = category;
  29311. return index;
  29312. }
  29313. var map$$1 = getOrCreateMap(this);
  29314. index = map$$1.get(category);
  29315. if (index == null) {
  29316. if (needCollect) {
  29317. index = this.categories.length;
  29318. this.categories[index] = category;
  29319. map$$1.set(category, index);
  29320. }
  29321. else {
  29322. index = NaN;
  29323. }
  29324. }
  29325. return index;
  29326. };
  29327. // Consider big data, do not create map until needed.
  29328. function getOrCreateMap(ordinalMeta) {
  29329. return ordinalMeta._map || (
  29330. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29331. );
  29332. }
  29333. function getName(obj) {
  29334. if (isObject$1(obj) && obj.value != null) {
  29335. return obj.value;
  29336. }
  29337. else {
  29338. return obj + '';
  29339. }
  29340. }
  29341. /*
  29342. * Licensed to the Apache Software Foundation (ASF) under one
  29343. * or more contributor license agreements. See the NOTICE file
  29344. * distributed with this work for additional information
  29345. * regarding copyright ownership. The ASF licenses this file
  29346. * to you under the Apache License, Version 2.0 (the
  29347. * "License"); you may not use this file except in compliance
  29348. * with the License. You may obtain a copy of the License at
  29349. *
  29350. * http://www.apache.org/licenses/LICENSE-2.0
  29351. *
  29352. * Unless required by applicable law or agreed to in writing,
  29353. * software distributed under the License is distributed on an
  29354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29355. * KIND, either express or implied. See the License for the
  29356. * specific language governing permissions and limitations
  29357. * under the License.
  29358. */
  29359. /**
  29360. * Linear continuous scale
  29361. * @module echarts/coord/scale/Ordinal
  29362. *
  29363. * http://en.wikipedia.org/wiki/Level_of_measurement
  29364. */
  29365. // FIXME only one data
  29366. var scaleProto = Scale.prototype;
  29367. var OrdinalScale = Scale.extend({
  29368. type: 'ordinal',
  29369. /**
  29370. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29371. */
  29372. init: function (ordinalMeta, extent) {
  29373. // Caution: Should not use instanceof, consider ec-extensions using
  29374. // import approach to get OrdinalMeta class.
  29375. if (!ordinalMeta || isArray(ordinalMeta)) {
  29376. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29377. }
  29378. this._ordinalMeta = ordinalMeta;
  29379. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29380. },
  29381. parse: function (val) {
  29382. return typeof val === 'string'
  29383. ? this._ordinalMeta.getOrdinal(val)
  29384. // val might be float.
  29385. : Math.round(val);
  29386. },
  29387. contain: function (rank) {
  29388. rank = this.parse(rank);
  29389. return scaleProto.contain.call(this, rank)
  29390. && this._ordinalMeta.categories[rank] != null;
  29391. },
  29392. /**
  29393. * Normalize given rank or name to linear [0, 1]
  29394. * @param {number|string} [val]
  29395. * @return {number}
  29396. */
  29397. normalize: function (val) {
  29398. return scaleProto.normalize.call(this, this.parse(val));
  29399. },
  29400. scale: function (val) {
  29401. return Math.round(scaleProto.scale.call(this, val));
  29402. },
  29403. /**
  29404. * @return {Array}
  29405. */
  29406. getTicks: function () {
  29407. var ticks = [];
  29408. var extent = this._extent;
  29409. var rank = extent[0];
  29410. while (rank <= extent[1]) {
  29411. ticks.push(rank);
  29412. rank++;
  29413. }
  29414. return ticks;
  29415. },
  29416. /**
  29417. * Get item on rank n
  29418. * @param {number} n
  29419. * @return {string}
  29420. */
  29421. getLabel: function (n) {
  29422. if (!this.isBlank()) {
  29423. // Note that if no data, ordinalMeta.categories is an empty array.
  29424. return this._ordinalMeta.categories[n];
  29425. }
  29426. },
  29427. /**
  29428. * @return {number}
  29429. */
  29430. count: function () {
  29431. return this._extent[1] - this._extent[0] + 1;
  29432. },
  29433. /**
  29434. * @override
  29435. */
  29436. unionExtentFromData: function (data, dim) {
  29437. this.unionExtent(data.getApproximateExtent(dim));
  29438. },
  29439. getOrdinalMeta: function () {
  29440. return this._ordinalMeta;
  29441. },
  29442. niceTicks: noop,
  29443. niceExtent: noop
  29444. });
  29445. /**
  29446. * @return {module:echarts/scale/Time}
  29447. */
  29448. OrdinalScale.create = function () {
  29449. return new OrdinalScale();
  29450. };
  29451. /*
  29452. * Licensed to the Apache Software Foundation (ASF) under one
  29453. * or more contributor license agreements. See the NOTICE file
  29454. * distributed with this work for additional information
  29455. * regarding copyright ownership. The ASF licenses this file
  29456. * to you under the Apache License, Version 2.0 (the
  29457. * "License"); you may not use this file except in compliance
  29458. * with the License. You may obtain a copy of the License at
  29459. *
  29460. * http://www.apache.org/licenses/LICENSE-2.0
  29461. *
  29462. * Unless required by applicable law or agreed to in writing,
  29463. * software distributed under the License is distributed on an
  29464. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29465. * KIND, either express or implied. See the License for the
  29466. * specific language governing permissions and limitations
  29467. * under the License.
  29468. */
  29469. /**
  29470. * For testable.
  29471. */
  29472. var roundNumber$1 = round$1;
  29473. /**
  29474. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29475. * Should be extent[0] < extent[1].
  29476. * @param {number} splitNumber splitNumber should be >= 1.
  29477. * @param {number} [minInterval]
  29478. * @param {number} [maxInterval]
  29479. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29480. */
  29481. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29482. var result = {};
  29483. var span = extent[1] - extent[0];
  29484. var interval = result.interval = nice(span / splitNumber, true);
  29485. if (minInterval != null && interval < minInterval) {
  29486. interval = result.interval = minInterval;
  29487. }
  29488. if (maxInterval != null && interval > maxInterval) {
  29489. interval = result.interval = maxInterval;
  29490. }
  29491. // Tow more digital for tick.
  29492. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29493. // Niced extent inside original extent
  29494. var niceTickExtent = result.niceTickExtent = [
  29495. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29496. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29497. ];
  29498. fixExtent(niceTickExtent, extent);
  29499. return result;
  29500. }
  29501. /**
  29502. * @param {number} interval
  29503. * @return {number} interval precision
  29504. */
  29505. function getIntervalPrecision(interval) {
  29506. // Tow more digital for tick.
  29507. return getPrecisionSafe(interval) + 2;
  29508. }
  29509. function clamp(niceTickExtent, idx, extent) {
  29510. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29511. }
  29512. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29513. function fixExtent(niceTickExtent, extent) {
  29514. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29515. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29516. clamp(niceTickExtent, 0, extent);
  29517. clamp(niceTickExtent, 1, extent);
  29518. if (niceTickExtent[0] > niceTickExtent[1]) {
  29519. niceTickExtent[0] = niceTickExtent[1];
  29520. }
  29521. }
  29522. /*
  29523. * Licensed to the Apache Software Foundation (ASF) under one
  29524. * or more contributor license agreements. See the NOTICE file
  29525. * distributed with this work for additional information
  29526. * regarding copyright ownership. The ASF licenses this file
  29527. * to you under the Apache License, Version 2.0 (the
  29528. * "License"); you may not use this file except in compliance
  29529. * with the License. You may obtain a copy of the License at
  29530. *
  29531. * http://www.apache.org/licenses/LICENSE-2.0
  29532. *
  29533. * Unless required by applicable law or agreed to in writing,
  29534. * software distributed under the License is distributed on an
  29535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29536. * KIND, either express or implied. See the License for the
  29537. * specific language governing permissions and limitations
  29538. * under the License.
  29539. */
  29540. /**
  29541. * Interval scale
  29542. * @module echarts/scale/Interval
  29543. */
  29544. var roundNumber = round$1;
  29545. /**
  29546. * @alias module:echarts/coord/scale/Interval
  29547. * @constructor
  29548. */
  29549. var IntervalScale = Scale.extend({
  29550. type: 'interval',
  29551. _interval: 0,
  29552. _intervalPrecision: 2,
  29553. setExtent: function (start, end) {
  29554. var thisExtent = this._extent;
  29555. //start,end may be a Number like '25',so...
  29556. if (!isNaN(start)) {
  29557. thisExtent[0] = parseFloat(start);
  29558. }
  29559. if (!isNaN(end)) {
  29560. thisExtent[1] = parseFloat(end);
  29561. }
  29562. },
  29563. unionExtent: function (other) {
  29564. var extent = this._extent;
  29565. other[0] < extent[0] && (extent[0] = other[0]);
  29566. other[1] > extent[1] && (extent[1] = other[1]);
  29567. // unionExtent may called by it's sub classes
  29568. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29569. },
  29570. /**
  29571. * Get interval
  29572. */
  29573. getInterval: function () {
  29574. return this._interval;
  29575. },
  29576. /**
  29577. * Set interval
  29578. */
  29579. setInterval: function (interval) {
  29580. this._interval = interval;
  29581. // Dropped auto calculated niceExtent and use user setted extent
  29582. // We assume user wan't to set both interval, min, max to get a better result
  29583. this._niceExtent = this._extent.slice();
  29584. this._intervalPrecision = getIntervalPrecision(interval);
  29585. },
  29586. /**
  29587. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29588. * @return {Array.<number>}
  29589. */
  29590. getTicks: function (expandToNicedExtent) {
  29591. var interval = this._interval;
  29592. var extent = this._extent;
  29593. var niceTickExtent = this._niceExtent;
  29594. var intervalPrecision = this._intervalPrecision;
  29595. var ticks = [];
  29596. // If interval is 0, return [];
  29597. if (!interval) {
  29598. return ticks;
  29599. }
  29600. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29601. var safeLimit = 10000;
  29602. if (extent[0] < niceTickExtent[0]) {
  29603. if (expandToNicedExtent) {
  29604. ticks.push(roundNumber(niceTickExtent[0] - interval));
  29605. }
  29606. else {
  29607. ticks.push(extent[0]);
  29608. }
  29609. }
  29610. var tick = niceTickExtent[0];
  29611. while (tick <= niceTickExtent[1]) {
  29612. ticks.push(tick);
  29613. // Avoid rounding error
  29614. tick = roundNumber(tick + interval, intervalPrecision);
  29615. if (tick === ticks[ticks.length - 1]) {
  29616. // Consider out of safe float point, e.g.,
  29617. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29618. break;
  29619. }
  29620. if (ticks.length > safeLimit) {
  29621. return [];
  29622. }
  29623. }
  29624. // Consider this case: the last item of ticks is smaller
  29625. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29626. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29627. if (extent[1] > lastNiceTick) {
  29628. if (expandToNicedExtent) {
  29629. ticks.push(lastNiceTick + interval);
  29630. }
  29631. else {
  29632. ticks.push(extent[1]);
  29633. }
  29634. }
  29635. return ticks;
  29636. },
  29637. /**
  29638. * @param {number} [splitNumber=5]
  29639. * @return {Array.<Array.<number>>}
  29640. */
  29641. getMinorTicks: function (splitNumber) {
  29642. var ticks = this.getTicks(true);
  29643. var minorTicks = [];
  29644. var extent = this.getExtent();
  29645. for (var i = 1; i < ticks.length; i++) {
  29646. var nextTick = ticks[i];
  29647. var prevTick = ticks[i - 1];
  29648. var count = 0;
  29649. var minorTicksGroup = [];
  29650. var interval = nextTick - prevTick;
  29651. var minorInterval = interval / splitNumber;
  29652. while (count < splitNumber - 1) {
  29653. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29654. // For the first and last interval. The count may be less than splitNumber.
  29655. if (minorTick > extent[0] && minorTick < extent[1]) {
  29656. minorTicksGroup.push(minorTick);
  29657. }
  29658. count++;
  29659. }
  29660. minorTicks.push(minorTicksGroup);
  29661. }
  29662. return minorTicks;
  29663. },
  29664. /**
  29665. * @param {number} data
  29666. * @param {Object} [opt]
  29667. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29668. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29669. * @return {string}
  29670. */
  29671. getLabel: function (data, opt) {
  29672. if (data == null) {
  29673. return '';
  29674. }
  29675. var precision = opt && opt.precision;
  29676. if (precision == null) {
  29677. precision = getPrecisionSafe(data) || 0;
  29678. }
  29679. else if (precision === 'auto') {
  29680. // Should be more precise then tick.
  29681. precision = this._intervalPrecision;
  29682. }
  29683. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29684. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29685. data = roundNumber(data, precision, true);
  29686. return addCommas(data);
  29687. },
  29688. /**
  29689. * Update interval and extent of intervals for nice ticks
  29690. *
  29691. * @param {number} [splitNumber = 5] Desired number of ticks
  29692. * @param {number} [minInterval]
  29693. * @param {number} [maxInterval]
  29694. */
  29695. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29696. splitNumber = splitNumber || 5;
  29697. var extent = this._extent;
  29698. var span = extent[1] - extent[0];
  29699. if (!isFinite(span)) {
  29700. return;
  29701. }
  29702. // User may set axis min 0 and data are all negative
  29703. // FIXME If it needs to reverse ?
  29704. if (span < 0) {
  29705. span = -span;
  29706. extent.reverse();
  29707. }
  29708. var result = intervalScaleNiceTicks(
  29709. extent, splitNumber, minInterval, maxInterval
  29710. );
  29711. this._intervalPrecision = result.intervalPrecision;
  29712. this._interval = result.interval;
  29713. this._niceExtent = result.niceTickExtent;
  29714. },
  29715. /**
  29716. * Nice extent.
  29717. * @param {Object} opt
  29718. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29719. * @param {boolean} [opt.fixMin=false]
  29720. * @param {boolean} [opt.fixMax=false]
  29721. * @param {boolean} [opt.minInterval]
  29722. * @param {boolean} [opt.maxInterval]
  29723. */
  29724. niceExtent: function (opt) {
  29725. var extent = this._extent;
  29726. // If extent start and end are same, expand them
  29727. if (extent[0] === extent[1]) {
  29728. if (extent[0] !== 0) {
  29729. // Expand extent
  29730. var expandSize = extent[0];
  29731. // In the fowllowing case
  29732. // Axis has been fixed max 100
  29733. // Plus data are all 100 and axis extent are [100, 100].
  29734. // Extend to the both side will cause expanded max is larger than fixed max.
  29735. // So only expand to the smaller side.
  29736. if (!opt.fixMax) {
  29737. extent[1] += expandSize / 2;
  29738. extent[0] -= expandSize / 2;
  29739. }
  29740. else {
  29741. extent[0] -= expandSize / 2;
  29742. }
  29743. }
  29744. else {
  29745. extent[1] = 1;
  29746. }
  29747. }
  29748. var span = extent[1] - extent[0];
  29749. // If there are no data and extent are [Infinity, -Infinity]
  29750. if (!isFinite(span)) {
  29751. extent[0] = 0;
  29752. extent[1] = 1;
  29753. }
  29754. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29755. // var extent = this._extent;
  29756. var interval = this._interval;
  29757. if (!opt.fixMin) {
  29758. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29759. }
  29760. if (!opt.fixMax) {
  29761. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29762. }
  29763. }
  29764. });
  29765. /**
  29766. * @return {module:echarts/scale/Time}
  29767. */
  29768. IntervalScale.create = function () {
  29769. return new IntervalScale();
  29770. };
  29771. /*
  29772. * Licensed to the Apache Software Foundation (ASF) under one
  29773. * or more contributor license agreements. See the NOTICE file
  29774. * distributed with this work for additional information
  29775. * regarding copyright ownership. The ASF licenses this file
  29776. * to you under the Apache License, Version 2.0 (the
  29777. * "License"); you may not use this file except in compliance
  29778. * with the License. You may obtain a copy of the License at
  29779. *
  29780. * http://www.apache.org/licenses/LICENSE-2.0
  29781. *
  29782. * Unless required by applicable law or agreed to in writing,
  29783. * software distributed under the License is distributed on an
  29784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29785. * KIND, either express or implied. See the License for the
  29786. * specific language governing permissions and limitations
  29787. * under the License.
  29788. */
  29789. /* global Float32Array */
  29790. var STACK_PREFIX = '__ec_stack_';
  29791. var LARGE_BAR_MIN_WIDTH = 0.5;
  29792. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29793. function getSeriesStackId(seriesModel) {
  29794. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29795. }
  29796. function getAxisKey(axis) {
  29797. return axis.dim + axis.index;
  29798. }
  29799. /**
  29800. * @param {Object} opt
  29801. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29802. * @param {number} opt.count Positive interger.
  29803. * @param {number} [opt.barWidth]
  29804. * @param {number} [opt.barMaxWidth]
  29805. * @param {number} [opt.barMinWidth]
  29806. * @param {number} [opt.barGap]
  29807. * @param {number} [opt.barCategoryGap]
  29808. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29809. */
  29810. function getLayoutOnAxis(opt) {
  29811. var params = [];
  29812. var baseAxis = opt.axis;
  29813. var axisKey = 'axis0';
  29814. if (baseAxis.type !== 'category') {
  29815. return;
  29816. }
  29817. var bandWidth = baseAxis.getBandWidth();
  29818. for (var i = 0; i < opt.count || 0; i++) {
  29819. params.push(defaults({
  29820. bandWidth: bandWidth,
  29821. axisKey: axisKey,
  29822. stackId: STACK_PREFIX + i
  29823. }, opt));
  29824. }
  29825. var widthAndOffsets = doCalBarWidthAndOffset(params);
  29826. var result = [];
  29827. for (var i = 0; i < opt.count; i++) {
  29828. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  29829. item.offsetCenter = item.offset + item.width / 2;
  29830. result.push(item);
  29831. }
  29832. return result;
  29833. }
  29834. function prepareLayoutBarSeries(seriesType, ecModel) {
  29835. var seriesModels = [];
  29836. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29837. // Check series coordinate, do layout for cartesian2d only
  29838. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29839. seriesModels.push(seriesModel);
  29840. }
  29841. });
  29842. return seriesModels;
  29843. }
  29844. /**
  29845. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29846. * values.
  29847. * This works for time axes, value axes, and log axes.
  29848. * For a single time axis, return value is in the form like
  29849. * {'x_0': [1000000]}.
  29850. * The value of 1000000 is in milliseconds.
  29851. */
  29852. function getValueAxesMinGaps(barSeries) {
  29853. /**
  29854. * Map from axis.index to values.
  29855. * For a single time axis, axisValues is in the form like
  29856. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29857. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29858. * series.
  29859. */
  29860. var axisValues = {};
  29861. each$1(barSeries, function (seriesModel) {
  29862. var cartesian = seriesModel.coordinateSystem;
  29863. var baseAxis = cartesian.getBaseAxis();
  29864. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29865. return;
  29866. }
  29867. var data = seriesModel.getData();
  29868. var key = baseAxis.dim + '_' + baseAxis.index;
  29869. var dim = data.mapDimension(baseAxis.dim);
  29870. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29871. var value = data.get(dim, i);
  29872. if (!axisValues[key]) {
  29873. // No previous data for the axis
  29874. axisValues[key] = [value];
  29875. }
  29876. else {
  29877. // No value in previous series
  29878. axisValues[key].push(value);
  29879. }
  29880. // Ignore duplicated time values in the same axis
  29881. }
  29882. });
  29883. var axisMinGaps = [];
  29884. for (var key in axisValues) {
  29885. if (axisValues.hasOwnProperty(key)) {
  29886. var valuesInAxis = axisValues[key];
  29887. if (valuesInAxis) {
  29888. // Sort axis values into ascending order to calculate gaps
  29889. valuesInAxis.sort(function (a, b) {
  29890. return a - b;
  29891. });
  29892. var min = null;
  29893. for (var j = 1; j < valuesInAxis.length; ++j) {
  29894. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29895. if (delta > 0) {
  29896. // Ignore 0 delta because they are of the same axis value
  29897. min = min === null ? delta : Math.min(min, delta);
  29898. }
  29899. }
  29900. // Set to null if only have one data
  29901. axisMinGaps[key] = min;
  29902. }
  29903. }
  29904. }
  29905. return axisMinGaps;
  29906. }
  29907. function makeColumnLayout(barSeries) {
  29908. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29909. var seriesInfoList = [];
  29910. each$1(barSeries, function (seriesModel) {
  29911. var cartesian = seriesModel.coordinateSystem;
  29912. var baseAxis = cartesian.getBaseAxis();
  29913. var axisExtent = baseAxis.getExtent();
  29914. var bandWidth;
  29915. if (baseAxis.type === 'category') {
  29916. bandWidth = baseAxis.getBandWidth();
  29917. }
  29918. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29919. var key = baseAxis.dim + '_' + baseAxis.index;
  29920. var minGap = axisMinGaps[key];
  29921. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29922. var scale = baseAxis.scale.getExtent();
  29923. var scaleSpan = Math.abs(scale[1] - scale[0]);
  29924. bandWidth = minGap
  29925. ? extentSpan / scaleSpan * minGap
  29926. : extentSpan; // When there is only one data value
  29927. }
  29928. else {
  29929. var data = seriesModel.getData();
  29930. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  29931. }
  29932. var barWidth = parsePercent$1(
  29933. seriesModel.get('barWidth'), bandWidth
  29934. );
  29935. var barMaxWidth = parsePercent$1(
  29936. seriesModel.get('barMaxWidth'), bandWidth
  29937. );
  29938. var barMinWidth = parsePercent$1(
  29939. // barMinWidth by default is 1 in cartesian. Because in value axis,
  29940. // the auto-calculated bar width might be less than 1.
  29941. seriesModel.get('barMinWidth') || 1, bandWidth
  29942. );
  29943. var barGap = seriesModel.get('barGap');
  29944. var barCategoryGap = seriesModel.get('barCategoryGap');
  29945. seriesInfoList.push({
  29946. bandWidth: bandWidth,
  29947. barWidth: barWidth,
  29948. barMaxWidth: barMaxWidth,
  29949. barMinWidth: barMinWidth,
  29950. barGap: barGap,
  29951. barCategoryGap: barCategoryGap,
  29952. axisKey: getAxisKey(baseAxis),
  29953. stackId: getSeriesStackId(seriesModel)
  29954. });
  29955. });
  29956. return doCalBarWidthAndOffset(seriesInfoList);
  29957. }
  29958. function doCalBarWidthAndOffset(seriesInfoList) {
  29959. // Columns info on each category axis. Key is cartesian name
  29960. var columnsMap = {};
  29961. each$1(seriesInfoList, function (seriesInfo, idx) {
  29962. var axisKey = seriesInfo.axisKey;
  29963. var bandWidth = seriesInfo.bandWidth;
  29964. var columnsOnAxis = columnsMap[axisKey] || {
  29965. bandWidth: bandWidth,
  29966. remainedWidth: bandWidth,
  29967. autoWidthCount: 0,
  29968. categoryGap: '20%',
  29969. gap: '30%',
  29970. stacks: {}
  29971. };
  29972. var stacks = columnsOnAxis.stacks;
  29973. columnsMap[axisKey] = columnsOnAxis;
  29974. var stackId = seriesInfo.stackId;
  29975. if (!stacks[stackId]) {
  29976. columnsOnAxis.autoWidthCount++;
  29977. }
  29978. stacks[stackId] = stacks[stackId] || {
  29979. width: 0,
  29980. maxWidth: 0
  29981. };
  29982. // Caution: In a single coordinate system, these barGrid attributes
  29983. // will be shared by series. Consider that they have default values,
  29984. // only the attributes set on the last series will work.
  29985. // Do not change this fact unless there will be a break change.
  29986. var barWidth = seriesInfo.barWidth;
  29987. if (barWidth && !stacks[stackId].width) {
  29988. // See #6312, do not restrict width.
  29989. stacks[stackId].width = barWidth;
  29990. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  29991. columnsOnAxis.remainedWidth -= barWidth;
  29992. }
  29993. var barMaxWidth = seriesInfo.barMaxWidth;
  29994. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  29995. var barMinWidth = seriesInfo.barMinWidth;
  29996. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  29997. var barGap = seriesInfo.barGap;
  29998. (barGap != null) && (columnsOnAxis.gap = barGap);
  29999. var barCategoryGap = seriesInfo.barCategoryGap;
  30000. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30001. });
  30002. var result = {};
  30003. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30004. result[coordSysName] = {};
  30005. var stacks = columnsOnAxis.stacks;
  30006. var bandWidth = columnsOnAxis.bandWidth;
  30007. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30008. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30009. var remainedWidth = columnsOnAxis.remainedWidth;
  30010. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30011. var autoWidth = (remainedWidth - categoryGap)
  30012. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30013. autoWidth = Math.max(autoWidth, 0);
  30014. // Find if any auto calculated bar exceeded maxBarWidth
  30015. each$1(stacks, function (column) {
  30016. var maxWidth = column.maxWidth;
  30017. var minWidth = column.minWidth;
  30018. if (!column.width) {
  30019. var finalWidth = autoWidth;
  30020. if (maxWidth && maxWidth < finalWidth) {
  30021. finalWidth = Math.min(maxWidth, remainedWidth);
  30022. }
  30023. // `minWidth` has higher priority. `minWidth` decide that wheter the
  30024. // bar is able to be visible. So `minWidth` should not be restricted
  30025. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30026. // the extreme cases for `value` axis, bars are allowed to overlap
  30027. // with each other if `minWidth` specified.
  30028. if (minWidth && minWidth > finalWidth) {
  30029. finalWidth = minWidth;
  30030. }
  30031. if (finalWidth !== autoWidth) {
  30032. column.width = finalWidth;
  30033. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30034. autoWidthCount--;
  30035. }
  30036. }
  30037. else {
  30038. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30039. // CSS does. Becuase barWidth can be a percent value, where
  30040. // `barMaxWidth` can be used to restrict the final width.
  30041. var finalWidth = column.width;
  30042. if (maxWidth) {
  30043. finalWidth = Math.min(finalWidth, maxWidth);
  30044. }
  30045. // `minWidth` has higher priority, as described above
  30046. if (minWidth) {
  30047. finalWidth = Math.max(finalWidth, minWidth);
  30048. }
  30049. column.width = finalWidth;
  30050. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30051. autoWidthCount--;
  30052. }
  30053. });
  30054. // Recalculate width again
  30055. autoWidth = (remainedWidth - categoryGap)
  30056. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30057. autoWidth = Math.max(autoWidth, 0);
  30058. var widthSum = 0;
  30059. var lastColumn;
  30060. each$1(stacks, function (column, idx) {
  30061. if (!column.width) {
  30062. column.width = autoWidth;
  30063. }
  30064. lastColumn = column;
  30065. widthSum += column.width * (1 + barGapPercent);
  30066. });
  30067. if (lastColumn) {
  30068. widthSum -= lastColumn.width * barGapPercent;
  30069. }
  30070. var offset = -widthSum / 2;
  30071. each$1(stacks, function (column, stackId) {
  30072. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30073. bandWidth: bandWidth,
  30074. offset: offset,
  30075. width: column.width
  30076. };
  30077. offset += column.width * (1 + barGapPercent);
  30078. });
  30079. });
  30080. return result;
  30081. }
  30082. /**
  30083. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30084. * @param {module:echarts/coord/Axis} axis
  30085. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30086. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30087. */
  30088. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30089. if (barWidthAndOffset && axis) {
  30090. var result = barWidthAndOffset[getAxisKey(axis)];
  30091. if (result != null && seriesModel != null) {
  30092. result = result[getSeriesStackId(seriesModel)];
  30093. }
  30094. return result;
  30095. }
  30096. }
  30097. /**
  30098. * @param {string} seriesType
  30099. * @param {module:echarts/model/Global} ecModel
  30100. */
  30101. function layout(seriesType, ecModel) {
  30102. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30103. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30104. var lastStackCoords = {};
  30105. each$1(seriesModels, function (seriesModel) {
  30106. var data = seriesModel.getData();
  30107. var cartesian = seriesModel.coordinateSystem;
  30108. var baseAxis = cartesian.getBaseAxis();
  30109. var stackId = getSeriesStackId(seriesModel);
  30110. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30111. var columnOffset = columnLayoutInfo.offset;
  30112. var columnWidth = columnLayoutInfo.width;
  30113. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30114. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30115. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30116. data.setLayout({
  30117. bandWidth: columnLayoutInfo.bandWidth,
  30118. offset: columnOffset,
  30119. size: columnWidth
  30120. });
  30121. var valueDim = data.mapDimension(valueAxis.dim);
  30122. var baseDim = data.mapDimension(baseAxis.dim);
  30123. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30124. var isValueAxisH = valueAxis.isHorizontal();
  30125. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30126. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30127. var value = data.get(valueDim, idx);
  30128. var baseValue = data.get(baseDim, idx);
  30129. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  30130. if (isNaN(value) || isNaN(baseValue)) {
  30131. continue;
  30132. }
  30133. var sign = value >= 0 ? 'p' : 'n';
  30134. var baseCoord = valueAxisStart;
  30135. // Because of the barMinHeight, we can not use the value in
  30136. // stackResultDimension directly.
  30137. if (stacked) {
  30138. // Only ordinal axis can be stacked.
  30139. if (!lastStackCoords[stackId][baseValue]) {
  30140. lastStackCoords[stackId][baseValue] = {
  30141. p: valueAxisStart, // Positive stack
  30142. n: valueAxisStart // Negative stack
  30143. };
  30144. }
  30145. // Should also consider #4243
  30146. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30147. }
  30148. var x;
  30149. var y;
  30150. var width;
  30151. var height;
  30152. if (isValueAxisH) {
  30153. var coord = cartesian.dataToPoint([value, baseValue]);
  30154. x = baseCoord;
  30155. y = coord[1] + columnOffset;
  30156. width = coord[0] - valueAxisStart;
  30157. height = columnWidth;
  30158. if (Math.abs(width) < barMinHeight) {
  30159. width = (width < 0 ? -1 : 1) * barMinHeight;
  30160. }
  30161. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30162. }
  30163. else {
  30164. var coord = cartesian.dataToPoint([baseValue, value]);
  30165. x = coord[0] + columnOffset;
  30166. y = baseCoord;
  30167. width = columnWidth;
  30168. height = coord[1] - valueAxisStart;
  30169. if (Math.abs(height) < barMinHeight) {
  30170. // Include zero to has a positive bar
  30171. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30172. }
  30173. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30174. }
  30175. data.setItemLayout(idx, {
  30176. x: x,
  30177. y: y,
  30178. width: width,
  30179. height: height
  30180. });
  30181. }
  30182. }, this);
  30183. }
  30184. // TODO: Do not support stack in large mode yet.
  30185. var largeLayout = {
  30186. seriesType: 'bar',
  30187. plan: createRenderPlanner(),
  30188. reset: function (seriesModel) {
  30189. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30190. return;
  30191. }
  30192. var data = seriesModel.getData();
  30193. var cartesian = seriesModel.coordinateSystem;
  30194. var baseAxis = cartesian.getBaseAxis();
  30195. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30196. var valueDim = data.mapDimension(valueAxis.dim);
  30197. var baseDim = data.mapDimension(baseAxis.dim);
  30198. var valueAxisHorizontal = valueAxis.isHorizontal();
  30199. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30200. var barWidth = retrieveColumnLayout(
  30201. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30202. ).width;
  30203. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30204. barWidth = LARGE_BAR_MIN_WIDTH;
  30205. }
  30206. return {progress: progress};
  30207. function progress(params, data) {
  30208. var count = params.count;
  30209. var largePoints = new LargeArr(count * 2);
  30210. var largeDataIndices = new LargeArr(count);
  30211. var dataIndex;
  30212. var coord = [];
  30213. var valuePair = [];
  30214. var pointsOffset = 0;
  30215. var idxOffset = 0;
  30216. while ((dataIndex = params.next()) != null) {
  30217. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30218. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30219. coord = cartesian.dataToPoint(valuePair, null, coord);
  30220. // Data index might not be in order, depends on `progressiveChunkMode`.
  30221. largePoints[pointsOffset++] = coord[0];
  30222. largePoints[pointsOffset++] = coord[1];
  30223. largeDataIndices[idxOffset++] = dataIndex;
  30224. }
  30225. data.setLayout({
  30226. largePoints: largePoints,
  30227. largeDataIndices: largeDataIndices,
  30228. barWidth: barWidth,
  30229. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30230. valueAxisHorizontal: valueAxisHorizontal
  30231. });
  30232. }
  30233. }
  30234. };
  30235. function isOnCartesian(seriesModel) {
  30236. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30237. }
  30238. function isInLargeMode(seriesModel) {
  30239. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30240. }
  30241. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30242. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30243. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30244. }
  30245. /*
  30246. * Licensed to the Apache Software Foundation (ASF) under one
  30247. * or more contributor license agreements. See the NOTICE file
  30248. * distributed with this work for additional information
  30249. * regarding copyright ownership. The ASF licenses this file
  30250. * to you under the Apache License, Version 2.0 (the
  30251. * "License"); you may not use this file except in compliance
  30252. * with the License. You may obtain a copy of the License at
  30253. *
  30254. * http://www.apache.org/licenses/LICENSE-2.0
  30255. *
  30256. * Unless required by applicable law or agreed to in writing,
  30257. * software distributed under the License is distributed on an
  30258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30259. * KIND, either express or implied. See the License for the
  30260. * specific language governing permissions and limitations
  30261. * under the License.
  30262. */
  30263. /*
  30264. * A third-party license is embeded for some of the code in this file:
  30265. * The "scaleLevels" was originally copied from "d3.js" with some
  30266. * modifications made for this project.
  30267. * (See more details in the comment on the definition of "scaleLevels" below.)
  30268. * The use of the source code of this file is also subject to the terms
  30269. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30270. * </licenses/LICENSE-d3>).
  30271. */
  30272. // [About UTC and local time zone]:
  30273. // In most cases, `number.parseDate` will treat input data string as local time
  30274. // (except time zone is specified in time string). And `format.formateTime` returns
  30275. // local time by default. option.useUTC is false by default. This design have
  30276. // concidered these common case:
  30277. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30278. // in local time by default.
  30279. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30280. // as its original time, without any time difference.
  30281. var intervalScaleProto = IntervalScale.prototype;
  30282. var mathCeil = Math.ceil;
  30283. var mathFloor = Math.floor;
  30284. var ONE_SECOND = 1000;
  30285. var ONE_MINUTE = ONE_SECOND * 60;
  30286. var ONE_HOUR = ONE_MINUTE * 60;
  30287. var ONE_DAY = ONE_HOUR * 24;
  30288. // FIXME 公用?
  30289. var bisect = function (a, x, lo, hi) {
  30290. while (lo < hi) {
  30291. var mid = lo + hi >>> 1;
  30292. if (a[mid][1] < x) {
  30293. lo = mid + 1;
  30294. }
  30295. else {
  30296. hi = mid;
  30297. }
  30298. }
  30299. return lo;
  30300. };
  30301. /**
  30302. * @alias module:echarts/coord/scale/Time
  30303. * @constructor
  30304. */
  30305. var TimeScale = IntervalScale.extend({
  30306. type: 'time',
  30307. /**
  30308. * @override
  30309. */
  30310. getLabel: function (val) {
  30311. var stepLvl = this._stepLvl;
  30312. var date = new Date(val);
  30313. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30314. },
  30315. /**
  30316. * @override
  30317. */
  30318. niceExtent: function (opt) {
  30319. var extent = this._extent;
  30320. // If extent start and end are same, expand them
  30321. if (extent[0] === extent[1]) {
  30322. // Expand extent
  30323. extent[0] -= ONE_DAY;
  30324. extent[1] += ONE_DAY;
  30325. }
  30326. // If there are no data and extent are [Infinity, -Infinity]
  30327. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30328. var d = new Date();
  30329. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30330. extent[0] = extent[1] - ONE_DAY;
  30331. }
  30332. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30333. // var extent = this._extent;
  30334. var interval = this._interval;
  30335. if (!opt.fixMin) {
  30336. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30337. }
  30338. if (!opt.fixMax) {
  30339. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30340. }
  30341. },
  30342. /**
  30343. * @override
  30344. */
  30345. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30346. approxTickNum = approxTickNum || 10;
  30347. var extent = this._extent;
  30348. var span = extent[1] - extent[0];
  30349. var approxInterval = span / approxTickNum;
  30350. if (minInterval != null && approxInterval < minInterval) {
  30351. approxInterval = minInterval;
  30352. }
  30353. if (maxInterval != null && approxInterval > maxInterval) {
  30354. approxInterval = maxInterval;
  30355. }
  30356. var scaleLevelsLen = scaleLevels.length;
  30357. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30358. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30359. var interval = level[1];
  30360. // Same with interval scale if span is much larger than 1 year
  30361. if (level[0] === 'year') {
  30362. var yearSpan = span / interval;
  30363. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30364. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30365. var yearStep = nice(yearSpan / approxTickNum, true);
  30366. interval *= yearStep;
  30367. }
  30368. var timezoneOffset = this.getSetting('useUTC')
  30369. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30370. var niceExtent = [
  30371. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30372. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30373. ];
  30374. fixExtent(niceExtent, extent);
  30375. this._stepLvl = level;
  30376. // Interval will be used in getTicks
  30377. this._interval = interval;
  30378. this._niceExtent = niceExtent;
  30379. },
  30380. parse: function (val) {
  30381. // val might be float.
  30382. return +parseDate(val);
  30383. }
  30384. });
  30385. each$1(['contain', 'normalize'], function (methodName) {
  30386. TimeScale.prototype[methodName] = function (val) {
  30387. return intervalScaleProto[methodName].call(this, this.parse(val));
  30388. };
  30389. });
  30390. /**
  30391. * This implementation was originally copied from "d3.js"
  30392. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30393. * with some modifications made for this program.
  30394. * See the license statement at the head of this file.
  30395. */
  30396. var scaleLevels = [
  30397. // Format interval
  30398. ['hh:mm:ss', ONE_SECOND], // 1s
  30399. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30400. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30401. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30402. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30403. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30404. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30405. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30406. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30407. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30408. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30409. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30410. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30411. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30412. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30413. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30414. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30415. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30416. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30417. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30418. ['week', ONE_DAY * 7], // 7d
  30419. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30420. ['week', ONE_DAY * 14], // 2w
  30421. ['week', ONE_DAY * 21], // 3w
  30422. ['month', ONE_DAY * 31], // 1M
  30423. ['week', ONE_DAY * 42], // 6w
  30424. ['month', ONE_DAY * 62], // 2M
  30425. ['week', ONE_DAY * 70], // 10w
  30426. ['quarter', ONE_DAY * 95], // 3M
  30427. ['month', ONE_DAY * 31 * 4], // 4M
  30428. ['month', ONE_DAY * 31 * 5], // 5M
  30429. ['half-year', ONE_DAY * 380 / 2], // 6M
  30430. ['month', ONE_DAY * 31 * 8], // 8M
  30431. ['month', ONE_DAY * 31 * 10], // 10M
  30432. ['year', ONE_DAY * 380] // 1Y
  30433. ];
  30434. /**
  30435. * @param {module:echarts/model/Model}
  30436. * @return {module:echarts/scale/Time}
  30437. */
  30438. TimeScale.create = function (model) {
  30439. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30440. };
  30441. /*
  30442. * Licensed to the Apache Software Foundation (ASF) under one
  30443. * or more contributor license agreements. See the NOTICE file
  30444. * distributed with this work for additional information
  30445. * regarding copyright ownership. The ASF licenses this file
  30446. * to you under the Apache License, Version 2.0 (the
  30447. * "License"); you may not use this file except in compliance
  30448. * with the License. You may obtain a copy of the License at
  30449. *
  30450. * http://www.apache.org/licenses/LICENSE-2.0
  30451. *
  30452. * Unless required by applicable law or agreed to in writing,
  30453. * software distributed under the License is distributed on an
  30454. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30455. * KIND, either express or implied. See the License for the
  30456. * specific language governing permissions and limitations
  30457. * under the License.
  30458. */
  30459. /**
  30460. * Log scale
  30461. * @module echarts/scale/Log
  30462. */
  30463. // Use some method of IntervalScale
  30464. var scaleProto$1 = Scale.prototype;
  30465. var intervalScaleProto$1 = IntervalScale.prototype;
  30466. var getPrecisionSafe$1 = getPrecisionSafe;
  30467. var roundingErrorFix = round$1;
  30468. var mathFloor$1 = Math.floor;
  30469. var mathCeil$1 = Math.ceil;
  30470. var mathPow$1 = Math.pow;
  30471. var mathLog = Math.log;
  30472. var LogScale = Scale.extend({
  30473. type: 'log',
  30474. base: 10,
  30475. $constructor: function () {
  30476. Scale.apply(this, arguments);
  30477. this._originalScale = new IntervalScale();
  30478. },
  30479. /**
  30480. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30481. * @return {Array.<number>}
  30482. */
  30483. getTicks: function (expandToNicedExtent) {
  30484. var originalScale = this._originalScale;
  30485. var extent = this._extent;
  30486. var originalExtent = originalScale.getExtent();
  30487. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30488. var powVal = round$1(mathPow$1(this.base, val));
  30489. // Fix #4158
  30490. powVal = (val === extent[0] && originalScale.__fixMin)
  30491. ? fixRoundingError(powVal, originalExtent[0])
  30492. : powVal;
  30493. powVal = (val === extent[1] && originalScale.__fixMax)
  30494. ? fixRoundingError(powVal, originalExtent[1])
  30495. : powVal;
  30496. return powVal;
  30497. }, this);
  30498. },
  30499. /**
  30500. * @param {number} splitNumber
  30501. * @return {Array.<Array.<number>>}
  30502. */
  30503. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30504. /**
  30505. * @param {number} val
  30506. * @return {string}
  30507. */
  30508. getLabel: intervalScaleProto$1.getLabel,
  30509. /**
  30510. * @param {number} val
  30511. * @return {number}
  30512. */
  30513. scale: function (val) {
  30514. val = scaleProto$1.scale.call(this, val);
  30515. return mathPow$1(this.base, val);
  30516. },
  30517. /**
  30518. * @param {number} start
  30519. * @param {number} end
  30520. */
  30521. setExtent: function (start, end) {
  30522. var base = this.base;
  30523. start = mathLog(start) / mathLog(base);
  30524. end = mathLog(end) / mathLog(base);
  30525. intervalScaleProto$1.setExtent.call(this, start, end);
  30526. },
  30527. /**
  30528. * @return {number} end
  30529. */
  30530. getExtent: function () {
  30531. var base = this.base;
  30532. var extent = scaleProto$1.getExtent.call(this);
  30533. extent[0] = mathPow$1(base, extent[0]);
  30534. extent[1] = mathPow$1(base, extent[1]);
  30535. // Fix #4158
  30536. var originalScale = this._originalScale;
  30537. var originalExtent = originalScale.getExtent();
  30538. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30539. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30540. return extent;
  30541. },
  30542. /**
  30543. * @param {Array.<number>} extent
  30544. */
  30545. unionExtent: function (extent) {
  30546. this._originalScale.unionExtent(extent);
  30547. var base = this.base;
  30548. extent[0] = mathLog(extent[0]) / mathLog(base);
  30549. extent[1] = mathLog(extent[1]) / mathLog(base);
  30550. scaleProto$1.unionExtent.call(this, extent);
  30551. },
  30552. /**
  30553. * @override
  30554. */
  30555. unionExtentFromData: function (data, dim) {
  30556. // TODO
  30557. // filter value that <= 0
  30558. this.unionExtent(data.getApproximateExtent(dim));
  30559. },
  30560. /**
  30561. * Update interval and extent of intervals for nice ticks
  30562. * @param {number} [approxTickNum = 10] Given approx tick number
  30563. */
  30564. niceTicks: function (approxTickNum) {
  30565. approxTickNum = approxTickNum || 10;
  30566. var extent = this._extent;
  30567. var span = extent[1] - extent[0];
  30568. if (span === Infinity || span <= 0) {
  30569. return;
  30570. }
  30571. var interval = quantity(span);
  30572. var err = approxTickNum / span * interval;
  30573. // Filter ticks to get closer to the desired count.
  30574. if (err <= 0.5) {
  30575. interval *= 10;
  30576. }
  30577. // Interval should be integer
  30578. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30579. interval *= 10;
  30580. }
  30581. var niceExtent = [
  30582. round$1(mathCeil$1(extent[0] / interval) * interval),
  30583. round$1(mathFloor$1(extent[1] / interval) * interval)
  30584. ];
  30585. this._interval = interval;
  30586. this._niceExtent = niceExtent;
  30587. },
  30588. /**
  30589. * Nice extent.
  30590. * @override
  30591. */
  30592. niceExtent: function (opt) {
  30593. intervalScaleProto$1.niceExtent.call(this, opt);
  30594. var originalScale = this._originalScale;
  30595. originalScale.__fixMin = opt.fixMin;
  30596. originalScale.__fixMax = opt.fixMax;
  30597. }
  30598. });
  30599. each$1(['contain', 'normalize'], function (methodName) {
  30600. LogScale.prototype[methodName] = function (val) {
  30601. val = mathLog(val) / mathLog(this.base);
  30602. return scaleProto$1[methodName].call(this, val);
  30603. };
  30604. });
  30605. LogScale.create = function () {
  30606. return new LogScale();
  30607. };
  30608. function fixRoundingError(val, originalVal) {
  30609. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30610. }
  30611. /*
  30612. * Licensed to the Apache Software Foundation (ASF) under one
  30613. * or more contributor license agreements. See the NOTICE file
  30614. * distributed with this work for additional information
  30615. * regarding copyright ownership. The ASF licenses this file
  30616. * to you under the Apache License, Version 2.0 (the
  30617. * "License"); you may not use this file except in compliance
  30618. * with the License. You may obtain a copy of the License at
  30619. *
  30620. * http://www.apache.org/licenses/LICENSE-2.0
  30621. *
  30622. * Unless required by applicable law or agreed to in writing,
  30623. * software distributed under the License is distributed on an
  30624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30625. * KIND, either express or implied. See the License for the
  30626. * specific language governing permissions and limitations
  30627. * under the License.
  30628. */
  30629. /**
  30630. * Get axis scale extent before niced.
  30631. * Item of returned array can only be number (including Infinity and NaN).
  30632. */
  30633. function getScaleExtent(scale, model) {
  30634. var scaleType = scale.type;
  30635. var min = model.getMin();
  30636. var max = model.getMax();
  30637. var fixMin = min != null;
  30638. var fixMax = max != null;
  30639. var originalExtent = scale.getExtent();
  30640. var axisDataLen;
  30641. var boundaryGap;
  30642. var span;
  30643. if (scaleType === 'ordinal') {
  30644. axisDataLen = model.getCategories().length;
  30645. }
  30646. else {
  30647. boundaryGap = model.get('boundaryGap');
  30648. if (!isArray(boundaryGap)) {
  30649. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30650. }
  30651. if (typeof boundaryGap[0] === 'boolean') {
  30652. if (__DEV__) {
  30653. console.warn('Boolean type for boundaryGap is only '
  30654. + 'allowed for ordinal axis. Please use string in '
  30655. + 'percentage instead, e.g., "20%". Currently, '
  30656. + 'boundaryGap is set to be 0.');
  30657. }
  30658. boundaryGap = [0, 0];
  30659. }
  30660. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30661. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30662. span = (originalExtent[1] - originalExtent[0])
  30663. || Math.abs(originalExtent[0]);
  30664. }
  30665. // Notice: When min/max is not set (that is, when there are null/undefined,
  30666. // which is the most common case), these cases should be ensured:
  30667. // (1) For 'ordinal', show all axis.data.
  30668. // (2) For others:
  30669. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30670. // disabled).
  30671. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30672. // be the result that originalExtent enlarged by boundaryGap.
  30673. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30674. // FIXME
  30675. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30676. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30677. // that the results processed by boundaryGap are positive/negative?
  30678. if (min == null) {
  30679. min = scaleType === 'ordinal'
  30680. ? (axisDataLen ? 0 : NaN)
  30681. : originalExtent[0] - boundaryGap[0] * span;
  30682. }
  30683. if (max == null) {
  30684. max = scaleType === 'ordinal'
  30685. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30686. : originalExtent[1] + boundaryGap[1] * span;
  30687. }
  30688. if (min === 'dataMin') {
  30689. min = originalExtent[0];
  30690. }
  30691. else if (typeof min === 'function') {
  30692. min = min({
  30693. min: originalExtent[0],
  30694. max: originalExtent[1]
  30695. });
  30696. }
  30697. if (max === 'dataMax') {
  30698. max = originalExtent[1];
  30699. }
  30700. else if (typeof max === 'function') {
  30701. max = max({
  30702. min: originalExtent[0],
  30703. max: originalExtent[1]
  30704. });
  30705. }
  30706. (min == null || !isFinite(min)) && (min = NaN);
  30707. (max == null || !isFinite(max)) && (max = NaN);
  30708. scale.setBlank(
  30709. eqNaN(min)
  30710. || eqNaN(max)
  30711. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30712. );
  30713. // Evaluate if axis needs cross zero
  30714. if (model.getNeedCrossZero()) {
  30715. // Axis is over zero and min is not set
  30716. if (min > 0 && max > 0 && !fixMin) {
  30717. min = 0;
  30718. }
  30719. // Axis is under zero and max is not set
  30720. if (min < 0 && max < 0 && !fixMax) {
  30721. max = 0;
  30722. }
  30723. }
  30724. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30725. // is base axis
  30726. // FIXME
  30727. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30728. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30729. // Should not depend on series type `bar`?
  30730. // (3) Fix that might overlap when using dataZoom.
  30731. // (4) Consider other chart types using `barGrid`?
  30732. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30733. var ecModel = model.ecModel;
  30734. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30735. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30736. var isBaseAxisAndHasBarSeries;
  30737. each$1(barSeriesModels, function (seriesModel) {
  30738. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30739. });
  30740. if (isBaseAxisAndHasBarSeries) {
  30741. // Calculate placement of bars on axis
  30742. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30743. // Adjust axis min and max to account for overflow
  30744. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30745. min = adjustedScale.min;
  30746. max = adjustedScale.max;
  30747. }
  30748. }
  30749. return [min, max];
  30750. }
  30751. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30752. // Get Axis Length
  30753. var axisExtent = model.axis.getExtent();
  30754. var axisLength = axisExtent[1] - axisExtent[0];
  30755. // Get bars on current base axis and calculate min and max overflow
  30756. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30757. if (barsOnCurrentAxis === undefined) {
  30758. return {min: min, max: max};
  30759. }
  30760. var minOverflow = Infinity;
  30761. each$1(barsOnCurrentAxis, function (item) {
  30762. minOverflow = Math.min(item.offset, minOverflow);
  30763. });
  30764. var maxOverflow = -Infinity;
  30765. each$1(barsOnCurrentAxis, function (item) {
  30766. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30767. });
  30768. minOverflow = Math.abs(minOverflow);
  30769. maxOverflow = Math.abs(maxOverflow);
  30770. var totalOverFlow = minOverflow + maxOverflow;
  30771. // Calulate required buffer based on old range and overflow
  30772. var oldRange = max - min;
  30773. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30774. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30775. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30776. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30777. return {min: min, max: max};
  30778. }
  30779. function niceScaleExtent(scale, model) {
  30780. var extent = getScaleExtent(scale, model);
  30781. var fixMin = model.getMin() != null;
  30782. var fixMax = model.getMax() != null;
  30783. var splitNumber = model.get('splitNumber');
  30784. if (scale.type === 'log') {
  30785. scale.base = model.get('logBase');
  30786. }
  30787. var scaleType = scale.type;
  30788. scale.setExtent(extent[0], extent[1]);
  30789. scale.niceExtent({
  30790. splitNumber: splitNumber,
  30791. fixMin: fixMin,
  30792. fixMax: fixMax,
  30793. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30794. ? model.get('minInterval') : null,
  30795. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30796. ? model.get('maxInterval') : null
  30797. });
  30798. // If some one specified the min, max. And the default calculated interval
  30799. // is not good enough. He can specify the interval. It is often appeared
  30800. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30801. // to be 60.
  30802. // FIXME
  30803. var interval = model.get('interval');
  30804. if (interval != null) {
  30805. scale.setInterval && scale.setInterval(interval);
  30806. }
  30807. }
  30808. /**
  30809. * @param {module:echarts/model/Model} model
  30810. * @param {string} [axisType] Default retrieve from model.type
  30811. * @return {module:echarts/scale/*}
  30812. */
  30813. function createScaleByModel(model, axisType) {
  30814. axisType = axisType || model.get('type');
  30815. if (axisType) {
  30816. switch (axisType) {
  30817. // Buildin scale
  30818. case 'category':
  30819. return new OrdinalScale(
  30820. model.getOrdinalMeta
  30821. ? model.getOrdinalMeta()
  30822. : model.getCategories(),
  30823. [Infinity, -Infinity]
  30824. );
  30825. case 'value':
  30826. return new IntervalScale();
  30827. // Extended scale, like time and log
  30828. default:
  30829. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30830. }
  30831. }
  30832. }
  30833. /**
  30834. * Check if the axis corss 0
  30835. */
  30836. function ifAxisCrossZero(axis) {
  30837. var dataExtent = axis.scale.getExtent();
  30838. var min = dataExtent[0];
  30839. var max = dataExtent[1];
  30840. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30841. }
  30842. /**
  30843. * @param {module:echarts/coord/Axis} axis
  30844. * @return {Function} Label formatter function.
  30845. * param: {number} tickValue,
  30846. * param: {number} idx, the index in all ticks.
  30847. * If category axis, this param is not requied.
  30848. * return: {string} label string.
  30849. */
  30850. function makeLabelFormatter(axis) {
  30851. var labelFormatter = axis.getLabelModel().get('formatter');
  30852. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30853. if (typeof labelFormatter === 'string') {
  30854. labelFormatter = (function (tpl) {
  30855. return function (val) {
  30856. // For category axis, get raw value; for numeric axis,
  30857. // get foramtted label like '1,333,444'.
  30858. val = axis.scale.getLabel(val);
  30859. return tpl.replace('{value}', val != null ? val : '');
  30860. };
  30861. })(labelFormatter);
  30862. // Consider empty array
  30863. return labelFormatter;
  30864. }
  30865. else if (typeof labelFormatter === 'function') {
  30866. return function (tickValue, idx) {
  30867. // The original intention of `idx` is "the index of the tick in all ticks".
  30868. // But the previous implementation of category axis do not consider the
  30869. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30870. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30871. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30872. // the definition here for back compatibility.
  30873. if (categoryTickStart != null) {
  30874. idx = tickValue - categoryTickStart;
  30875. }
  30876. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30877. };
  30878. }
  30879. else {
  30880. return function (tick) {
  30881. return axis.scale.getLabel(tick);
  30882. };
  30883. }
  30884. }
  30885. function getAxisRawValue(axis, value) {
  30886. // In category axis with data zoom, tick is not the original
  30887. // index of axis.data. So tick should not be exposed to user
  30888. // in category axis.
  30889. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30890. }
  30891. /**
  30892. * @param {module:echarts/coord/Axis} axis
  30893. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30894. */
  30895. function estimateLabelUnionRect(axis) {
  30896. var axisModel = axis.model;
  30897. var scale = axis.scale;
  30898. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30899. return;
  30900. }
  30901. var isCategory = axis.type === 'category';
  30902. var realNumberScaleTicks;
  30903. var tickCount;
  30904. var categoryScaleExtent = scale.getExtent();
  30905. // Optimize for large category data, avoid call `getTicks()`.
  30906. if (isCategory) {
  30907. tickCount = scale.count();
  30908. }
  30909. else {
  30910. realNumberScaleTicks = scale.getTicks();
  30911. tickCount = realNumberScaleTicks.length;
  30912. }
  30913. var axisLabelModel = axis.getLabelModel();
  30914. var labelFormatter = makeLabelFormatter(axis);
  30915. var rect;
  30916. var step = 1;
  30917. // Simple optimization for large amount of labels
  30918. if (tickCount > 40) {
  30919. step = Math.ceil(tickCount / 40);
  30920. }
  30921. for (var i = 0; i < tickCount; i += step) {
  30922. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  30923. var label = labelFormatter(tickValue);
  30924. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  30925. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  30926. rect ? rect.union(singleRect) : (rect = singleRect);
  30927. }
  30928. return rect;
  30929. }
  30930. function rotateTextRect(textRect, rotate) {
  30931. var rotateRadians = rotate * Math.PI / 180;
  30932. var boundingBox = textRect.plain();
  30933. var beforeWidth = boundingBox.width;
  30934. var beforeHeight = boundingBox.height;
  30935. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  30936. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  30937. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  30938. return rotatedRect;
  30939. }
  30940. /**
  30941. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  30942. * @return {number|String} Can be null|'auto'|number|function
  30943. */
  30944. function getOptionCategoryInterval(model) {
  30945. var interval = model.get('interval');
  30946. return interval == null ? 'auto' : interval;
  30947. }
  30948. /**
  30949. * Set `categoryInterval` as 0 implicitly indicates that
  30950. * show all labels reguardless of overlap.
  30951. * @param {Object} axis axisModel.axis
  30952. * @return {boolean}
  30953. */
  30954. function shouldShowAllLabels(axis) {
  30955. return axis.type === 'category'
  30956. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  30957. }
  30958. /*
  30959. * Licensed to the Apache Software Foundation (ASF) under one
  30960. * or more contributor license agreements. See the NOTICE file
  30961. * distributed with this work for additional information
  30962. * regarding copyright ownership. The ASF licenses this file
  30963. * to you under the Apache License, Version 2.0 (the
  30964. * "License"); you may not use this file except in compliance
  30965. * with the License. You may obtain a copy of the License at
  30966. *
  30967. * http://www.apache.org/licenses/LICENSE-2.0
  30968. *
  30969. * Unless required by applicable law or agreed to in writing,
  30970. * software distributed under the License is distributed on an
  30971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30972. * KIND, either express or implied. See the License for the
  30973. * specific language governing permissions and limitations
  30974. * under the License.
  30975. */
  30976. // import * as axisHelper from './axisHelper';
  30977. var axisModelCommonMixin = {
  30978. /**
  30979. * @param {boolean} origin
  30980. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  30981. */
  30982. getMin: function (origin) {
  30983. var option = this.option;
  30984. var min = (!origin && option.rangeStart != null)
  30985. ? option.rangeStart : option.min;
  30986. if (this.axis
  30987. && min != null
  30988. && min !== 'dataMin'
  30989. && typeof min !== 'function'
  30990. && !eqNaN(min)
  30991. ) {
  30992. min = this.axis.scale.parse(min);
  30993. }
  30994. return min;
  30995. },
  30996. /**
  30997. * @param {boolean} origin
  30998. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  30999. */
  31000. getMax: function (origin) {
  31001. var option = this.option;
  31002. var max = (!origin && option.rangeEnd != null)
  31003. ? option.rangeEnd : option.max;
  31004. if (this.axis
  31005. && max != null
  31006. && max !== 'dataMax'
  31007. && typeof max !== 'function'
  31008. && !eqNaN(max)
  31009. ) {
  31010. max = this.axis.scale.parse(max);
  31011. }
  31012. return max;
  31013. },
  31014. /**
  31015. * @return {boolean}
  31016. */
  31017. getNeedCrossZero: function () {
  31018. var option = this.option;
  31019. return (option.rangeStart != null || option.rangeEnd != null)
  31020. ? false : !option.scale;
  31021. },
  31022. /**
  31023. * Should be implemented by each axis model if necessary.
  31024. * @return {module:echarts/model/Component} coordinate system model
  31025. */
  31026. getCoordSysModel: noop,
  31027. /**
  31028. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  31029. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  31030. */
  31031. setRange: function (rangeStart, rangeEnd) {
  31032. this.option.rangeStart = rangeStart;
  31033. this.option.rangeEnd = rangeEnd;
  31034. },
  31035. /**
  31036. * Reset range
  31037. */
  31038. resetRange: function () {
  31039. // rangeStart and rangeEnd is readonly.
  31040. this.option.rangeStart = this.option.rangeEnd = null;
  31041. }
  31042. };
  31043. /*
  31044. * Licensed to the Apache Software Foundation (ASF) under one
  31045. * or more contributor license agreements. See the NOTICE file
  31046. * distributed with this work for additional information
  31047. * regarding copyright ownership. The ASF licenses this file
  31048. * to you under the Apache License, Version 2.0 (the
  31049. * "License"); you may not use this file except in compliance
  31050. * with the License. You may obtain a copy of the License at
  31051. *
  31052. * http://www.apache.org/licenses/LICENSE-2.0
  31053. *
  31054. * Unless required by applicable law or agreed to in writing,
  31055. * software distributed under the License is distributed on an
  31056. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31057. * KIND, either express or implied. See the License for the
  31058. * specific language governing permissions and limitations
  31059. * under the License.
  31060. */
  31061. // Symbol factory
  31062. /**
  31063. * Triangle shape
  31064. * @inner
  31065. */
  31066. var Triangle = extendShape({
  31067. type: 'triangle',
  31068. shape: {
  31069. cx: 0,
  31070. cy: 0,
  31071. width: 0,
  31072. height: 0
  31073. },
  31074. buildPath: function (path, shape) {
  31075. var cx = shape.cx;
  31076. var cy = shape.cy;
  31077. var width = shape.width / 2;
  31078. var height = shape.height / 2;
  31079. path.moveTo(cx, cy - height);
  31080. path.lineTo(cx + width, cy + height);
  31081. path.lineTo(cx - width, cy + height);
  31082. path.closePath();
  31083. }
  31084. });
  31085. /**
  31086. * Diamond shape
  31087. * @inner
  31088. */
  31089. var Diamond = extendShape({
  31090. type: 'diamond',
  31091. shape: {
  31092. cx: 0,
  31093. cy: 0,
  31094. width: 0,
  31095. height: 0
  31096. },
  31097. buildPath: function (path, shape) {
  31098. var cx = shape.cx;
  31099. var cy = shape.cy;
  31100. var width = shape.width / 2;
  31101. var height = shape.height / 2;
  31102. path.moveTo(cx, cy - height);
  31103. path.lineTo(cx + width, cy);
  31104. path.lineTo(cx, cy + height);
  31105. path.lineTo(cx - width, cy);
  31106. path.closePath();
  31107. }
  31108. });
  31109. /**
  31110. * Pin shape
  31111. * @inner
  31112. */
  31113. var Pin = extendShape({
  31114. type: 'pin',
  31115. shape: {
  31116. // x, y on the cusp
  31117. x: 0,
  31118. y: 0,
  31119. width: 0,
  31120. height: 0
  31121. },
  31122. buildPath: function (path, shape) {
  31123. var x = shape.x;
  31124. var y = shape.y;
  31125. var w = shape.width / 5 * 3;
  31126. // Height must be larger than width
  31127. var h = Math.max(w, shape.height);
  31128. var r = w / 2;
  31129. // Dist on y with tangent point and circle center
  31130. var dy = r * r / (h - r);
  31131. var cy = y - h + r + dy;
  31132. var angle = Math.asin(dy / r);
  31133. // Dist on x with tangent point and circle center
  31134. var dx = Math.cos(angle) * r;
  31135. var tanX = Math.sin(angle);
  31136. var tanY = Math.cos(angle);
  31137. var cpLen = r * 0.6;
  31138. var cpLen2 = r * 0.7;
  31139. path.moveTo(x - dx, cy + dy);
  31140. path.arc(
  31141. x, cy, r,
  31142. Math.PI - angle,
  31143. Math.PI * 2 + angle
  31144. );
  31145. path.bezierCurveTo(
  31146. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31147. x, y - cpLen2,
  31148. x, y
  31149. );
  31150. path.bezierCurveTo(
  31151. x, y - cpLen2,
  31152. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31153. x - dx, cy + dy
  31154. );
  31155. path.closePath();
  31156. }
  31157. });
  31158. /**
  31159. * Arrow shape
  31160. * @inner
  31161. */
  31162. var Arrow = extendShape({
  31163. type: 'arrow',
  31164. shape: {
  31165. x: 0,
  31166. y: 0,
  31167. width: 0,
  31168. height: 0
  31169. },
  31170. buildPath: function (ctx, shape) {
  31171. var height = shape.height;
  31172. var width = shape.width;
  31173. var x = shape.x;
  31174. var y = shape.y;
  31175. var dx = width / 3 * 2;
  31176. ctx.moveTo(x, y);
  31177. ctx.lineTo(x + dx, y + height);
  31178. ctx.lineTo(x, y + height / 4 * 3);
  31179. ctx.lineTo(x - dx, y + height);
  31180. ctx.lineTo(x, y);
  31181. ctx.closePath();
  31182. }
  31183. });
  31184. /**
  31185. * Map of path contructors
  31186. * @type {Object.<string, module:zrender/graphic/Path>}
  31187. */
  31188. var symbolCtors = {
  31189. line: Line,
  31190. rect: Rect,
  31191. roundRect: Rect,
  31192. square: Rect,
  31193. circle: Circle,
  31194. diamond: Diamond,
  31195. pin: Pin,
  31196. arrow: Arrow,
  31197. triangle: Triangle
  31198. };
  31199. var symbolShapeMakers = {
  31200. line: function (x, y, w, h, shape) {
  31201. // FIXME
  31202. shape.x1 = x;
  31203. shape.y1 = y + h / 2;
  31204. shape.x2 = x + w;
  31205. shape.y2 = y + h / 2;
  31206. },
  31207. rect: function (x, y, w, h, shape) {
  31208. shape.x = x;
  31209. shape.y = y;
  31210. shape.width = w;
  31211. shape.height = h;
  31212. },
  31213. roundRect: function (x, y, w, h, shape) {
  31214. shape.x = x;
  31215. shape.y = y;
  31216. shape.width = w;
  31217. shape.height = h;
  31218. shape.r = Math.min(w, h) / 4;
  31219. },
  31220. square: function (x, y, w, h, shape) {
  31221. var size = Math.min(w, h);
  31222. shape.x = x;
  31223. shape.y = y;
  31224. shape.width = size;
  31225. shape.height = size;
  31226. },
  31227. circle: function (x, y, w, h, shape) {
  31228. // Put circle in the center of square
  31229. shape.cx = x + w / 2;
  31230. shape.cy = y + h / 2;
  31231. shape.r = Math.min(w, h) / 2;
  31232. },
  31233. diamond: function (x, y, w, h, shape) {
  31234. shape.cx = x + w / 2;
  31235. shape.cy = y + h / 2;
  31236. shape.width = w;
  31237. shape.height = h;
  31238. },
  31239. pin: function (x, y, w, h, shape) {
  31240. shape.x = x + w / 2;
  31241. shape.y = y + h / 2;
  31242. shape.width = w;
  31243. shape.height = h;
  31244. },
  31245. arrow: function (x, y, w, h, shape) {
  31246. shape.x = x + w / 2;
  31247. shape.y = y + h / 2;
  31248. shape.width = w;
  31249. shape.height = h;
  31250. },
  31251. triangle: function (x, y, w, h, shape) {
  31252. shape.cx = x + w / 2;
  31253. shape.cy = y + h / 2;
  31254. shape.width = w;
  31255. shape.height = h;
  31256. }
  31257. };
  31258. var symbolBuildProxies = {};
  31259. each$1(symbolCtors, function (Ctor, name) {
  31260. symbolBuildProxies[name] = new Ctor();
  31261. });
  31262. var SymbolClz = extendShape({
  31263. type: 'symbol',
  31264. shape: {
  31265. symbolType: '',
  31266. x: 0,
  31267. y: 0,
  31268. width: 0,
  31269. height: 0
  31270. },
  31271. calculateTextPosition: function (out, style, rect) {
  31272. var res = calculateTextPosition(out, style, rect);
  31273. var shape = this.shape;
  31274. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31275. res.y = rect.y + rect.height * 0.4;
  31276. }
  31277. return res;
  31278. },
  31279. buildPath: function (ctx, shape, inBundle) {
  31280. var symbolType = shape.symbolType;
  31281. if (symbolType !== 'none') {
  31282. var proxySymbol = symbolBuildProxies[symbolType];
  31283. if (!proxySymbol) {
  31284. // Default rect
  31285. symbolType = 'rect';
  31286. proxySymbol = symbolBuildProxies[symbolType];
  31287. }
  31288. symbolShapeMakers[symbolType](
  31289. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31290. );
  31291. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31292. }
  31293. }
  31294. });
  31295. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31296. function symbolPathSetColor(color, innerColor) {
  31297. if (this.type !== 'image') {
  31298. var symbolStyle = this.style;
  31299. var symbolShape = this.shape;
  31300. if (symbolShape && symbolShape.symbolType === 'line') {
  31301. symbolStyle.stroke = color;
  31302. }
  31303. else if (this.__isEmptyBrush) {
  31304. symbolStyle.stroke = color;
  31305. symbolStyle.fill = innerColor || '#fff';
  31306. }
  31307. else {
  31308. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31309. symbolStyle.fill && (symbolStyle.fill = color);
  31310. symbolStyle.stroke && (symbolStyle.stroke = color);
  31311. }
  31312. this.dirty(false);
  31313. }
  31314. }
  31315. /**
  31316. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31317. * @param {string} symbolType
  31318. * @param {number} x
  31319. * @param {number} y
  31320. * @param {number} w
  31321. * @param {number} h
  31322. * @param {string} color
  31323. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31324. * for path and image only.
  31325. */
  31326. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31327. // TODO Support image object, DynamicImage.
  31328. var isEmpty = symbolType.indexOf('empty') === 0;
  31329. if (isEmpty) {
  31330. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31331. }
  31332. var symbolPath;
  31333. if (symbolType.indexOf('image://') === 0) {
  31334. symbolPath = makeImage(
  31335. symbolType.slice(8),
  31336. new BoundingRect(x, y, w, h),
  31337. keepAspect ? 'center' : 'cover'
  31338. );
  31339. }
  31340. else if (symbolType.indexOf('path://') === 0) {
  31341. symbolPath = makePath(
  31342. symbolType.slice(7),
  31343. {},
  31344. new BoundingRect(x, y, w, h),
  31345. keepAspect ? 'center' : 'cover'
  31346. );
  31347. }
  31348. else {
  31349. symbolPath = new SymbolClz({
  31350. shape: {
  31351. symbolType: symbolType,
  31352. x: x,
  31353. y: y,
  31354. width: w,
  31355. height: h
  31356. }
  31357. });
  31358. }
  31359. symbolPath.__isEmptyBrush = isEmpty;
  31360. symbolPath.setColor = symbolPathSetColor;
  31361. symbolPath.setColor(color);
  31362. return symbolPath;
  31363. }
  31364. /*
  31365. * Licensed to the Apache Software Foundation (ASF) under one
  31366. * or more contributor license agreements. See the NOTICE file
  31367. * distributed with this work for additional information
  31368. * regarding copyright ownership. The ASF licenses this file
  31369. * to you under the Apache License, Version 2.0 (the
  31370. * "License"); you may not use this file except in compliance
  31371. * with the License. You may obtain a copy of the License at
  31372. *
  31373. * http://www.apache.org/licenses/LICENSE-2.0
  31374. *
  31375. * Unless required by applicable law or agreed to in writing,
  31376. * software distributed under the License is distributed on an
  31377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31378. * KIND, either express or implied. See the License for the
  31379. * specific language governing permissions and limitations
  31380. * under the License.
  31381. */
  31382. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31383. /**
  31384. * Create a muti dimension List structure from seriesModel.
  31385. * @param {module:echarts/model/Model} seriesModel
  31386. * @return {module:echarts/data/List} list
  31387. */
  31388. function createList(seriesModel) {
  31389. return createListFromArray(seriesModel.getSource(), seriesModel);
  31390. }
  31391. var dataStack$1 = {
  31392. isDimensionStacked: isDimensionStacked,
  31393. enableDataStack: enableDataStack,
  31394. getStackedDimension: getStackedDimension
  31395. };
  31396. /**
  31397. * Create scale
  31398. * @param {Array.<number>} dataExtent
  31399. * @param {Object|module:echarts/Model} option
  31400. */
  31401. function createScale(dataExtent, option) {
  31402. var axisModel = option;
  31403. if (!Model.isInstance(option)) {
  31404. axisModel = new Model(option);
  31405. mixin(axisModel, axisModelCommonMixin);
  31406. }
  31407. var scale = createScaleByModel(axisModel);
  31408. scale.setExtent(dataExtent[0], dataExtent[1]);
  31409. niceScaleExtent(scale, axisModel);
  31410. return scale;
  31411. }
  31412. /**
  31413. * Mixin common methods to axis model,
  31414. *
  31415. * Inlcude methods
  31416. * `getFormattedLabels() => Array.<string>`
  31417. * `getCategories() => Array.<string>`
  31418. * `getMin(origin: boolean) => number`
  31419. * `getMax(origin: boolean) => number`
  31420. * `getNeedCrossZero() => boolean`
  31421. * `setRange(start: number, end: number)`
  31422. * `resetRange()`
  31423. */
  31424. function mixinAxisModelCommonMethods(Model$$1) {
  31425. mixin(Model$$1, axisModelCommonMixin);
  31426. }
  31427. var helper = (Object.freeze || Object)({
  31428. createList: createList,
  31429. getLayoutRect: getLayoutRect,
  31430. dataStack: dataStack$1,
  31431. createScale: createScale,
  31432. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31433. completeDimensions: completeDimensions,
  31434. createDimensions: createDimensions,
  31435. createSymbol: createSymbol
  31436. });
  31437. var EPSILON$3 = 1e-8;
  31438. function isAroundEqual$1(a, b) {
  31439. return Math.abs(a - b) < EPSILON$3;
  31440. }
  31441. function contain$1(points, x, y) {
  31442. var w = 0;
  31443. var p = points[0];
  31444. if (!p) {
  31445. return false;
  31446. }
  31447. for (var i = 1; i < points.length; i++) {
  31448. var p2 = points[i];
  31449. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31450. p = p2;
  31451. }
  31452. // Close polygon
  31453. var p0 = points[0];
  31454. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31455. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31456. }
  31457. return w !== 0;
  31458. }
  31459. /*
  31460. * Licensed to the Apache Software Foundation (ASF) under one
  31461. * or more contributor license agreements. See the NOTICE file
  31462. * distributed with this work for additional information
  31463. * regarding copyright ownership. The ASF licenses this file
  31464. * to you under the Apache License, Version 2.0 (the
  31465. * "License"); you may not use this file except in compliance
  31466. * with the License. You may obtain a copy of the License at
  31467. *
  31468. * http://www.apache.org/licenses/LICENSE-2.0
  31469. *
  31470. * Unless required by applicable law or agreed to in writing,
  31471. * software distributed under the License is distributed on an
  31472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31473. * KIND, either express or implied. See the License for the
  31474. * specific language governing permissions and limitations
  31475. * under the License.
  31476. */
  31477. /**
  31478. * @module echarts/coord/geo/Region
  31479. */
  31480. /**
  31481. * @param {string|Region} name
  31482. * @param {Array} geometries
  31483. * @param {Array.<number>} cp
  31484. */
  31485. function Region(name, geometries, cp) {
  31486. /**
  31487. * @type {string}
  31488. * @readOnly
  31489. */
  31490. this.name = name;
  31491. /**
  31492. * @type {Array.<Array>}
  31493. * @readOnly
  31494. */
  31495. this.geometries = geometries;
  31496. if (!cp) {
  31497. var rect = this.getBoundingRect();
  31498. cp = [
  31499. rect.x + rect.width / 2,
  31500. rect.y + rect.height / 2
  31501. ];
  31502. }
  31503. else {
  31504. cp = [cp[0], cp[1]];
  31505. }
  31506. /**
  31507. * @type {Array.<number>}
  31508. */
  31509. this.center = cp;
  31510. }
  31511. Region.prototype = {
  31512. constructor: Region,
  31513. properties: null,
  31514. /**
  31515. * @return {module:zrender/core/BoundingRect}
  31516. */
  31517. getBoundingRect: function () {
  31518. var rect = this._rect;
  31519. if (rect) {
  31520. return rect;
  31521. }
  31522. var MAX_NUMBER = Number.MAX_VALUE;
  31523. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31524. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31525. var min2 = [];
  31526. var max2 = [];
  31527. var geometries = this.geometries;
  31528. for (var i = 0; i < geometries.length; i++) {
  31529. // Only support polygon
  31530. if (geometries[i].type !== 'polygon') {
  31531. continue;
  31532. }
  31533. // Doesn't consider hole
  31534. var exterior = geometries[i].exterior;
  31535. fromPoints(exterior, min2, max2);
  31536. min(min$$1, min$$1, min2);
  31537. max(max$$1, max$$1, max2);
  31538. }
  31539. // No data
  31540. if (i === 0) {
  31541. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31542. }
  31543. return (this._rect = new BoundingRect(
  31544. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31545. ));
  31546. },
  31547. /**
  31548. * @param {<Array.<number>} coord
  31549. * @return {boolean}
  31550. */
  31551. contain: function (coord) {
  31552. var rect = this.getBoundingRect();
  31553. var geometries = this.geometries;
  31554. if (!rect.contain(coord[0], coord[1])) {
  31555. return false;
  31556. }
  31557. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31558. // Only support polygon.
  31559. if (geometries[i].type !== 'polygon') {
  31560. continue;
  31561. }
  31562. var exterior = geometries[i].exterior;
  31563. var interiors = geometries[i].interiors;
  31564. if (contain$1(exterior, coord[0], coord[1])) {
  31565. // Not in the region if point is in the hole.
  31566. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31567. if (contain$1(interiors[k])) {
  31568. continue loopGeo;
  31569. }
  31570. }
  31571. return true;
  31572. }
  31573. }
  31574. return false;
  31575. },
  31576. transformTo: function (x, y, width, height) {
  31577. var rect = this.getBoundingRect();
  31578. var aspect = rect.width / rect.height;
  31579. if (!width) {
  31580. width = aspect * height;
  31581. }
  31582. else if (!height) {
  31583. height = width / aspect;
  31584. }
  31585. var target = new BoundingRect(x, y, width, height);
  31586. var transform = rect.calculateTransform(target);
  31587. var geometries = this.geometries;
  31588. for (var i = 0; i < geometries.length; i++) {
  31589. // Only support polygon.
  31590. if (geometries[i].type !== 'polygon') {
  31591. continue;
  31592. }
  31593. var exterior = geometries[i].exterior;
  31594. var interiors = geometries[i].interiors;
  31595. for (var p = 0; p < exterior.length; p++) {
  31596. applyTransform(exterior[p], exterior[p], transform);
  31597. }
  31598. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31599. for (var p = 0; p < interiors[h].length; p++) {
  31600. applyTransform(interiors[h][p], interiors[h][p], transform);
  31601. }
  31602. }
  31603. }
  31604. rect = this._rect;
  31605. rect.copy(target);
  31606. // Update center
  31607. this.center = [
  31608. rect.x + rect.width / 2,
  31609. rect.y + rect.height / 2
  31610. ];
  31611. },
  31612. cloneShallow: function (name) {
  31613. name == null && (name = this.name);
  31614. var newRegion = new Region(name, this.geometries, this.center);
  31615. newRegion._rect = this._rect;
  31616. newRegion.transformTo = null; // Simply avoid to be called.
  31617. return newRegion;
  31618. }
  31619. };
  31620. /*
  31621. * Licensed to the Apache Software Foundation (ASF) under one
  31622. * or more contributor license agreements. See the NOTICE file
  31623. * distributed with this work for additional information
  31624. * regarding copyright ownership. The ASF licenses this file
  31625. * to you under the Apache License, Version 2.0 (the
  31626. * "License"); you may not use this file except in compliance
  31627. * with the License. You may obtain a copy of the License at
  31628. *
  31629. * http://www.apache.org/licenses/LICENSE-2.0
  31630. *
  31631. * Unless required by applicable law or agreed to in writing,
  31632. * software distributed under the License is distributed on an
  31633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31634. * KIND, either express or implied. See the License for the
  31635. * specific language governing permissions and limitations
  31636. * under the License.
  31637. */
  31638. /**
  31639. * Parse and decode geo json
  31640. * @module echarts/coord/geo/parseGeoJson
  31641. */
  31642. function decode(json) {
  31643. if (!json.UTF8Encoding) {
  31644. return json;
  31645. }
  31646. var encodeScale = json.UTF8Scale;
  31647. if (encodeScale == null) {
  31648. encodeScale = 1024;
  31649. }
  31650. var features = json.features;
  31651. for (var f = 0; f < features.length; f++) {
  31652. var feature = features[f];
  31653. var geometry = feature.geometry;
  31654. var coordinates = geometry.coordinates;
  31655. var encodeOffsets = geometry.encodeOffsets;
  31656. for (var c = 0; c < coordinates.length; c++) {
  31657. var coordinate = coordinates[c];
  31658. if (geometry.type === 'Polygon') {
  31659. coordinates[c] = decodePolygon(
  31660. coordinate,
  31661. encodeOffsets[c],
  31662. encodeScale
  31663. );
  31664. }
  31665. else if (geometry.type === 'MultiPolygon') {
  31666. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31667. var polygon = coordinate[c2];
  31668. coordinate[c2] = decodePolygon(
  31669. polygon,
  31670. encodeOffsets[c][c2],
  31671. encodeScale
  31672. );
  31673. }
  31674. }
  31675. }
  31676. }
  31677. // Has been decoded
  31678. json.UTF8Encoding = false;
  31679. return json;
  31680. }
  31681. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31682. var result = [];
  31683. var prevX = encodeOffsets[0];
  31684. var prevY = encodeOffsets[1];
  31685. for (var i = 0; i < coordinate.length; i += 2) {
  31686. var x = coordinate.charCodeAt(i) - 64;
  31687. var y = coordinate.charCodeAt(i + 1) - 64;
  31688. // ZigZag decoding
  31689. x = (x >> 1) ^ (-(x & 1));
  31690. y = (y >> 1) ^ (-(y & 1));
  31691. // Delta deocding
  31692. x += prevX;
  31693. y += prevY;
  31694. prevX = x;
  31695. prevY = y;
  31696. // Dequantize
  31697. result.push([x / encodeScale, y / encodeScale]);
  31698. }
  31699. return result;
  31700. }
  31701. /**
  31702. * @alias module:echarts/coord/geo/parseGeoJson
  31703. * @param {Object} geoJson
  31704. * @return {module:zrender/container/Group}
  31705. */
  31706. var parseGeoJson$1 = function (geoJson) {
  31707. decode(geoJson);
  31708. return map(filter(geoJson.features, function (featureObj) {
  31709. // Output of mapshaper may have geometry null
  31710. return featureObj.geometry
  31711. && featureObj.properties
  31712. && featureObj.geometry.coordinates.length > 0;
  31713. }), function (featureObj) {
  31714. var properties = featureObj.properties;
  31715. var geo = featureObj.geometry;
  31716. var coordinates = geo.coordinates;
  31717. var geometries = [];
  31718. if (geo.type === 'Polygon') {
  31719. geometries.push({
  31720. type: 'polygon',
  31721. // According to the GeoJSON specification.
  31722. // First must be exterior, and the rest are all interior(holes).
  31723. exterior: coordinates[0],
  31724. interiors: coordinates.slice(1)
  31725. });
  31726. }
  31727. if (geo.type === 'MultiPolygon') {
  31728. each$1(coordinates, function (item) {
  31729. if (item[0]) {
  31730. geometries.push({
  31731. type: 'polygon',
  31732. exterior: item[0],
  31733. interiors: item.slice(1)
  31734. });
  31735. }
  31736. });
  31737. }
  31738. var region = new Region(
  31739. properties.name,
  31740. geometries,
  31741. properties.cp
  31742. );
  31743. region.properties = properties;
  31744. return region;
  31745. });
  31746. };
  31747. /*
  31748. * Licensed to the Apache Software Foundation (ASF) under one
  31749. * or more contributor license agreements. See the NOTICE file
  31750. * distributed with this work for additional information
  31751. * regarding copyright ownership. The ASF licenses this file
  31752. * to you under the Apache License, Version 2.0 (the
  31753. * "License"); you may not use this file except in compliance
  31754. * with the License. You may obtain a copy of the License at
  31755. *
  31756. * http://www.apache.org/licenses/LICENSE-2.0
  31757. *
  31758. * Unless required by applicable law or agreed to in writing,
  31759. * software distributed under the License is distributed on an
  31760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31761. * KIND, either express or implied. See the License for the
  31762. * specific language governing permissions and limitations
  31763. * under the License.
  31764. */
  31765. var inner$6 = makeInner();
  31766. /**
  31767. * @param {module:echats/coord/Axis} axis
  31768. * @return {Object} {
  31769. * labels: [{
  31770. * formattedLabel: string,
  31771. * rawLabel: string,
  31772. * tickValue: number
  31773. * }, ...],
  31774. * labelCategoryInterval: number
  31775. * }
  31776. */
  31777. function createAxisLabels(axis) {
  31778. // Only ordinal scale support tick interval
  31779. return axis.type === 'category'
  31780. ? makeCategoryLabels(axis)
  31781. : makeRealNumberLabels(axis);
  31782. }
  31783. /**
  31784. * @param {module:echats/coord/Axis} axis
  31785. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31786. * @return {Object} {
  31787. * ticks: Array.<number>
  31788. * tickCategoryInterval: number
  31789. * }
  31790. */
  31791. function createAxisTicks(axis, tickModel) {
  31792. // Only ordinal scale support tick interval
  31793. return axis.type === 'category'
  31794. ? makeCategoryTicks(axis, tickModel)
  31795. : {ticks: axis.scale.getTicks()};
  31796. }
  31797. function makeCategoryLabels(axis) {
  31798. var labelModel = axis.getLabelModel();
  31799. var result = makeCategoryLabelsActually(axis, labelModel);
  31800. return (!labelModel.get('show') || axis.scale.isBlank())
  31801. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31802. : result;
  31803. }
  31804. function makeCategoryLabelsActually(axis, labelModel) {
  31805. var labelsCache = getListCache(axis, 'labels');
  31806. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31807. var result = listCacheGet(labelsCache, optionLabelInterval);
  31808. if (result) {
  31809. return result;
  31810. }
  31811. var labels;
  31812. var numericLabelInterval;
  31813. if (isFunction$1(optionLabelInterval)) {
  31814. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31815. }
  31816. else {
  31817. numericLabelInterval = optionLabelInterval === 'auto'
  31818. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31819. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31820. }
  31821. // Cache to avoid calling interval function repeatly.
  31822. return listCacheSet(labelsCache, optionLabelInterval, {
  31823. labels: labels, labelCategoryInterval: numericLabelInterval
  31824. });
  31825. }
  31826. function makeCategoryTicks(axis, tickModel) {
  31827. var ticksCache = getListCache(axis, 'ticks');
  31828. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31829. var result = listCacheGet(ticksCache, optionTickInterval);
  31830. if (result) {
  31831. return result;
  31832. }
  31833. var ticks;
  31834. var tickCategoryInterval;
  31835. // Optimize for the case that large category data and no label displayed,
  31836. // we should not return all ticks.
  31837. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31838. ticks = [];
  31839. }
  31840. if (isFunction$1(optionTickInterval)) {
  31841. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31842. }
  31843. // Always use label interval by default despite label show. Consider this
  31844. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31845. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31846. else if (optionTickInterval === 'auto') {
  31847. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31848. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31849. ticks = map(labelsResult.labels, function (labelItem) {
  31850. return labelItem.tickValue;
  31851. });
  31852. }
  31853. else {
  31854. tickCategoryInterval = optionTickInterval;
  31855. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31856. }
  31857. // Cache to avoid calling interval function repeatly.
  31858. return listCacheSet(ticksCache, optionTickInterval, {
  31859. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31860. });
  31861. }
  31862. function makeRealNumberLabels(axis) {
  31863. var ticks = axis.scale.getTicks();
  31864. var labelFormatter = makeLabelFormatter(axis);
  31865. return {
  31866. labels: map(ticks, function (tickValue, idx) {
  31867. return {
  31868. formattedLabel: labelFormatter(tickValue, idx),
  31869. rawLabel: axis.scale.getLabel(tickValue),
  31870. tickValue: tickValue
  31871. };
  31872. })
  31873. };
  31874. }
  31875. // Large category data calculation is performence sensitive, and ticks and label
  31876. // probably be fetched by multiple times. So we cache the result.
  31877. // axis is created each time during a ec process, so we do not need to clear cache.
  31878. function getListCache(axis, prop) {
  31879. // Because key can be funciton, and cache size always be small, we use array cache.
  31880. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31881. }
  31882. function listCacheGet(cache, key) {
  31883. for (var i = 0; i < cache.length; i++) {
  31884. if (cache[i].key === key) {
  31885. return cache[i].value;
  31886. }
  31887. }
  31888. }
  31889. function listCacheSet(cache, key, value) {
  31890. cache.push({key: key, value: value});
  31891. return value;
  31892. }
  31893. function makeAutoCategoryInterval(axis) {
  31894. var result = inner$6(axis).autoInterval;
  31895. return result != null
  31896. ? result
  31897. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31898. }
  31899. /**
  31900. * Calculate interval for category axis ticks and labels.
  31901. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31902. * should be implemented in axis.
  31903. */
  31904. function calculateCategoryInterval(axis) {
  31905. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31906. var labelFormatter = makeLabelFormatter(axis);
  31907. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31908. var ordinalScale = axis.scale;
  31909. var ordinalExtent = ordinalScale.getExtent();
  31910. // Providing this method is for optimization:
  31911. // avoid generating a long array by `getTicks`
  31912. // in large category data case.
  31913. var tickCount = ordinalScale.count();
  31914. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31915. return 0;
  31916. }
  31917. var step = 1;
  31918. // Simple optimization. Empirical value: tick count should less than 40.
  31919. if (tickCount > 40) {
  31920. step = Math.max(1, Math.floor(tickCount / 40));
  31921. }
  31922. var tickValue = ordinalExtent[0];
  31923. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31924. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31925. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31926. var maxW = 0;
  31927. var maxH = 0;
  31928. // Caution: Performance sensitive for large category data.
  31929. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31930. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31931. var width = 0;
  31932. var height = 0;
  31933. // Not precise, do not consider align and vertical align
  31934. // and each distance from axis line yet.
  31935. var rect = getBoundingRect(
  31936. labelFormatter(tickValue), params.font, 'center', 'top'
  31937. );
  31938. // Magic number
  31939. width = rect.width * 1.3;
  31940. height = rect.height * 1.3;
  31941. // Min size, void long loop.
  31942. maxW = Math.max(maxW, width, 7);
  31943. maxH = Math.max(maxH, height, 7);
  31944. }
  31945. var dw = maxW / unitW;
  31946. var dh = maxH / unitH;
  31947. // 0/0 is NaN, 1/0 is Infinity.
  31948. isNaN(dw) && (dw = Infinity);
  31949. isNaN(dh) && (dh = Infinity);
  31950. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31951. var cache = inner$6(axis.model);
  31952. var axisExtent = axis.getExtent();
  31953. var lastAutoInterval = cache.lastAutoInterval;
  31954. var lastTickCount = cache.lastTickCount;
  31955. // Use cache to keep interval stable while moving zoom window,
  31956. // otherwise the calculated interval might jitter when the zoom
  31957. // window size is close to the interval-changing size.
  31958. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31959. // The jitter will cause that sometimes the displayed labels are
  31960. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31961. if (lastAutoInterval != null
  31962. && lastTickCount != null
  31963. && Math.abs(lastAutoInterval - interval) <= 1
  31964. && Math.abs(lastTickCount - tickCount) <= 1
  31965. // Always choose the bigger one, otherwise the critical
  31966. // point is not the same when zooming in or zooming out.
  31967. && lastAutoInterval > interval
  31968. // If the axis change is caused by chart resize, the cache should not
  31969. // be used. Otherwise some hiden labels might not be shown again.
  31970. && cache.axisExtend0 === axisExtent[0]
  31971. && cache.axisExtend1 === axisExtent[1]
  31972. ) {
  31973. interval = lastAutoInterval;
  31974. }
  31975. // Only update cache if cache not used, otherwise the
  31976. // changing of interval is too insensitive.
  31977. else {
  31978. cache.lastTickCount = tickCount;
  31979. cache.lastAutoInterval = interval;
  31980. cache.axisExtend0 = axisExtent[0];
  31981. cache.axisExtend1 = axisExtent[1];
  31982. }
  31983. return interval;
  31984. }
  31985. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31986. var labelModel = axis.getLabelModel();
  31987. return {
  31988. axisRotate: axis.getRotate
  31989. ? axis.getRotate()
  31990. : (axis.isHorizontal && !axis.isHorizontal())
  31991. ? 90
  31992. : 0,
  31993. labelRotate: labelModel.get('rotate') || 0,
  31994. font: labelModel.getFont()
  31995. };
  31996. }
  31997. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31998. var labelFormatter = makeLabelFormatter(axis);
  31999. var ordinalScale = axis.scale;
  32000. var ordinalExtent = ordinalScale.getExtent();
  32001. var labelModel = axis.getLabelModel();
  32002. var result = [];
  32003. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32004. var step = Math.max((categoryInterval || 0) + 1, 1);
  32005. var startTick = ordinalExtent[0];
  32006. var tickCount = ordinalScale.count();
  32007. // Calculate start tick based on zero if possible to keep label consistent
  32008. // while zooming and moving while interval > 0. Otherwise the selection
  32009. // of displayable ticks and symbols probably keep changing.
  32010. // 3 is empirical value.
  32011. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32012. startTick = Math.round(Math.ceil(startTick / step) * step);
  32013. }
  32014. // (1) Only add min max label here but leave overlap checking
  32015. // to render stage, which also ensure the returned list
  32016. // suitable for splitLine and splitArea rendering.
  32017. // (2) Scales except category always contain min max label so
  32018. // do not need to perform this process.
  32019. var showAllLabel = shouldShowAllLabels(axis);
  32020. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32021. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32022. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32023. addItem(ordinalExtent[0]);
  32024. }
  32025. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32026. var tickValue = startTick;
  32027. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32028. addItem(tickValue);
  32029. }
  32030. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32031. addItem(ordinalExtent[1]);
  32032. }
  32033. function addItem(tVal) {
  32034. result.push(onlyTick
  32035. ? tVal
  32036. : {
  32037. formattedLabel: labelFormatter(tVal),
  32038. rawLabel: ordinalScale.getLabel(tVal),
  32039. tickValue: tVal
  32040. }
  32041. );
  32042. }
  32043. return result;
  32044. }
  32045. // When interval is function, the result `false` means ignore the tick.
  32046. // It is time consuming for large category data.
  32047. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32048. var ordinalScale = axis.scale;
  32049. var labelFormatter = makeLabelFormatter(axis);
  32050. var result = [];
  32051. each$1(ordinalScale.getTicks(), function (tickValue) {
  32052. var rawLabel = ordinalScale.getLabel(tickValue);
  32053. if (categoryInterval(tickValue, rawLabel)) {
  32054. result.push(onlyTick
  32055. ? tickValue
  32056. : {
  32057. formattedLabel: labelFormatter(tickValue),
  32058. rawLabel: rawLabel,
  32059. tickValue: tickValue
  32060. }
  32061. );
  32062. }
  32063. });
  32064. return result;
  32065. }
  32066. /*
  32067. * Licensed to the Apache Software Foundation (ASF) under one
  32068. * or more contributor license agreements. See the NOTICE file
  32069. * distributed with this work for additional information
  32070. * regarding copyright ownership. The ASF licenses this file
  32071. * to you under the Apache License, Version 2.0 (the
  32072. * "License"); you may not use this file except in compliance
  32073. * with the License. You may obtain a copy of the License at
  32074. *
  32075. * http://www.apache.org/licenses/LICENSE-2.0
  32076. *
  32077. * Unless required by applicable law or agreed to in writing,
  32078. * software distributed under the License is distributed on an
  32079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32080. * KIND, either express or implied. See the License for the
  32081. * specific language governing permissions and limitations
  32082. * under the License.
  32083. */
  32084. var NORMALIZED_EXTENT = [0, 1];
  32085. /**
  32086. * Base class of Axis.
  32087. * @constructor
  32088. */
  32089. var Axis = function (dim, scale, extent) {
  32090. /**
  32091. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32092. * @type {string}
  32093. */
  32094. this.dim = dim;
  32095. /**
  32096. * Axis scale
  32097. * @type {module:echarts/coord/scale/*}
  32098. */
  32099. this.scale = scale;
  32100. /**
  32101. * @type {Array.<number>}
  32102. * @private
  32103. */
  32104. this._extent = extent || [0, 0];
  32105. /**
  32106. * @type {boolean}
  32107. */
  32108. this.inverse = false;
  32109. /**
  32110. * Usually true when axis has a ordinal scale
  32111. * @type {boolean}
  32112. */
  32113. this.onBand = false;
  32114. };
  32115. Axis.prototype = {
  32116. constructor: Axis,
  32117. /**
  32118. * If axis extent contain given coord
  32119. * @param {number} coord
  32120. * @return {boolean}
  32121. */
  32122. contain: function (coord) {
  32123. var extent = this._extent;
  32124. var min = Math.min(extent[0], extent[1]);
  32125. var max = Math.max(extent[0], extent[1]);
  32126. return coord >= min && coord <= max;
  32127. },
  32128. /**
  32129. * If axis extent contain given data
  32130. * @param {number} data
  32131. * @return {boolean}
  32132. */
  32133. containData: function (data) {
  32134. return this.scale.contain(data);
  32135. },
  32136. /**
  32137. * Get coord extent.
  32138. * @return {Array.<number>}
  32139. */
  32140. getExtent: function () {
  32141. return this._extent.slice();
  32142. },
  32143. /**
  32144. * Get precision used for formatting
  32145. * @param {Array.<number>} [dataExtent]
  32146. * @return {number}
  32147. */
  32148. getPixelPrecision: function (dataExtent) {
  32149. return getPixelPrecision(
  32150. dataExtent || this.scale.getExtent(),
  32151. this._extent
  32152. );
  32153. },
  32154. /**
  32155. * Set coord extent
  32156. * @param {number} start
  32157. * @param {number} end
  32158. */
  32159. setExtent: function (start, end) {
  32160. var extent = this._extent;
  32161. extent[0] = start;
  32162. extent[1] = end;
  32163. },
  32164. /**
  32165. * Convert data to coord. Data is the rank if it has an ordinal scale
  32166. * @param {number} data
  32167. * @param {boolean} clamp
  32168. * @return {number}
  32169. */
  32170. dataToCoord: function (data, clamp) {
  32171. var extent = this._extent;
  32172. var scale = this.scale;
  32173. data = scale.normalize(data);
  32174. if (this.onBand && scale.type === 'ordinal') {
  32175. extent = extent.slice();
  32176. fixExtentWithBands(extent, scale.count());
  32177. }
  32178. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32179. },
  32180. /**
  32181. * Convert coord to data. Data is the rank if it has an ordinal scale
  32182. * @param {number} coord
  32183. * @param {boolean} clamp
  32184. * @return {number}
  32185. */
  32186. coordToData: function (coord, clamp) {
  32187. var extent = this._extent;
  32188. var scale = this.scale;
  32189. if (this.onBand && scale.type === 'ordinal') {
  32190. extent = extent.slice();
  32191. fixExtentWithBands(extent, scale.count());
  32192. }
  32193. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32194. return this.scale.scale(t);
  32195. },
  32196. /**
  32197. * Convert pixel point to data in axis
  32198. * @param {Array.<number>} point
  32199. * @param {boolean} clamp
  32200. * @return {number} data
  32201. */
  32202. pointToData: function (point, clamp) {
  32203. // Should be implemented in derived class if necessary.
  32204. },
  32205. /**
  32206. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32207. * `axis.getTicksCoords` considers `onBand`, which is used by
  32208. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32209. * @param {Object} [opt]
  32210. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32211. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32212. * tick must be at the axis end points. Otherwise, clip ticks
  32213. * that outside the axis extent.
  32214. * @return {Array.<Object>} [{
  32215. * coord: ...,
  32216. * tickValue: ...
  32217. * }, ...]
  32218. */
  32219. getTicksCoords: function (opt) {
  32220. opt = opt || {};
  32221. var tickModel = opt.tickModel || this.getTickModel();
  32222. var result = createAxisTicks(this, tickModel);
  32223. var ticks = result.ticks;
  32224. var ticksCoords = map(ticks, function (tickValue) {
  32225. return {
  32226. coord: this.dataToCoord(tickValue),
  32227. tickValue: tickValue
  32228. };
  32229. }, this);
  32230. var alignWithLabel = tickModel.get('alignWithLabel');
  32231. fixOnBandTicksCoords(
  32232. this, ticksCoords, alignWithLabel, opt.clamp
  32233. );
  32234. return ticksCoords;
  32235. },
  32236. /**
  32237. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32238. */
  32239. getMinorTicksCoords: function () {
  32240. if (this.scale.type === 'ordinal') {
  32241. // Category axis doesn't support minor ticks
  32242. return [];
  32243. }
  32244. var minorTickModel = this.model.getModel('minorTick');
  32245. var splitNumber = minorTickModel.get('splitNumber');
  32246. // Protection.
  32247. if (!(splitNumber > 0 && splitNumber < 100)) {
  32248. splitNumber = 5;
  32249. }
  32250. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32251. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32252. return map(minorTicksGroup, function (minorTick) {
  32253. return {
  32254. coord: this.dataToCoord(minorTick),
  32255. tickValue: minorTick
  32256. };
  32257. }, this);
  32258. }, this);
  32259. return minorTicksCoords;
  32260. },
  32261. /**
  32262. * @return {Array.<Object>} [{
  32263. * formattedLabel: string,
  32264. * rawLabel: axis.scale.getLabel(tickValue)
  32265. * tickValue: number
  32266. * }, ...]
  32267. */
  32268. getViewLabels: function () {
  32269. return createAxisLabels(this).labels;
  32270. },
  32271. /**
  32272. * @return {module:echarts/coord/model/Model}
  32273. */
  32274. getLabelModel: function () {
  32275. return this.model.getModel('axisLabel');
  32276. },
  32277. /**
  32278. * Notice here we only get the default tick model. For splitLine
  32279. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32280. * manually when calling `getTicksCoords`.
  32281. * In GL, this method may be overrided to:
  32282. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32283. * @return {module:echarts/coord/model/Model}
  32284. */
  32285. getTickModel: function () {
  32286. return this.model.getModel('axisTick');
  32287. },
  32288. /**
  32289. * Get width of band
  32290. * @return {number}
  32291. */
  32292. getBandWidth: function () {
  32293. var axisExtent = this._extent;
  32294. var dataExtent = this.scale.getExtent();
  32295. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32296. // Fix #2728, avoid NaN when only one data.
  32297. len === 0 && (len = 1);
  32298. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32299. return Math.abs(size) / len;
  32300. },
  32301. /**
  32302. * @abstract
  32303. * @return {boolean} Is horizontal
  32304. */
  32305. isHorizontal: null,
  32306. /**
  32307. * @abstract
  32308. * @return {number} Get axis rotate, by degree.
  32309. */
  32310. getRotate: null,
  32311. /**
  32312. * Only be called in category axis.
  32313. * Can be overrided, consider other axes like in 3D.
  32314. * @return {number} Auto interval for cateogry axis tick and label
  32315. */
  32316. calculateCategoryInterval: function () {
  32317. return calculateCategoryInterval(this);
  32318. }
  32319. };
  32320. function fixExtentWithBands(extent, nTick) {
  32321. var size = extent[1] - extent[0];
  32322. var len = nTick;
  32323. var margin = size / len / 2;
  32324. extent[0] += margin;
  32325. extent[1] -= margin;
  32326. }
  32327. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32328. // |---1---|---2---|---3---|---4---|.
  32329. // So the displayed ticks and splitLine/splitArea should between
  32330. // each data item, otherwise cause misleading (e.g., split tow bars
  32331. // of a single data item when there are two bar series).
  32332. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32333. // splitLine/spliteArea should layout appropriately corresponding
  32334. // to displayed labels. (So we should not use `getBandWidth` in this
  32335. // case).
  32336. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32337. var ticksLen = ticksCoords.length;
  32338. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32339. return;
  32340. }
  32341. var axisExtent = axis.getExtent();
  32342. var last;
  32343. var diffSize;
  32344. if (ticksLen === 1) {
  32345. ticksCoords[0].coord = axisExtent[0];
  32346. last = ticksCoords[1] = {coord: axisExtent[0]};
  32347. }
  32348. else {
  32349. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32350. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32351. each$1(ticksCoords, function (ticksItem) {
  32352. ticksItem.coord -= shift / 2;
  32353. });
  32354. var dataExtent = axis.scale.getExtent();
  32355. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32356. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32357. ticksCoords.push(last);
  32358. }
  32359. var inverse = axisExtent[0] > axisExtent[1];
  32360. // Handling clamp.
  32361. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32362. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32363. }
  32364. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32365. ticksCoords.unshift({coord: axisExtent[0]});
  32366. }
  32367. if (littleThan(axisExtent[1], last.coord)) {
  32368. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32369. }
  32370. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32371. ticksCoords.push({coord: axisExtent[1]});
  32372. }
  32373. function littleThan(a, b) {
  32374. // Avoid rounding error cause calculated tick coord different with extent.
  32375. // It may cause an extra unecessary tick added.
  32376. a = round$1(a);
  32377. b = round$1(b);
  32378. return inverse ? a > b : a < b;
  32379. }
  32380. }
  32381. /*
  32382. * Licensed to the Apache Software Foundation (ASF) under one
  32383. * or more contributor license agreements. See the NOTICE file
  32384. * distributed with this work for additional information
  32385. * regarding copyright ownership. The ASF licenses this file
  32386. * to you under the Apache License, Version 2.0 (the
  32387. * "License"); you may not use this file except in compliance
  32388. * with the License. You may obtain a copy of the License at
  32389. *
  32390. * http://www.apache.org/licenses/LICENSE-2.0
  32391. *
  32392. * Unless required by applicable law or agreed to in writing,
  32393. * software distributed under the License is distributed on an
  32394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32395. * KIND, either express or implied. See the License for the
  32396. * specific language governing permissions and limitations
  32397. * under the License.
  32398. */
  32399. /**
  32400. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32401. */
  32402. var parseGeoJson = parseGeoJson$1;
  32403. var ecUtil = {};
  32404. each$1(
  32405. [
  32406. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32407. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32408. 'extend', 'defaults', 'clone', 'merge'
  32409. ],
  32410. function (name) {
  32411. ecUtil[name] = zrUtil[name];
  32412. }
  32413. );
  32414. var graphic$1 = {};
  32415. each$1(
  32416. [
  32417. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32418. 'mergePath', 'resizePath', 'createIcon',
  32419. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32420. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32421. 'clipPointsByRect', 'clipRectByRect',
  32422. 'registerShape', 'getShapeClass',
  32423. 'Group',
  32424. 'Image',
  32425. 'Text',
  32426. 'Circle',
  32427. 'Sector',
  32428. 'Ring',
  32429. 'Polygon',
  32430. 'Polyline',
  32431. 'Rect',
  32432. 'Line',
  32433. 'BezierCurve',
  32434. 'Arc',
  32435. 'IncrementalDisplayable',
  32436. 'CompoundPath',
  32437. 'LinearGradient',
  32438. 'RadialGradient',
  32439. 'BoundingRect'
  32440. ],
  32441. function (name) {
  32442. graphic$1[name] = graphic[name];
  32443. }
  32444. );
  32445. /*
  32446. * Licensed to the Apache Software Foundation (ASF) under one
  32447. * or more contributor license agreements. See the NOTICE file
  32448. * distributed with this work for additional information
  32449. * regarding copyright ownership. The ASF licenses this file
  32450. * to you under the Apache License, Version 2.0 (the
  32451. * "License"); you may not use this file except in compliance
  32452. * with the License. You may obtain a copy of the License at
  32453. *
  32454. * http://www.apache.org/licenses/LICENSE-2.0
  32455. *
  32456. * Unless required by applicable law or agreed to in writing,
  32457. * software distributed under the License is distributed on an
  32458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32459. * KIND, either express or implied. See the License for the
  32460. * specific language governing permissions and limitations
  32461. * under the License.
  32462. */
  32463. SeriesModel.extend({
  32464. type: 'series.line',
  32465. dependencies: ['grid', 'polar'],
  32466. getInitialData: function (option, ecModel) {
  32467. if (__DEV__) {
  32468. var coordSys = option.coordinateSystem;
  32469. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32470. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32471. }
  32472. }
  32473. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32474. },
  32475. defaultOption: {
  32476. zlevel: 0,
  32477. z: 2,
  32478. coordinateSystem: 'cartesian2d',
  32479. legendHoverLink: true,
  32480. hoverAnimation: true,
  32481. // stack: null
  32482. // xAxisIndex: 0,
  32483. // yAxisIndex: 0,
  32484. // polarIndex: 0,
  32485. // If clip the overflow value
  32486. clip: true,
  32487. // cursor: null,
  32488. label: {
  32489. position: 'top'
  32490. },
  32491. // itemStyle: {
  32492. // },
  32493. lineStyle: {
  32494. width: 2,
  32495. type: 'solid'
  32496. },
  32497. // areaStyle: {
  32498. // origin of areaStyle. Valid values:
  32499. // `'auto'/null/undefined`: from axisLine to data
  32500. // `'start'`: from min to data
  32501. // `'end'`: from data to max
  32502. // origin: 'auto'
  32503. // },
  32504. // false, 'start', 'end', 'middle'
  32505. step: false,
  32506. // Disabled if step is true
  32507. smooth: false,
  32508. smoothMonotone: null,
  32509. symbol: 'emptyCircle',
  32510. symbolSize: 4,
  32511. symbolRotate: null,
  32512. showSymbol: true,
  32513. // `false`: follow the label interval strategy.
  32514. // `true`: show all symbols.
  32515. // `'auto'`: If possible, show all symbols, otherwise
  32516. // follow the label interval strategy.
  32517. showAllSymbol: 'auto',
  32518. // Whether to connect break point.
  32519. connectNulls: false,
  32520. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32521. sampling: 'none',
  32522. animationEasing: 'linear',
  32523. // Disable progressive
  32524. progressive: 0,
  32525. hoverLayerThreshold: Infinity
  32526. }
  32527. });
  32528. /*
  32529. * Licensed to the Apache Software Foundation (ASF) under one
  32530. * or more contributor license agreements. See the NOTICE file
  32531. * distributed with this work for additional information
  32532. * regarding copyright ownership. The ASF licenses this file
  32533. * to you under the Apache License, Version 2.0 (the
  32534. * "License"); you may not use this file except in compliance
  32535. * with the License. You may obtain a copy of the License at
  32536. *
  32537. * http://www.apache.org/licenses/LICENSE-2.0
  32538. *
  32539. * Unless required by applicable law or agreed to in writing,
  32540. * software distributed under the License is distributed on an
  32541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32542. * KIND, either express or implied. See the License for the
  32543. * specific language governing permissions and limitations
  32544. * under the License.
  32545. */
  32546. /**
  32547. * @param {module:echarts/data/List} data
  32548. * @param {number} dataIndex
  32549. * @return {string} label string. Not null/undefined
  32550. */
  32551. function getDefaultLabel(data, dataIndex) {
  32552. var labelDims = data.mapDimension('defaultedLabel', true);
  32553. var len = labelDims.length;
  32554. // Simple optimization (in lots of cases, label dims length is 1)
  32555. if (len === 1) {
  32556. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32557. }
  32558. else if (len) {
  32559. var vals = [];
  32560. for (var i = 0; i < labelDims.length; i++) {
  32561. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32562. vals.push(val);
  32563. }
  32564. return vals.join(' ');
  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. /**
  32586. * @module echarts/chart/helper/Symbol
  32587. */
  32588. /**
  32589. * @constructor
  32590. * @alias {module:echarts/chart/helper/Symbol}
  32591. * @param {module:echarts/data/List} data
  32592. * @param {number} idx
  32593. * @extends {module:zrender/graphic/Group}
  32594. */
  32595. function SymbolClz$1(data, idx, seriesScope) {
  32596. Group.call(this);
  32597. this.updateData(data, idx, seriesScope);
  32598. }
  32599. var symbolProto = SymbolClz$1.prototype;
  32600. /**
  32601. * @public
  32602. * @static
  32603. * @param {module:echarts/data/List} data
  32604. * @param {number} dataIndex
  32605. * @return {Array.<number>} [width, height]
  32606. */
  32607. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32608. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32609. return symbolSize instanceof Array
  32610. ? symbolSize.slice()
  32611. : [+symbolSize, +symbolSize];
  32612. };
  32613. function getScale(symbolSize) {
  32614. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32615. }
  32616. function driftSymbol(dx, dy) {
  32617. this.parent.drift(dx, dy);
  32618. }
  32619. symbolProto._createSymbol = function (
  32620. symbolType,
  32621. data,
  32622. idx,
  32623. symbolSize,
  32624. keepAspect
  32625. ) {
  32626. // Remove paths created before
  32627. this.removeAll();
  32628. var color = data.getItemVisual(idx, 'color');
  32629. // var symbolPath = createSymbol(
  32630. // symbolType, -0.5, -0.5, 1, 1, color
  32631. // );
  32632. // If width/height are set too small (e.g., set to 1) on ios10
  32633. // and macOS Sierra, a circle stroke become a rect, no matter what
  32634. // the scale is set. So we set width/height as 2. See #4150.
  32635. var symbolPath = createSymbol(
  32636. symbolType, -1, -1, 2, 2, color, keepAspect
  32637. );
  32638. symbolPath.attr({
  32639. z2: 100,
  32640. culling: true,
  32641. scale: getScale(symbolSize)
  32642. });
  32643. // Rewrite drift method
  32644. symbolPath.drift = driftSymbol;
  32645. this._symbolType = symbolType;
  32646. this.add(symbolPath);
  32647. };
  32648. /**
  32649. * Stop animation
  32650. * @param {boolean} toLastFrame
  32651. */
  32652. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32653. this.childAt(0).stopAnimation(toLastFrame);
  32654. };
  32655. /**
  32656. * FIXME:
  32657. * Caution: This method breaks the encapsulation of this module,
  32658. * but it indeed brings convenience. So do not use the method
  32659. * unless you detailedly know all the implements of `Symbol`,
  32660. * especially animation.
  32661. *
  32662. * Get symbol path element.
  32663. */
  32664. symbolProto.getSymbolPath = function () {
  32665. return this.childAt(0);
  32666. };
  32667. /**
  32668. * Get scale(aka, current symbol size).
  32669. * Including the change caused by animation
  32670. */
  32671. symbolProto.getScale = function () {
  32672. return this.childAt(0).scale;
  32673. };
  32674. /**
  32675. * Highlight symbol
  32676. */
  32677. symbolProto.highlight = function () {
  32678. this.childAt(0).trigger('emphasis');
  32679. };
  32680. /**
  32681. * Downplay symbol
  32682. */
  32683. symbolProto.downplay = function () {
  32684. this.childAt(0).trigger('normal');
  32685. };
  32686. /**
  32687. * @param {number} zlevel
  32688. * @param {number} z
  32689. */
  32690. symbolProto.setZ = function (zlevel, z) {
  32691. var symbolPath = this.childAt(0);
  32692. symbolPath.zlevel = zlevel;
  32693. symbolPath.z = z;
  32694. };
  32695. symbolProto.setDraggable = function (draggable) {
  32696. var symbolPath = this.childAt(0);
  32697. symbolPath.draggable = draggable;
  32698. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32699. };
  32700. /**
  32701. * Update symbol properties
  32702. * @param {module:echarts/data/List} data
  32703. * @param {number} idx
  32704. * @param {Object} [seriesScope]
  32705. * @param {Object} [seriesScope.itemStyle]
  32706. * @param {Object} [seriesScope.hoverItemStyle]
  32707. * @param {Object} [seriesScope.symbolRotate]
  32708. * @param {Object} [seriesScope.symbolOffset]
  32709. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32710. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32711. * @param {boolean} [seriesScope.hoverAnimation]
  32712. * @param {Object} [seriesScope.cursorStyle]
  32713. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32714. * @param {string} [seriesScope.symbolInnerColor]
  32715. * @param {Object} [seriesScope.fadeIn=false]
  32716. */
  32717. symbolProto.updateData = function (data, idx, seriesScope) {
  32718. this.silent = false;
  32719. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32720. var seriesModel = data.hostModel;
  32721. var symbolSize = getSymbolSize(data, idx);
  32722. var isInit = symbolType !== this._symbolType;
  32723. if (isInit) {
  32724. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32725. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32726. }
  32727. else {
  32728. var symbolPath = this.childAt(0);
  32729. symbolPath.silent = false;
  32730. updateProps(symbolPath, {
  32731. scale: getScale(symbolSize)
  32732. }, seriesModel, idx);
  32733. }
  32734. this._updateCommon(data, idx, symbolSize, seriesScope);
  32735. if (isInit) {
  32736. var symbolPath = this.childAt(0);
  32737. var fadeIn = seriesScope && seriesScope.fadeIn;
  32738. var target = {scale: symbolPath.scale.slice()};
  32739. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32740. symbolPath.scale = [0, 0];
  32741. fadeIn && (symbolPath.style.opacity = 0);
  32742. initProps(symbolPath, target, seriesModel, idx);
  32743. }
  32744. this._seriesModel = seriesModel;
  32745. };
  32746. // Update common properties
  32747. var normalStyleAccessPath = ['itemStyle'];
  32748. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32749. var normalLabelAccessPath = ['label'];
  32750. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32751. /**
  32752. * @param {module:echarts/data/List} data
  32753. * @param {number} idx
  32754. * @param {Array.<number>} symbolSize
  32755. * @param {Object} [seriesScope]
  32756. */
  32757. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32758. var symbolPath = this.childAt(0);
  32759. var seriesModel = data.hostModel;
  32760. var color = data.getItemVisual(idx, 'color');
  32761. // Reset style
  32762. if (symbolPath.type !== 'image') {
  32763. symbolPath.useStyle({
  32764. strokeNoScale: true
  32765. });
  32766. }
  32767. else {
  32768. symbolPath.setStyle({
  32769. opacity: null,
  32770. shadowBlur: null,
  32771. shadowOffsetX: null,
  32772. shadowOffsetY: null,
  32773. shadowColor: null
  32774. });
  32775. }
  32776. var itemStyle = seriesScope && seriesScope.itemStyle;
  32777. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32778. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  32779. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32780. var labelModel = seriesScope && seriesScope.labelModel;
  32781. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32782. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32783. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32784. if (!seriesScope || data.hasItemOption) {
  32785. var itemModel = (seriesScope && seriesScope.itemModel)
  32786. ? seriesScope.itemModel : data.getItemModel(idx);
  32787. // Color must be excluded.
  32788. // Because symbol provide setColor individually to set fill and stroke
  32789. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32790. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32791. symbolRotate = itemModel.getShallow('symbolRotate');
  32792. symbolOffset = itemModel.getShallow('symbolOffset');
  32793. labelModel = itemModel.getModel(normalLabelAccessPath);
  32794. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32795. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32796. cursorStyle = itemModel.getShallow('cursor');
  32797. }
  32798. else {
  32799. hoverItemStyle = extend({}, hoverItemStyle);
  32800. }
  32801. var elStyle = symbolPath.style;
  32802. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32803. if (symbolOffset) {
  32804. symbolPath.attr('position', [
  32805. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32806. parsePercent$1(symbolOffset[1], symbolSize[1])
  32807. ]);
  32808. }
  32809. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32810. // PENDING setColor before setStyle!!!
  32811. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32812. symbolPath.setStyle(itemStyle);
  32813. var opacity = data.getItemVisual(idx, 'opacity');
  32814. if (opacity != null) {
  32815. elStyle.opacity = opacity;
  32816. }
  32817. var liftZ = data.getItemVisual(idx, 'liftZ');
  32818. var z2Origin = symbolPath.__z2Origin;
  32819. if (liftZ != null) {
  32820. if (z2Origin == null) {
  32821. symbolPath.__z2Origin = symbolPath.z2;
  32822. symbolPath.z2 += liftZ;
  32823. }
  32824. }
  32825. else if (z2Origin != null) {
  32826. symbolPath.z2 = z2Origin;
  32827. symbolPath.__z2Origin = null;
  32828. }
  32829. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32830. setLabelStyle(
  32831. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32832. {
  32833. labelFetcher: seriesModel,
  32834. labelDataIndex: idx,
  32835. defaultText: getLabelDefaultText,
  32836. isRectText: true,
  32837. autoColor: color
  32838. }
  32839. );
  32840. // Do not execute util needed.
  32841. function getLabelDefaultText(idx, opt) {
  32842. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32843. }
  32844. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32845. symbolPath.hoverStyle = hoverItemStyle;
  32846. symbolPath.highDownOnUpdate = (
  32847. hoverAnimation && seriesModel.isAnimationEnabled()
  32848. ) ? highDownOnUpdate : null;
  32849. setHoverStyle(symbolPath);
  32850. };
  32851. function highDownOnUpdate(fromState, toState) {
  32852. // Do not support this hover animation util some scenario required.
  32853. // Animation can only be supported in hover layer when using `el.incremetal`.
  32854. if (this.incremental || this.useHoverLayer) {
  32855. return;
  32856. }
  32857. if (toState === 'emphasis') {
  32858. var scale = this.__symbolOriginalScale;
  32859. var ratio = scale[1] / scale[0];
  32860. var emphasisOpt = {
  32861. scale: [
  32862. Math.max(scale[0] * 1.1, scale[0] + 3),
  32863. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32864. ]
  32865. };
  32866. // FIXME
  32867. // modify it after support stop specified animation.
  32868. // toState === fromState
  32869. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32870. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32871. }
  32872. else if (toState === 'normal') {
  32873. this.animateTo({
  32874. scale: this.__symbolOriginalScale
  32875. }, 400, 'elasticOut');
  32876. }
  32877. }
  32878. /**
  32879. * @param {Function} cb
  32880. * @param {Object} [opt]
  32881. * @param {Object} [opt.keepLabel=true]
  32882. */
  32883. symbolProto.fadeOut = function (cb, opt) {
  32884. var symbolPath = this.childAt(0);
  32885. // Avoid mistaken hover when fading out
  32886. this.silent = symbolPath.silent = true;
  32887. // Not show text when animating
  32888. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32889. updateProps(
  32890. symbolPath,
  32891. {
  32892. style: {opacity: 0},
  32893. scale: [0, 0]
  32894. },
  32895. this._seriesModel,
  32896. this.dataIndex,
  32897. cb
  32898. );
  32899. };
  32900. inherits(SymbolClz$1, Group);
  32901. /*
  32902. * Licensed to the Apache Software Foundation (ASF) under one
  32903. * or more contributor license agreements. See the NOTICE file
  32904. * distributed with this work for additional information
  32905. * regarding copyright ownership. The ASF licenses this file
  32906. * to you under the Apache License, Version 2.0 (the
  32907. * "License"); you may not use this file except in compliance
  32908. * with the License. You may obtain a copy of the License at
  32909. *
  32910. * http://www.apache.org/licenses/LICENSE-2.0
  32911. *
  32912. * Unless required by applicable law or agreed to in writing,
  32913. * software distributed under the License is distributed on an
  32914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32915. * KIND, either express or implied. See the License for the
  32916. * specific language governing permissions and limitations
  32917. * under the License.
  32918. */
  32919. /**
  32920. * @module echarts/chart/helper/SymbolDraw
  32921. */
  32922. /**
  32923. * @constructor
  32924. * @alias module:echarts/chart/helper/SymbolDraw
  32925. * @param {module:zrender/graphic/Group} [symbolCtor]
  32926. */
  32927. function SymbolDraw(symbolCtor) {
  32928. this.group = new Group();
  32929. this._symbolCtor = symbolCtor || SymbolClz$1;
  32930. }
  32931. var symbolDrawProto = SymbolDraw.prototype;
  32932. function symbolNeedsDraw(data, point, idx, opt) {
  32933. return point && !isNaN(point[0]) && !isNaN(point[1])
  32934. && !(opt.isIgnore && opt.isIgnore(idx))
  32935. // We do not set clipShape on group, because it will cut part of
  32936. // the symbol element shape. We use the same clip shape here as
  32937. // the line clip.
  32938. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  32939. && data.getItemVisual(idx, 'symbol') !== 'none';
  32940. }
  32941. /**
  32942. * Update symbols draw by new data
  32943. * @param {module:echarts/data/List} data
  32944. * @param {Object} [opt] Or isIgnore
  32945. * @param {Function} [opt.isIgnore]
  32946. * @param {Object} [opt.clipShape]
  32947. */
  32948. symbolDrawProto.updateData = function (data, opt) {
  32949. opt = normalizeUpdateOpt(opt);
  32950. var group = this.group;
  32951. var seriesModel = data.hostModel;
  32952. var oldData = this._data;
  32953. var SymbolCtor = this._symbolCtor;
  32954. var seriesScope = makeSeriesScope(data);
  32955. // There is no oldLineData only when first rendering or switching from
  32956. // stream mode to normal mode, where previous elements should be removed.
  32957. if (!oldData) {
  32958. group.removeAll();
  32959. }
  32960. data.diff(oldData)
  32961. .add(function (newIdx) {
  32962. var point = data.getItemLayout(newIdx);
  32963. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  32964. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  32965. symbolEl.attr('position', point);
  32966. data.setItemGraphicEl(newIdx, symbolEl);
  32967. group.add(symbolEl);
  32968. }
  32969. })
  32970. .update(function (newIdx, oldIdx) {
  32971. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32972. var point = data.getItemLayout(newIdx);
  32973. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  32974. group.remove(symbolEl);
  32975. return;
  32976. }
  32977. if (!symbolEl) {
  32978. symbolEl = new SymbolCtor(data, newIdx);
  32979. symbolEl.attr('position', point);
  32980. }
  32981. else {
  32982. symbolEl.updateData(data, newIdx, seriesScope);
  32983. updateProps(symbolEl, {
  32984. position: point
  32985. }, seriesModel);
  32986. }
  32987. // Add back
  32988. group.add(symbolEl);
  32989. data.setItemGraphicEl(newIdx, symbolEl);
  32990. })
  32991. .remove(function (oldIdx) {
  32992. var el = oldData.getItemGraphicEl(oldIdx);
  32993. el && el.fadeOut(function () {
  32994. group.remove(el);
  32995. });
  32996. })
  32997. .execute();
  32998. this._data = data;
  32999. };
  33000. symbolDrawProto.isPersistent = function () {
  33001. return true;
  33002. };
  33003. symbolDrawProto.updateLayout = function () {
  33004. var data = this._data;
  33005. if (data) {
  33006. // Not use animation
  33007. data.eachItemGraphicEl(function (el, idx) {
  33008. var point = data.getItemLayout(idx);
  33009. el.attr('position', point);
  33010. });
  33011. }
  33012. };
  33013. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33014. this._seriesScope = makeSeriesScope(data);
  33015. this._data = null;
  33016. this.group.removeAll();
  33017. };
  33018. /**
  33019. * Update symbols draw by new data
  33020. * @param {module:echarts/data/List} data
  33021. * @param {Object} [opt] Or isIgnore
  33022. * @param {Function} [opt.isIgnore]
  33023. * @param {Object} [opt.clipShape]
  33024. */
  33025. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33026. opt = normalizeUpdateOpt(opt);
  33027. function updateIncrementalAndHover(el) {
  33028. if (!el.isGroup) {
  33029. el.incremental = el.useHoverLayer = true;
  33030. }
  33031. }
  33032. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33033. var point = data.getItemLayout(idx);
  33034. if (symbolNeedsDraw(data, point, idx, opt)) {
  33035. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33036. el.traverse(updateIncrementalAndHover);
  33037. el.attr('position', point);
  33038. this.group.add(el);
  33039. data.setItemGraphicEl(idx, el);
  33040. }
  33041. }
  33042. };
  33043. function normalizeUpdateOpt(opt) {
  33044. if (opt != null && !isObject$1(opt)) {
  33045. opt = {isIgnore: opt};
  33046. }
  33047. return opt || {};
  33048. }
  33049. symbolDrawProto.remove = function (enableAnimation) {
  33050. var group = this.group;
  33051. var data = this._data;
  33052. // Incremental model do not have this._data.
  33053. if (data && enableAnimation) {
  33054. data.eachItemGraphicEl(function (el) {
  33055. el.fadeOut(function () {
  33056. group.remove(el);
  33057. });
  33058. });
  33059. }
  33060. else {
  33061. group.removeAll();
  33062. }
  33063. };
  33064. function makeSeriesScope(data) {
  33065. var seriesModel = data.hostModel;
  33066. return {
  33067. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33068. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33069. symbolRotate: seriesModel.get('symbolRotate'),
  33070. symbolOffset: seriesModel.get('symbolOffset'),
  33071. hoverAnimation: seriesModel.get('hoverAnimation'),
  33072. labelModel: seriesModel.getModel('label'),
  33073. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33074. cursorStyle: seriesModel.get('cursor')
  33075. };
  33076. }
  33077. /*
  33078. * Licensed to the Apache Software Foundation (ASF) under one
  33079. * or more contributor license agreements. See the NOTICE file
  33080. * distributed with this work for additional information
  33081. * regarding copyright ownership. The ASF licenses this file
  33082. * to you under the Apache License, Version 2.0 (the
  33083. * "License"); you may not use this file except in compliance
  33084. * with the License. You may obtain a copy of the License at
  33085. *
  33086. * http://www.apache.org/licenses/LICENSE-2.0
  33087. *
  33088. * Unless required by applicable law or agreed to in writing,
  33089. * software distributed under the License is distributed on an
  33090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33091. * KIND, either express or implied. See the License for the
  33092. * specific language governing permissions and limitations
  33093. * under the License.
  33094. */
  33095. /**
  33096. * @param {Object} coordSys
  33097. * @param {module:echarts/data/List} data
  33098. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33099. */
  33100. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33101. var baseAxis = coordSys.getBaseAxis();
  33102. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33103. var valueStart = getValueStart(valueAxis, valueOrigin);
  33104. var baseAxisDim = baseAxis.dim;
  33105. var valueAxisDim = valueAxis.dim;
  33106. var valueDim = data.mapDimension(valueAxisDim);
  33107. var baseDim = data.mapDimension(baseAxisDim);
  33108. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33109. var dims = map(coordSys.dimensions, function (coordDim) {
  33110. return data.mapDimension(coordDim);
  33111. });
  33112. var stacked;
  33113. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33114. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33115. dims[0] = stackResultDim;
  33116. }
  33117. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33118. dims[1] = stackResultDim;
  33119. }
  33120. return {
  33121. dataDimsForPoint: dims,
  33122. valueStart: valueStart,
  33123. valueAxisDim: valueAxisDim,
  33124. baseAxisDim: baseAxisDim,
  33125. stacked: !!stacked,
  33126. valueDim: valueDim,
  33127. baseDim: baseDim,
  33128. baseDataOffset: baseDataOffset,
  33129. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33130. };
  33131. }
  33132. function getValueStart(valueAxis, valueOrigin) {
  33133. var valueStart = 0;
  33134. var extent = valueAxis.scale.getExtent();
  33135. if (valueOrigin === 'start') {
  33136. valueStart = extent[0];
  33137. }
  33138. else if (valueOrigin === 'end') {
  33139. valueStart = extent[1];
  33140. }
  33141. // auto
  33142. else {
  33143. // Both positive
  33144. if (extent[0] > 0) {
  33145. valueStart = extent[0];
  33146. }
  33147. // Both negative
  33148. else if (extent[1] < 0) {
  33149. valueStart = extent[1];
  33150. }
  33151. // If is one positive, and one negative, onZero shall be true
  33152. }
  33153. return valueStart;
  33154. }
  33155. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33156. var value = NaN;
  33157. if (dataCoordInfo.stacked) {
  33158. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33159. }
  33160. if (isNaN(value)) {
  33161. value = dataCoordInfo.valueStart;
  33162. }
  33163. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33164. var stackedData = [];
  33165. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33166. stackedData[1 - baseDataOffset] = value;
  33167. return coordSys.dataToPoint(stackedData);
  33168. }
  33169. /*
  33170. * Licensed to the Apache Software Foundation (ASF) under one
  33171. * or more contributor license agreements. See the NOTICE file
  33172. * distributed with this work for additional information
  33173. * regarding copyright ownership. The ASF licenses this file
  33174. * to you under the Apache License, Version 2.0 (the
  33175. * "License"); you may not use this file except in compliance
  33176. * with the License. You may obtain a copy of the License at
  33177. *
  33178. * http://www.apache.org/licenses/LICENSE-2.0
  33179. *
  33180. * Unless required by applicable law or agreed to in writing,
  33181. * software distributed under the License is distributed on an
  33182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33183. * KIND, either express or implied. See the License for the
  33184. * specific language governing permissions and limitations
  33185. * under the License.
  33186. */
  33187. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33188. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33189. // not do well in performance when roam with fixed dataZoom window.
  33190. // function convertToIntId(newIdList, oldIdList) {
  33191. // // Generate int id instead of string id.
  33192. // // Compare string maybe slow in score function of arrDiff
  33193. // // Assume id in idList are all unique
  33194. // var idIndicesMap = {};
  33195. // var idx = 0;
  33196. // for (var i = 0; i < newIdList.length; i++) {
  33197. // idIndicesMap[newIdList[i]] = idx;
  33198. // newIdList[i] = idx++;
  33199. // }
  33200. // for (var i = 0; i < oldIdList.length; i++) {
  33201. // var oldId = oldIdList[i];
  33202. // // Same with newIdList
  33203. // if (idIndicesMap[oldId]) {
  33204. // oldIdList[i] = idIndicesMap[oldId];
  33205. // }
  33206. // else {
  33207. // oldIdList[i] = idx++;
  33208. // }
  33209. // }
  33210. // }
  33211. function diffData(oldData, newData) {
  33212. var diffResult = [];
  33213. newData.diff(oldData)
  33214. .add(function (idx) {
  33215. diffResult.push({cmd: '+', idx: idx});
  33216. })
  33217. .update(function (newIdx, oldIdx) {
  33218. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33219. })
  33220. .remove(function (idx) {
  33221. diffResult.push({cmd: '-', idx: idx});
  33222. })
  33223. .execute();
  33224. return diffResult;
  33225. }
  33226. var lineAnimationDiff = function (
  33227. oldData, newData,
  33228. oldStackedOnPoints, newStackedOnPoints,
  33229. oldCoordSys, newCoordSys,
  33230. oldValueOrigin, newValueOrigin
  33231. ) {
  33232. var diff = diffData(oldData, newData);
  33233. // var newIdList = newData.mapArray(newData.getId);
  33234. // var oldIdList = oldData.mapArray(oldData.getId);
  33235. // convertToIntId(newIdList, oldIdList);
  33236. // // FIXME One data ?
  33237. // diff = arrayDiff(oldIdList, newIdList);
  33238. var currPoints = [];
  33239. var nextPoints = [];
  33240. // Points for stacking base line
  33241. var currStackedPoints = [];
  33242. var nextStackedPoints = [];
  33243. var status = [];
  33244. var sortedIndices = [];
  33245. var rawIndices = [];
  33246. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33247. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33248. for (var i = 0; i < diff.length; i++) {
  33249. var diffItem = diff[i];
  33250. var pointAdded = true;
  33251. // FIXME, animation is not so perfect when dataZoom window moves fast
  33252. // Which is in case remvoing or add more than one data in the tail or head
  33253. switch (diffItem.cmd) {
  33254. case '=':
  33255. var currentPt = oldData.getItemLayout(diffItem.idx);
  33256. var nextPt = newData.getItemLayout(diffItem.idx1);
  33257. // If previous data is NaN, use next point directly
  33258. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33259. currentPt = nextPt.slice();
  33260. }
  33261. currPoints.push(currentPt);
  33262. nextPoints.push(nextPt);
  33263. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33264. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33265. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33266. break;
  33267. case '+':
  33268. var idx = diffItem.idx;
  33269. currPoints.push(
  33270. oldCoordSys.dataToPoint([
  33271. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33272. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33273. ])
  33274. );
  33275. nextPoints.push(newData.getItemLayout(idx).slice());
  33276. currStackedPoints.push(
  33277. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33278. );
  33279. nextStackedPoints.push(newStackedOnPoints[idx]);
  33280. rawIndices.push(newData.getRawIndex(idx));
  33281. break;
  33282. case '-':
  33283. var idx = diffItem.idx;
  33284. var rawIndex = oldData.getRawIndex(idx);
  33285. // Data is replaced. In the case of dynamic data queue
  33286. // FIXME FIXME FIXME
  33287. if (rawIndex !== idx) {
  33288. currPoints.push(oldData.getItemLayout(idx));
  33289. nextPoints.push(newCoordSys.dataToPoint([
  33290. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33291. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33292. ]));
  33293. currStackedPoints.push(oldStackedOnPoints[idx]);
  33294. nextStackedPoints.push(
  33295. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33296. );
  33297. rawIndices.push(rawIndex);
  33298. }
  33299. else {
  33300. pointAdded = false;
  33301. }
  33302. }
  33303. // Original indices
  33304. if (pointAdded) {
  33305. status.push(diffItem);
  33306. sortedIndices.push(sortedIndices.length);
  33307. }
  33308. }
  33309. // Diff result may be crossed if all items are changed
  33310. // Sort by data index
  33311. sortedIndices.sort(function (a, b) {
  33312. return rawIndices[a] - rawIndices[b];
  33313. });
  33314. var sortedCurrPoints = [];
  33315. var sortedNextPoints = [];
  33316. var sortedCurrStackedPoints = [];
  33317. var sortedNextStackedPoints = [];
  33318. var sortedStatus = [];
  33319. for (var i = 0; i < sortedIndices.length; i++) {
  33320. var idx = sortedIndices[i];
  33321. sortedCurrPoints[i] = currPoints[idx];
  33322. sortedNextPoints[i] = nextPoints[idx];
  33323. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33324. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33325. sortedStatus[i] = status[idx];
  33326. }
  33327. return {
  33328. current: sortedCurrPoints,
  33329. next: sortedNextPoints,
  33330. stackedOnCurrent: sortedCurrStackedPoints,
  33331. stackedOnNext: sortedNextStackedPoints,
  33332. status: sortedStatus
  33333. };
  33334. };
  33335. /*
  33336. * Licensed to the Apache Software Foundation (ASF) under one
  33337. * or more contributor license agreements. See the NOTICE file
  33338. * distributed with this work for additional information
  33339. * regarding copyright ownership. The ASF licenses this file
  33340. * to you under the Apache License, Version 2.0 (the
  33341. * "License"); you may not use this file except in compliance
  33342. * with the License. You may obtain a copy of the License at
  33343. *
  33344. * http://www.apache.org/licenses/LICENSE-2.0
  33345. *
  33346. * Unless required by applicable law or agreed to in writing,
  33347. * software distributed under the License is distributed on an
  33348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33349. * KIND, either express or implied. See the License for the
  33350. * specific language governing permissions and limitations
  33351. * under the License.
  33352. */
  33353. // Poly path support NaN point
  33354. var vec2Min = min;
  33355. var vec2Max = max;
  33356. var scaleAndAdd$1 = scaleAndAdd;
  33357. var v2Copy = copy;
  33358. // Temporary variable
  33359. var v = [];
  33360. var cp0 = [];
  33361. var cp1 = [];
  33362. function isPointNull(p) {
  33363. return isNaN(p[0]) || isNaN(p[1]);
  33364. }
  33365. function drawSegment(
  33366. ctx, points, start, segLen, allLen,
  33367. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33368. ) {
  33369. // if (smoothMonotone == null) {
  33370. // if (isMono(points, 'x')) {
  33371. // return drawMono(ctx, points, start, segLen, allLen,
  33372. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33373. // }
  33374. // else if (isMono(points, 'y')) {
  33375. // return drawMono(ctx, points, start, segLen, allLen,
  33376. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33377. // }
  33378. // else {
  33379. // return drawNonMono.apply(this, arguments);
  33380. // }
  33381. // }
  33382. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33383. // return drawMono.apply(this, arguments);
  33384. // }
  33385. // else {
  33386. // return drawNonMono.apply(this, arguments);
  33387. // }
  33388. if (smoothMonotone === 'none' || !smoothMonotone) {
  33389. return drawNonMono.apply(this, arguments);
  33390. }
  33391. else {
  33392. return drawMono.apply(this, arguments);
  33393. }
  33394. }
  33395. /**
  33396. * Check if points is in monotone.
  33397. *
  33398. * @param {number[][]} points Array of points which is in [x, y] form
  33399. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33400. * dimension that is checking.
  33401. * If is 'none', `drawNonMono` should be
  33402. * called.
  33403. * If is undefined, either being monotone
  33404. * in 'x' or 'y' will call `drawMono`.
  33405. */
  33406. // function isMono(points, smoothMonotone) {
  33407. // if (points.length <= 1) {
  33408. // return true;
  33409. // }
  33410. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33411. // var last = points[0][dim];
  33412. // var lastDiff = 0;
  33413. // for (var i = 1; i < points.length; ++i) {
  33414. // var diff = points[i][dim] - last;
  33415. // if (!isNaN(diff) && !isNaN(lastDiff)
  33416. // && diff !== 0 && lastDiff !== 0
  33417. // && ((diff >= 0) !== (lastDiff >= 0))
  33418. // ) {
  33419. // return false;
  33420. // }
  33421. // if (!isNaN(diff) && diff !== 0) {
  33422. // lastDiff = diff;
  33423. // last = points[i][dim];
  33424. // }
  33425. // }
  33426. // return true;
  33427. // }
  33428. /**
  33429. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33430. * control points will be used. This should be used when points are monotone
  33431. * either in x or y dimension.
  33432. */
  33433. function drawMono(
  33434. ctx, points, start, segLen, allLen,
  33435. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33436. ) {
  33437. var prevIdx = 0;
  33438. var idx = start;
  33439. for (var k = 0; k < segLen; k++) {
  33440. var p = points[idx];
  33441. if (idx >= allLen || idx < 0) {
  33442. break;
  33443. }
  33444. if (isPointNull(p)) {
  33445. if (connectNulls) {
  33446. idx += dir;
  33447. continue;
  33448. }
  33449. break;
  33450. }
  33451. if (idx === start) {
  33452. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33453. }
  33454. else {
  33455. if (smooth > 0) {
  33456. var prevP = points[prevIdx];
  33457. var dim = smoothMonotone === 'y' ? 1 : 0;
  33458. // Length of control point to p, either in x or y, but not both
  33459. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33460. v2Copy(cp0, prevP);
  33461. cp0[dim] = prevP[dim] + ctrlLen;
  33462. v2Copy(cp1, p);
  33463. cp1[dim] = p[dim] - ctrlLen;
  33464. ctx.bezierCurveTo(
  33465. cp0[0], cp0[1],
  33466. cp1[0], cp1[1],
  33467. p[0], p[1]
  33468. );
  33469. }
  33470. else {
  33471. ctx.lineTo(p[0], p[1]);
  33472. }
  33473. }
  33474. prevIdx = idx;
  33475. idx += dir;
  33476. }
  33477. return k;
  33478. }
  33479. /**
  33480. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33481. * situations. This should be used when points are non-monotone neither in x or
  33482. * y dimension.
  33483. */
  33484. function drawNonMono(
  33485. ctx, points, start, segLen, allLen,
  33486. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33487. ) {
  33488. var prevIdx = 0;
  33489. var idx = start;
  33490. for (var k = 0; k < segLen; k++) {
  33491. var p = points[idx];
  33492. if (idx >= allLen || idx < 0) {
  33493. break;
  33494. }
  33495. if (isPointNull(p)) {
  33496. if (connectNulls) {
  33497. idx += dir;
  33498. continue;
  33499. }
  33500. break;
  33501. }
  33502. if (idx === start) {
  33503. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33504. v2Copy(cp0, p);
  33505. }
  33506. else {
  33507. if (smooth > 0) {
  33508. var nextIdx = idx + dir;
  33509. var nextP = points[nextIdx];
  33510. if (connectNulls) {
  33511. // Find next point not null
  33512. while (nextP && isPointNull(points[nextIdx])) {
  33513. nextIdx += dir;
  33514. nextP = points[nextIdx];
  33515. }
  33516. }
  33517. var ratioNextSeg = 0.5;
  33518. var prevP = points[prevIdx];
  33519. var nextP = points[nextIdx];
  33520. // Last point
  33521. if (!nextP || isPointNull(nextP)) {
  33522. v2Copy(cp1, p);
  33523. }
  33524. else {
  33525. // If next data is null in not connect case
  33526. if (isPointNull(nextP) && !connectNulls) {
  33527. nextP = p;
  33528. }
  33529. sub(v, nextP, prevP);
  33530. var lenPrevSeg;
  33531. var lenNextSeg;
  33532. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33533. var dim = smoothMonotone === 'x' ? 0 : 1;
  33534. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33535. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33536. }
  33537. else {
  33538. lenPrevSeg = dist(p, prevP);
  33539. lenNextSeg = dist(p, nextP);
  33540. }
  33541. // Use ratio of seg length
  33542. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33543. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33544. }
  33545. // Smooth constraint
  33546. vec2Min(cp0, cp0, smoothMax);
  33547. vec2Max(cp0, cp0, smoothMin);
  33548. vec2Min(cp1, cp1, smoothMax);
  33549. vec2Max(cp1, cp1, smoothMin);
  33550. ctx.bezierCurveTo(
  33551. cp0[0], cp0[1],
  33552. cp1[0], cp1[1],
  33553. p[0], p[1]
  33554. );
  33555. // cp0 of next segment
  33556. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33557. }
  33558. else {
  33559. ctx.lineTo(p[0], p[1]);
  33560. }
  33561. }
  33562. prevIdx = idx;
  33563. idx += dir;
  33564. }
  33565. return k;
  33566. }
  33567. function getBoundingBox(points, smoothConstraint) {
  33568. var ptMin = [Infinity, Infinity];
  33569. var ptMax = [-Infinity, -Infinity];
  33570. if (smoothConstraint) {
  33571. for (var i = 0; i < points.length; i++) {
  33572. var pt = points[i];
  33573. if (pt[0] < ptMin[0]) {
  33574. ptMin[0] = pt[0];
  33575. }
  33576. if (pt[1] < ptMin[1]) {
  33577. ptMin[1] = pt[1];
  33578. }
  33579. if (pt[0] > ptMax[0]) {
  33580. ptMax[0] = pt[0];
  33581. }
  33582. if (pt[1] > ptMax[1]) {
  33583. ptMax[1] = pt[1];
  33584. }
  33585. }
  33586. }
  33587. return {
  33588. min: smoothConstraint ? ptMin : ptMax,
  33589. max: smoothConstraint ? ptMax : ptMin
  33590. };
  33591. }
  33592. var Polyline$1 = Path.extend({
  33593. type: 'ec-polyline',
  33594. shape: {
  33595. points: [],
  33596. smooth: 0,
  33597. smoothConstraint: true,
  33598. smoothMonotone: null,
  33599. connectNulls: false
  33600. },
  33601. style: {
  33602. fill: null,
  33603. stroke: '#000'
  33604. },
  33605. brush: fixClipWithShadow(Path.prototype.brush),
  33606. buildPath: function (ctx, shape) {
  33607. var points = shape.points;
  33608. var i = 0;
  33609. var len$$1 = points.length;
  33610. var result = getBoundingBox(points, shape.smoothConstraint);
  33611. if (shape.connectNulls) {
  33612. // Must remove first and last null values avoid draw error in polygon
  33613. for (; len$$1 > 0; len$$1--) {
  33614. if (!isPointNull(points[len$$1 - 1])) {
  33615. break;
  33616. }
  33617. }
  33618. for (; i < len$$1; i++) {
  33619. if (!isPointNull(points[i])) {
  33620. break;
  33621. }
  33622. }
  33623. }
  33624. while (i < len$$1) {
  33625. i += drawSegment(
  33626. ctx, points, i, len$$1, len$$1,
  33627. 1, result.min, result.max, shape.smooth,
  33628. shape.smoothMonotone, shape.connectNulls
  33629. ) + 1;
  33630. }
  33631. }
  33632. });
  33633. var Polygon$1 = Path.extend({
  33634. type: 'ec-polygon',
  33635. shape: {
  33636. points: [],
  33637. // Offset between stacked base points and points
  33638. stackedOnPoints: [],
  33639. smooth: 0,
  33640. stackedOnSmooth: 0,
  33641. smoothConstraint: true,
  33642. smoothMonotone: null,
  33643. connectNulls: false
  33644. },
  33645. brush: fixClipWithShadow(Path.prototype.brush),
  33646. buildPath: function (ctx, shape) {
  33647. var points = shape.points;
  33648. var stackedOnPoints = shape.stackedOnPoints;
  33649. var i = 0;
  33650. var len$$1 = points.length;
  33651. var smoothMonotone = shape.smoothMonotone;
  33652. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33653. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33654. if (shape.connectNulls) {
  33655. // Must remove first and last null values avoid draw error in polygon
  33656. for (; len$$1 > 0; len$$1--) {
  33657. if (!isPointNull(points[len$$1 - 1])) {
  33658. break;
  33659. }
  33660. }
  33661. for (; i < len$$1; i++) {
  33662. if (!isPointNull(points[i])) {
  33663. break;
  33664. }
  33665. }
  33666. }
  33667. while (i < len$$1) {
  33668. var k = drawSegment(
  33669. ctx, points, i, len$$1, len$$1,
  33670. 1, bbox.min, bbox.max, shape.smooth,
  33671. smoothMonotone, shape.connectNulls
  33672. );
  33673. drawSegment(
  33674. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33675. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33676. smoothMonotone, shape.connectNulls
  33677. );
  33678. i += k + 1;
  33679. ctx.closePath();
  33680. }
  33681. }
  33682. });
  33683. /*
  33684. * Licensed to the Apache Software Foundation (ASF) under one
  33685. * or more contributor license agreements. See the NOTICE file
  33686. * distributed with this work for additional information
  33687. * regarding copyright ownership. The ASF licenses this file
  33688. * to you under the Apache License, Version 2.0 (the
  33689. * "License"); you may not use this file except in compliance
  33690. * with the License. You may obtain a copy of the License at
  33691. *
  33692. * http://www.apache.org/licenses/LICENSE-2.0
  33693. *
  33694. * Unless required by applicable law or agreed to in writing,
  33695. * software distributed under the License is distributed on an
  33696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33697. * KIND, either express or implied. See the License for the
  33698. * specific language governing permissions and limitations
  33699. * under the License.
  33700. */
  33701. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33702. var rect = cartesian.getArea();
  33703. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33704. var x = rect.x;
  33705. var y = rect.y;
  33706. var width = rect.width;
  33707. var height = rect.height;
  33708. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33709. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33710. x -= lineWidth / 2;
  33711. y -= lineWidth / 2;
  33712. width += lineWidth;
  33713. height += lineWidth;
  33714. var clipPath = new Rect({
  33715. shape: {
  33716. x: x,
  33717. y: y,
  33718. width: width,
  33719. height: height
  33720. }
  33721. });
  33722. if (hasAnimation) {
  33723. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33724. initProps(clipPath, {
  33725. shape: {
  33726. width: width,
  33727. height: height
  33728. }
  33729. }, seriesModel);
  33730. }
  33731. return clipPath;
  33732. }
  33733. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33734. var sectorArea = polar.getArea();
  33735. // Avoid float number rounding error for symbol on the edge of axis extent.
  33736. var clipPath = new Sector({
  33737. shape: {
  33738. cx: round$1(polar.cx, 1),
  33739. cy: round$1(polar.cy, 1),
  33740. r0: round$1(sectorArea.r0, 1),
  33741. r: round$1(sectorArea.r, 1),
  33742. startAngle: sectorArea.startAngle,
  33743. endAngle: sectorArea.endAngle,
  33744. clockwise: sectorArea.clockwise
  33745. }
  33746. });
  33747. if (hasAnimation) {
  33748. clipPath.shape.endAngle = sectorArea.startAngle;
  33749. initProps(clipPath, {
  33750. shape: {
  33751. endAngle: sectorArea.endAngle
  33752. }
  33753. }, seriesModel);
  33754. }
  33755. return clipPath;
  33756. }
  33757. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33758. if (!coordSys) {
  33759. return null;
  33760. }
  33761. else if (coordSys.type === 'polar') {
  33762. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33763. }
  33764. else if (coordSys.type === 'cartesian2d') {
  33765. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33766. }
  33767. return null;
  33768. }
  33769. /*
  33770. * Licensed to the Apache Software Foundation (ASF) under one
  33771. * or more contributor license agreements. See the NOTICE file
  33772. * distributed with this work for additional information
  33773. * regarding copyright ownership. The ASF licenses this file
  33774. * to you under the Apache License, Version 2.0 (the
  33775. * "License"); you may not use this file except in compliance
  33776. * with the License. You may obtain a copy of the License at
  33777. *
  33778. * http://www.apache.org/licenses/LICENSE-2.0
  33779. *
  33780. * Unless required by applicable law or agreed to in writing,
  33781. * software distributed under the License is distributed on an
  33782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33783. * KIND, either express or implied. See the License for the
  33784. * specific language governing permissions and limitations
  33785. * under the License.
  33786. */
  33787. // FIXME step not support polar
  33788. function isPointsSame(points1, points2) {
  33789. if (points1.length !== points2.length) {
  33790. return;
  33791. }
  33792. for (var i = 0; i < points1.length; i++) {
  33793. var p1 = points1[i];
  33794. var p2 = points2[i];
  33795. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33796. return;
  33797. }
  33798. }
  33799. return true;
  33800. }
  33801. function getSmooth(smooth) {
  33802. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33803. }
  33804. /**
  33805. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33806. * @param {module:echarts/data/List} data
  33807. * @param {Object} dataCoordInfo
  33808. * @param {Array.<Array.<number>>} points
  33809. */
  33810. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33811. if (!dataCoordInfo.valueDim) {
  33812. return [];
  33813. }
  33814. var points = [];
  33815. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33816. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33817. }
  33818. return points;
  33819. }
  33820. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33821. var baseAxis = coordSys.getBaseAxis();
  33822. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33823. var stepPoints = [];
  33824. for (var i = 0; i < points.length - 1; i++) {
  33825. var nextPt = points[i + 1];
  33826. var pt = points[i];
  33827. stepPoints.push(pt);
  33828. var stepPt = [];
  33829. switch (stepTurnAt) {
  33830. case 'end':
  33831. stepPt[baseIndex] = nextPt[baseIndex];
  33832. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33833. // default is start
  33834. stepPoints.push(stepPt);
  33835. break;
  33836. case 'middle':
  33837. // default is start
  33838. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33839. var stepPt2 = [];
  33840. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33841. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33842. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33843. stepPoints.push(stepPt);
  33844. stepPoints.push(stepPt2);
  33845. break;
  33846. default:
  33847. stepPt[baseIndex] = pt[baseIndex];
  33848. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33849. // default is start
  33850. stepPoints.push(stepPt);
  33851. }
  33852. }
  33853. // Last points
  33854. points[i] && stepPoints.push(points[i]);
  33855. return stepPoints;
  33856. }
  33857. function getVisualGradient(data, coordSys) {
  33858. var visualMetaList = data.getVisual('visualMeta');
  33859. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33860. // When data.count() is 0, gradient range can not be calculated.
  33861. return;
  33862. }
  33863. if (coordSys.type !== 'cartesian2d') {
  33864. if (__DEV__) {
  33865. console.warn('Visual map on line style is only supported on cartesian2d.');
  33866. }
  33867. return;
  33868. }
  33869. var coordDim;
  33870. var visualMeta;
  33871. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33872. var dimIndex = visualMetaList[i].dimension;
  33873. var dimName = data.dimensions[dimIndex];
  33874. var dimInfo = data.getDimensionInfo(dimName);
  33875. coordDim = dimInfo && dimInfo.coordDim;
  33876. // Can only be x or y
  33877. if (coordDim === 'x' || coordDim === 'y') {
  33878. visualMeta = visualMetaList[i];
  33879. break;
  33880. }
  33881. }
  33882. if (!visualMeta) {
  33883. if (__DEV__) {
  33884. console.warn('Visual map on line style only support x or y dimension.');
  33885. }
  33886. return;
  33887. }
  33888. // If the area to be rendered is bigger than area defined by LinearGradient,
  33889. // the canvas spec prescribes that the color of the first stop and the last
  33890. // stop should be used. But if two stops are added at offset 0, in effect
  33891. // browsers use the color of the second stop to render area outside
  33892. // LinearGradient. So we can only infinitesimally extend area defined in
  33893. // LinearGradient to render `outerColors`.
  33894. var axis = coordSys.getAxis(coordDim);
  33895. // dataToCoor mapping may not be linear, but must be monotonic.
  33896. var colorStops = map(visualMeta.stops, function (stop) {
  33897. return {
  33898. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  33899. color: stop.color
  33900. };
  33901. });
  33902. var stopLen = colorStops.length;
  33903. var outerColors = visualMeta.outerColors.slice();
  33904. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  33905. colorStops.reverse();
  33906. outerColors.reverse();
  33907. }
  33908. var tinyExtent = 10; // Arbitrary value: 10px
  33909. var minCoord = colorStops[0].coord - tinyExtent;
  33910. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  33911. var coordSpan = maxCoord - minCoord;
  33912. if (coordSpan < 1e-3) {
  33913. return 'transparent';
  33914. }
  33915. each$1(colorStops, function (stop) {
  33916. stop.offset = (stop.coord - minCoord) / coordSpan;
  33917. });
  33918. colorStops.push({
  33919. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  33920. color: outerColors[1] || 'transparent'
  33921. });
  33922. colorStops.unshift({ // notice colorStops.length have been changed.
  33923. offset: stopLen ? colorStops[0].offset : 0.5,
  33924. color: outerColors[0] || 'transparent'
  33925. });
  33926. // zrUtil.each(colorStops, function (colorStop) {
  33927. // // Make sure each offset has rounded px to avoid not sharp edge
  33928. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  33929. // });
  33930. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  33931. gradient[coordDim] = minCoord;
  33932. gradient[coordDim + '2'] = maxCoord;
  33933. return gradient;
  33934. }
  33935. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  33936. var showAllSymbol = seriesModel.get('showAllSymbol');
  33937. var isAuto = showAllSymbol === 'auto';
  33938. if (showAllSymbol && !isAuto) {
  33939. return;
  33940. }
  33941. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  33942. if (!categoryAxis) {
  33943. return;
  33944. }
  33945. // Note that category label interval strategy might bring some weird effect
  33946. // in some scenario: users may wonder why some of the symbols are not
  33947. // displayed. So we show all symbols as possible as we can.
  33948. if (isAuto
  33949. // Simplify the logic, do not determine label overlap here.
  33950. && canShowAllSymbolForCategory(categoryAxis, data)
  33951. ) {
  33952. return;
  33953. }
  33954. // Otherwise follow the label interval strategy on category axis.
  33955. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  33956. var labelMap = {};
  33957. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  33958. labelMap[labelItem.tickValue] = 1;
  33959. });
  33960. return function (dataIndex) {
  33961. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  33962. };
  33963. }
  33964. function canShowAllSymbolForCategory(categoryAxis, data) {
  33965. // In mose cases, line is monotonous on category axis, and the label size
  33966. // is close with each other. So we check the symbol size and some of the
  33967. // label size alone with the category axis to estimate whether all symbol
  33968. // can be shown without overlap.
  33969. var axisExtent = categoryAxis.getExtent();
  33970. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  33971. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  33972. // Sampling some points, max 5.
  33973. var dataLen = data.count();
  33974. var step = Math.max(1, Math.round(dataLen / 5));
  33975. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  33976. if (SymbolClz$1.getSymbolSize(
  33977. data, dataIndex
  33978. // Only for cartesian, where `isHorizontal` exists.
  33979. )[categoryAxis.isHorizontal() ? 1 : 0]
  33980. // Empirical number
  33981. * 1.5 > availSize
  33982. ) {
  33983. return false;
  33984. }
  33985. }
  33986. return true;
  33987. }
  33988. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  33989. if (coordSys.type === 'cartesian2d') {
  33990. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  33991. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  33992. // Expand clip shape to avoid clipping when line value exceeds axis
  33993. if (!seriesModel.get('clip', true)) {
  33994. var rectShape = clipPath.shape;
  33995. var expandSize = Math.max(rectShape.width, rectShape.height);
  33996. if (isHorizontal) {
  33997. rectShape.y -= expandSize;
  33998. rectShape.height += expandSize * 2;
  33999. }
  34000. else {
  34001. rectShape.x -= expandSize;
  34002. rectShape.width += expandSize * 2;
  34003. }
  34004. }
  34005. return clipPath;
  34006. }
  34007. else {
  34008. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34009. }
  34010. }
  34011. Chart.extend({
  34012. type: 'line',
  34013. init: function () {
  34014. var lineGroup = new Group();
  34015. var symbolDraw = new SymbolDraw();
  34016. this.group.add(symbolDraw.group);
  34017. this._symbolDraw = symbolDraw;
  34018. this._lineGroup = lineGroup;
  34019. },
  34020. render: function (seriesModel, ecModel, api) {
  34021. var coordSys = seriesModel.coordinateSystem;
  34022. var group = this.group;
  34023. var data = seriesModel.getData();
  34024. var lineStyleModel = seriesModel.getModel('lineStyle');
  34025. var areaStyleModel = seriesModel.getModel('areaStyle');
  34026. var points = data.mapArray(data.getItemLayout);
  34027. var isCoordSysPolar = coordSys.type === 'polar';
  34028. var prevCoordSys = this._coordSys;
  34029. var symbolDraw = this._symbolDraw;
  34030. var polyline = this._polyline;
  34031. var polygon = this._polygon;
  34032. var lineGroup = this._lineGroup;
  34033. var hasAnimation = seriesModel.get('animation');
  34034. var isAreaChart = !areaStyleModel.isEmpty();
  34035. var valueOrigin = areaStyleModel.get('origin');
  34036. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34037. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34038. var showSymbol = seriesModel.get('showSymbol');
  34039. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  34040. && getIsIgnoreFunc(seriesModel, data, coordSys);
  34041. // Remove temporary symbols
  34042. var oldData = this._data;
  34043. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34044. if (el.__temp) {
  34045. group.remove(el);
  34046. oldData.setItemGraphicEl(idx, null);
  34047. }
  34048. });
  34049. // Remove previous created symbols if showSymbol changed to false
  34050. if (!showSymbol) {
  34051. symbolDraw.remove();
  34052. }
  34053. group.add(lineGroup);
  34054. // FIXME step not support polar
  34055. var step = !isCoordSysPolar && seriesModel.get('step');
  34056. var clipShapeForSymbol;
  34057. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34058. clipShapeForSymbol = coordSys.getArea();
  34059. // Avoid float number rounding error for symbol on the edge of axis extent.
  34060. // See #7913 and `test/dataZoom-clip.html`.
  34061. if (clipShapeForSymbol.width != null) {
  34062. clipShapeForSymbol.x -= 0.1;
  34063. clipShapeForSymbol.y -= 0.1;
  34064. clipShapeForSymbol.width += 0.2;
  34065. clipShapeForSymbol.height += 0.2;
  34066. }
  34067. else if (clipShapeForSymbol.r0) {
  34068. clipShapeForSymbol.r0 -= 0.5;
  34069. clipShapeForSymbol.r1 += 0.5;
  34070. }
  34071. }
  34072. this._clipShapeForSymbol = clipShapeForSymbol;
  34073. // Initialization animation or coordinate system changed
  34074. if (
  34075. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  34076. ) {
  34077. showSymbol && symbolDraw.updateData(data, {
  34078. isIgnore: isIgnoreFunc,
  34079. clipShape: clipShapeForSymbol
  34080. });
  34081. if (step) {
  34082. // TODO If stacked series is not step
  34083. points = turnPointsIntoStep(points, coordSys, step);
  34084. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34085. }
  34086. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34087. if (isAreaChart) {
  34088. polygon = this._newPolygon(
  34089. points, stackedOnPoints,
  34090. coordSys, hasAnimation
  34091. );
  34092. }
  34093. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34094. }
  34095. else {
  34096. if (isAreaChart && !polygon) {
  34097. // If areaStyle is added
  34098. polygon = this._newPolygon(
  34099. points, stackedOnPoints,
  34100. coordSys, hasAnimation
  34101. );
  34102. }
  34103. else if (polygon && !isAreaChart) {
  34104. // If areaStyle is removed
  34105. lineGroup.remove(polygon);
  34106. polygon = this._polygon = null;
  34107. }
  34108. // Update clipPath
  34109. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34110. // Always update, or it is wrong in the case turning on legend
  34111. // because points are not changed
  34112. showSymbol && symbolDraw.updateData(data, {
  34113. isIgnore: isIgnoreFunc,
  34114. clipShape: clipShapeForSymbol
  34115. });
  34116. // Stop symbol animation and sync with line points
  34117. // FIXME performance?
  34118. data.eachItemGraphicEl(function (el) {
  34119. el.stopAnimation(true);
  34120. });
  34121. // In the case data zoom triggerred refreshing frequently
  34122. // Data may not change if line has a category axis. So it should animate nothing
  34123. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34124. || !isPointsSame(this._points, points)
  34125. ) {
  34126. if (hasAnimation) {
  34127. this._updateAnimation(
  34128. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34129. );
  34130. }
  34131. else {
  34132. // Not do it in update with animation
  34133. if (step) {
  34134. // TODO If stacked series is not step
  34135. points = turnPointsIntoStep(points, coordSys, step);
  34136. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34137. }
  34138. polyline.setShape({
  34139. points: points
  34140. });
  34141. polygon && polygon.setShape({
  34142. points: points,
  34143. stackedOnPoints: stackedOnPoints
  34144. });
  34145. }
  34146. }
  34147. }
  34148. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34149. polyline.useStyle(defaults(
  34150. // Use color in lineStyle first
  34151. lineStyleModel.getLineStyle(),
  34152. {
  34153. fill: 'none',
  34154. stroke: visualColor,
  34155. lineJoin: 'bevel'
  34156. }
  34157. ));
  34158. var smooth = seriesModel.get('smooth');
  34159. smooth = getSmooth(seriesModel.get('smooth'));
  34160. polyline.setShape({
  34161. smooth: smooth,
  34162. smoothMonotone: seriesModel.get('smoothMonotone'),
  34163. connectNulls: seriesModel.get('connectNulls')
  34164. });
  34165. if (polygon) {
  34166. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34167. var stackedOnSmooth = 0;
  34168. polygon.useStyle(defaults(
  34169. areaStyleModel.getAreaStyle(),
  34170. {
  34171. fill: visualColor,
  34172. opacity: 0.7,
  34173. lineJoin: 'bevel'
  34174. }
  34175. ));
  34176. if (stackedOnSeries) {
  34177. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34178. }
  34179. polygon.setShape({
  34180. smooth: smooth,
  34181. stackedOnSmooth: stackedOnSmooth,
  34182. smoothMonotone: seriesModel.get('smoothMonotone'),
  34183. connectNulls: seriesModel.get('connectNulls')
  34184. });
  34185. }
  34186. this._data = data;
  34187. // Save the coordinate system for transition animation when data changed
  34188. this._coordSys = coordSys;
  34189. this._stackedOnPoints = stackedOnPoints;
  34190. this._points = points;
  34191. this._step = step;
  34192. this._valueOrigin = valueOrigin;
  34193. },
  34194. dispose: function () {},
  34195. highlight: function (seriesModel, ecModel, api, payload) {
  34196. var data = seriesModel.getData();
  34197. var dataIndex = queryDataIndex(data, payload);
  34198. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34199. var symbol = data.getItemGraphicEl(dataIndex);
  34200. if (!symbol) {
  34201. // Create a temporary symbol if it is not exists
  34202. var pt = data.getItemLayout(dataIndex);
  34203. if (!pt) {
  34204. // Null data
  34205. return;
  34206. }
  34207. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34208. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34209. return;
  34210. }
  34211. symbol = new SymbolClz$1(data, dataIndex);
  34212. symbol.position = pt;
  34213. symbol.setZ(
  34214. seriesModel.get('zlevel'),
  34215. seriesModel.get('z')
  34216. );
  34217. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34218. symbol.__temp = true;
  34219. data.setItemGraphicEl(dataIndex, symbol);
  34220. // Stop scale animation
  34221. symbol.stopSymbolAnimation(true);
  34222. this.group.add(symbol);
  34223. }
  34224. symbol.highlight();
  34225. }
  34226. else {
  34227. // Highlight whole series
  34228. Chart.prototype.highlight.call(
  34229. this, seriesModel, ecModel, api, payload
  34230. );
  34231. }
  34232. },
  34233. downplay: function (seriesModel, ecModel, api, payload) {
  34234. var data = seriesModel.getData();
  34235. var dataIndex = queryDataIndex(data, payload);
  34236. if (dataIndex != null && dataIndex >= 0) {
  34237. var symbol = data.getItemGraphicEl(dataIndex);
  34238. if (symbol) {
  34239. if (symbol.__temp) {
  34240. data.setItemGraphicEl(dataIndex, null);
  34241. this.group.remove(symbol);
  34242. }
  34243. else {
  34244. symbol.downplay();
  34245. }
  34246. }
  34247. }
  34248. else {
  34249. // FIXME
  34250. // can not downplay completely.
  34251. // Downplay whole series
  34252. Chart.prototype.downplay.call(
  34253. this, seriesModel, ecModel, api, payload
  34254. );
  34255. }
  34256. },
  34257. /**
  34258. * @param {module:zrender/container/Group} group
  34259. * @param {Array.<Array.<number>>} points
  34260. * @private
  34261. */
  34262. _newPolyline: function (points) {
  34263. var polyline = this._polyline;
  34264. // Remove previous created polyline
  34265. if (polyline) {
  34266. this._lineGroup.remove(polyline);
  34267. }
  34268. polyline = new Polyline$1({
  34269. shape: {
  34270. points: points
  34271. },
  34272. silent: true,
  34273. z2: 10
  34274. });
  34275. this._lineGroup.add(polyline);
  34276. this._polyline = polyline;
  34277. return polyline;
  34278. },
  34279. /**
  34280. * @param {module:zrender/container/Group} group
  34281. * @param {Array.<Array.<number>>} stackedOnPoints
  34282. * @param {Array.<Array.<number>>} points
  34283. * @private
  34284. */
  34285. _newPolygon: function (points, stackedOnPoints) {
  34286. var polygon = this._polygon;
  34287. // Remove previous created polygon
  34288. if (polygon) {
  34289. this._lineGroup.remove(polygon);
  34290. }
  34291. polygon = new Polygon$1({
  34292. shape: {
  34293. points: points,
  34294. stackedOnPoints: stackedOnPoints
  34295. },
  34296. silent: true
  34297. });
  34298. this._lineGroup.add(polygon);
  34299. this._polygon = polygon;
  34300. return polygon;
  34301. },
  34302. /**
  34303. * @private
  34304. */
  34305. // FIXME Two value axis
  34306. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34307. var polyline = this._polyline;
  34308. var polygon = this._polygon;
  34309. var seriesModel = data.hostModel;
  34310. var diff = lineAnimationDiff(
  34311. this._data, data,
  34312. this._stackedOnPoints, stackedOnPoints,
  34313. this._coordSys, coordSys,
  34314. this._valueOrigin, valueOrigin
  34315. );
  34316. var current = diff.current;
  34317. var stackedOnCurrent = diff.stackedOnCurrent;
  34318. var next = diff.next;
  34319. var stackedOnNext = diff.stackedOnNext;
  34320. if (step) {
  34321. // TODO If stacked series is not step
  34322. current = turnPointsIntoStep(diff.current, coordSys, step);
  34323. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34324. next = turnPointsIntoStep(diff.next, coordSys, step);
  34325. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34326. }
  34327. // `diff.current` is subset of `current` (which should be ensured by
  34328. // turnPointsIntoStep), so points in `__points` can be updated when
  34329. // points in `current` are update during animation.
  34330. polyline.shape.__points = diff.current;
  34331. polyline.shape.points = current;
  34332. updateProps(polyline, {
  34333. shape: {
  34334. points: next
  34335. }
  34336. }, seriesModel);
  34337. if (polygon) {
  34338. polygon.setShape({
  34339. points: current,
  34340. stackedOnPoints: stackedOnCurrent
  34341. });
  34342. updateProps(polygon, {
  34343. shape: {
  34344. points: next,
  34345. stackedOnPoints: stackedOnNext
  34346. }
  34347. }, seriesModel);
  34348. }
  34349. var updatedDataInfo = [];
  34350. var diffStatus = diff.status;
  34351. for (var i = 0; i < diffStatus.length; i++) {
  34352. var cmd = diffStatus[i].cmd;
  34353. if (cmd === '=') {
  34354. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34355. if (el) {
  34356. updatedDataInfo.push({
  34357. el: el,
  34358. ptIdx: i // Index of points
  34359. });
  34360. }
  34361. }
  34362. }
  34363. if (polyline.animators && polyline.animators.length) {
  34364. polyline.animators[0].during(function () {
  34365. for (var i = 0; i < updatedDataInfo.length; i++) {
  34366. var el = updatedDataInfo[i].el;
  34367. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34368. }
  34369. });
  34370. }
  34371. },
  34372. remove: function (ecModel) {
  34373. var group = this.group;
  34374. var oldData = this._data;
  34375. this._lineGroup.removeAll();
  34376. this._symbolDraw.remove(true);
  34377. // Remove temporary created elements when highlighting
  34378. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34379. if (el.__temp) {
  34380. group.remove(el);
  34381. oldData.setItemGraphicEl(idx, null);
  34382. }
  34383. });
  34384. this._polyline =
  34385. this._polygon =
  34386. this._coordSys =
  34387. this._points =
  34388. this._stackedOnPoints =
  34389. this._data = null;
  34390. }
  34391. });
  34392. /*
  34393. * Licensed to the Apache Software Foundation (ASF) under one
  34394. * or more contributor license agreements. See the NOTICE file
  34395. * distributed with this work for additional information
  34396. * regarding copyright ownership. The ASF licenses this file
  34397. * to you under the Apache License, Version 2.0 (the
  34398. * "License"); you may not use this file except in compliance
  34399. * with the License. You may obtain a copy of the License at
  34400. *
  34401. * http://www.apache.org/licenses/LICENSE-2.0
  34402. *
  34403. * Unless required by applicable law or agreed to in writing,
  34404. * software distributed under the License is distributed on an
  34405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34406. * KIND, either express or implied. See the License for the
  34407. * specific language governing permissions and limitations
  34408. * under the License.
  34409. */
  34410. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34411. // Encoding visual for all series include which is filtered for legend drawing
  34412. return {
  34413. seriesType: seriesType,
  34414. // For legend.
  34415. performRawSeries: true,
  34416. reset: function (seriesModel, ecModel, api) {
  34417. var data = seriesModel.getData();
  34418. var symbolType = seriesModel.get('symbol');
  34419. var symbolSize = seriesModel.get('symbolSize');
  34420. var keepAspect = seriesModel.get('symbolKeepAspect');
  34421. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34422. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34423. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  34424. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34425. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34426. data.setVisual({
  34427. legendSymbol: legendSymbol || seriesSymbol,
  34428. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34429. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34430. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34431. // some cases but generally it is not recommanded.
  34432. symbol: seriesSymbol,
  34433. symbolSize: seriesSymbolSize,
  34434. symbolKeepAspect: keepAspect
  34435. });
  34436. // Only visible series has each data be visual encoded
  34437. if (ecModel.isSeriesFiltered(seriesModel)) {
  34438. return;
  34439. }
  34440. function dataEach(data, idx) {
  34441. if (hasCallback) {
  34442. var rawValue = seriesModel.getRawValue(idx);
  34443. var params = seriesModel.getDataParams(idx);
  34444. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34445. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34446. }
  34447. if (data.hasItemOption) {
  34448. var itemModel = data.getItemModel(idx);
  34449. var itemSymbolType = itemModel.getShallow('symbol', true);
  34450. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34451. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34452. // If has item symbol
  34453. if (itemSymbolType != null) {
  34454. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34455. }
  34456. if (itemSymbolSize != null) {
  34457. // PENDING Transform symbolSize ?
  34458. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34459. }
  34460. if (itemSymbolKeepAspect != null) {
  34461. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34462. }
  34463. }
  34464. }
  34465. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34466. }
  34467. };
  34468. };
  34469. /*
  34470. * Licensed to the Apache Software Foundation (ASF) under one
  34471. * or more contributor license agreements. See the NOTICE file
  34472. * distributed with this work for additional information
  34473. * regarding copyright ownership. The ASF licenses this file
  34474. * to you under the Apache License, Version 2.0 (the
  34475. * "License"); you may not use this file except in compliance
  34476. * with the License. You may obtain a copy of the License at
  34477. *
  34478. * http://www.apache.org/licenses/LICENSE-2.0
  34479. *
  34480. * Unless required by applicable law or agreed to in writing,
  34481. * software distributed under the License is distributed on an
  34482. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34483. * KIND, either express or implied. See the License for the
  34484. * specific language governing permissions and limitations
  34485. * under the License.
  34486. */
  34487. /* global Float32Array */
  34488. var pointsLayout = function (seriesType) {
  34489. return {
  34490. seriesType: seriesType,
  34491. plan: createRenderPlanner(),
  34492. reset: function (seriesModel) {
  34493. var data = seriesModel.getData();
  34494. var coordSys = seriesModel.coordinateSystem;
  34495. var pipelineContext = seriesModel.pipelineContext;
  34496. var isLargeRender = pipelineContext.large;
  34497. if (!coordSys) {
  34498. return;
  34499. }
  34500. var dims = map(coordSys.dimensions, function (dim) {
  34501. return data.mapDimension(dim);
  34502. }).slice(0, 2);
  34503. var dimLen = dims.length;
  34504. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34505. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34506. dims[0] = stackResultDim;
  34507. }
  34508. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34509. dims[1] = stackResultDim;
  34510. }
  34511. function progress(params, data) {
  34512. var segCount = params.end - params.start;
  34513. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34514. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34515. var point;
  34516. if (dimLen === 1) {
  34517. var x = data.get(dims[0], i);
  34518. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34519. }
  34520. else {
  34521. var x = tmpIn[0] = data.get(dims[0], i);
  34522. var y = tmpIn[1] = data.get(dims[1], i);
  34523. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34524. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34525. }
  34526. if (isLargeRender) {
  34527. points[offset++] = point ? point[0] : NaN;
  34528. points[offset++] = point ? point[1] : NaN;
  34529. }
  34530. else {
  34531. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34532. }
  34533. }
  34534. isLargeRender && data.setLayout('symbolPoints', points);
  34535. }
  34536. return dimLen && {progress: progress};
  34537. }
  34538. };
  34539. };
  34540. /*
  34541. * Licensed to the Apache Software Foundation (ASF) under one
  34542. * or more contributor license agreements. See the NOTICE file
  34543. * distributed with this work for additional information
  34544. * regarding copyright ownership. The ASF licenses this file
  34545. * to you under the Apache License, Version 2.0 (the
  34546. * "License"); you may not use this file except in compliance
  34547. * with the License. You may obtain a copy of the License at
  34548. *
  34549. * http://www.apache.org/licenses/LICENSE-2.0
  34550. *
  34551. * Unless required by applicable law or agreed to in writing,
  34552. * software distributed under the License is distributed on an
  34553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34554. * KIND, either express or implied. See the License for the
  34555. * specific language governing permissions and limitations
  34556. * under the License.
  34557. */
  34558. var samplers = {
  34559. average: function (frame) {
  34560. var sum = 0;
  34561. var count = 0;
  34562. for (var i = 0; i < frame.length; i++) {
  34563. if (!isNaN(frame[i])) {
  34564. sum += frame[i];
  34565. count++;
  34566. }
  34567. }
  34568. // Return NaN if count is 0
  34569. return count === 0 ? NaN : sum / count;
  34570. },
  34571. sum: function (frame) {
  34572. var sum = 0;
  34573. for (var i = 0; i < frame.length; i++) {
  34574. // Ignore NaN
  34575. sum += frame[i] || 0;
  34576. }
  34577. return sum;
  34578. },
  34579. max: function (frame) {
  34580. var max = -Infinity;
  34581. for (var i = 0; i < frame.length; i++) {
  34582. frame[i] > max && (max = frame[i]);
  34583. }
  34584. // NaN will cause illegal axis extent.
  34585. return isFinite(max) ? max : NaN;
  34586. },
  34587. min: function (frame) {
  34588. var min = Infinity;
  34589. for (var i = 0; i < frame.length; i++) {
  34590. frame[i] < min && (min = frame[i]);
  34591. }
  34592. // NaN will cause illegal axis extent.
  34593. return isFinite(min) ? min : NaN;
  34594. },
  34595. // TODO
  34596. // Median
  34597. nearest: function (frame) {
  34598. return frame[0];
  34599. }
  34600. };
  34601. var indexSampler = function (frame, value) {
  34602. return Math.round(frame.length / 2);
  34603. };
  34604. var dataSample = function (seriesType) {
  34605. return {
  34606. seriesType: seriesType,
  34607. modifyOutputEnd: true,
  34608. reset: function (seriesModel, ecModel, api) {
  34609. var data = seriesModel.getData();
  34610. var sampling = seriesModel.get('sampling');
  34611. var coordSys = seriesModel.coordinateSystem;
  34612. // Only cartesian2d support down sampling
  34613. if (coordSys.type === 'cartesian2d' && sampling) {
  34614. var baseAxis = coordSys.getBaseAxis();
  34615. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34616. var extent = baseAxis.getExtent();
  34617. // Coordinste system has been resized
  34618. var size = extent[1] - extent[0];
  34619. var rate = Math.round(data.count() / size);
  34620. if (rate > 1) {
  34621. var sampler;
  34622. if (typeof sampling === 'string') {
  34623. sampler = samplers[sampling];
  34624. }
  34625. else if (typeof sampling === 'function') {
  34626. sampler = sampling;
  34627. }
  34628. if (sampler) {
  34629. // Only support sample the first dim mapped from value axis.
  34630. seriesModel.setData(data.downSample(
  34631. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34632. ));
  34633. }
  34634. }
  34635. }
  34636. }
  34637. };
  34638. };
  34639. /*
  34640. * Licensed to the Apache Software Foundation (ASF) under one
  34641. * or more contributor license agreements. See the NOTICE file
  34642. * distributed with this work for additional information
  34643. * regarding copyright ownership. The ASF licenses this file
  34644. * to you under the Apache License, Version 2.0 (the
  34645. * "License"); you may not use this file except in compliance
  34646. * with the License. You may obtain a copy of the License at
  34647. *
  34648. * http://www.apache.org/licenses/LICENSE-2.0
  34649. *
  34650. * Unless required by applicable law or agreed to in writing,
  34651. * software distributed under the License is distributed on an
  34652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34653. * KIND, either express or implied. See the License for the
  34654. * specific language governing permissions and limitations
  34655. * under the License.
  34656. */
  34657. /**
  34658. * Cartesian coordinate system
  34659. * @module echarts/coord/Cartesian
  34660. *
  34661. */
  34662. function dimAxisMapper(dim) {
  34663. return this._axes[dim];
  34664. }
  34665. /**
  34666. * @alias module:echarts/coord/Cartesian
  34667. * @constructor
  34668. */
  34669. var Cartesian = function (name) {
  34670. this._axes = {};
  34671. this._dimList = [];
  34672. /**
  34673. * @type {string}
  34674. */
  34675. this.name = name || '';
  34676. };
  34677. Cartesian.prototype = {
  34678. constructor: Cartesian,
  34679. type: 'cartesian',
  34680. /**
  34681. * Get axis
  34682. * @param {number|string} dim
  34683. * @return {module:echarts/coord/Cartesian~Axis}
  34684. */
  34685. getAxis: function (dim) {
  34686. return this._axes[dim];
  34687. },
  34688. /**
  34689. * Get axes list
  34690. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34691. */
  34692. getAxes: function () {
  34693. return map(this._dimList, dimAxisMapper, this);
  34694. },
  34695. /**
  34696. * Get axes list by given scale type
  34697. */
  34698. getAxesByScale: function (scaleType) {
  34699. scaleType = scaleType.toLowerCase();
  34700. return filter(
  34701. this.getAxes(),
  34702. function (axis) {
  34703. return axis.scale.type === scaleType;
  34704. }
  34705. );
  34706. },
  34707. /**
  34708. * Add axis
  34709. * @param {module:echarts/coord/Cartesian.Axis}
  34710. */
  34711. addAxis: function (axis) {
  34712. var dim = axis.dim;
  34713. this._axes[dim] = axis;
  34714. this._dimList.push(dim);
  34715. },
  34716. /**
  34717. * Convert data to coord in nd space
  34718. * @param {Array.<number>|Object.<string, number>} val
  34719. * @return {Array.<number>|Object.<string, number>}
  34720. */
  34721. dataToCoord: function (val) {
  34722. return this._dataCoordConvert(val, 'dataToCoord');
  34723. },
  34724. /**
  34725. * Convert coord in nd space to data
  34726. * @param {Array.<number>|Object.<string, number>} val
  34727. * @return {Array.<number>|Object.<string, number>}
  34728. */
  34729. coordToData: function (val) {
  34730. return this._dataCoordConvert(val, 'coordToData');
  34731. },
  34732. _dataCoordConvert: function (input, method) {
  34733. var dimList = this._dimList;
  34734. var output = input instanceof Array ? [] : {};
  34735. for (var i = 0; i < dimList.length; i++) {
  34736. var dim = dimList[i];
  34737. var axis = this._axes[dim];
  34738. output[dim] = axis[method](input[dim]);
  34739. }
  34740. return output;
  34741. }
  34742. };
  34743. /*
  34744. * Licensed to the Apache Software Foundation (ASF) under one
  34745. * or more contributor license agreements. See the NOTICE file
  34746. * distributed with this work for additional information
  34747. * regarding copyright ownership. The ASF licenses this file
  34748. * to you under the Apache License, Version 2.0 (the
  34749. * "License"); you may not use this file except in compliance
  34750. * with the License. You may obtain a copy of the License at
  34751. *
  34752. * http://www.apache.org/licenses/LICENSE-2.0
  34753. *
  34754. * Unless required by applicable law or agreed to in writing,
  34755. * software distributed under the License is distributed on an
  34756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34757. * KIND, either express or implied. See the License for the
  34758. * specific language governing permissions and limitations
  34759. * under the License.
  34760. */
  34761. function Cartesian2D(name) {
  34762. Cartesian.call(this, name);
  34763. }
  34764. Cartesian2D.prototype = {
  34765. constructor: Cartesian2D,
  34766. type: 'cartesian2d',
  34767. /**
  34768. * @type {Array.<string>}
  34769. * @readOnly
  34770. */
  34771. dimensions: ['x', 'y'],
  34772. /**
  34773. * Base axis will be used on stacking.
  34774. *
  34775. * @return {module:echarts/coord/cartesian/Axis2D}
  34776. */
  34777. getBaseAxis: function () {
  34778. return this.getAxesByScale('ordinal')[0]
  34779. || this.getAxesByScale('time')[0]
  34780. || this.getAxis('x');
  34781. },
  34782. /**
  34783. * If contain point
  34784. * @param {Array.<number>} point
  34785. * @return {boolean}
  34786. */
  34787. containPoint: function (point) {
  34788. var axisX = this.getAxis('x');
  34789. var axisY = this.getAxis('y');
  34790. return axisX.contain(axisX.toLocalCoord(point[0]))
  34791. && axisY.contain(axisY.toLocalCoord(point[1]));
  34792. },
  34793. /**
  34794. * If contain data
  34795. * @param {Array.<number>} data
  34796. * @return {boolean}
  34797. */
  34798. containData: function (data) {
  34799. return this.getAxis('x').containData(data[0])
  34800. && this.getAxis('y').containData(data[1]);
  34801. },
  34802. /**
  34803. * @param {Array.<number>} data
  34804. * @param {Array.<number>} out
  34805. * @return {Array.<number>}
  34806. */
  34807. dataToPoint: function (data, reserved, out) {
  34808. var xAxis = this.getAxis('x');
  34809. var yAxis = this.getAxis('y');
  34810. out = out || [];
  34811. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34812. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34813. return out;
  34814. },
  34815. /**
  34816. * @param {Array.<number>} data
  34817. * @param {Array.<number>} out
  34818. * @return {Array.<number>}
  34819. */
  34820. clampData: function (data, out) {
  34821. var xScale = this.getAxis('x').scale;
  34822. var yScale = this.getAxis('y').scale;
  34823. var xAxisExtent = xScale.getExtent();
  34824. var yAxisExtent = yScale.getExtent();
  34825. var x = xScale.parse(data[0]);
  34826. var y = yScale.parse(data[1]);
  34827. out = out || [];
  34828. out[0] = Math.min(
  34829. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34830. Math.max(xAxisExtent[0], xAxisExtent[1])
  34831. );
  34832. out[1] = Math.min(
  34833. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34834. Math.max(yAxisExtent[0], yAxisExtent[1])
  34835. );
  34836. return out;
  34837. },
  34838. /**
  34839. * @param {Array.<number>} point
  34840. * @param {Array.<number>} out
  34841. * @return {Array.<number>}
  34842. */
  34843. pointToData: function (point, out) {
  34844. var xAxis = this.getAxis('x');
  34845. var yAxis = this.getAxis('y');
  34846. out = out || [];
  34847. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34848. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34849. return out;
  34850. },
  34851. /**
  34852. * Get other axis
  34853. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34854. */
  34855. getOtherAxis: function (axis) {
  34856. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34857. },
  34858. /**
  34859. * Get rect area of cartesian.
  34860. * Area will have a contain function to determine if a point is in the coordinate system.
  34861. * @return {BoundingRect}
  34862. */
  34863. getArea: function () {
  34864. var xExtent = this.getAxis('x').getGlobalExtent();
  34865. var yExtent = this.getAxis('y').getGlobalExtent();
  34866. var x = Math.min(xExtent[0], xExtent[1]);
  34867. var y = Math.min(yExtent[0], yExtent[1]);
  34868. var width = Math.max(xExtent[0], xExtent[1]) - x;
  34869. var height = Math.max(yExtent[0], yExtent[1]) - y;
  34870. var rect = new BoundingRect(x, y, width, height);
  34871. return rect;
  34872. }
  34873. };
  34874. inherits(Cartesian2D, Cartesian);
  34875. /*
  34876. * Licensed to the Apache Software Foundation (ASF) under one
  34877. * or more contributor license agreements. See the NOTICE file
  34878. * distributed with this work for additional information
  34879. * regarding copyright ownership. The ASF licenses this file
  34880. * to you under the Apache License, Version 2.0 (the
  34881. * "License"); you may not use this file except in compliance
  34882. * with the License. You may obtain a copy of the License at
  34883. *
  34884. * http://www.apache.org/licenses/LICENSE-2.0
  34885. *
  34886. * Unless required by applicable law or agreed to in writing,
  34887. * software distributed under the License is distributed on an
  34888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34889. * KIND, either express or implied. See the License for the
  34890. * specific language governing permissions and limitations
  34891. * under the License.
  34892. */
  34893. /**
  34894. * Extend axis 2d
  34895. * @constructor module:echarts/coord/cartesian/Axis2D
  34896. * @extends {module:echarts/coord/cartesian/Axis}
  34897. * @param {string} dim
  34898. * @param {*} scale
  34899. * @param {Array.<number>} coordExtent
  34900. * @param {string} axisType
  34901. * @param {string} position
  34902. */
  34903. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  34904. Axis.call(this, dim, scale, coordExtent);
  34905. /**
  34906. * Axis type
  34907. * - 'category'
  34908. * - 'value'
  34909. * - 'time'
  34910. * - 'log'
  34911. * @type {string}
  34912. */
  34913. this.type = axisType || 'value';
  34914. /**
  34915. * Axis position
  34916. * - 'top'
  34917. * - 'bottom'
  34918. * - 'left'
  34919. * - 'right'
  34920. */
  34921. this.position = position || 'bottom';
  34922. };
  34923. Axis2D.prototype = {
  34924. constructor: Axis2D,
  34925. /**
  34926. * Index of axis, can be used as key
  34927. */
  34928. index: 0,
  34929. /**
  34930. * Implemented in <module:echarts/coord/cartesian/Grid>.
  34931. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  34932. * If not on zero of other axis, return null/undefined.
  34933. * If no axes, return an empty array.
  34934. */
  34935. getAxesOnZeroOf: null,
  34936. /**
  34937. * Axis model
  34938. * @param {module:echarts/coord/cartesian/AxisModel}
  34939. */
  34940. model: null,
  34941. isHorizontal: function () {
  34942. var position = this.position;
  34943. return position === 'top' || position === 'bottom';
  34944. },
  34945. /**
  34946. * Each item cooresponds to this.getExtent(), which
  34947. * means globalExtent[0] may greater than globalExtent[1],
  34948. * unless `asc` is input.
  34949. *
  34950. * @param {boolean} [asc]
  34951. * @return {Array.<number>}
  34952. */
  34953. getGlobalExtent: function (asc) {
  34954. var ret = this.getExtent();
  34955. ret[0] = this.toGlobalCoord(ret[0]);
  34956. ret[1] = this.toGlobalCoord(ret[1]);
  34957. asc && ret[0] > ret[1] && ret.reverse();
  34958. return ret;
  34959. },
  34960. getOtherAxis: function () {
  34961. this.grid.getOtherAxis();
  34962. },
  34963. /**
  34964. * @override
  34965. */
  34966. pointToData: function (point, clamp) {
  34967. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  34968. },
  34969. /**
  34970. * Transform global coord to local coord,
  34971. * i.e. var localCoord = axis.toLocalCoord(80);
  34972. * designate by module:echarts/coord/cartesian/Grid.
  34973. * @type {Function}
  34974. */
  34975. toLocalCoord: null,
  34976. /**
  34977. * Transform global coord to local coord,
  34978. * i.e. var globalCoord = axis.toLocalCoord(40);
  34979. * designate by module:echarts/coord/cartesian/Grid.
  34980. * @type {Function}
  34981. */
  34982. toGlobalCoord: null
  34983. };
  34984. inherits(Axis2D, Axis);
  34985. /*
  34986. * Licensed to the Apache Software Foundation (ASF) under one
  34987. * or more contributor license agreements. See the NOTICE file
  34988. * distributed with this work for additional information
  34989. * regarding copyright ownership. The ASF licenses this file
  34990. * to you under the Apache License, Version 2.0 (the
  34991. * "License"); you may not use this file except in compliance
  34992. * with the License. You may obtain a copy of the License at
  34993. *
  34994. * http://www.apache.org/licenses/LICENSE-2.0
  34995. *
  34996. * Unless required by applicable law or agreed to in writing,
  34997. * software distributed under the License is distributed on an
  34998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34999. * KIND, either express or implied. See the License for the
  35000. * specific language governing permissions and limitations
  35001. * under the License.
  35002. */
  35003. var defaultOption = {
  35004. show: true,
  35005. zlevel: 0,
  35006. z: 0,
  35007. // Inverse the axis.
  35008. inverse: false,
  35009. // Axis name displayed.
  35010. name: '',
  35011. // 'start' | 'middle' | 'end'
  35012. nameLocation: 'end',
  35013. // By degree. By defualt auto rotate by nameLocation.
  35014. nameRotate: null,
  35015. nameTruncate: {
  35016. maxWidth: null,
  35017. ellipsis: '...',
  35018. placeholder: '.'
  35019. },
  35020. // Use global text style by default.
  35021. nameTextStyle: {},
  35022. // The gap between axisName and axisLine.
  35023. nameGap: 15,
  35024. // Default `false` to support tooltip.
  35025. silent: false,
  35026. // Default `false` to avoid legacy user event listener fail.
  35027. triggerEvent: false,
  35028. tooltip: {
  35029. show: false
  35030. },
  35031. axisPointer: {},
  35032. axisLine: {
  35033. show: true,
  35034. onZero: true,
  35035. onZeroAxisIndex: null,
  35036. lineStyle: {
  35037. color: '#333',
  35038. width: 1,
  35039. type: 'solid'
  35040. },
  35041. // The arrow at both ends the the axis.
  35042. symbol: ['none', 'none'],
  35043. symbolSize: [10, 15]
  35044. },
  35045. axisTick: {
  35046. show: true,
  35047. // Whether axisTick is inside the grid or outside the grid.
  35048. inside: false,
  35049. // The length of axisTick.
  35050. length: 5,
  35051. lineStyle: {
  35052. width: 1
  35053. }
  35054. },
  35055. axisLabel: {
  35056. show: true,
  35057. // Whether axisLabel is inside the grid or outside the grid.
  35058. inside: false,
  35059. rotate: 0,
  35060. // true | false | null/undefined (auto)
  35061. showMinLabel: null,
  35062. // true | false | null/undefined (auto)
  35063. showMaxLabel: null,
  35064. margin: 8,
  35065. // formatter: null,
  35066. fontSize: 12
  35067. },
  35068. splitLine: {
  35069. show: true,
  35070. lineStyle: {
  35071. color: ['#ccc'],
  35072. width: 1,
  35073. type: 'solid'
  35074. }
  35075. },
  35076. splitArea: {
  35077. show: false,
  35078. areaStyle: {
  35079. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  35080. }
  35081. }
  35082. };
  35083. var axisDefault = {};
  35084. axisDefault.categoryAxis = merge({
  35085. // The gap at both ends of the axis. For categoryAxis, boolean.
  35086. boundaryGap: true,
  35087. // Set false to faster category collection.
  35088. // Only usefull in the case like: category is
  35089. // ['2012-01-01', '2012-01-02', ...], where the input
  35090. // data has been ensured not duplicate and is large data.
  35091. // null means "auto":
  35092. // if axis.data provided, do not deduplication,
  35093. // else do deduplication.
  35094. deduplication: null,
  35095. // splitArea: {
  35096. // show: false
  35097. // },
  35098. splitLine: {
  35099. show: false
  35100. },
  35101. axisTick: {
  35102. // If tick is align with label when boundaryGap is true
  35103. alignWithLabel: false,
  35104. interval: 'auto'
  35105. },
  35106. axisLabel: {
  35107. interval: 'auto'
  35108. }
  35109. }, defaultOption);
  35110. axisDefault.valueAxis = merge({
  35111. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35112. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35113. boundaryGap: [0, 0],
  35114. // TODO
  35115. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35116. // Min value of the axis. can be:
  35117. // + a number
  35118. // + 'dataMin': use the min value in data.
  35119. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35120. // min: null,
  35121. // Max value of the axis. can be:
  35122. // + a number
  35123. // + 'dataMax': use the max value in data.
  35124. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35125. // max: null,
  35126. // Readonly prop, specifies start value of the range when using data zoom.
  35127. // rangeStart: null
  35128. // Readonly prop, specifies end value of the range when using data zoom.
  35129. // rangeEnd: null
  35130. // Optional value can be:
  35131. // + `false`: always include value 0.
  35132. // + `true`: the extent do not consider value 0.
  35133. // scale: false,
  35134. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35135. splitNumber: 5,
  35136. // Interval specifies the span of the ticks is mandatorily.
  35137. // interval: null
  35138. // Specify min interval when auto calculate tick interval.
  35139. // minInterval: null
  35140. // Specify max interval when auto calculate tick interval.
  35141. // maxInterval: null
  35142. minorTick: {
  35143. // Minor tick, not available for cateogry axis.
  35144. show: false,
  35145. // Split number of minor ticks. The value should be in range of (0, 100)
  35146. splitNumber: 5,
  35147. // Lenght of minor tick
  35148. length: 3,
  35149. // Same inside with axisTick
  35150. // Line style
  35151. lineStyle: {
  35152. // Default to be same with axisTick
  35153. }
  35154. },
  35155. minorSplitLine: {
  35156. show: false,
  35157. lineStyle: {
  35158. color: '#eee',
  35159. width: 1
  35160. }
  35161. }
  35162. }, defaultOption);
  35163. axisDefault.timeAxis = defaults({
  35164. scale: true,
  35165. min: 'dataMin',
  35166. max: 'dataMax'
  35167. }, axisDefault.valueAxis);
  35168. axisDefault.logAxis = defaults({
  35169. scale: true,
  35170. logBase: 10
  35171. }, axisDefault.valueAxis);
  35172. /*
  35173. * Licensed to the Apache Software Foundation (ASF) under one
  35174. * or more contributor license agreements. See the NOTICE file
  35175. * distributed with this work for additional information
  35176. * regarding copyright ownership. The ASF licenses this file
  35177. * to you under the Apache License, Version 2.0 (the
  35178. * "License"); you may not use this file except in compliance
  35179. * with the License. You may obtain a copy of the License at
  35180. *
  35181. * http://www.apache.org/licenses/LICENSE-2.0
  35182. *
  35183. * Unless required by applicable law or agreed to in writing,
  35184. * software distributed under the License is distributed on an
  35185. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35186. * KIND, either express or implied. See the License for the
  35187. * specific language governing permissions and limitations
  35188. * under the License.
  35189. */
  35190. // FIXME axisType is fixed ?
  35191. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35192. /**
  35193. * Generate sub axis model class
  35194. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35195. * @param {module:echarts/model/Component} BaseAxisModelClass
  35196. * @param {Function} axisTypeDefaulter
  35197. * @param {Object} [extraDefaultOption]
  35198. */
  35199. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35200. each$1(AXIS_TYPES, function (axisType) {
  35201. BaseAxisModelClass.extend({
  35202. /**
  35203. * @readOnly
  35204. */
  35205. type: axisName + 'Axis.' + axisType,
  35206. mergeDefaultAndTheme: function (option, ecModel) {
  35207. var layoutMode = this.layoutMode;
  35208. var inputPositionParams = layoutMode
  35209. ? getLayoutParams(option) : {};
  35210. var themeModel = ecModel.getTheme();
  35211. merge(option, themeModel.get(axisType + 'Axis'));
  35212. merge(option, this.getDefaultOption());
  35213. option.type = axisTypeDefaulter(axisName, option);
  35214. if (layoutMode) {
  35215. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35216. }
  35217. },
  35218. /**
  35219. * @override
  35220. */
  35221. optionUpdated: function () {
  35222. var thisOption = this.option;
  35223. if (thisOption.type === 'category') {
  35224. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35225. }
  35226. },
  35227. /**
  35228. * Should not be called before all of 'getInitailData' finished.
  35229. * Because categories are collected during initializing data.
  35230. */
  35231. getCategories: function (rawData) {
  35232. var option = this.option;
  35233. // FIXME
  35234. // warning if called before all of 'getInitailData' finished.
  35235. if (option.type === 'category') {
  35236. if (rawData) {
  35237. return option.data;
  35238. }
  35239. return this.__ordinalMeta.categories;
  35240. }
  35241. },
  35242. getOrdinalMeta: function () {
  35243. return this.__ordinalMeta;
  35244. },
  35245. defaultOption: mergeAll(
  35246. [
  35247. {},
  35248. axisDefault[axisType + 'Axis'],
  35249. extraDefaultOption
  35250. ],
  35251. true
  35252. )
  35253. });
  35254. });
  35255. ComponentModel.registerSubTypeDefaulter(
  35256. axisName + 'Axis',
  35257. curry(axisTypeDefaulter, axisName)
  35258. );
  35259. };
  35260. /*
  35261. * Licensed to the Apache Software Foundation (ASF) under one
  35262. * or more contributor license agreements. See the NOTICE file
  35263. * distributed with this work for additional information
  35264. * regarding copyright ownership. The ASF licenses this file
  35265. * to you under the Apache License, Version 2.0 (the
  35266. * "License"); you may not use this file except in compliance
  35267. * with the License. You may obtain a copy of the License at
  35268. *
  35269. * http://www.apache.org/licenses/LICENSE-2.0
  35270. *
  35271. * Unless required by applicable law or agreed to in writing,
  35272. * software distributed under the License is distributed on an
  35273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35274. * KIND, either express or implied. See the License for the
  35275. * specific language governing permissions and limitations
  35276. * under the License.
  35277. */
  35278. var AxisModel = ComponentModel.extend({
  35279. type: 'cartesian2dAxis',
  35280. /**
  35281. * @type {module:echarts/coord/cartesian/Axis2D}
  35282. */
  35283. axis: null,
  35284. /**
  35285. * @override
  35286. */
  35287. init: function () {
  35288. AxisModel.superApply(this, 'init', arguments);
  35289. this.resetRange();
  35290. },
  35291. /**
  35292. * @override
  35293. */
  35294. mergeOption: function () {
  35295. AxisModel.superApply(this, 'mergeOption', arguments);
  35296. this.resetRange();
  35297. },
  35298. /**
  35299. * @override
  35300. */
  35301. restoreData: function () {
  35302. AxisModel.superApply(this, 'restoreData', arguments);
  35303. this.resetRange();
  35304. },
  35305. /**
  35306. * @override
  35307. * @return {module:echarts/model/Component}
  35308. */
  35309. getCoordSysModel: function () {
  35310. return this.ecModel.queryComponents({
  35311. mainType: 'grid',
  35312. index: this.option.gridIndex,
  35313. id: this.option.gridId
  35314. })[0];
  35315. }
  35316. });
  35317. function getAxisType(axisDim, option) {
  35318. // Default axis with data is category axis
  35319. return option.type || (option.data ? 'category' : 'value');
  35320. }
  35321. merge(AxisModel.prototype, axisModelCommonMixin);
  35322. var extraOption = {
  35323. // gridIndex: 0,
  35324. // gridId: '',
  35325. // Offset is for multiple axis on the same position
  35326. offset: 0
  35327. };
  35328. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35329. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35330. /*
  35331. * Licensed to the Apache Software Foundation (ASF) under one
  35332. * or more contributor license agreements. See the NOTICE file
  35333. * distributed with this work for additional information
  35334. * regarding copyright ownership. The ASF licenses this file
  35335. * to you under the Apache License, Version 2.0 (the
  35336. * "License"); you may not use this file except in compliance
  35337. * with the License. You may obtain a copy of the License at
  35338. *
  35339. * http://www.apache.org/licenses/LICENSE-2.0
  35340. *
  35341. * Unless required by applicable law or agreed to in writing,
  35342. * software distributed under the License is distributed on an
  35343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35344. * KIND, either express or implied. See the License for the
  35345. * specific language governing permissions and limitations
  35346. * under the License.
  35347. */
  35348. // Grid 是在有直角坐标系的时候必须要存在的
  35349. // 所以这里也要被 Cartesian2D 依赖
  35350. ComponentModel.extend({
  35351. type: 'grid',
  35352. dependencies: ['xAxis', 'yAxis'],
  35353. layoutMode: 'box',
  35354. /**
  35355. * @type {module:echarts/coord/cartesian/Grid}
  35356. */
  35357. coordinateSystem: null,
  35358. defaultOption: {
  35359. show: false,
  35360. zlevel: 0,
  35361. z: 0,
  35362. left: '10%',
  35363. top: 60,
  35364. right: '10%',
  35365. bottom: 60,
  35366. // If grid size contain label
  35367. containLabel: false,
  35368. // width: {totalWidth} - left - right,
  35369. // height: {totalHeight} - top - bottom,
  35370. backgroundColor: 'rgba(0,0,0,0)',
  35371. borderWidth: 1,
  35372. borderColor: '#ccc'
  35373. }
  35374. });
  35375. /*
  35376. * Licensed to the Apache Software Foundation (ASF) under one
  35377. * or more contributor license agreements. See the NOTICE file
  35378. * distributed with this work for additional information
  35379. * regarding copyright ownership. The ASF licenses this file
  35380. * to you under the Apache License, Version 2.0 (the
  35381. * "License"); you may not use this file except in compliance
  35382. * with the License. You may obtain a copy of the License at
  35383. *
  35384. * http://www.apache.org/licenses/LICENSE-2.0
  35385. *
  35386. * Unless required by applicable law or agreed to in writing,
  35387. * software distributed under the License is distributed on an
  35388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35389. * KIND, either express or implied. See the License for the
  35390. * specific language governing permissions and limitations
  35391. * under the License.
  35392. */
  35393. /**
  35394. * Grid is a region which contains at most 4 cartesian systems
  35395. *
  35396. * TODO Default cartesian
  35397. */
  35398. // Depends on GridModel, AxisModel, which performs preprocess.
  35399. /**
  35400. * Check if the axis is used in the specified grid
  35401. * @inner
  35402. */
  35403. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35404. return axisModel.getCoordSysModel() === gridModel;
  35405. }
  35406. function Grid(gridModel, ecModel, api) {
  35407. /**
  35408. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35409. * @private
  35410. */
  35411. this._coordsMap = {};
  35412. /**
  35413. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35414. * @private
  35415. */
  35416. this._coordsList = [];
  35417. /**
  35418. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35419. * @private
  35420. */
  35421. this._axesMap = {};
  35422. /**
  35423. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35424. * @private
  35425. */
  35426. this._axesList = [];
  35427. this._initCartesian(gridModel, ecModel, api);
  35428. this.model = gridModel;
  35429. }
  35430. var gridProto = Grid.prototype;
  35431. gridProto.type = 'grid';
  35432. gridProto.axisPointerEnabled = true;
  35433. gridProto.getRect = function () {
  35434. return this._rect;
  35435. };
  35436. gridProto.update = function (ecModel, api) {
  35437. var axesMap = this._axesMap;
  35438. this._updateScale(ecModel, this.model);
  35439. each$1(axesMap.x, function (xAxis) {
  35440. niceScaleExtent(xAxis.scale, xAxis.model);
  35441. });
  35442. each$1(axesMap.y, function (yAxis) {
  35443. niceScaleExtent(yAxis.scale, yAxis.model);
  35444. });
  35445. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35446. var onZeroRecords = {};
  35447. each$1(axesMap.x, function (xAxis) {
  35448. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35449. });
  35450. each$1(axesMap.y, function (yAxis) {
  35451. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35452. });
  35453. // Resize again if containLabel is enabled
  35454. // FIXME It may cause getting wrong grid size in data processing stage
  35455. this.resize(this.model, api);
  35456. };
  35457. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35458. axis.getAxesOnZeroOf = function () {
  35459. // TODO: onZero of multiple axes.
  35460. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35461. };
  35462. // onZero can not be enabled in these two situations:
  35463. // 1. When any other axis is a category axis.
  35464. // 2. When no axis is cross 0 point.
  35465. var otherAxes = axesMap[otherAxisDim];
  35466. var otherAxisOnZeroOf;
  35467. var axisModel = axis.model;
  35468. var onZero = axisModel.get('axisLine.onZero');
  35469. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35470. if (!onZero) {
  35471. return;
  35472. }
  35473. // If target axis is specified.
  35474. if (onZeroAxisIndex != null) {
  35475. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35476. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35477. }
  35478. }
  35479. else {
  35480. // Find the first available other axis.
  35481. for (var idx in otherAxes) {
  35482. if (otherAxes.hasOwnProperty(idx)
  35483. && canOnZeroToAxis(otherAxes[idx])
  35484. // Consider that two Y axes on one value axis,
  35485. // if both onZero, the two Y axes overlap.
  35486. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35487. ) {
  35488. otherAxisOnZeroOf = otherAxes[idx];
  35489. break;
  35490. }
  35491. }
  35492. }
  35493. if (otherAxisOnZeroOf) {
  35494. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35495. }
  35496. function getOnZeroRecordKey(axis) {
  35497. return axis.dim + '_' + axis.index;
  35498. }
  35499. }
  35500. function canOnZeroToAxis(axis) {
  35501. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35502. }
  35503. /**
  35504. * Resize the grid
  35505. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35506. * @param {module:echarts/ExtensionAPI} api
  35507. */
  35508. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35509. var gridRect = getLayoutRect(
  35510. gridModel.getBoxLayoutParams(), {
  35511. width: api.getWidth(),
  35512. height: api.getHeight()
  35513. });
  35514. this._rect = gridRect;
  35515. var axesList = this._axesList;
  35516. adjustAxes();
  35517. // Minus label size
  35518. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35519. each$1(axesList, function (axis) {
  35520. if (!axis.model.get('axisLabel.inside')) {
  35521. var labelUnionRect = estimateLabelUnionRect(axis);
  35522. if (labelUnionRect) {
  35523. var dim = axis.isHorizontal() ? 'height' : 'width';
  35524. var margin = axis.model.get('axisLabel.margin');
  35525. gridRect[dim] -= labelUnionRect[dim] + margin;
  35526. if (axis.position === 'top') {
  35527. gridRect.y += labelUnionRect.height + margin;
  35528. }
  35529. else if (axis.position === 'left') {
  35530. gridRect.x += labelUnionRect.width + margin;
  35531. }
  35532. }
  35533. }
  35534. });
  35535. adjustAxes();
  35536. }
  35537. function adjustAxes() {
  35538. each$1(axesList, function (axis) {
  35539. var isHorizontal = axis.isHorizontal();
  35540. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35541. var idx = axis.inverse ? 1 : 0;
  35542. axis.setExtent(extent[idx], extent[1 - idx]);
  35543. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35544. });
  35545. }
  35546. };
  35547. /**
  35548. * @param {string} axisType
  35549. * @param {number} [axisIndex]
  35550. */
  35551. gridProto.getAxis = function (axisType, axisIndex) {
  35552. var axesMapOnDim = this._axesMap[axisType];
  35553. if (axesMapOnDim != null) {
  35554. if (axisIndex == null) {
  35555. // Find first axis
  35556. for (var name in axesMapOnDim) {
  35557. if (axesMapOnDim.hasOwnProperty(name)) {
  35558. return axesMapOnDim[name];
  35559. }
  35560. }
  35561. }
  35562. return axesMapOnDim[axisIndex];
  35563. }
  35564. };
  35565. /**
  35566. * @return {Array.<module:echarts/coord/Axis>}
  35567. */
  35568. gridProto.getAxes = function () {
  35569. return this._axesList.slice();
  35570. };
  35571. /**
  35572. * Usage:
  35573. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35574. * grid.getCartesian(xAxisIndex);
  35575. * grid.getCartesian(null, yAxisIndex);
  35576. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35577. *
  35578. * @param {number|Object} [xAxisIndex]
  35579. * @param {number} [yAxisIndex]
  35580. */
  35581. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35582. if (xAxisIndex != null && yAxisIndex != null) {
  35583. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35584. return this._coordsMap[key];
  35585. }
  35586. if (isObject$1(xAxisIndex)) {
  35587. yAxisIndex = xAxisIndex.yAxisIndex;
  35588. xAxisIndex = xAxisIndex.xAxisIndex;
  35589. }
  35590. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35591. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35592. if (coordList[i].getAxis('x').index === xAxisIndex
  35593. || coordList[i].getAxis('y').index === yAxisIndex
  35594. ) {
  35595. return coordList[i];
  35596. }
  35597. }
  35598. };
  35599. gridProto.getCartesians = function () {
  35600. return this._coordsList.slice();
  35601. };
  35602. /**
  35603. * @implements
  35604. * see {module:echarts/CoodinateSystem}
  35605. */
  35606. gridProto.convertToPixel = function (ecModel, finder, value) {
  35607. var target = this._findConvertTarget(ecModel, finder);
  35608. return target.cartesian
  35609. ? target.cartesian.dataToPoint(value)
  35610. : target.axis
  35611. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35612. : null;
  35613. };
  35614. /**
  35615. * @implements
  35616. * see {module:echarts/CoodinateSystem}
  35617. */
  35618. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35619. var target = this._findConvertTarget(ecModel, finder);
  35620. return target.cartesian
  35621. ? target.cartesian.pointToData(value)
  35622. : target.axis
  35623. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35624. : null;
  35625. };
  35626. /**
  35627. * @inner
  35628. */
  35629. gridProto._findConvertTarget = function (ecModel, finder) {
  35630. var seriesModel = finder.seriesModel;
  35631. var xAxisModel = finder.xAxisModel
  35632. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35633. var yAxisModel = finder.yAxisModel
  35634. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35635. var gridModel = finder.gridModel;
  35636. var coordsList = this._coordsList;
  35637. var cartesian;
  35638. var axis;
  35639. if (seriesModel) {
  35640. cartesian = seriesModel.coordinateSystem;
  35641. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35642. }
  35643. else if (xAxisModel && yAxisModel) {
  35644. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35645. }
  35646. else if (xAxisModel) {
  35647. axis = this.getAxis('x', xAxisModel.componentIndex);
  35648. }
  35649. else if (yAxisModel) {
  35650. axis = this.getAxis('y', yAxisModel.componentIndex);
  35651. }
  35652. // Lowest priority.
  35653. else if (gridModel) {
  35654. var grid = gridModel.coordinateSystem;
  35655. if (grid === this) {
  35656. cartesian = this._coordsList[0];
  35657. }
  35658. }
  35659. return {cartesian: cartesian, axis: axis};
  35660. };
  35661. /**
  35662. * @implements
  35663. * see {module:echarts/CoodinateSystem}
  35664. */
  35665. gridProto.containPoint = function (point) {
  35666. var coord = this._coordsList[0];
  35667. if (coord) {
  35668. return coord.containPoint(point);
  35669. }
  35670. };
  35671. /**
  35672. * Initialize cartesian coordinate systems
  35673. * @private
  35674. */
  35675. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35676. var axisPositionUsed = {
  35677. left: false,
  35678. right: false,
  35679. top: false,
  35680. bottom: false
  35681. };
  35682. var axesMap = {
  35683. x: {},
  35684. y: {}
  35685. };
  35686. var axesCount = {
  35687. x: 0,
  35688. y: 0
  35689. };
  35690. /// Create axis
  35691. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35692. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35693. if (!axesCount.x || !axesCount.y) {
  35694. // Roll back when there no either x or y axis
  35695. this._axesMap = {};
  35696. this._axesList = [];
  35697. return;
  35698. }
  35699. this._axesMap = axesMap;
  35700. /// Create cartesian2d
  35701. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35702. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35703. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35704. var cartesian = new Cartesian2D(key);
  35705. cartesian.grid = this;
  35706. cartesian.model = gridModel;
  35707. this._coordsMap[key] = cartesian;
  35708. this._coordsList.push(cartesian);
  35709. cartesian.addAxis(xAxis);
  35710. cartesian.addAxis(yAxis);
  35711. }, this);
  35712. }, this);
  35713. function createAxisCreator(axisType) {
  35714. return function (axisModel, idx) {
  35715. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35716. return;
  35717. }
  35718. var axisPosition = axisModel.get('position');
  35719. if (axisType === 'x') {
  35720. // Fix position
  35721. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35722. // Default bottom of X
  35723. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35724. }
  35725. }
  35726. else {
  35727. // Fix position
  35728. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35729. // Default left of Y
  35730. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35731. }
  35732. }
  35733. axisPositionUsed[axisPosition] = true;
  35734. var axis = new Axis2D(
  35735. axisType, createScaleByModel(axisModel),
  35736. [0, 0],
  35737. axisModel.get('type'),
  35738. axisPosition
  35739. );
  35740. var isCategory = axis.type === 'category';
  35741. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35742. axis.inverse = axisModel.get('inverse');
  35743. // Inject axis into axisModel
  35744. axisModel.axis = axis;
  35745. // Inject axisModel into axis
  35746. axis.model = axisModel;
  35747. // Inject grid info axis
  35748. axis.grid = this;
  35749. // Index of axis, can be used as key
  35750. axis.index = idx;
  35751. this._axesList.push(axis);
  35752. axesMap[axisType][idx] = axis;
  35753. axesCount[axisType]++;
  35754. };
  35755. }
  35756. };
  35757. /**
  35758. * Update cartesian properties from series
  35759. * @param {module:echarts/model/Option} option
  35760. * @private
  35761. */
  35762. gridProto._updateScale = function (ecModel, gridModel) {
  35763. // Reset scale
  35764. each$1(this._axesList, function (axis) {
  35765. axis.scale.setExtent(Infinity, -Infinity);
  35766. });
  35767. ecModel.eachSeries(function (seriesModel) {
  35768. if (isCartesian2D(seriesModel)) {
  35769. var axesModels = findAxesModels(seriesModel, ecModel);
  35770. var xAxisModel = axesModels[0];
  35771. var yAxisModel = axesModels[1];
  35772. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35773. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35774. ) {
  35775. return;
  35776. }
  35777. var cartesian = this.getCartesian(
  35778. xAxisModel.componentIndex, yAxisModel.componentIndex
  35779. );
  35780. var data = seriesModel.getData();
  35781. var xAxis = cartesian.getAxis('x');
  35782. var yAxis = cartesian.getAxis('y');
  35783. if (data.type === 'list') {
  35784. unionExtent(data, xAxis, seriesModel);
  35785. unionExtent(data, yAxis, seriesModel);
  35786. }
  35787. }
  35788. }, this);
  35789. function unionExtent(data, axis, seriesModel) {
  35790. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35791. axis.scale.unionExtentFromData(
  35792. // For example, the extent of the orginal dimension
  35793. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35794. // is [7, 9], the final extent should not include [0.1, 0.5].
  35795. data, getStackedDimension(data, dim)
  35796. );
  35797. });
  35798. }
  35799. };
  35800. /**
  35801. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35802. * @return {Object} {baseAxes: [], otherAxes: []}
  35803. */
  35804. gridProto.getTooltipAxes = function (dim) {
  35805. var baseAxes = [];
  35806. var otherAxes = [];
  35807. each$1(this.getCartesians(), function (cartesian) {
  35808. var baseAxis = (dim != null && dim !== 'auto')
  35809. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35810. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35811. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35812. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35813. });
  35814. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35815. };
  35816. /**
  35817. * @inner
  35818. */
  35819. function updateAxisTransform(axis, coordBase) {
  35820. var axisExtent = axis.getExtent();
  35821. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35822. // Fast transform
  35823. axis.toGlobalCoord = axis.dim === 'x'
  35824. ? function (coord) {
  35825. return coord + coordBase;
  35826. }
  35827. : function (coord) {
  35828. return axisExtentSum - coord + coordBase;
  35829. };
  35830. axis.toLocalCoord = axis.dim === 'x'
  35831. ? function (coord) {
  35832. return coord - coordBase;
  35833. }
  35834. : function (coord) {
  35835. return axisExtentSum - coord + coordBase;
  35836. };
  35837. }
  35838. var axesTypes = ['xAxis', 'yAxis'];
  35839. /**
  35840. * @inner
  35841. */
  35842. function findAxesModels(seriesModel, ecModel) {
  35843. return map(axesTypes, function (axisType) {
  35844. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35845. if (__DEV__) {
  35846. if (!axisModel) {
  35847. throw new Error(axisType + ' "' + retrieve(
  35848. seriesModel.get(axisType + 'Index'),
  35849. seriesModel.get(axisType + 'Id'),
  35850. 0
  35851. ) + '" not found');
  35852. }
  35853. }
  35854. return axisModel;
  35855. });
  35856. }
  35857. /**
  35858. * @inner
  35859. */
  35860. function isCartesian2D(seriesModel) {
  35861. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35862. }
  35863. Grid.create = function (ecModel, api) {
  35864. var grids = [];
  35865. ecModel.eachComponent('grid', function (gridModel, idx) {
  35866. var grid = new Grid(gridModel, ecModel, api);
  35867. grid.name = 'grid_' + idx;
  35868. // dataSampling requires axis extent, so resize
  35869. // should be performed in create stage.
  35870. grid.resize(gridModel, api, true);
  35871. gridModel.coordinateSystem = grid;
  35872. grids.push(grid);
  35873. });
  35874. // Inject the coordinateSystems into seriesModel
  35875. ecModel.eachSeries(function (seriesModel) {
  35876. if (!isCartesian2D(seriesModel)) {
  35877. return;
  35878. }
  35879. var axesModels = findAxesModels(seriesModel, ecModel);
  35880. var xAxisModel = axesModels[0];
  35881. var yAxisModel = axesModels[1];
  35882. var gridModel = xAxisModel.getCoordSysModel();
  35883. if (__DEV__) {
  35884. if (!gridModel) {
  35885. throw new Error(
  35886. 'Grid "' + retrieve(
  35887. xAxisModel.get('gridIndex'),
  35888. xAxisModel.get('gridId'),
  35889. 0
  35890. ) + '" not found'
  35891. );
  35892. }
  35893. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  35894. throw new Error('xAxis and yAxis must use the same grid');
  35895. }
  35896. }
  35897. var grid = gridModel.coordinateSystem;
  35898. seriesModel.coordinateSystem = grid.getCartesian(
  35899. xAxisModel.componentIndex, yAxisModel.componentIndex
  35900. );
  35901. });
  35902. return grids;
  35903. };
  35904. // For deciding which dimensions to use when creating list data
  35905. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  35906. CoordinateSystemManager.register('cartesian2d', Grid);
  35907. /*
  35908. * Licensed to the Apache Software Foundation (ASF) under one
  35909. * or more contributor license agreements. See the NOTICE file
  35910. * distributed with this work for additional information
  35911. * regarding copyright ownership. The ASF licenses this file
  35912. * to you under the Apache License, Version 2.0 (the
  35913. * "License"); you may not use this file except in compliance
  35914. * with the License. You may obtain a copy of the License at
  35915. *
  35916. * http://www.apache.org/licenses/LICENSE-2.0
  35917. *
  35918. * Unless required by applicable law or agreed to in writing,
  35919. * software distributed under the License is distributed on an
  35920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35921. * KIND, either express or implied. See the License for the
  35922. * specific language governing permissions and limitations
  35923. * under the License.
  35924. */
  35925. var PI$2 = Math.PI;
  35926. /**
  35927. * A final axis is translated and rotated from a "standard axis".
  35928. * So opt.position and opt.rotation is required.
  35929. *
  35930. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  35931. * for example: (0, 0) ------------> (0, 50)
  35932. *
  35933. * nameDirection or tickDirection or labelDirection is 1 means tick
  35934. * or label is below the standard axis, whereas is -1 means above
  35935. * the standard axis. labelOffset means offset between label and axis,
  35936. * which is useful when 'onZero', where axisLabel is in the grid and
  35937. * label in outside grid.
  35938. *
  35939. * Tips: like always,
  35940. * positive rotation represents anticlockwise, and negative rotation
  35941. * represents clockwise.
  35942. * The direction of position coordinate is the same as the direction
  35943. * of screen coordinate.
  35944. *
  35945. * Do not need to consider axis 'inverse', which is auto processed by
  35946. * axis extent.
  35947. *
  35948. * @param {module:zrender/container/Group} group
  35949. * @param {Object} axisModel
  35950. * @param {Object} opt Standard axis parameters.
  35951. * @param {Array.<number>} opt.position [x, y]
  35952. * @param {number} opt.rotation by radian
  35953. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  35954. * @param {number} [opt.tickDirection=1] 1 or -1
  35955. * @param {number} [opt.labelDirection=1] 1 or -1
  35956. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  35957. * @param {string} [opt.axisLabelShow] default get from axisModel.
  35958. * @param {string} [opt.axisName] default get from axisModel.
  35959. * @param {number} [opt.axisNameAvailableWidth]
  35960. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  35961. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  35962. * @param {number} [opt.nameTruncateMaxWidth]
  35963. */
  35964. var AxisBuilder = function (axisModel, opt) {
  35965. /**
  35966. * @readOnly
  35967. */
  35968. this.opt = opt;
  35969. /**
  35970. * @readOnly
  35971. */
  35972. this.axisModel = axisModel;
  35973. // Default value
  35974. defaults(
  35975. opt,
  35976. {
  35977. labelOffset: 0,
  35978. nameDirection: 1,
  35979. tickDirection: 1,
  35980. labelDirection: 1,
  35981. silent: true
  35982. }
  35983. );
  35984. /**
  35985. * @readOnly
  35986. */
  35987. this.group = new Group();
  35988. // FIXME Not use a seperate text group?
  35989. var dumbGroup = new Group({
  35990. position: opt.position.slice(),
  35991. rotation: opt.rotation
  35992. });
  35993. // this.group.add(dumbGroup);
  35994. // this._dumbGroup = dumbGroup;
  35995. dumbGroup.updateTransform();
  35996. this._transform = dumbGroup.transform;
  35997. this._dumbGroup = dumbGroup;
  35998. };
  35999. AxisBuilder.prototype = {
  36000. constructor: AxisBuilder,
  36001. hasBuilder: function (name) {
  36002. return !!builders[name];
  36003. },
  36004. add: function (name) {
  36005. builders[name].call(this);
  36006. },
  36007. getGroup: function () {
  36008. return this.group;
  36009. }
  36010. };
  36011. var builders = {
  36012. /**
  36013. * @private
  36014. */
  36015. axisLine: function () {
  36016. var opt = this.opt;
  36017. var axisModel = this.axisModel;
  36018. if (!axisModel.get('axisLine.show')) {
  36019. return;
  36020. }
  36021. var extent = this.axisModel.axis.getExtent();
  36022. var matrix = this._transform;
  36023. var pt1 = [extent[0], 0];
  36024. var pt2 = [extent[1], 0];
  36025. if (matrix) {
  36026. applyTransform(pt1, pt1, matrix);
  36027. applyTransform(pt2, pt2, matrix);
  36028. }
  36029. var lineStyle = extend(
  36030. {
  36031. lineCap: 'round'
  36032. },
  36033. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  36034. );
  36035. this.group.add(new Line({
  36036. // Id for animation
  36037. anid: 'line',
  36038. subPixelOptimize: true,
  36039. shape: {
  36040. x1: pt1[0],
  36041. y1: pt1[1],
  36042. x2: pt2[0],
  36043. y2: pt2[1]
  36044. },
  36045. style: lineStyle,
  36046. strokeContainThreshold: opt.strokeContainThreshold || 5,
  36047. silent: true,
  36048. z2: 1
  36049. }));
  36050. var arrows = axisModel.get('axisLine.symbol');
  36051. var arrowSize = axisModel.get('axisLine.symbolSize');
  36052. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  36053. if (typeof arrowOffset === 'number') {
  36054. arrowOffset = [arrowOffset, arrowOffset];
  36055. }
  36056. if (arrows != null) {
  36057. if (typeof arrows === 'string') {
  36058. // Use the same arrow for start and end point
  36059. arrows = [arrows, arrows];
  36060. }
  36061. if (typeof arrowSize === 'string'
  36062. || typeof arrowSize === 'number'
  36063. ) {
  36064. // Use the same size for width and height
  36065. arrowSize = [arrowSize, arrowSize];
  36066. }
  36067. var symbolWidth = arrowSize[0];
  36068. var symbolHeight = arrowSize[1];
  36069. each$1([{
  36070. rotate: opt.rotation + Math.PI / 2,
  36071. offset: arrowOffset[0],
  36072. r: 0
  36073. }, {
  36074. rotate: opt.rotation - Math.PI / 2,
  36075. offset: arrowOffset[1],
  36076. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  36077. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  36078. }], function (point, index) {
  36079. if (arrows[index] !== 'none' && arrows[index] != null) {
  36080. var symbol = createSymbol(
  36081. arrows[index],
  36082. -symbolWidth / 2,
  36083. -symbolHeight / 2,
  36084. symbolWidth,
  36085. symbolHeight,
  36086. lineStyle.stroke,
  36087. true
  36088. );
  36089. // Calculate arrow position with offset
  36090. var r = point.r + point.offset;
  36091. var pos = [
  36092. pt1[0] + r * Math.cos(opt.rotation),
  36093. pt1[1] - r * Math.sin(opt.rotation)
  36094. ];
  36095. symbol.attr({
  36096. rotation: point.rotate,
  36097. position: pos,
  36098. silent: true,
  36099. z2: 11
  36100. });
  36101. this.group.add(symbol);
  36102. }
  36103. }, this);
  36104. }
  36105. },
  36106. /**
  36107. * @private
  36108. */
  36109. axisTickLabel: function () {
  36110. var axisModel = this.axisModel;
  36111. var opt = this.opt;
  36112. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36113. var labelEls = buildAxisLabel(this, axisModel, opt);
  36114. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36115. buildAxisMinorTicks(this, axisModel, opt);
  36116. },
  36117. /**
  36118. * @private
  36119. */
  36120. axisName: function () {
  36121. var opt = this.opt;
  36122. var axisModel = this.axisModel;
  36123. var name = retrieve(opt.axisName, axisModel.get('name'));
  36124. if (!name) {
  36125. return;
  36126. }
  36127. var nameLocation = axisModel.get('nameLocation');
  36128. var nameDirection = opt.nameDirection;
  36129. var textStyleModel = axisModel.getModel('nameTextStyle');
  36130. var gap = axisModel.get('nameGap') || 0;
  36131. var extent = this.axisModel.axis.getExtent();
  36132. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36133. var pos = [
  36134. nameLocation === 'start'
  36135. ? extent[0] - gapSignal * gap
  36136. : nameLocation === 'end'
  36137. ? extent[1] + gapSignal * gap
  36138. : (extent[0] + extent[1]) / 2, // 'middle'
  36139. // Reuse labelOffset.
  36140. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36141. ];
  36142. var labelLayout;
  36143. var nameRotation = axisModel.get('nameRotate');
  36144. if (nameRotation != null) {
  36145. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36146. }
  36147. var axisNameAvailableWidth;
  36148. if (isNameLocationCenter(nameLocation)) {
  36149. labelLayout = innerTextLayout(
  36150. opt.rotation,
  36151. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36152. nameDirection
  36153. );
  36154. }
  36155. else {
  36156. labelLayout = endTextLayout(
  36157. opt, nameLocation, nameRotation || 0, extent
  36158. );
  36159. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36160. if (axisNameAvailableWidth != null) {
  36161. axisNameAvailableWidth = Math.abs(
  36162. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36163. );
  36164. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36165. }
  36166. }
  36167. var textFont = textStyleModel.getFont();
  36168. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36169. var ellipsis = truncateOpt.ellipsis;
  36170. var maxWidth = retrieve(
  36171. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36172. );
  36173. // FIXME
  36174. // truncate rich text? (consider performance)
  36175. var truncatedText = (ellipsis != null && maxWidth != null)
  36176. ? truncateText$1(
  36177. name, maxWidth, textFont, ellipsis,
  36178. {minChar: 2, placeholder: truncateOpt.placeholder}
  36179. )
  36180. : name;
  36181. var tooltipOpt = axisModel.get('tooltip', true);
  36182. var mainType = axisModel.mainType;
  36183. var formatterParams = {
  36184. componentType: mainType,
  36185. name: name,
  36186. $vars: ['name']
  36187. };
  36188. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36189. var textEl = new Text({
  36190. // Id for animation
  36191. anid: 'name',
  36192. __fullText: name,
  36193. __truncatedText: truncatedText,
  36194. position: pos,
  36195. rotation: labelLayout.rotation,
  36196. silent: isLabelSilent(axisModel),
  36197. z2: 1,
  36198. tooltip: (tooltipOpt && tooltipOpt.show)
  36199. ? extend({
  36200. content: name,
  36201. formatter: function () {
  36202. return name;
  36203. },
  36204. formatterParams: formatterParams
  36205. }, tooltipOpt)
  36206. : null
  36207. });
  36208. setTextStyle(textEl.style, textStyleModel, {
  36209. text: truncatedText,
  36210. textFont: textFont,
  36211. textFill: textStyleModel.getTextColor()
  36212. || axisModel.get('axisLine.lineStyle.color'),
  36213. textAlign: textStyleModel.get('align')
  36214. || labelLayout.textAlign,
  36215. textVerticalAlign: textStyleModel.get('verticalAlign')
  36216. || labelLayout.textVerticalAlign
  36217. });
  36218. if (axisModel.get('triggerEvent')) {
  36219. textEl.eventData = makeAxisEventDataBase(axisModel);
  36220. textEl.eventData.targetType = 'axisName';
  36221. textEl.eventData.name = name;
  36222. }
  36223. // FIXME
  36224. this._dumbGroup.add(textEl);
  36225. textEl.updateTransform();
  36226. this.group.add(textEl);
  36227. textEl.decomposeTransform();
  36228. }
  36229. };
  36230. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36231. var eventData = {
  36232. componentType: axisModel.mainType,
  36233. componentIndex: axisModel.componentIndex
  36234. };
  36235. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36236. return eventData;
  36237. };
  36238. /**
  36239. * @public
  36240. * @static
  36241. * @param {Object} opt
  36242. * @param {number} axisRotation in radian
  36243. * @param {number} textRotation in radian
  36244. * @param {number} direction
  36245. * @return {Object} {
  36246. * rotation, // according to axis
  36247. * textAlign,
  36248. * textVerticalAlign
  36249. * }
  36250. */
  36251. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36252. var rotationDiff = remRadian(textRotation - axisRotation);
  36253. var textAlign;
  36254. var textVerticalAlign;
  36255. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36256. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36257. textAlign = 'center';
  36258. }
  36259. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36260. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36261. textAlign = 'center';
  36262. }
  36263. else {
  36264. textVerticalAlign = 'middle';
  36265. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36266. textAlign = direction > 0 ? 'right' : 'left';
  36267. }
  36268. else {
  36269. textAlign = direction > 0 ? 'left' : 'right';
  36270. }
  36271. }
  36272. return {
  36273. rotation: rotationDiff,
  36274. textAlign: textAlign,
  36275. textVerticalAlign: textVerticalAlign
  36276. };
  36277. };
  36278. function endTextLayout(opt, textPosition, textRotate, extent) {
  36279. var rotationDiff = remRadian(textRotate - opt.rotation);
  36280. var textAlign;
  36281. var textVerticalAlign;
  36282. var inverse = extent[0] > extent[1];
  36283. var onLeft = (textPosition === 'start' && !inverse)
  36284. || (textPosition !== 'start' && inverse);
  36285. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36286. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36287. textAlign = 'center';
  36288. }
  36289. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36290. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36291. textAlign = 'center';
  36292. }
  36293. else {
  36294. textVerticalAlign = 'middle';
  36295. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36296. textAlign = onLeft ? 'left' : 'right';
  36297. }
  36298. else {
  36299. textAlign = onLeft ? 'right' : 'left';
  36300. }
  36301. }
  36302. return {
  36303. rotation: rotationDiff,
  36304. textAlign: textAlign,
  36305. textVerticalAlign: textVerticalAlign
  36306. };
  36307. }
  36308. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36309. var tooltipOpt = axisModel.get('tooltip');
  36310. return axisModel.get('silent')
  36311. // Consider mouse cursor, add these restrictions.
  36312. || !(
  36313. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36314. );
  36315. };
  36316. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36317. if (shouldShowAllLabels(axisModel.axis)) {
  36318. return;
  36319. }
  36320. // If min or max are user set, we need to check
  36321. // If the tick on min(max) are overlap on their neighbour tick
  36322. // If they are overlapped, we need to hide the min(max) tick label
  36323. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36324. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36325. // FIXME
  36326. // Have not consider onBand yet, where tick els is more than label els.
  36327. labelEls = labelEls || [];
  36328. tickEls = tickEls || [];
  36329. var firstLabel = labelEls[0];
  36330. var nextLabel = labelEls[1];
  36331. var lastLabel = labelEls[labelEls.length - 1];
  36332. var prevLabel = labelEls[labelEls.length - 2];
  36333. var firstTick = tickEls[0];
  36334. var nextTick = tickEls[1];
  36335. var lastTick = tickEls[tickEls.length - 1];
  36336. var prevTick = tickEls[tickEls.length - 2];
  36337. if (showMinLabel === false) {
  36338. ignoreEl(firstLabel);
  36339. ignoreEl(firstTick);
  36340. }
  36341. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36342. if (showMinLabel) {
  36343. ignoreEl(nextLabel);
  36344. ignoreEl(nextTick);
  36345. }
  36346. else {
  36347. ignoreEl(firstLabel);
  36348. ignoreEl(firstTick);
  36349. }
  36350. }
  36351. if (showMaxLabel === false) {
  36352. ignoreEl(lastLabel);
  36353. ignoreEl(lastTick);
  36354. }
  36355. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36356. if (showMaxLabel) {
  36357. ignoreEl(prevLabel);
  36358. ignoreEl(prevTick);
  36359. }
  36360. else {
  36361. ignoreEl(lastLabel);
  36362. ignoreEl(lastTick);
  36363. }
  36364. }
  36365. }
  36366. function ignoreEl(el) {
  36367. el && (el.ignore = true);
  36368. }
  36369. function isTwoLabelOverlapped(current, next, labelLayout) {
  36370. // current and next has the same rotation.
  36371. var firstRect = current && current.getBoundingRect().clone();
  36372. var nextRect = next && next.getBoundingRect().clone();
  36373. if (!firstRect || !nextRect) {
  36374. return;
  36375. }
  36376. // When checking intersect of two rotated labels, we use mRotationBack
  36377. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36378. var mRotationBack = identity([]);
  36379. rotate(mRotationBack, mRotationBack, -current.rotation);
  36380. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36381. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36382. return firstRect.intersect(nextRect);
  36383. }
  36384. function isNameLocationCenter(nameLocation) {
  36385. return nameLocation === 'middle' || nameLocation === 'center';
  36386. }
  36387. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36388. var tickEls = [];
  36389. var pt1 = [];
  36390. var pt2 = [];
  36391. for (var i = 0; i < ticksCoords.length; i++) {
  36392. var tickCoord = ticksCoords[i].coord;
  36393. pt1[0] = tickCoord;
  36394. pt1[1] = 0;
  36395. pt2[0] = tickCoord;
  36396. pt2[1] = tickEndCoord;
  36397. if (tickTransform) {
  36398. applyTransform(pt1, pt1, tickTransform);
  36399. applyTransform(pt2, pt2, tickTransform);
  36400. }
  36401. // Tick line, Not use group transform to have better line draw
  36402. var tickEl = new Line({
  36403. // Id for animation
  36404. anid: aniid + '_' + ticksCoords[i].tickValue,
  36405. subPixelOptimize: true,
  36406. shape: {
  36407. x1: pt1[0],
  36408. y1: pt1[1],
  36409. x2: pt2[0],
  36410. y2: pt2[1]
  36411. },
  36412. style: tickLineStyle,
  36413. z2: 2,
  36414. silent: true
  36415. });
  36416. tickEls.push(tickEl);
  36417. }
  36418. return tickEls;
  36419. }
  36420. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36421. var axis = axisModel.axis;
  36422. var tickModel = axisModel.getModel('axisTick');
  36423. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36424. return;
  36425. }
  36426. var lineStyleModel = tickModel.getModel('lineStyle');
  36427. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36428. var ticksCoords = axis.getTicksCoords();
  36429. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36430. lineStyleModel.getLineStyle(),
  36431. {
  36432. stroke: axisModel.get('axisLine.lineStyle.color')
  36433. }
  36434. ), 'ticks');
  36435. for (var i = 0; i < ticksEls.length; i++) {
  36436. axisBuilder.group.add(ticksEls[i]);
  36437. }
  36438. return ticksEls;
  36439. }
  36440. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36441. var axis = axisModel.axis;
  36442. var minorTickModel = axisModel.getModel('minorTick');
  36443. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36444. return;
  36445. }
  36446. var minorTicksCoords = axis.getMinorTicksCoords();
  36447. if (!minorTicksCoords.length) {
  36448. return;
  36449. }
  36450. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36451. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36452. var minorTickLineStyle = defaults(
  36453. lineStyleModel.getLineStyle(),
  36454. defaults(
  36455. axisModel.getModel('axisTick').getLineStyle(),
  36456. {
  36457. stroke: axisModel.get('axisLine.lineStyle.color')
  36458. }
  36459. )
  36460. );
  36461. for (var i = 0; i < minorTicksCoords.length; i++) {
  36462. var minorTicksEls = createTicks(
  36463. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36464. );
  36465. for (var k = 0; k < minorTicksEls.length; k++) {
  36466. axisBuilder.group.add(minorTicksEls[k]);
  36467. }
  36468. }
  36469. }
  36470. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36471. var axis = axisModel.axis;
  36472. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36473. if (!show || axis.scale.isBlank()) {
  36474. return;
  36475. }
  36476. var labelModel = axisModel.getModel('axisLabel');
  36477. var labelMargin = labelModel.get('margin');
  36478. var labels = axis.getViewLabels();
  36479. // Special label rotate.
  36480. var labelRotation = (
  36481. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36482. ) * PI$2 / 180;
  36483. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36484. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36485. var labelEls = [];
  36486. var silent = isLabelSilent(axisModel);
  36487. var triggerEvent = axisModel.get('triggerEvent');
  36488. each$1(labels, function (labelItem, index) {
  36489. var tickValue = labelItem.tickValue;
  36490. var formattedLabel = labelItem.formattedLabel;
  36491. var rawLabel = labelItem.rawLabel;
  36492. var itemLabelModel = labelModel;
  36493. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36494. itemLabelModel = new Model(
  36495. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36496. );
  36497. }
  36498. var textColor = itemLabelModel.getTextColor()
  36499. || axisModel.get('axisLine.lineStyle.color');
  36500. var tickCoord = axis.dataToCoord(tickValue);
  36501. var pos = [
  36502. tickCoord,
  36503. opt.labelOffset + opt.labelDirection * labelMargin
  36504. ];
  36505. var textEl = new Text({
  36506. // Id for animation
  36507. anid: 'label_' + tickValue,
  36508. position: pos,
  36509. rotation: labelLayout.rotation,
  36510. silent: silent,
  36511. z2: 10
  36512. });
  36513. setTextStyle(textEl.style, itemLabelModel, {
  36514. text: formattedLabel,
  36515. textAlign: itemLabelModel.getShallow('align', true)
  36516. || labelLayout.textAlign,
  36517. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36518. || itemLabelModel.getShallow('baseline', true)
  36519. || labelLayout.textVerticalAlign,
  36520. textFill: typeof textColor === 'function'
  36521. ? textColor(
  36522. // (1) In category axis with data zoom, tick is not the original
  36523. // index of axis.data. So tick should not be exposed to user
  36524. // in category axis.
  36525. // (2) Compatible with previous version, which always use formatted label as
  36526. // input. But in interval scale the formatted label is like '223,445', which
  36527. // maked user repalce ','. So we modify it to return original val but remain
  36528. // it as 'string' to avoid error in replacing.
  36529. axis.type === 'category'
  36530. ? rawLabel
  36531. : axis.type === 'value'
  36532. ? tickValue + ''
  36533. : tickValue,
  36534. index
  36535. )
  36536. : textColor
  36537. });
  36538. // Pack data for mouse event
  36539. if (triggerEvent) {
  36540. textEl.eventData = makeAxisEventDataBase(axisModel);
  36541. textEl.eventData.targetType = 'axisLabel';
  36542. textEl.eventData.value = rawLabel;
  36543. }
  36544. // FIXME
  36545. axisBuilder._dumbGroup.add(textEl);
  36546. textEl.updateTransform();
  36547. labelEls.push(textEl);
  36548. axisBuilder.group.add(textEl);
  36549. textEl.decomposeTransform();
  36550. });
  36551. return labelEls;
  36552. }
  36553. /*
  36554. * Licensed to the Apache Software Foundation (ASF) under one
  36555. * or more contributor license agreements. See the NOTICE file
  36556. * distributed with this work for additional information
  36557. * regarding copyright ownership. The ASF licenses this file
  36558. * to you under the Apache License, Version 2.0 (the
  36559. * "License"); you may not use this file except in compliance
  36560. * with the License. You may obtain a copy of the License at
  36561. *
  36562. * http://www.apache.org/licenses/LICENSE-2.0
  36563. *
  36564. * Unless required by applicable law or agreed to in writing,
  36565. * software distributed under the License is distributed on an
  36566. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36567. * KIND, either express or implied. See the License for the
  36568. * specific language governing permissions and limitations
  36569. * under the License.
  36570. */
  36571. var each$6 = each$1;
  36572. var curry$1 = curry;
  36573. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36574. // allAxesInfo should be updated when setOption performed.
  36575. function collect(ecModel, api) {
  36576. var result = {
  36577. /**
  36578. * key: makeKey(axis.model)
  36579. * value: {
  36580. * axis,
  36581. * coordSys,
  36582. * axisPointerModel,
  36583. * triggerTooltip,
  36584. * involveSeries,
  36585. * snap,
  36586. * seriesModels,
  36587. * seriesDataCount
  36588. * }
  36589. */
  36590. axesInfo: {},
  36591. seriesInvolved: false,
  36592. /**
  36593. * key: makeKey(coordSys.model)
  36594. * value: Object: key makeKey(axis.model), value: axisInfo
  36595. */
  36596. coordSysAxesInfo: {},
  36597. coordSysMap: {}
  36598. };
  36599. collectAxesInfo(result, ecModel, api);
  36600. // Check seriesInvolved for performance, in case too many series in some chart.
  36601. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36602. return result;
  36603. }
  36604. function collectAxesInfo(result, ecModel, api) {
  36605. var globalTooltipModel = ecModel.getComponent('tooltip');
  36606. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36607. // links can only be set on global.
  36608. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36609. var linkGroups = [];
  36610. // Collect axes info.
  36611. each$6(api.getCoordinateSystems(), function (coordSys) {
  36612. // Some coordinate system do not support axes, like geo.
  36613. if (!coordSys.axisPointerEnabled) {
  36614. return;
  36615. }
  36616. var coordSysKey = makeKey(coordSys.model);
  36617. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36618. result.coordSysMap[coordSysKey] = coordSys;
  36619. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36620. // for user. So we enable seting tooltip on coordSys model.
  36621. var coordSysModel = coordSys.model;
  36622. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36623. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36624. // If axis tooltip used, choose tooltip axis for each coordSys.
  36625. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36626. if (coordSys.getTooltipAxes
  36627. && globalTooltipModel
  36628. // If tooltip.showContent is set as false, tooltip will not
  36629. // show but axisPointer will show as normal.
  36630. && baseTooltipModel.get('show')
  36631. ) {
  36632. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36633. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36634. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36635. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36636. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36637. if (triggerAxis || cross) {
  36638. each$6(tooltipAxes.baseAxes, curry$1(
  36639. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36640. ));
  36641. }
  36642. if (cross) {
  36643. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36644. }
  36645. }
  36646. // fromTooltip: true | false | 'cross'
  36647. // triggerTooltip: true | false | null
  36648. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36649. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36650. var axisPointerShow = axisPointerModel.get('show');
  36651. if (!axisPointerShow || (
  36652. axisPointerShow === 'auto'
  36653. && !fromTooltip
  36654. && !isHandleTrigger(axisPointerModel)
  36655. )) {
  36656. return;
  36657. }
  36658. if (triggerTooltip == null) {
  36659. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36660. }
  36661. axisPointerModel = fromTooltip
  36662. ? makeAxisPointerModel(
  36663. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36664. fromTooltip, triggerTooltip
  36665. )
  36666. : axisPointerModel;
  36667. var snap = axisPointerModel.get('snap');
  36668. var key = makeKey(axis.model);
  36669. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36670. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36671. var axisInfo = result.axesInfo[key] = {
  36672. key: key,
  36673. axis: axis,
  36674. coordSys: coordSys,
  36675. axisPointerModel: axisPointerModel,
  36676. triggerTooltip: triggerTooltip,
  36677. involveSeries: involveSeries,
  36678. snap: snap,
  36679. useHandle: isHandleTrigger(axisPointerModel),
  36680. seriesModels: []
  36681. };
  36682. axesInfoInCoordSys[key] = axisInfo;
  36683. result.seriesInvolved |= involveSeries;
  36684. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36685. if (groupIndex != null) {
  36686. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36687. linkGroup.axesInfo[key] = axisInfo;
  36688. linkGroup.mapper = linksOption[groupIndex].mapper;
  36689. axisInfo.linkGroup = linkGroup;
  36690. }
  36691. }
  36692. });
  36693. }
  36694. function makeAxisPointerModel(
  36695. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36696. ) {
  36697. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36698. var volatileOption = {};
  36699. each$6(
  36700. [
  36701. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36702. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36703. ],
  36704. function (field) {
  36705. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36706. }
  36707. );
  36708. // category axis do not auto snap, otherwise some tick that do not
  36709. // has value can not be hovered. value/time/log axis default snap if
  36710. // triggered from tooltip and trigger tooltip.
  36711. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36712. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36713. // Only these properties can be overrided from tooltip to axisPointer.
  36714. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36715. volatileOption.type = 'line';
  36716. }
  36717. var labelOption = volatileOption.label || (volatileOption.label = {});
  36718. // Follow the convention, do not show label when triggered by tooltip by default.
  36719. labelOption.show == null && (labelOption.show = false);
  36720. if (fromTooltip === 'cross') {
  36721. // When 'cross', both axes show labels.
  36722. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36723. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36724. // If triggerTooltip, this is a base axis, which should better not use cross style
  36725. // (cross style is dashed by default)
  36726. if (!triggerTooltip) {
  36727. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36728. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36729. }
  36730. }
  36731. return axis.model.getModel(
  36732. 'axisPointer',
  36733. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36734. );
  36735. }
  36736. function collectSeriesInfo(result, ecModel) {
  36737. // Prepare data for axis trigger
  36738. ecModel.eachSeries(function (seriesModel) {
  36739. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36740. var coordSys = seriesModel.coordinateSystem;
  36741. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36742. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36743. if (!coordSys
  36744. || seriesTooltipTrigger === 'none'
  36745. || seriesTooltipTrigger === false
  36746. || seriesTooltipTrigger === 'item'
  36747. || seriesTooltipShow === false
  36748. || seriesModel.get('axisPointer.show', true) === false
  36749. ) {
  36750. return;
  36751. }
  36752. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36753. var axis = axisInfo.axis;
  36754. if (coordSys.getAxis(axis.dim) === axis) {
  36755. axisInfo.seriesModels.push(seriesModel);
  36756. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36757. axisInfo.seriesDataCount += seriesModel.getData().count();
  36758. }
  36759. });
  36760. }, this);
  36761. }
  36762. /**
  36763. * For example:
  36764. * {
  36765. * axisPointer: {
  36766. * links: [{
  36767. * xAxisIndex: [2, 4],
  36768. * yAxisIndex: 'all'
  36769. * }, {
  36770. * xAxisId: ['a5', 'a7'],
  36771. * xAxisName: 'xxx'
  36772. * }]
  36773. * }
  36774. * }
  36775. */
  36776. function getLinkGroupIndex(linksOption, axis) {
  36777. var axisModel = axis.model;
  36778. var dim = axis.dim;
  36779. for (var i = 0; i < linksOption.length; i++) {
  36780. var linkOption = linksOption[i] || {};
  36781. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36782. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36783. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36784. ) {
  36785. return i;
  36786. }
  36787. }
  36788. }
  36789. function checkPropInLink(linkPropValue, axisPropValue) {
  36790. return linkPropValue === 'all'
  36791. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36792. || linkPropValue === axisPropValue;
  36793. }
  36794. function fixValue(axisModel) {
  36795. var axisInfo = getAxisInfo(axisModel);
  36796. if (!axisInfo) {
  36797. return;
  36798. }
  36799. var axisPointerModel = axisInfo.axisPointerModel;
  36800. var scale = axisInfo.axis.scale;
  36801. var option = axisPointerModel.option;
  36802. var status = axisPointerModel.get('status');
  36803. var value = axisPointerModel.get('value');
  36804. // Parse init value for category and time axis.
  36805. if (value != null) {
  36806. value = scale.parse(value);
  36807. }
  36808. var useHandle = isHandleTrigger(axisPointerModel);
  36809. // If `handle` used, `axisPointer` will always be displayed, so value
  36810. // and status should be initialized.
  36811. if (status == null) {
  36812. option.status = useHandle ? 'show' : 'hide';
  36813. }
  36814. var extent = scale.getExtent().slice();
  36815. extent[0] > extent[1] && extent.reverse();
  36816. if (// Pick a value on axis when initializing.
  36817. value == null
  36818. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36819. // where we should re-pick a value to keep `handle` displaying normally.
  36820. || value > extent[1]
  36821. ) {
  36822. // Make handle displayed on the end of the axis when init, which looks better.
  36823. value = extent[1];
  36824. }
  36825. if (value < extent[0]) {
  36826. value = extent[0];
  36827. }
  36828. option.value = value;
  36829. if (useHandle) {
  36830. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36831. }
  36832. }
  36833. function getAxisInfo(axisModel) {
  36834. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36835. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36836. }
  36837. function getAxisPointerModel(axisModel) {
  36838. var axisInfo = getAxisInfo(axisModel);
  36839. return axisInfo && axisInfo.axisPointerModel;
  36840. }
  36841. function isHandleTrigger(axisPointerModel) {
  36842. return !!axisPointerModel.get('handle.show');
  36843. }
  36844. /**
  36845. * @param {module:echarts/model/Model} model
  36846. * @return {string} unique key
  36847. */
  36848. function makeKey(model) {
  36849. return model.type + '||' + model.id;
  36850. }
  36851. /*
  36852. * Licensed to the Apache Software Foundation (ASF) under one
  36853. * or more contributor license agreements. See the NOTICE file
  36854. * distributed with this work for additional information
  36855. * regarding copyright ownership. The ASF licenses this file
  36856. * to you under the Apache License, Version 2.0 (the
  36857. * "License"); you may not use this file except in compliance
  36858. * with the License. You may obtain a copy of the License at
  36859. *
  36860. * http://www.apache.org/licenses/LICENSE-2.0
  36861. *
  36862. * Unless required by applicable law or agreed to in writing,
  36863. * software distributed under the License is distributed on an
  36864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36865. * KIND, either express or implied. See the License for the
  36866. * specific language governing permissions and limitations
  36867. * under the License.
  36868. */
  36869. /**
  36870. * Base class of AxisView.
  36871. */
  36872. var AxisView = extendComponentView({
  36873. type: 'axis',
  36874. /**
  36875. * @private
  36876. */
  36877. _axisPointer: null,
  36878. /**
  36879. * @protected
  36880. * @type {string}
  36881. */
  36882. axisPointerClass: null,
  36883. /**
  36884. * @override
  36885. */
  36886. render: function (axisModel, ecModel, api, payload) {
  36887. // FIXME
  36888. // This process should proformed after coordinate systems updated
  36889. // (axis scale updated), and should be performed each time update.
  36890. // So put it here temporarily, although it is not appropriate to
  36891. // put a model-writing procedure in `view`.
  36892. this.axisPointerClass && fixValue(axisModel);
  36893. AxisView.superApply(this, 'render', arguments);
  36894. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  36895. },
  36896. /**
  36897. * Action handler.
  36898. * @public
  36899. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36900. * @param {module:echarts/model/Global} ecModel
  36901. * @param {module:echarts/ExtensionAPI} api
  36902. * @param {Object} payload
  36903. */
  36904. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  36905. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  36906. },
  36907. /**
  36908. * @override
  36909. */
  36910. remove: function (ecModel, api) {
  36911. var axisPointer = this._axisPointer;
  36912. axisPointer && axisPointer.remove(api);
  36913. AxisView.superApply(this, 'remove', arguments);
  36914. },
  36915. /**
  36916. * @override
  36917. */
  36918. dispose: function (ecModel, api) {
  36919. disposeAxisPointer(this, api);
  36920. AxisView.superApply(this, 'dispose', arguments);
  36921. }
  36922. });
  36923. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  36924. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  36925. if (!Clazz) {
  36926. return;
  36927. }
  36928. var axisPointerModel = getAxisPointerModel(axisModel);
  36929. axisPointerModel
  36930. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  36931. .render(axisModel, axisPointerModel, api, forceRender)
  36932. : disposeAxisPointer(axisView, api);
  36933. }
  36934. function disposeAxisPointer(axisView, ecModel, api) {
  36935. var axisPointer = axisView._axisPointer;
  36936. axisPointer && axisPointer.dispose(ecModel, api);
  36937. axisView._axisPointer = null;
  36938. }
  36939. var axisPointerClazz = [];
  36940. AxisView.registerAxisPointerClass = function (type, clazz) {
  36941. if (__DEV__) {
  36942. if (axisPointerClazz[type]) {
  36943. throw new Error('axisPointer ' + type + ' exists');
  36944. }
  36945. }
  36946. axisPointerClazz[type] = clazz;
  36947. };
  36948. AxisView.getAxisPointerClass = function (type) {
  36949. return type && axisPointerClazz[type];
  36950. };
  36951. /*
  36952. * Licensed to the Apache Software Foundation (ASF) under one
  36953. * or more contributor license agreements. See the NOTICE file
  36954. * distributed with this work for additional information
  36955. * regarding copyright ownership. The ASF licenses this file
  36956. * to you under the Apache License, Version 2.0 (the
  36957. * "License"); you may not use this file except in compliance
  36958. * with the License. You may obtain a copy of the License at
  36959. *
  36960. * http://www.apache.org/licenses/LICENSE-2.0
  36961. *
  36962. * Unless required by applicable law or agreed to in writing,
  36963. * software distributed under the License is distributed on an
  36964. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36965. * KIND, either express or implied. See the License for the
  36966. * specific language governing permissions and limitations
  36967. * under the License.
  36968. */
  36969. /**
  36970. * Can only be called after coordinate system creation stage.
  36971. * (Can be called before coordinate system update stage).
  36972. *
  36973. * @param {Object} opt {labelInside}
  36974. * @return {Object} {
  36975. * position, rotation, labelDirection, labelOffset,
  36976. * tickDirection, labelRotate, z2
  36977. * }
  36978. */
  36979. function layout$1(gridModel, axisModel, opt) {
  36980. opt = opt || {};
  36981. var grid = gridModel.coordinateSystem;
  36982. var axis = axisModel.axis;
  36983. var layout = {};
  36984. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  36985. var rawAxisPosition = axis.position;
  36986. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  36987. var axisDim = axis.dim;
  36988. var rect = grid.getRect();
  36989. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  36990. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  36991. var axisOffset = axisModel.get('offset') || 0;
  36992. var posBound = axisDim === 'x'
  36993. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  36994. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  36995. if (otherAxisOnZeroOf) {
  36996. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  36997. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  36998. }
  36999. // Axis position
  37000. layout.position = [
  37001. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  37002. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  37003. ];
  37004. // Axis rotation
  37005. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  37006. // Tick and label direction, x y is axisDim
  37007. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  37008. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  37009. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  37010. if (axisModel.get('axisTick.inside')) {
  37011. layout.tickDirection = -layout.tickDirection;
  37012. }
  37013. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  37014. layout.labelDirection = -layout.labelDirection;
  37015. }
  37016. // Special label rotation
  37017. var labelRotate = axisModel.get('axisLabel.rotate');
  37018. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  37019. // Over splitLine and splitArea
  37020. layout.z2 = 1;
  37021. return layout;
  37022. }
  37023. /*
  37024. * Licensed to the Apache Software Foundation (ASF) under one
  37025. * or more contributor license agreements. See the NOTICE file
  37026. * distributed with this work for additional information
  37027. * regarding copyright ownership. The ASF licenses this file
  37028. * to you under the Apache License, Version 2.0 (the
  37029. * "License"); you may not use this file except in compliance
  37030. * with the License. You may obtain a copy of the License at
  37031. *
  37032. * http://www.apache.org/licenses/LICENSE-2.0
  37033. *
  37034. * Unless required by applicable law or agreed to in writing,
  37035. * software distributed under the License is distributed on an
  37036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37037. * KIND, either express or implied. See the License for the
  37038. * specific language governing permissions and limitations
  37039. * under the License.
  37040. */
  37041. var axisBuilderAttrs = [
  37042. 'axisLine', 'axisTickLabel', 'axisName'
  37043. ];
  37044. var selfBuilderAttrs = [
  37045. 'splitArea', 'splitLine', 'minorSplitLine'
  37046. ];
  37047. var CartesianAxisView = AxisView.extend({
  37048. type: 'cartesianAxis',
  37049. axisPointerClass: 'CartesianAxisPointer',
  37050. /**
  37051. * @override
  37052. */
  37053. render: function (axisModel, ecModel, api, payload) {
  37054. this.group.removeAll();
  37055. var oldAxisGroup = this._axisGroup;
  37056. this._axisGroup = new Group();
  37057. this.group.add(this._axisGroup);
  37058. if (!axisModel.get('show')) {
  37059. return;
  37060. }
  37061. var gridModel = axisModel.getCoordSysModel();
  37062. var layout = layout$1(gridModel, axisModel);
  37063. var axisBuilder = new AxisBuilder(axisModel, layout);
  37064. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  37065. this._axisGroup.add(axisBuilder.getGroup());
  37066. each$1(selfBuilderAttrs, function (name) {
  37067. if (axisModel.get(name + '.show')) {
  37068. this['_' + name](axisModel, gridModel);
  37069. }
  37070. }, this);
  37071. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  37072. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  37073. },
  37074. remove: function () {
  37075. this._splitAreaColors = null;
  37076. },
  37077. /**
  37078. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37079. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37080. * @private
  37081. */
  37082. _splitLine: function (axisModel, gridModel) {
  37083. var axis = axisModel.axis;
  37084. if (axis.scale.isBlank()) {
  37085. return;
  37086. }
  37087. var splitLineModel = axisModel.getModel('splitLine');
  37088. var lineStyleModel = splitLineModel.getModel('lineStyle');
  37089. var lineColors = lineStyleModel.get('color');
  37090. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  37091. var gridRect = gridModel.coordinateSystem.getRect();
  37092. var isHorizontal = axis.isHorizontal();
  37093. var lineCount = 0;
  37094. var ticksCoords = axis.getTicksCoords({
  37095. tickModel: splitLineModel
  37096. });
  37097. var p1 = [];
  37098. var p2 = [];
  37099. var lineStyle = lineStyleModel.getLineStyle();
  37100. for (var i = 0; i < ticksCoords.length; i++) {
  37101. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37102. if (isHorizontal) {
  37103. p1[0] = tickCoord;
  37104. p1[1] = gridRect.y;
  37105. p2[0] = tickCoord;
  37106. p2[1] = gridRect.y + gridRect.height;
  37107. }
  37108. else {
  37109. p1[0] = gridRect.x;
  37110. p1[1] = tickCoord;
  37111. p2[0] = gridRect.x + gridRect.width;
  37112. p2[1] = tickCoord;
  37113. }
  37114. var colorIndex = (lineCount++) % lineColors.length;
  37115. var tickValue = ticksCoords[i].tickValue;
  37116. this._axisGroup.add(new Line({
  37117. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37118. subPixelOptimize: true,
  37119. shape: {
  37120. x1: p1[0],
  37121. y1: p1[1],
  37122. x2: p2[0],
  37123. y2: p2[1]
  37124. },
  37125. style: defaults({
  37126. stroke: lineColors[colorIndex]
  37127. }, lineStyle),
  37128. silent: true
  37129. }));
  37130. }
  37131. },
  37132. /**
  37133. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37134. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37135. * @private
  37136. */
  37137. _minorSplitLine: function (axisModel, gridModel) {
  37138. var axis = axisModel.axis;
  37139. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37140. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37141. var gridRect = gridModel.coordinateSystem.getRect();
  37142. var isHorizontal = axis.isHorizontal();
  37143. var minorTicksCoords = axis.getMinorTicksCoords();
  37144. if (!minorTicksCoords.length) {
  37145. return;
  37146. }
  37147. var p1 = [];
  37148. var p2 = [];
  37149. var lineStyle = lineStyleModel.getLineStyle();
  37150. for (var i = 0; i < minorTicksCoords.length; i++) {
  37151. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37152. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37153. if (isHorizontal) {
  37154. p1[0] = tickCoord;
  37155. p1[1] = gridRect.y;
  37156. p2[0] = tickCoord;
  37157. p2[1] = gridRect.y + gridRect.height;
  37158. }
  37159. else {
  37160. p1[0] = gridRect.x;
  37161. p1[1] = tickCoord;
  37162. p2[0] = gridRect.x + gridRect.width;
  37163. p2[1] = tickCoord;
  37164. }
  37165. this._axisGroup.add(new Line({
  37166. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37167. subPixelOptimize: true,
  37168. shape: {
  37169. x1: p1[0],
  37170. y1: p1[1],
  37171. x2: p2[0],
  37172. y2: p2[1]
  37173. },
  37174. style: lineStyle,
  37175. silent: true
  37176. }));
  37177. }
  37178. }
  37179. },
  37180. /**
  37181. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37182. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37183. * @private
  37184. */
  37185. _splitArea: function (axisModel, gridModel) {
  37186. var axis = axisModel.axis;
  37187. if (axis.scale.isBlank()) {
  37188. return;
  37189. }
  37190. var splitAreaModel = axisModel.getModel('splitArea');
  37191. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37192. var areaColors = areaStyleModel.get('color');
  37193. var gridRect = gridModel.coordinateSystem.getRect();
  37194. var ticksCoords = axis.getTicksCoords({
  37195. tickModel: splitAreaModel,
  37196. clamp: true
  37197. });
  37198. if (!ticksCoords.length) {
  37199. return;
  37200. }
  37201. // For Making appropriate splitArea animation, the color and anid
  37202. // should be corresponding to previous one if possible.
  37203. var areaColorsLen = areaColors.length;
  37204. var lastSplitAreaColors = this._splitAreaColors;
  37205. var newSplitAreaColors = createHashMap();
  37206. var colorIndex = 0;
  37207. if (lastSplitAreaColors) {
  37208. for (var i = 0; i < ticksCoords.length; i++) {
  37209. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37210. if (cIndex != null) {
  37211. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37212. break;
  37213. }
  37214. }
  37215. }
  37216. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37217. var areaStyle = areaStyleModel.getAreaStyle();
  37218. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37219. for (var i = 1; i < ticksCoords.length; i++) {
  37220. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37221. var x;
  37222. var y;
  37223. var width;
  37224. var height;
  37225. if (axis.isHorizontal()) {
  37226. x = prev;
  37227. y = gridRect.y;
  37228. width = tickCoord - x;
  37229. height = gridRect.height;
  37230. prev = x + width;
  37231. }
  37232. else {
  37233. x = gridRect.x;
  37234. y = prev;
  37235. width = gridRect.width;
  37236. height = tickCoord - y;
  37237. prev = y + height;
  37238. }
  37239. var tickValue = ticksCoords[i - 1].tickValue;
  37240. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37241. this._axisGroup.add(new Rect({
  37242. anid: tickValue != null ? 'area_' + tickValue : null,
  37243. shape: {
  37244. x: x,
  37245. y: y,
  37246. width: width,
  37247. height: height
  37248. },
  37249. style: defaults({
  37250. fill: areaColors[colorIndex]
  37251. }, areaStyle),
  37252. silent: true
  37253. }));
  37254. colorIndex = (colorIndex + 1) % areaColorsLen;
  37255. }
  37256. this._splitAreaColors = newSplitAreaColors;
  37257. }
  37258. });
  37259. CartesianAxisView.extend({
  37260. type: 'xAxis'
  37261. });
  37262. CartesianAxisView.extend({
  37263. type: 'yAxis'
  37264. });
  37265. /*
  37266. * Licensed to the Apache Software Foundation (ASF) under one
  37267. * or more contributor license agreements. See the NOTICE file
  37268. * distributed with this work for additional information
  37269. * regarding copyright ownership. The ASF licenses this file
  37270. * to you under the Apache License, Version 2.0 (the
  37271. * "License"); you may not use this file except in compliance
  37272. * with the License. You may obtain a copy of the License at
  37273. *
  37274. * http://www.apache.org/licenses/LICENSE-2.0
  37275. *
  37276. * Unless required by applicable law or agreed to in writing,
  37277. * software distributed under the License is distributed on an
  37278. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37279. * KIND, either express or implied. See the License for the
  37280. * specific language governing permissions and limitations
  37281. * under the License.
  37282. */
  37283. /*
  37284. * Licensed to the Apache Software Foundation (ASF) under one
  37285. * or more contributor license agreements. See the NOTICE file
  37286. * distributed with this work for additional information
  37287. * regarding copyright ownership. The ASF licenses this file
  37288. * to you under the Apache License, Version 2.0 (the
  37289. * "License"); you may not use this file except in compliance
  37290. * with the License. You may obtain a copy of the License at
  37291. *
  37292. * http://www.apache.org/licenses/LICENSE-2.0
  37293. *
  37294. * Unless required by applicable law or agreed to in writing,
  37295. * software distributed under the License is distributed on an
  37296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37297. * KIND, either express or implied. See the License for the
  37298. * specific language governing permissions and limitations
  37299. * under the License.
  37300. */
  37301. // Grid view
  37302. extendComponentView({
  37303. type: 'grid',
  37304. render: function (gridModel, ecModel) {
  37305. this.group.removeAll();
  37306. if (gridModel.get('show')) {
  37307. this.group.add(new Rect({
  37308. shape: gridModel.coordinateSystem.getRect(),
  37309. style: defaults({
  37310. fill: gridModel.get('backgroundColor')
  37311. }, gridModel.getItemStyle()),
  37312. silent: true,
  37313. z2: -1
  37314. }));
  37315. }
  37316. }
  37317. });
  37318. registerPreprocessor(function (option) {
  37319. // Only create grid when need
  37320. if (option.xAxis && option.yAxis && !option.grid) {
  37321. option.grid = {};
  37322. }
  37323. });
  37324. /*
  37325. * Licensed to the Apache Software Foundation (ASF) under one
  37326. * or more contributor license agreements. See the NOTICE file
  37327. * distributed with this work for additional information
  37328. * regarding copyright ownership. The ASF licenses this file
  37329. * to you under the Apache License, Version 2.0 (the
  37330. * "License"); you may not use this file except in compliance
  37331. * with the License. You may obtain a copy of the License at
  37332. *
  37333. * http://www.apache.org/licenses/LICENSE-2.0
  37334. *
  37335. * Unless required by applicable law or agreed to in writing,
  37336. * software distributed under the License is distributed on an
  37337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37338. * KIND, either express or implied. See the License for the
  37339. * specific language governing permissions and limitations
  37340. * under the License.
  37341. */
  37342. // In case developer forget to include grid component
  37343. registerVisual(visualSymbol('line', 'circle', 'line'));
  37344. registerLayout(pointsLayout('line'));
  37345. // Down sample after filter
  37346. registerProcessor(
  37347. PRIORITY.PROCESSOR.STATISTIC,
  37348. dataSample('line')
  37349. );
  37350. /*
  37351. * Licensed to the Apache Software Foundation (ASF) under one
  37352. * or more contributor license agreements. See the NOTICE file
  37353. * distributed with this work for additional information
  37354. * regarding copyright ownership. The ASF licenses this file
  37355. * to you under the Apache License, Version 2.0 (the
  37356. * "License"); you may not use this file except in compliance
  37357. * with the License. You may obtain a copy of the License at
  37358. *
  37359. * http://www.apache.org/licenses/LICENSE-2.0
  37360. *
  37361. * Unless required by applicable law or agreed to in writing,
  37362. * software distributed under the License is distributed on an
  37363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37364. * KIND, either express or implied. See the License for the
  37365. * specific language governing permissions and limitations
  37366. * under the License.
  37367. */
  37368. var BaseBarSeries = SeriesModel.extend({
  37369. type: 'series.__base_bar__',
  37370. getInitialData: function (option, ecModel) {
  37371. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37372. },
  37373. getMarkerPosition: function (value) {
  37374. var coordSys = this.coordinateSystem;
  37375. if (coordSys) {
  37376. // PENDING if clamp ?
  37377. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37378. var data = this.getData();
  37379. var offset = data.getLayout('offset');
  37380. var size = data.getLayout('size');
  37381. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37382. pt[offsetIndex] += offset + size / 2;
  37383. return pt;
  37384. }
  37385. return [NaN, NaN];
  37386. },
  37387. defaultOption: {
  37388. zlevel: 0, // 一级层叠
  37389. z: 2, // 二级层叠
  37390. coordinateSystem: 'cartesian2d',
  37391. legendHoverLink: true,
  37392. // stack: null
  37393. // Cartesian coordinate system
  37394. // xAxisIndex: 0,
  37395. // yAxisIndex: 0,
  37396. // 最小高度改为0
  37397. barMinHeight: 0,
  37398. // 最小角度为0,仅对极坐标系下的柱状图有效
  37399. barMinAngle: 0,
  37400. // cursor: null,
  37401. large: false,
  37402. largeThreshold: 400,
  37403. progressive: 3e3,
  37404. progressiveChunkMode: 'mod',
  37405. // barMaxWidth: null,
  37406. // In cartesian, the default value is 1. Otherwise null.
  37407. // barMinWidth: null,
  37408. // 默认自适应
  37409. // barWidth: null,
  37410. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37411. // barGap: '30%',
  37412. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37413. // barCategoryGap: '20%',
  37414. // label: {
  37415. // show: false
  37416. // },
  37417. itemStyle: {},
  37418. emphasis: {}
  37419. }
  37420. });
  37421. /*
  37422. * Licensed to the Apache Software Foundation (ASF) under one
  37423. * or more contributor license agreements. See the NOTICE file
  37424. * distributed with this work for additional information
  37425. * regarding copyright ownership. The ASF licenses this file
  37426. * to you under the Apache License, Version 2.0 (the
  37427. * "License"); you may not use this file except in compliance
  37428. * with the License. You may obtain a copy of the License at
  37429. *
  37430. * http://www.apache.org/licenses/LICENSE-2.0
  37431. *
  37432. * Unless required by applicable law or agreed to in writing,
  37433. * software distributed under the License is distributed on an
  37434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37435. * KIND, either express or implied. See the License for the
  37436. * specific language governing permissions and limitations
  37437. * under the License.
  37438. */
  37439. BaseBarSeries.extend({
  37440. type: 'series.bar',
  37441. dependencies: ['grid', 'polar'],
  37442. brushSelector: 'rect',
  37443. /**
  37444. * @override
  37445. */
  37446. getProgressive: function () {
  37447. // Do not support progressive in normal mode.
  37448. return this.get('large')
  37449. ? this.get('progressive')
  37450. : false;
  37451. },
  37452. /**
  37453. * @override
  37454. */
  37455. getProgressiveThreshold: function () {
  37456. // Do not support progressive in normal mode.
  37457. var progressiveThreshold = this.get('progressiveThreshold');
  37458. var largeThreshold = this.get('largeThreshold');
  37459. if (largeThreshold > progressiveThreshold) {
  37460. progressiveThreshold = largeThreshold;
  37461. }
  37462. return progressiveThreshold;
  37463. },
  37464. defaultOption: {
  37465. // If clipped
  37466. // Only available on cartesian2d
  37467. clip: true,
  37468. // If use caps on two sides of bars
  37469. // Only available on tangential polar bar
  37470. roundCap: false
  37471. }
  37472. });
  37473. /*
  37474. * Licensed to the Apache Software Foundation (ASF) under one
  37475. * or more contributor license agreements. See the NOTICE file
  37476. * distributed with this work for additional information
  37477. * regarding copyright ownership. The ASF licenses this file
  37478. * to you under the Apache License, Version 2.0 (the
  37479. * "License"); you may not use this file except in compliance
  37480. * with the License. You may obtain a copy of the License at
  37481. *
  37482. * http://www.apache.org/licenses/LICENSE-2.0
  37483. *
  37484. * Unless required by applicable law or agreed to in writing,
  37485. * software distributed under the License is distributed on an
  37486. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37487. * KIND, either express or implied. See the License for the
  37488. * specific language governing permissions and limitations
  37489. * under the License.
  37490. */
  37491. function setLabel(
  37492. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37493. ) {
  37494. var labelModel = itemModel.getModel('label');
  37495. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37496. setLabelStyle(
  37497. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37498. {
  37499. labelFetcher: seriesModel,
  37500. labelDataIndex: dataIndex,
  37501. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37502. isRectText: true,
  37503. autoColor: color
  37504. }
  37505. );
  37506. fixPosition(normalStyle);
  37507. fixPosition(hoverStyle);
  37508. }
  37509. function fixPosition(style, labelPositionOutside) {
  37510. if (style.textPosition === 'outside') {
  37511. style.textPosition = labelPositionOutside;
  37512. }
  37513. }
  37514. /*
  37515. * Licensed to the Apache Software Foundation (ASF) under one
  37516. * or more contributor license agreements. See the NOTICE file
  37517. * distributed with this work for additional information
  37518. * regarding copyright ownership. The ASF licenses this file
  37519. * to you under the Apache License, Version 2.0 (the
  37520. * "License"); you may not use this file except in compliance
  37521. * with the License. You may obtain a copy of the License at
  37522. *
  37523. * http://www.apache.org/licenses/LICENSE-2.0
  37524. *
  37525. * Unless required by applicable law or agreed to in writing,
  37526. * software distributed under the License is distributed on an
  37527. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37528. * KIND, either express or implied. See the License for the
  37529. * specific language governing permissions and limitations
  37530. * under the License.
  37531. */
  37532. var getBarItemStyle = makeStyleMapper(
  37533. [
  37534. ['fill', 'color'],
  37535. ['stroke', 'borderColor'],
  37536. ['lineWidth', 'borderWidth'],
  37537. // Compatitable with 2
  37538. ['stroke', 'barBorderColor'],
  37539. ['lineWidth', 'barBorderWidth'],
  37540. ['opacity'],
  37541. ['shadowBlur'],
  37542. ['shadowOffsetX'],
  37543. ['shadowOffsetY'],
  37544. ['shadowColor']
  37545. ]
  37546. );
  37547. var barItemStyle = {
  37548. getBarItemStyle: function (excludes) {
  37549. var style = getBarItemStyle(this, excludes);
  37550. if (this.getBorderLineDash) {
  37551. var lineDash = this.getBorderLineDash();
  37552. lineDash && (style.lineDash = lineDash);
  37553. }
  37554. return style;
  37555. }
  37556. };
  37557. /*
  37558. * Licensed to the Apache Software Foundation (ASF) under one
  37559. * or more contributor license agreements. See the NOTICE file
  37560. * distributed with this work for additional information
  37561. * regarding copyright ownership. The ASF licenses this file
  37562. * to you under the Apache License, Version 2.0 (the
  37563. * "License"); you may not use this file except in compliance
  37564. * with the License. You may obtain a copy of the License at
  37565. *
  37566. * http://www.apache.org/licenses/LICENSE-2.0
  37567. *
  37568. * Unless required by applicable law or agreed to in writing,
  37569. * software distributed under the License is distributed on an
  37570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37571. * KIND, either express or implied. See the License for the
  37572. * specific language governing permissions and limitations
  37573. * under the License.
  37574. */
  37575. /**
  37576. * Sausage: similar to sector, but have half circle on both sides
  37577. * @public
  37578. */
  37579. var Sausage = extendShape({
  37580. type: 'sausage',
  37581. shape: {
  37582. cx: 0,
  37583. cy: 0,
  37584. r0: 0,
  37585. r: 0,
  37586. startAngle: 0,
  37587. endAngle: Math.PI * 2,
  37588. clockwise: true
  37589. },
  37590. buildPath: function (ctx, shape) {
  37591. var x = shape.cx;
  37592. var y = shape.cy;
  37593. var r0 = Math.max(shape.r0 || 0, 0);
  37594. var r = Math.max(shape.r, 0);
  37595. var dr = (r - r0) * 0.5;
  37596. var rCenter = r0 + dr;
  37597. var startAngle = shape.startAngle;
  37598. var endAngle = shape.endAngle;
  37599. var clockwise = shape.clockwise;
  37600. var unitStartX = Math.cos(startAngle);
  37601. var unitStartY = Math.sin(startAngle);
  37602. var unitEndX = Math.cos(endAngle);
  37603. var unitEndY = Math.sin(endAngle);
  37604. var lessThanCircle = clockwise
  37605. ? endAngle - startAngle < Math.PI * 2
  37606. : startAngle - endAngle < Math.PI * 2;
  37607. if (lessThanCircle) {
  37608. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37609. ctx.arc(
  37610. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37611. -Math.PI + startAngle, startAngle, !clockwise
  37612. );
  37613. }
  37614. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37615. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37616. ctx.arc(
  37617. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37618. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37619. );
  37620. if (r0 !== 0) {
  37621. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37622. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37623. }
  37624. ctx.closePath();
  37625. }
  37626. });
  37627. /*
  37628. * Licensed to the Apache Software Foundation (ASF) under one
  37629. * or more contributor license agreements. See the NOTICE file
  37630. * distributed with this work for additional information
  37631. * regarding copyright ownership. The ASF licenses this file
  37632. * to you under the Apache License, Version 2.0 (the
  37633. * "License"); you may not use this file except in compliance
  37634. * with the License. You may obtain a copy of the License at
  37635. *
  37636. * http://www.apache.org/licenses/LICENSE-2.0
  37637. *
  37638. * Unless required by applicable law or agreed to in writing,
  37639. * software distributed under the License is distributed on an
  37640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37641. * KIND, either express or implied. See the License for the
  37642. * specific language governing permissions and limitations
  37643. * under the License.
  37644. */
  37645. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37646. var _eventPos = [0, 0];
  37647. // FIXME
  37648. // Just for compatible with ec2.
  37649. extend(Model.prototype, barItemStyle);
  37650. function getClipArea(coord, data) {
  37651. var coordSysClipArea = coord.getArea && coord.getArea();
  37652. if (coord.type === 'cartesian2d') {
  37653. var baseAxis = coord.getBaseAxis();
  37654. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37655. // We should not clip this part.
  37656. // See test/bar2.html
  37657. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37658. var expandWidth = data.getLayout('bandWidth');
  37659. if (baseAxis.isHorizontal()) {
  37660. coordSysClipArea.x -= expandWidth;
  37661. coordSysClipArea.width += expandWidth * 2;
  37662. }
  37663. else {
  37664. coordSysClipArea.y -= expandWidth;
  37665. coordSysClipArea.height += expandWidth * 2;
  37666. }
  37667. }
  37668. }
  37669. return coordSysClipArea;
  37670. }
  37671. extendChartView({
  37672. type: 'bar',
  37673. render: function (seriesModel, ecModel, api) {
  37674. this._updateDrawMode(seriesModel);
  37675. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37676. if (coordinateSystemType === 'cartesian2d'
  37677. || coordinateSystemType === 'polar'
  37678. ) {
  37679. this._isLargeDraw
  37680. ? this._renderLarge(seriesModel, ecModel, api)
  37681. : this._renderNormal(seriesModel, ecModel, api);
  37682. }
  37683. else if (__DEV__) {
  37684. console.warn('Only cartesian2d and polar supported for bar.');
  37685. }
  37686. return this.group;
  37687. },
  37688. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37689. this._clear();
  37690. this._updateDrawMode(seriesModel);
  37691. },
  37692. incrementalRender: function (params, seriesModel, ecModel, api) {
  37693. // Do not support progressive in normal mode.
  37694. this._incrementalRenderLarge(params, seriesModel);
  37695. },
  37696. _updateDrawMode: function (seriesModel) {
  37697. var isLargeDraw = seriesModel.pipelineContext.large;
  37698. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37699. this._isLargeDraw = isLargeDraw;
  37700. this._clear();
  37701. }
  37702. },
  37703. _renderNormal: function (seriesModel, ecModel, api) {
  37704. var group = this.group;
  37705. var data = seriesModel.getData();
  37706. var oldData = this._data;
  37707. var coord = seriesModel.coordinateSystem;
  37708. var baseAxis = coord.getBaseAxis();
  37709. var isHorizontalOrRadial;
  37710. if (coord.type === 'cartesian2d') {
  37711. isHorizontalOrRadial = baseAxis.isHorizontal();
  37712. }
  37713. else if (coord.type === 'polar') {
  37714. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37715. }
  37716. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37717. var needsClip = seriesModel.get('clip', true);
  37718. var coordSysClipArea = getClipArea(coord, data);
  37719. // If there is clipPath created in large mode. Remove it.
  37720. group.removeClipPath();
  37721. // We don't use clipPath in normal mode because we needs a perfect animation
  37722. // And don't want the label are clipped.
  37723. var roundCap = seriesModel.get('roundCap', true);
  37724. data.diff(oldData)
  37725. .add(function (dataIndex) {
  37726. if (!data.hasValue(dataIndex)) {
  37727. return;
  37728. }
  37729. var itemModel = data.getItemModel(dataIndex);
  37730. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37731. if (needsClip) {
  37732. // Clip will modify the layout params.
  37733. // And return a boolean to determine if the shape are fully clipped.
  37734. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37735. if (isClipped) {
  37736. group.remove(el);
  37737. return;
  37738. }
  37739. }
  37740. var el = elementCreator[coord.type](
  37741. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37742. );
  37743. data.setItemGraphicEl(dataIndex, el);
  37744. group.add(el);
  37745. updateStyle(
  37746. el, data, dataIndex, itemModel, layout,
  37747. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37748. );
  37749. })
  37750. .update(function (newIndex, oldIndex) {
  37751. var el = oldData.getItemGraphicEl(oldIndex);
  37752. if (!data.hasValue(newIndex)) {
  37753. group.remove(el);
  37754. return;
  37755. }
  37756. var itemModel = data.getItemModel(newIndex);
  37757. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37758. if (needsClip) {
  37759. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37760. if (isClipped) {
  37761. group.remove(el);
  37762. return;
  37763. }
  37764. }
  37765. if (el) {
  37766. updateProps(el, {shape: layout}, animationModel, newIndex);
  37767. }
  37768. else {
  37769. el = elementCreator[coord.type](
  37770. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37771. );
  37772. }
  37773. data.setItemGraphicEl(newIndex, el);
  37774. // Add back
  37775. group.add(el);
  37776. updateStyle(
  37777. el, data, newIndex, itemModel, layout,
  37778. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37779. );
  37780. })
  37781. .remove(function (dataIndex) {
  37782. var el = oldData.getItemGraphicEl(dataIndex);
  37783. if (coord.type === 'cartesian2d') {
  37784. el && removeRect(dataIndex, animationModel, el);
  37785. }
  37786. else {
  37787. el && removeSector(dataIndex, animationModel, el);
  37788. }
  37789. })
  37790. .execute();
  37791. this._data = data;
  37792. },
  37793. _renderLarge: function (seriesModel, ecModel, api) {
  37794. this._clear();
  37795. createLarge(seriesModel, this.group);
  37796. // Use clipPath in large mode.
  37797. var clipPath = seriesModel.get('clip', true)
  37798. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  37799. : null;
  37800. if (clipPath) {
  37801. this.group.setClipPath(clipPath);
  37802. }
  37803. else {
  37804. this.group.removeClipPath();
  37805. }
  37806. },
  37807. _incrementalRenderLarge: function (params, seriesModel) {
  37808. createLarge(seriesModel, this.group, true);
  37809. },
  37810. dispose: noop,
  37811. remove: function (ecModel) {
  37812. this._clear(ecModel);
  37813. },
  37814. _clear: function (ecModel) {
  37815. var group = this.group;
  37816. var data = this._data;
  37817. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  37818. data.eachItemGraphicEl(function (el) {
  37819. if (el.type === 'sector') {
  37820. removeSector(el.dataIndex, ecModel, el);
  37821. }
  37822. else {
  37823. removeRect(el.dataIndex, ecModel, el);
  37824. }
  37825. });
  37826. }
  37827. else {
  37828. group.removeAll();
  37829. }
  37830. this._data = null;
  37831. }
  37832. });
  37833. var mathMax$4 = Math.max;
  37834. var mathMin$4 = Math.min;
  37835. var clip = {
  37836. cartesian2d: function (coordSysBoundingRect, layout) {
  37837. var signWidth = layout.width < 0 ? -1 : 1;
  37838. var signHeight = layout.height < 0 ? -1 : 1;
  37839. // Needs positive width and height
  37840. if (signWidth < 0) {
  37841. layout.x += layout.width;
  37842. layout.width = -layout.width;
  37843. }
  37844. if (signHeight < 0) {
  37845. layout.y += layout.height;
  37846. layout.height = -layout.height;
  37847. }
  37848. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  37849. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  37850. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  37851. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  37852. layout.x = x;
  37853. layout.y = y;
  37854. layout.width = x2 - x;
  37855. layout.height = y2 - y;
  37856. var clipped = layout.width < 0 || layout.height < 0;
  37857. // Reverse back
  37858. if (signWidth < 0) {
  37859. layout.x += layout.width;
  37860. layout.width = -layout.width;
  37861. }
  37862. if (signHeight < 0) {
  37863. layout.y += layout.height;
  37864. layout.height = -layout.height;
  37865. }
  37866. return clipped;
  37867. },
  37868. polar: function (coordSysClipArea) {
  37869. return false;
  37870. }
  37871. };
  37872. var elementCreator = {
  37873. cartesian2d: function (
  37874. dataIndex, layout, isHorizontal,
  37875. animationModel, isUpdate
  37876. ) {
  37877. var rect = new Rect({shape: extend({}, layout)});
  37878. // Animation
  37879. if (animationModel) {
  37880. var rectShape = rect.shape;
  37881. var animateProperty = isHorizontal ? 'height' : 'width';
  37882. var animateTarget = {};
  37883. rectShape[animateProperty] = 0;
  37884. animateTarget[animateProperty] = layout[animateProperty];
  37885. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  37886. shape: animateTarget
  37887. }, animationModel, dataIndex);
  37888. }
  37889. return rect;
  37890. },
  37891. polar: function (
  37892. dataIndex, layout, isRadial,
  37893. animationModel, isUpdate, roundCap
  37894. ) {
  37895. // Keep the same logic with bar in catesion: use end value to control
  37896. // direction. Notice that if clockwise is true (by default), the sector
  37897. // will always draw clockwisely, no matter whether endAngle is greater
  37898. // or less than startAngle.
  37899. var clockwise = layout.startAngle < layout.endAngle;
  37900. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  37901. var sector = new ShapeClass({
  37902. shape: defaults({clockwise: clockwise}, layout)
  37903. });
  37904. // Animation
  37905. if (animationModel) {
  37906. var sectorShape = sector.shape;
  37907. var animateProperty = isRadial ? 'r' : 'endAngle';
  37908. var animateTarget = {};
  37909. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37910. animateTarget[animateProperty] = layout[animateProperty];
  37911. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  37912. shape: animateTarget
  37913. }, animationModel, dataIndex);
  37914. }
  37915. return sector;
  37916. }
  37917. };
  37918. function removeRect(dataIndex, animationModel, el) {
  37919. // Not show text when animating
  37920. el.style.text = null;
  37921. updateProps(el, {
  37922. shape: {
  37923. width: 0
  37924. }
  37925. }, animationModel, dataIndex, function () {
  37926. el.parent && el.parent.remove(el);
  37927. });
  37928. }
  37929. function removeSector(dataIndex, animationModel, el) {
  37930. // Not show text when animating
  37931. el.style.text = null;
  37932. updateProps(el, {
  37933. shape: {
  37934. r: el.shape.r0
  37935. }
  37936. }, animationModel, dataIndex, function () {
  37937. el.parent && el.parent.remove(el);
  37938. });
  37939. }
  37940. var getLayout = {
  37941. cartesian2d: function (data, dataIndex, itemModel) {
  37942. var layout = data.getItemLayout(dataIndex);
  37943. var fixedLineWidth = getLineWidth(itemModel, layout);
  37944. // fix layout with lineWidth
  37945. var signX = layout.width > 0 ? 1 : -1;
  37946. var signY = layout.height > 0 ? 1 : -1;
  37947. return {
  37948. x: layout.x + signX * fixedLineWidth / 2,
  37949. y: layout.y + signY * fixedLineWidth / 2,
  37950. width: layout.width - signX * fixedLineWidth,
  37951. height: layout.height - signY * fixedLineWidth
  37952. };
  37953. },
  37954. polar: function (data, dataIndex, itemModel) {
  37955. var layout = data.getItemLayout(dataIndex);
  37956. return {
  37957. cx: layout.cx,
  37958. cy: layout.cy,
  37959. r0: layout.r0,
  37960. r: layout.r,
  37961. startAngle: layout.startAngle,
  37962. endAngle: layout.endAngle
  37963. };
  37964. }
  37965. };
  37966. function isZeroOnPolar(layout) {
  37967. return layout.startAngle != null
  37968. && layout.endAngle != null
  37969. && layout.startAngle === layout.endAngle;
  37970. }
  37971. function updateStyle(
  37972. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  37973. ) {
  37974. var color = data.getItemVisual(dataIndex, 'color');
  37975. var opacity = data.getItemVisual(dataIndex, 'opacity');
  37976. var stroke = data.getVisual('borderColor');
  37977. var itemStyleModel = itemModel.getModel('itemStyle');
  37978. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  37979. if (!isPolar) {
  37980. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  37981. }
  37982. el.useStyle(defaults(
  37983. {
  37984. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  37985. fill: isZeroOnPolar(layout) ? 'none' : color,
  37986. opacity: opacity
  37987. },
  37988. itemStyleModel.getBarItemStyle()
  37989. ));
  37990. var cursorStyle = itemModel.getShallow('cursor');
  37991. cursorStyle && el.attr('cursor', cursorStyle);
  37992. var labelPositionOutside = isHorizontal
  37993. ? (layout.height > 0 ? 'bottom' : 'top')
  37994. : (layout.width > 0 ? 'left' : 'right');
  37995. if (!isPolar) {
  37996. setLabel(
  37997. el.style, hoverStyle, itemModel, color,
  37998. seriesModel, dataIndex, labelPositionOutside
  37999. );
  38000. }
  38001. if (isZeroOnPolar(layout)) {
  38002. hoverStyle.fill = hoverStyle.stroke = 'none';
  38003. }
  38004. setHoverStyle(el, hoverStyle);
  38005. }
  38006. // In case width or height are too small.
  38007. function getLineWidth(itemModel, rawLayout) {
  38008. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  38009. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  38010. }
  38011. var LargePath = Path.extend({
  38012. type: 'largeBar',
  38013. shape: {points: []},
  38014. buildPath: function (ctx, shape) {
  38015. // Drawing lines is more efficient than drawing
  38016. // a whole line or drawing rects.
  38017. var points = shape.points;
  38018. var startPoint = this.__startPoint;
  38019. var baseDimIdx = this.__baseDimIdx;
  38020. for (var i = 0; i < points.length; i += 2) {
  38021. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38022. ctx.moveTo(startPoint[0], startPoint[1]);
  38023. ctx.lineTo(points[i], points[i + 1]);
  38024. }
  38025. }
  38026. });
  38027. function createLarge(seriesModel, group, incremental) {
  38028. // TODO support polar
  38029. var data = seriesModel.getData();
  38030. var startPoint = [];
  38031. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38032. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  38033. var el = new LargePath({
  38034. shape: {points: data.getLayout('largePoints')},
  38035. incremental: !!incremental,
  38036. __startPoint: startPoint,
  38037. __baseDimIdx: baseDimIdx,
  38038. __largeDataIndices: data.getLayout('largeDataIndices'),
  38039. __barWidth: data.getLayout('barWidth')
  38040. });
  38041. group.add(el);
  38042. setLargeStyle(el, seriesModel, data);
  38043. // Enable tooltip and user mouse/touch event handlers.
  38044. el.seriesIndex = seriesModel.seriesIndex;
  38045. if (!seriesModel.get('silent')) {
  38046. el.on('mousedown', largePathUpdateDataIndex);
  38047. el.on('mousemove', largePathUpdateDataIndex);
  38048. }
  38049. }
  38050. // Use throttle to avoid frequently traverse to find dataIndex.
  38051. var largePathUpdateDataIndex = throttle(function (event) {
  38052. var largePath = this;
  38053. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38054. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  38055. }, 30, false);
  38056. function largePathFindDataIndex(largePath, x, y) {
  38057. var baseDimIdx = largePath.__baseDimIdx;
  38058. var valueDimIdx = 1 - baseDimIdx;
  38059. var points = largePath.shape.points;
  38060. var largeDataIndices = largePath.__largeDataIndices;
  38061. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  38062. var startValueVal = largePath.__startPoint[valueDimIdx];
  38063. _eventPos[0] = x;
  38064. _eventPos[1] = y;
  38065. var pointerBaseVal = _eventPos[baseDimIdx];
  38066. var pointerValueVal = _eventPos[1 - baseDimIdx];
  38067. var baseLowerBound = pointerBaseVal - barWidthHalf;
  38068. var baseUpperBound = pointerBaseVal + barWidthHalf;
  38069. for (var i = 0, len = points.length / 2; i < len; i++) {
  38070. var ii = i * 2;
  38071. var barBaseVal = points[ii + baseDimIdx];
  38072. var barValueVal = points[ii + valueDimIdx];
  38073. if (
  38074. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  38075. && (
  38076. startValueVal <= barValueVal
  38077. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  38078. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  38079. )
  38080. ) {
  38081. return largeDataIndices[i];
  38082. }
  38083. }
  38084. return -1;
  38085. }
  38086. function setLargeStyle(el, seriesModel, data) {
  38087. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  38088. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  38089. el.useStyle(itemStyle);
  38090. el.style.fill = null;
  38091. el.style.stroke = borderColor;
  38092. el.style.lineWidth = data.getLayout('barWidth');
  38093. }
  38094. /*
  38095. * Licensed to the Apache Software Foundation (ASF) under one
  38096. * or more contributor license agreements. See the NOTICE file
  38097. * distributed with this work for additional information
  38098. * regarding copyright ownership. The ASF licenses this file
  38099. * to you under the Apache License, Version 2.0 (the
  38100. * "License"); you may not use this file except in compliance
  38101. * with the License. You may obtain a copy of the License at
  38102. *
  38103. * http://www.apache.org/licenses/LICENSE-2.0
  38104. *
  38105. * Unless required by applicable law or agreed to in writing,
  38106. * software distributed under the License is distributed on an
  38107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38108. * KIND, either express or implied. See the License for the
  38109. * specific language governing permissions and limitations
  38110. * under the License.
  38111. */
  38112. // In case developer forget to include grid component
  38113. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38114. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38115. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38116. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38117. registerVisual({
  38118. seriesType: 'bar',
  38119. reset: function (seriesModel) {
  38120. // Visual coding for legend
  38121. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38122. }
  38123. });
  38124. /*
  38125. * Licensed to the Apache Software Foundation (ASF) under one
  38126. * or more contributor license agreements. See the NOTICE file
  38127. * distributed with this work for additional information
  38128. * regarding copyright ownership. The ASF licenses this file
  38129. * to you under the Apache License, Version 2.0 (the
  38130. * "License"); you may not use this file except in compliance
  38131. * with the License. You may obtain a copy of the License at
  38132. *
  38133. * http://www.apache.org/licenses/LICENSE-2.0
  38134. *
  38135. * Unless required by applicable law or agreed to in writing,
  38136. * software distributed under the License is distributed on an
  38137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38138. * KIND, either express or implied. See the License for the
  38139. * specific language governing permissions and limitations
  38140. * under the License.
  38141. */
  38142. /**
  38143. * [Usage]:
  38144. * (1)
  38145. * createListSimply(seriesModel, ['value']);
  38146. * (2)
  38147. * createListSimply(seriesModel, {
  38148. * coordDimensions: ['value'],
  38149. * dimensionsCount: 5
  38150. * });
  38151. *
  38152. * @param {module:echarts/model/Series} seriesModel
  38153. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38154. * The options in opt, see `echarts/data/helper/createDimensions`
  38155. * @param {Array.<string>} [nameList]
  38156. * @return {module:echarts/data/List}
  38157. */
  38158. var createListSimply = function (seriesModel, opt, nameList) {
  38159. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38160. var source = seriesModel.getSource();
  38161. var dimensionsInfo = createDimensions(source, opt);
  38162. var list = new List(dimensionsInfo, seriesModel);
  38163. list.initData(source, nameList);
  38164. return list;
  38165. };
  38166. /*
  38167. * Licensed to the Apache Software Foundation (ASF) under one
  38168. * or more contributor license agreements. See the NOTICE file
  38169. * distributed with this work for additional information
  38170. * regarding copyright ownership. The ASF licenses this file
  38171. * to you under the Apache License, Version 2.0 (the
  38172. * "License"); you may not use this file except in compliance
  38173. * with the License. You may obtain a copy of the License at
  38174. *
  38175. * http://www.apache.org/licenses/LICENSE-2.0
  38176. *
  38177. * Unless required by applicable law or agreed to in writing,
  38178. * software distributed under the License is distributed on an
  38179. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38180. * KIND, either express or implied. See the License for the
  38181. * specific language governing permissions and limitations
  38182. * under the License.
  38183. */
  38184. /**
  38185. * Data selectable mixin for chart series.
  38186. * To eanble data select, option of series must have `selectedMode`.
  38187. * And each data item will use `selected` to toggle itself selected status
  38188. */
  38189. var selectableMixin = {
  38190. /**
  38191. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38192. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38193. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38194. */
  38195. updateSelectedMap: function (targetList) {
  38196. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38197. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38198. targetMap.set(target.name, target);
  38199. return targetMap;
  38200. }, createHashMap());
  38201. },
  38202. /**
  38203. * Either name or id should be passed as input here.
  38204. * If both of them are defined, id is used.
  38205. *
  38206. * @param {string|undefined} name name of data
  38207. * @param {number|undefined} id dataIndex of data
  38208. */
  38209. // PENGING If selectedMode is null ?
  38210. select: function (name, id) {
  38211. var target = id != null
  38212. ? this._targetList[id]
  38213. : this._selectTargetMap.get(name);
  38214. var selectedMode = this.get('selectedMode');
  38215. if (selectedMode === 'single') {
  38216. this._selectTargetMap.each(function (target) {
  38217. target.selected = false;
  38218. });
  38219. }
  38220. target && (target.selected = true);
  38221. },
  38222. /**
  38223. * Either name or id should be passed as input here.
  38224. * If both of them are defined, id is used.
  38225. *
  38226. * @param {string|undefined} name name of data
  38227. * @param {number|undefined} id dataIndex of data
  38228. */
  38229. unSelect: function (name, id) {
  38230. var target = id != null
  38231. ? this._targetList[id]
  38232. : this._selectTargetMap.get(name);
  38233. // var selectedMode = this.get('selectedMode');
  38234. // selectedMode !== 'single' && target && (target.selected = false);
  38235. target && (target.selected = false);
  38236. },
  38237. /**
  38238. * Either name or id should be passed as input here.
  38239. * If both of them are defined, id is used.
  38240. *
  38241. * @param {string|undefined} name name of data
  38242. * @param {number|undefined} id dataIndex of data
  38243. */
  38244. toggleSelected: function (name, id) {
  38245. var target = id != null
  38246. ? this._targetList[id]
  38247. : this._selectTargetMap.get(name);
  38248. if (target != null) {
  38249. this[target.selected ? 'unSelect' : 'select'](name, id);
  38250. return target.selected;
  38251. }
  38252. },
  38253. /**
  38254. * Either name or id should be passed as input here.
  38255. * If both of them are defined, id is used.
  38256. *
  38257. * @param {string|undefined} name name of data
  38258. * @param {number|undefined} id dataIndex of data
  38259. */
  38260. isSelected: function (name, id) {
  38261. var target = id != null
  38262. ? this._targetList[id]
  38263. : this._selectTargetMap.get(name);
  38264. return target && target.selected;
  38265. }
  38266. };
  38267. /*
  38268. * Licensed to the Apache Software Foundation (ASF) under one
  38269. * or more contributor license agreements. See the NOTICE file
  38270. * distributed with this work for additional information
  38271. * regarding copyright ownership. The ASF licenses this file
  38272. * to you under the Apache License, Version 2.0 (the
  38273. * "License"); you may not use this file except in compliance
  38274. * with the License. You may obtain a copy of the License at
  38275. *
  38276. * http://www.apache.org/licenses/LICENSE-2.0
  38277. *
  38278. * Unless required by applicable law or agreed to in writing,
  38279. * software distributed under the License is distributed on an
  38280. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38281. * KIND, either express or implied. See the License for the
  38282. * specific language governing permissions and limitations
  38283. * under the License.
  38284. */
  38285. /**
  38286. * LegendVisualProvider is an bridge that pick encoded color from data and
  38287. * provide to the legend component.
  38288. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38289. * @param {Function} getRawData Function to get raw data before filtered.
  38290. */
  38291. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38292. this.getAllNames = function () {
  38293. var rawData = getRawData();
  38294. // We find the name from the raw data. In case it's filtered by the legend component.
  38295. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38296. return rawData.mapArray(rawData.getName);
  38297. };
  38298. this.containName = function (name) {
  38299. var rawData = getRawData();
  38300. return rawData.indexOfName(name) >= 0;
  38301. };
  38302. this.indexOfName = function (name) {
  38303. // Only get data when necessary.
  38304. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38305. // Invoking Series#getData immediately will throw an error.
  38306. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38307. return dataWithEncodedVisual.indexOfName(name);
  38308. };
  38309. this.getItemVisual = function (dataIndex, key) {
  38310. // Get encoded visual properties from final filtered data.
  38311. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38312. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38313. };
  38314. }
  38315. /*
  38316. * Licensed to the Apache Software Foundation (ASF) under one
  38317. * or more contributor license agreements. See the NOTICE file
  38318. * distributed with this work for additional information
  38319. * regarding copyright ownership. The ASF licenses this file
  38320. * to you under the Apache License, Version 2.0 (the
  38321. * "License"); you may not use this file except in compliance
  38322. * with the License. You may obtain a copy of the License at
  38323. *
  38324. * http://www.apache.org/licenses/LICENSE-2.0
  38325. *
  38326. * Unless required by applicable law or agreed to in writing,
  38327. * software distributed under the License is distributed on an
  38328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38329. * KIND, either express or implied. See the License for the
  38330. * specific language governing permissions and limitations
  38331. * under the License.
  38332. */
  38333. var PieSeries = extendSeriesModel({
  38334. type: 'series.pie',
  38335. // Overwrite
  38336. init: function (option) {
  38337. PieSeries.superApply(this, 'init', arguments);
  38338. // Enable legend selection for each data item
  38339. // Use a function instead of direct access because data reference may changed
  38340. this.legendVisualProvider = new LegendVisualProvider(
  38341. bind(this.getData, this), bind(this.getRawData, this)
  38342. );
  38343. this.updateSelectedMap(this._createSelectableList());
  38344. this._defaultLabelLine(option);
  38345. },
  38346. // Overwrite
  38347. mergeOption: function (newOption) {
  38348. PieSeries.superCall(this, 'mergeOption', newOption);
  38349. this.updateSelectedMap(this._createSelectableList());
  38350. },
  38351. getInitialData: function (option, ecModel) {
  38352. return createListSimply(this, {
  38353. coordDimensions: ['value'],
  38354. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38355. });
  38356. },
  38357. _createSelectableList: function () {
  38358. var data = this.getRawData();
  38359. var valueDim = data.mapDimension('value');
  38360. var targetList = [];
  38361. for (var i = 0, len = data.count(); i < len; i++) {
  38362. targetList.push({
  38363. name: data.getName(i),
  38364. value: data.get(valueDim, i),
  38365. selected: retrieveRawAttr(data, i, 'selected')
  38366. });
  38367. }
  38368. return targetList;
  38369. },
  38370. // Overwrite
  38371. getDataParams: function (dataIndex) {
  38372. var data = this.getData();
  38373. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38374. // FIXME toFixed?
  38375. var valueList = [];
  38376. data.each(data.mapDimension('value'), function (value) {
  38377. valueList.push(value);
  38378. });
  38379. params.percent = getPercentWithPrecision(
  38380. valueList,
  38381. dataIndex,
  38382. data.hostModel.get('percentPrecision')
  38383. );
  38384. params.$vars.push('percent');
  38385. return params;
  38386. },
  38387. _defaultLabelLine: function (option) {
  38388. // Extend labelLine emphasis
  38389. defaultEmphasis(option, 'labelLine', ['show']);
  38390. var labelLineNormalOpt = option.labelLine;
  38391. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38392. // Not show label line if `label.normal.show = false`
  38393. labelLineNormalOpt.show = labelLineNormalOpt.show
  38394. && option.label.show;
  38395. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38396. && option.emphasis.label.show;
  38397. },
  38398. defaultOption: {
  38399. zlevel: 0,
  38400. z: 2,
  38401. legendHoverLink: true,
  38402. hoverAnimation: true,
  38403. // 默认全局居中
  38404. center: ['50%', '50%'],
  38405. radius: [0, '75%'],
  38406. // 默认顺时针
  38407. clockwise: true,
  38408. startAngle: 90,
  38409. // 最小角度改为0
  38410. minAngle: 0,
  38411. // If the angle of a sector less than `minShowLabelAngle`,
  38412. // the label will not be displayed.
  38413. minShowLabelAngle: 0,
  38414. // 选中时扇区偏移量
  38415. selectedOffset: 10,
  38416. // 高亮扇区偏移量
  38417. hoverOffset: 10,
  38418. // If use strategy to avoid label overlapping
  38419. avoidLabelOverlap: true,
  38420. // 选择模式,默认关闭,可选single,multiple
  38421. // selectedMode: false,
  38422. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38423. // roseType: null,
  38424. percentPrecision: 2,
  38425. // If still show when all data zero.
  38426. stillShowZeroSum: true,
  38427. // cursor: null,
  38428. left: 0,
  38429. top: 0,
  38430. right: 0,
  38431. bottom: 0,
  38432. width: null,
  38433. height: null,
  38434. label: {
  38435. // If rotate around circle
  38436. rotate: false,
  38437. show: true,
  38438. // 'outer', 'inside', 'center'
  38439. position: 'outer',
  38440. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38441. alignTo: 'none',
  38442. // Closest distance between label and chart edge.
  38443. // Works only position is 'outer' and alignTo is 'edge'.
  38444. margin: '25%',
  38445. // Works only position is 'outer' and alignTo is not 'edge'.
  38446. bleedMargin: 10,
  38447. // Distance between text and label line.
  38448. distanceToLabelLine: 5
  38449. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38450. // 默认使用全局文本样式,详见TEXTSTYLE
  38451. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38452. },
  38453. // Enabled when label.normal.position is 'outer'
  38454. labelLine: {
  38455. show: true,
  38456. // 引导线两段中的第一段长度
  38457. length: 15,
  38458. // 引导线两段中的第二段长度
  38459. length2: 15,
  38460. smooth: false,
  38461. lineStyle: {
  38462. // color: 各异,
  38463. width: 1,
  38464. type: 'solid'
  38465. }
  38466. },
  38467. itemStyle: {
  38468. borderWidth: 1
  38469. },
  38470. // Animation type. Valid values: expansion, scale
  38471. animationType: 'expansion',
  38472. // Animation type when update. Valid values: transition, expansion
  38473. animationTypeUpdate: 'transition',
  38474. animationEasing: 'cubicOut'
  38475. }
  38476. });
  38477. mixin(PieSeries, selectableMixin);
  38478. /*
  38479. * Licensed to the Apache Software Foundation (ASF) under one
  38480. * or more contributor license agreements. See the NOTICE file
  38481. * distributed with this work for additional information
  38482. * regarding copyright ownership. The ASF licenses this file
  38483. * to you under the Apache License, Version 2.0 (the
  38484. * "License"); you may not use this file except in compliance
  38485. * with the License. You may obtain a copy of the License at
  38486. *
  38487. * http://www.apache.org/licenses/LICENSE-2.0
  38488. *
  38489. * Unless required by applicable law or agreed to in writing,
  38490. * software distributed under the License is distributed on an
  38491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38492. * KIND, either express or implied. See the License for the
  38493. * specific language governing permissions and limitations
  38494. * under the License.
  38495. */
  38496. /**
  38497. * @param {module:echarts/model/Series} seriesModel
  38498. * @param {boolean} hasAnimation
  38499. * @inner
  38500. */
  38501. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38502. var data = seriesModel.getData();
  38503. var dataIndex = this.dataIndex;
  38504. var name = data.getName(dataIndex);
  38505. var selectedOffset = seriesModel.get('selectedOffset');
  38506. api.dispatchAction({
  38507. type: 'pieToggleSelect',
  38508. from: uid,
  38509. name: name,
  38510. seriesId: seriesModel.id
  38511. });
  38512. data.each(function (idx) {
  38513. toggleItemSelected(
  38514. data.getItemGraphicEl(idx),
  38515. data.getItemLayout(idx),
  38516. seriesModel.isSelected(data.getName(idx)),
  38517. selectedOffset,
  38518. hasAnimation
  38519. );
  38520. });
  38521. }
  38522. /**
  38523. * @param {module:zrender/graphic/Sector} el
  38524. * @param {Object} layout
  38525. * @param {boolean} isSelected
  38526. * @param {number} selectedOffset
  38527. * @param {boolean} hasAnimation
  38528. * @inner
  38529. */
  38530. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38531. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38532. var dx = Math.cos(midAngle);
  38533. var dy = Math.sin(midAngle);
  38534. var offset = isSelected ? selectedOffset : 0;
  38535. var position = [dx * offset, dy * offset];
  38536. hasAnimation
  38537. // animateTo will stop revious animation like update transition
  38538. ? el.animate()
  38539. .when(200, {
  38540. position: position
  38541. })
  38542. .start('bounceOut')
  38543. : el.attr('position', position);
  38544. }
  38545. /**
  38546. * Piece of pie including Sector, Label, LabelLine
  38547. * @constructor
  38548. * @extends {module:zrender/graphic/Group}
  38549. */
  38550. function PiePiece(data, idx) {
  38551. Group.call(this);
  38552. var sector = new Sector({
  38553. z2: 2
  38554. });
  38555. var polyline = new Polyline();
  38556. var text = new Text();
  38557. this.add(sector);
  38558. this.add(polyline);
  38559. this.add(text);
  38560. this.updateData(data, idx, true);
  38561. }
  38562. var piePieceProto = PiePiece.prototype;
  38563. piePieceProto.updateData = function (data, idx, firstCreate) {
  38564. var sector = this.childAt(0);
  38565. var labelLine = this.childAt(1);
  38566. var labelText = this.childAt(2);
  38567. var seriesModel = data.hostModel;
  38568. var itemModel = data.getItemModel(idx);
  38569. var layout = data.getItemLayout(idx);
  38570. var sectorShape = extend({}, layout);
  38571. sectorShape.label = null;
  38572. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38573. if (firstCreate) {
  38574. sector.setShape(sectorShape);
  38575. var animationType = seriesModel.getShallow('animationType');
  38576. if (animationType === 'scale') {
  38577. sector.shape.r = layout.r0;
  38578. initProps(sector, {
  38579. shape: {
  38580. r: layout.r
  38581. }
  38582. }, seriesModel, idx);
  38583. }
  38584. // Expansion
  38585. else {
  38586. sector.shape.endAngle = layout.startAngle;
  38587. updateProps(sector, {
  38588. shape: {
  38589. endAngle: layout.endAngle
  38590. }
  38591. }, seriesModel, idx);
  38592. }
  38593. }
  38594. else {
  38595. if (animationTypeUpdate === 'expansion') {
  38596. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38597. sector.setShape(sectorShape);
  38598. }
  38599. else {
  38600. // Transition animation from the old shape
  38601. updateProps(sector, {
  38602. shape: sectorShape
  38603. }, seriesModel, idx);
  38604. }
  38605. }
  38606. // Update common style
  38607. var visualColor = data.getItemVisual(idx, 'color');
  38608. sector.useStyle(
  38609. defaults(
  38610. {
  38611. lineJoin: 'bevel',
  38612. fill: visualColor
  38613. },
  38614. itemModel.getModel('itemStyle').getItemStyle()
  38615. )
  38616. );
  38617. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38618. var cursorStyle = itemModel.getShallow('cursor');
  38619. cursorStyle && sector.attr('cursor', cursorStyle);
  38620. // Toggle selected
  38621. toggleItemSelected(
  38622. this,
  38623. data.getItemLayout(idx),
  38624. seriesModel.isSelected(null, idx),
  38625. seriesModel.get('selectedOffset'),
  38626. seriesModel.get('animation')
  38627. );
  38628. // Label and text animation should be applied only for transition type animation when update
  38629. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38630. this._updateLabel(data, idx, withAnimation);
  38631. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  38632. ? function (fromState, toState) {
  38633. if (toState === 'emphasis') {
  38634. labelLine.ignore = labelLine.hoverIgnore;
  38635. labelText.ignore = labelText.hoverIgnore;
  38636. // Sector may has animation of updating data. Force to move to the last frame
  38637. // Or it may stopped on the wrong shape
  38638. sector.stopAnimation(true);
  38639. sector.animateTo({
  38640. shape: {
  38641. r: layout.r + seriesModel.get('hoverOffset')
  38642. }
  38643. }, 300, 'elasticOut');
  38644. }
  38645. else {
  38646. labelLine.ignore = labelLine.normalIgnore;
  38647. labelText.ignore = labelText.normalIgnore;
  38648. sector.stopAnimation(true);
  38649. sector.animateTo({
  38650. shape: {
  38651. r: layout.r
  38652. }
  38653. }, 300, 'elasticOut');
  38654. }
  38655. }
  38656. : null;
  38657. setHoverStyle(this);
  38658. };
  38659. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38660. var labelLine = this.childAt(1);
  38661. var labelText = this.childAt(2);
  38662. var seriesModel = data.hostModel;
  38663. var itemModel = data.getItemModel(idx);
  38664. var layout = data.getItemLayout(idx);
  38665. var labelLayout = layout.label;
  38666. var visualColor = data.getItemVisual(idx, 'color');
  38667. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38668. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38669. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38670. return;
  38671. }
  38672. var targetLineShape = {
  38673. points: labelLayout.linePoints || [
  38674. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38675. ]
  38676. };
  38677. var targetTextStyle = {
  38678. x: labelLayout.x,
  38679. y: labelLayout.y
  38680. };
  38681. if (withAnimation) {
  38682. updateProps(labelLine, {
  38683. shape: targetLineShape
  38684. }, seriesModel, idx);
  38685. updateProps(labelText, {
  38686. style: targetTextStyle
  38687. }, seriesModel, idx);
  38688. }
  38689. else {
  38690. labelLine.attr({
  38691. shape: targetLineShape
  38692. });
  38693. labelText.attr({
  38694. style: targetTextStyle
  38695. });
  38696. }
  38697. labelText.attr({
  38698. rotation: labelLayout.rotation,
  38699. origin: [labelLayout.x, labelLayout.y],
  38700. z2: 10
  38701. });
  38702. var labelModel = itemModel.getModel('label');
  38703. var labelHoverModel = itemModel.getModel('emphasis.label');
  38704. var labelLineModel = itemModel.getModel('labelLine');
  38705. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  38706. var visualColor = data.getItemVisual(idx, 'color');
  38707. setLabelStyle(
  38708. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38709. {
  38710. labelFetcher: data.hostModel,
  38711. labelDataIndex: idx,
  38712. defaultText: labelLayout.text,
  38713. autoColor: visualColor,
  38714. useInsideStyle: !!labelLayout.inside
  38715. },
  38716. {
  38717. textAlign: labelLayout.textAlign,
  38718. textVerticalAlign: labelLayout.verticalAlign,
  38719. opacity: data.getItemVisual(idx, 'opacity')
  38720. }
  38721. );
  38722. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38723. labelText.hoverIgnore = !labelHoverModel.get('show');
  38724. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38725. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38726. // Default use item visual color
  38727. labelLine.setStyle({
  38728. stroke: visualColor,
  38729. opacity: data.getItemVisual(idx, 'opacity')
  38730. });
  38731. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38732. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38733. var smooth = labelLineModel.get('smooth');
  38734. if (smooth && smooth === true) {
  38735. smooth = 0.4;
  38736. }
  38737. labelLine.setShape({
  38738. smooth: smooth
  38739. });
  38740. };
  38741. inherits(PiePiece, Group);
  38742. // Pie view
  38743. var PieView = Chart.extend({
  38744. type: 'pie',
  38745. init: function () {
  38746. var sectorGroup = new Group();
  38747. this._sectorGroup = sectorGroup;
  38748. },
  38749. render: function (seriesModel, ecModel, api, payload) {
  38750. if (payload && (payload.from === this.uid)) {
  38751. return;
  38752. }
  38753. var data = seriesModel.getData();
  38754. var oldData = this._data;
  38755. var group = this.group;
  38756. var hasAnimation = ecModel.get('animation');
  38757. var isFirstRender = !oldData;
  38758. var animationType = seriesModel.get('animationType');
  38759. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  38760. var onSectorClick = curry(
  38761. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  38762. );
  38763. var selectedMode = seriesModel.get('selectedMode');
  38764. data.diff(oldData)
  38765. .add(function (idx) {
  38766. var piePiece = new PiePiece(data, idx);
  38767. // Default expansion animation
  38768. if (isFirstRender && animationType !== 'scale') {
  38769. piePiece.eachChild(function (child) {
  38770. child.stopAnimation(true);
  38771. });
  38772. }
  38773. selectedMode && piePiece.on('click', onSectorClick);
  38774. data.setItemGraphicEl(idx, piePiece);
  38775. group.add(piePiece);
  38776. })
  38777. .update(function (newIdx, oldIdx) {
  38778. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38779. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  38780. piePiece.eachChild(function (child) {
  38781. child.stopAnimation(true);
  38782. });
  38783. }
  38784. piePiece.updateData(data, newIdx);
  38785. piePiece.off('click');
  38786. selectedMode && piePiece.on('click', onSectorClick);
  38787. group.add(piePiece);
  38788. data.setItemGraphicEl(newIdx, piePiece);
  38789. })
  38790. .remove(function (idx) {
  38791. var piePiece = oldData.getItemGraphicEl(idx);
  38792. group.remove(piePiece);
  38793. })
  38794. .execute();
  38795. if (
  38796. hasAnimation && data.count() > 0
  38797. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  38798. ) {
  38799. var shape = data.getItemLayout(0);
  38800. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  38801. shape = data.getItemLayout(s);
  38802. }
  38803. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  38804. var removeClipPath = bind(group.removeClipPath, group);
  38805. group.setClipPath(this._createClipPath(
  38806. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  38807. ));
  38808. }
  38809. else {
  38810. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  38811. group.removeClipPath();
  38812. }
  38813. this._data = data;
  38814. },
  38815. dispose: function () {},
  38816. _createClipPath: function (
  38817. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  38818. ) {
  38819. var clipPath = new Sector({
  38820. shape: {
  38821. cx: cx,
  38822. cy: cy,
  38823. r0: 0,
  38824. r: r,
  38825. startAngle: startAngle,
  38826. endAngle: startAngle,
  38827. clockwise: clockwise
  38828. }
  38829. });
  38830. var initOrUpdate = isFirstRender ? initProps : updateProps;
  38831. initOrUpdate(clipPath, {
  38832. shape: {
  38833. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  38834. }
  38835. }, seriesModel, cb);
  38836. return clipPath;
  38837. },
  38838. /**
  38839. * @implement
  38840. */
  38841. containPoint: function (point, seriesModel) {
  38842. var data = seriesModel.getData();
  38843. var itemLayout = data.getItemLayout(0);
  38844. if (itemLayout) {
  38845. var dx = point[0] - itemLayout.cx;
  38846. var dy = point[1] - itemLayout.cy;
  38847. var radius = Math.sqrt(dx * dx + dy * dy);
  38848. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38849. }
  38850. }
  38851. });
  38852. /*
  38853. * Licensed to the Apache Software Foundation (ASF) under one
  38854. * or more contributor license agreements. See the NOTICE file
  38855. * distributed with this work for additional information
  38856. * regarding copyright ownership. The ASF licenses this file
  38857. * to you under the Apache License, Version 2.0 (the
  38858. * "License"); you may not use this file except in compliance
  38859. * with the License. You may obtain a copy of the License at
  38860. *
  38861. * http://www.apache.org/licenses/LICENSE-2.0
  38862. *
  38863. * Unless required by applicable law or agreed to in writing,
  38864. * software distributed under the License is distributed on an
  38865. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38866. * KIND, either express or implied. See the License for the
  38867. * specific language governing permissions and limitations
  38868. * under the License.
  38869. */
  38870. var createDataSelectAction = function (seriesType, actionInfos) {
  38871. each$1(actionInfos, function (actionInfo) {
  38872. actionInfo.update = 'updateView';
  38873. /**
  38874. * @payload
  38875. * @property {string} seriesName
  38876. * @property {string} name
  38877. */
  38878. registerAction(actionInfo, function (payload, ecModel) {
  38879. var selected = {};
  38880. ecModel.eachComponent(
  38881. {mainType: 'series', subType: seriesType, query: payload},
  38882. function (seriesModel) {
  38883. if (seriesModel[actionInfo.method]) {
  38884. seriesModel[actionInfo.method](
  38885. payload.name,
  38886. payload.dataIndex
  38887. );
  38888. }
  38889. var data = seriesModel.getData();
  38890. // Create selected map
  38891. data.each(function (idx) {
  38892. var name = data.getName(idx);
  38893. selected[name] = seriesModel.isSelected(name)
  38894. || false;
  38895. });
  38896. }
  38897. );
  38898. return {
  38899. name: payload.name,
  38900. selected: selected,
  38901. seriesId: payload.seriesId
  38902. };
  38903. });
  38904. });
  38905. };
  38906. /*
  38907. * Licensed to the Apache Software Foundation (ASF) under one
  38908. * or more contributor license agreements. See the NOTICE file
  38909. * distributed with this work for additional information
  38910. * regarding copyright ownership. The ASF licenses this file
  38911. * to you under the Apache License, Version 2.0 (the
  38912. * "License"); you may not use this file except in compliance
  38913. * with the License. You may obtain a copy of the License at
  38914. *
  38915. * http://www.apache.org/licenses/LICENSE-2.0
  38916. *
  38917. * Unless required by applicable law or agreed to in writing,
  38918. * software distributed under the License is distributed on an
  38919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38920. * KIND, either express or implied. See the License for the
  38921. * specific language governing permissions and limitations
  38922. * under the License.
  38923. */
  38924. // Pick color from palette for each data item.
  38925. // Applicable for charts that require applying color palette
  38926. // in data level (like pie, funnel, chord).
  38927. var dataColor = function (seriesType) {
  38928. return {
  38929. getTargetSeries: function (ecModel) {
  38930. // Pie and funnel may use diferrent scope
  38931. var paletteScope = {};
  38932. var seiresModelMap = createHashMap();
  38933. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38934. seriesModel.__paletteScope = paletteScope;
  38935. seiresModelMap.set(seriesModel.uid, seriesModel);
  38936. });
  38937. return seiresModelMap;
  38938. },
  38939. reset: function (seriesModel, ecModel) {
  38940. var dataAll = seriesModel.getRawData();
  38941. var idxMap = {};
  38942. var data = seriesModel.getData();
  38943. data.each(function (idx) {
  38944. var rawIdx = data.getRawIndex(idx);
  38945. idxMap[rawIdx] = idx;
  38946. });
  38947. dataAll.each(function (rawIdx) {
  38948. var filteredIdx = idxMap[rawIdx];
  38949. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  38950. var singleDataColor = filteredIdx != null
  38951. && data.getItemVisual(filteredIdx, 'color', true);
  38952. var singleDataBorderColor = filteredIdx != null
  38953. && data.getItemVisual(filteredIdx, 'borderColor', true);
  38954. var itemModel;
  38955. if (!singleDataColor || !singleDataBorderColor) {
  38956. // FIXME Performance
  38957. itemModel = dataAll.getItemModel(rawIdx);
  38958. }
  38959. if (!singleDataColor) {
  38960. var color = itemModel.get('itemStyle.color')
  38961. || seriesModel.getColorFromPalette(
  38962. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  38963. dataAll.count()
  38964. );
  38965. // Data is not filtered
  38966. if (filteredIdx != null) {
  38967. data.setItemVisual(filteredIdx, 'color', color);
  38968. }
  38969. }
  38970. if (!singleDataBorderColor) {
  38971. var borderColor = itemModel.get('itemStyle.borderColor');
  38972. // Data is not filtered
  38973. if (filteredIdx != null) {
  38974. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  38975. }
  38976. }
  38977. });
  38978. }
  38979. };
  38980. };
  38981. /*
  38982. * Licensed to the Apache Software Foundation (ASF) under one
  38983. * or more contributor license agreements. See the NOTICE file
  38984. * distributed with this work for additional information
  38985. * regarding copyright ownership. The ASF licenses this file
  38986. * to you under the Apache License, Version 2.0 (the
  38987. * "License"); you may not use this file except in compliance
  38988. * with the License. You may obtain a copy of the License at
  38989. *
  38990. * http://www.apache.org/licenses/LICENSE-2.0
  38991. *
  38992. * Unless required by applicable law or agreed to in writing,
  38993. * software distributed under the License is distributed on an
  38994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38995. * KIND, either express or implied. See the License for the
  38996. * specific language governing permissions and limitations
  38997. * under the License.
  38998. */
  38999. // FIXME emphasis label position is not same with normal label position
  39000. var RADIAN$1 = Math.PI / 180;
  39001. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  39002. list.sort(function (a, b) {
  39003. return a.y - b.y;
  39004. });
  39005. function shiftDown(start, end, delta, dir) {
  39006. for (var j = start; j < end; j++) {
  39007. if (list[j].y + delta > viewTop + viewHeight) {
  39008. break;
  39009. }
  39010. list[j].y += delta;
  39011. if (j > start
  39012. && j + 1 < end
  39013. && list[j + 1].y > list[j].y + list[j].height
  39014. ) {
  39015. shiftUp(j, delta / 2);
  39016. return;
  39017. }
  39018. }
  39019. shiftUp(end - 1, delta / 2);
  39020. }
  39021. function shiftUp(end, delta) {
  39022. for (var j = end; j >= 0; j--) {
  39023. if (list[j].y - delta < viewTop) {
  39024. break;
  39025. }
  39026. list[j].y -= delta;
  39027. if (j > 0
  39028. && list[j].y > list[j - 1].y + list[j - 1].height
  39029. ) {
  39030. break;
  39031. }
  39032. }
  39033. }
  39034. function changeX(list, isDownList, cx, cy, r, dir) {
  39035. var lastDeltaX = dir > 0
  39036. ? isDownList // right-side
  39037. ? Number.MAX_VALUE // down
  39038. : 0 // up
  39039. : isDownList // left-side
  39040. ? Number.MAX_VALUE // down
  39041. : 0; // up
  39042. for (var i = 0, l = list.length; i < l; i++) {
  39043. if (list[i].labelAlignTo !== 'none') {
  39044. continue;
  39045. }
  39046. var deltaY = Math.abs(list[i].y - cy);
  39047. var length = list[i].len;
  39048. var length2 = list[i].len2;
  39049. var deltaX = (deltaY < r + length)
  39050. ? Math.sqrt(
  39051. (r + length + length2) * (r + length + length2)
  39052. - deltaY * deltaY
  39053. )
  39054. : Math.abs(list[i].x - cx);
  39055. if (isDownList && deltaX >= lastDeltaX) {
  39056. // right-down, left-down
  39057. deltaX = lastDeltaX - 10;
  39058. }
  39059. if (!isDownList && deltaX <= lastDeltaX) {
  39060. // right-up, left-up
  39061. deltaX = lastDeltaX + 10;
  39062. }
  39063. list[i].x = cx + deltaX * dir;
  39064. lastDeltaX = deltaX;
  39065. }
  39066. }
  39067. var lastY = 0;
  39068. var delta;
  39069. var len = list.length;
  39070. var upList = [];
  39071. var downList = [];
  39072. for (var i = 0; i < len; i++) {
  39073. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39074. var dx = list[i].x - farthestX;
  39075. list[i].linePoints[1][0] += dx;
  39076. list[i].x = farthestX;
  39077. }
  39078. delta = list[i].y - lastY;
  39079. if (delta < 0) {
  39080. shiftDown(i, len, -delta, dir);
  39081. }
  39082. lastY = list[i].y + list[i].height;
  39083. }
  39084. if (viewHeight - lastY < 0) {
  39085. shiftUp(len - 1, lastY - viewHeight);
  39086. }
  39087. for (var i = 0; i < len; i++) {
  39088. if (list[i].y >= cy) {
  39089. downList.push(list[i]);
  39090. }
  39091. else {
  39092. upList.push(list[i]);
  39093. }
  39094. }
  39095. changeX(upList, false, cx, cy, r, dir);
  39096. changeX(downList, true, cx, cy, r, dir);
  39097. }
  39098. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39099. var leftList = [];
  39100. var rightList = [];
  39101. var leftmostX = Number.MAX_VALUE;
  39102. var rightmostX = -Number.MAX_VALUE;
  39103. for (var i = 0; i < labelLayoutList.length; i++) {
  39104. if (isPositionCenter(labelLayoutList[i])) {
  39105. continue;
  39106. }
  39107. if (labelLayoutList[i].x < cx) {
  39108. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39109. leftList.push(labelLayoutList[i]);
  39110. }
  39111. else {
  39112. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39113. rightList.push(labelLayoutList[i]);
  39114. }
  39115. }
  39116. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39117. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39118. for (var i = 0; i < labelLayoutList.length; i++) {
  39119. var layout = labelLayoutList[i];
  39120. if (isPositionCenter(layout)) {
  39121. continue;
  39122. }
  39123. var linePoints = layout.linePoints;
  39124. if (linePoints) {
  39125. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39126. var realTextWidth = layout.textRect.width;
  39127. var targetTextWidth;
  39128. if (isAlignToEdge) {
  39129. if (layout.x < cx) {
  39130. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39131. - viewLeft - layout.labelMargin;
  39132. }
  39133. else {
  39134. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39135. - linePoints[2][0] - layout.labelDistance;
  39136. }
  39137. }
  39138. else {
  39139. if (layout.x < cx) {
  39140. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39141. }
  39142. else {
  39143. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39144. }
  39145. }
  39146. if (targetTextWidth < layout.textRect.width) {
  39147. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39148. if (layout.labelAlignTo === 'edge') {
  39149. realTextWidth = getWidth(layout.text, layout.font);
  39150. }
  39151. }
  39152. var dist = linePoints[1][0] - linePoints[2][0];
  39153. if (isAlignToEdge) {
  39154. if (layout.x < cx) {
  39155. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39156. }
  39157. else {
  39158. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39159. - realTextWidth - layout.labelDistance;
  39160. }
  39161. }
  39162. else {
  39163. if (layout.x < cx) {
  39164. linePoints[2][0] = layout.x + layout.labelDistance;
  39165. }
  39166. else {
  39167. linePoints[2][0] = layout.x - layout.labelDistance;
  39168. }
  39169. linePoints[1][0] = linePoints[2][0] + dist;
  39170. }
  39171. linePoints[1][1] = linePoints[2][1] = layout.y;
  39172. }
  39173. }
  39174. }
  39175. function isPositionCenter(layout) {
  39176. // Not change x for center label
  39177. return layout.position === 'center';
  39178. }
  39179. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39180. var data = seriesModel.getData();
  39181. var labelLayoutList = [];
  39182. var cx;
  39183. var cy;
  39184. var hasLabelRotate = false;
  39185. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39186. data.each(function (idx) {
  39187. var layout = data.getItemLayout(idx);
  39188. var itemModel = data.getItemModel(idx);
  39189. var labelModel = itemModel.getModel('label');
  39190. // Use position in normal or emphasis
  39191. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39192. var labelDistance = labelModel.get('distanceToLabelLine');
  39193. var labelAlignTo = labelModel.get('alignTo');
  39194. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39195. var bleedMargin = labelModel.get('bleedMargin');
  39196. var font = labelModel.getFont();
  39197. var labelLineModel = itemModel.getModel('labelLine');
  39198. var labelLineLen = labelLineModel.get('length');
  39199. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39200. var labelLineLen2 = labelLineModel.get('length2');
  39201. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39202. if (layout.angle < minShowLabelRadian) {
  39203. return;
  39204. }
  39205. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39206. var dx = Math.cos(midAngle);
  39207. var dy = Math.sin(midAngle);
  39208. var textX;
  39209. var textY;
  39210. var linePoints;
  39211. var textAlign;
  39212. cx = layout.cx;
  39213. cy = layout.cy;
  39214. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39215. || data.getName(idx);
  39216. var textRect = getBoundingRect(
  39217. text, font, textAlign, 'top'
  39218. );
  39219. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39220. if (labelPosition === 'center') {
  39221. textX = layout.cx;
  39222. textY = layout.cy;
  39223. textAlign = 'center';
  39224. }
  39225. else {
  39226. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39227. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39228. textX = x1 + dx * 3;
  39229. textY = y1 + dy * 3;
  39230. if (!isLabelInside) {
  39231. // For roseType
  39232. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39233. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39234. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39235. var y3 = y2;
  39236. if (labelAlignTo === 'edge') {
  39237. // Adjust textX because text align of edge is opposite
  39238. textX = dx < 0
  39239. ? viewLeft + labelMargin
  39240. : viewLeft + viewWidth - labelMargin;
  39241. }
  39242. else {
  39243. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39244. }
  39245. textY = y3;
  39246. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39247. }
  39248. textAlign = isLabelInside
  39249. ? 'center'
  39250. : (labelAlignTo === 'edge'
  39251. ? (dx > 0 ? 'right' : 'left')
  39252. : (dx > 0 ? 'left' : 'right'));
  39253. }
  39254. var labelRotate;
  39255. var rotate = labelModel.get('rotate');
  39256. if (typeof rotate === 'number') {
  39257. labelRotate = rotate * (Math.PI / 180);
  39258. }
  39259. else {
  39260. labelRotate = rotate
  39261. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39262. : 0;
  39263. }
  39264. hasLabelRotate = !!labelRotate;
  39265. layout.label = {
  39266. x: textX,
  39267. y: textY,
  39268. position: labelPosition,
  39269. height: textRect.height,
  39270. len: labelLineLen,
  39271. len2: labelLineLen2,
  39272. linePoints: linePoints,
  39273. textAlign: textAlign,
  39274. verticalAlign: 'middle',
  39275. rotation: labelRotate,
  39276. inside: isLabelInside,
  39277. labelDistance: labelDistance,
  39278. labelAlignTo: labelAlignTo,
  39279. labelMargin:labelMargin,
  39280. bleedMargin: bleedMargin,
  39281. textRect: textRect,
  39282. text: text,
  39283. font: font
  39284. };
  39285. // Not layout the inside label
  39286. if (!isLabelInside) {
  39287. labelLayoutList.push(layout.label);
  39288. }
  39289. });
  39290. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39291. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39292. }
  39293. };
  39294. /*
  39295. * Licensed to the Apache Software Foundation (ASF) under one
  39296. * or more contributor license agreements. See the NOTICE file
  39297. * distributed with this work for additional information
  39298. * regarding copyright ownership. The ASF licenses this file
  39299. * to you under the Apache License, Version 2.0 (the
  39300. * "License"); you may not use this file except in compliance
  39301. * with the License. You may obtain a copy of the License at
  39302. *
  39303. * http://www.apache.org/licenses/LICENSE-2.0
  39304. *
  39305. * Unless required by applicable law or agreed to in writing,
  39306. * software distributed under the License is distributed on an
  39307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39308. * KIND, either express or implied. See the License for the
  39309. * specific language governing permissions and limitations
  39310. * under the License.
  39311. */
  39312. var PI2$4 = Math.PI * 2;
  39313. var RADIAN = Math.PI / 180;
  39314. function getViewRect(seriesModel, api) {
  39315. return getLayoutRect(
  39316. seriesModel.getBoxLayoutParams(), {
  39317. width: api.getWidth(),
  39318. height: api.getHeight()
  39319. }
  39320. );
  39321. }
  39322. var pieLayout = function (seriesType, ecModel, api, payload) {
  39323. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39324. var data = seriesModel.getData();
  39325. var valueDim = data.mapDimension('value');
  39326. var viewRect = getViewRect(seriesModel, api);
  39327. var center = seriesModel.get('center');
  39328. var radius = seriesModel.get('radius');
  39329. if (!isArray(radius)) {
  39330. radius = [0, radius];
  39331. }
  39332. if (!isArray(center)) {
  39333. center = [center, center];
  39334. }
  39335. var width = parsePercent$1(viewRect.width, api.getWidth());
  39336. var height = parsePercent$1(viewRect.height, api.getHeight());
  39337. var size = Math.min(width, height);
  39338. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39339. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39340. var r0 = parsePercent$1(radius[0], size / 2);
  39341. var r = parsePercent$1(radius[1], size / 2);
  39342. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39343. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39344. var validDataCount = 0;
  39345. data.each(valueDim, function (value) {
  39346. !isNaN(value) && validDataCount++;
  39347. });
  39348. var sum = data.getSum(valueDim);
  39349. // Sum may be 0
  39350. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39351. var clockwise = seriesModel.get('clockwise');
  39352. var roseType = seriesModel.get('roseType');
  39353. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39354. // [0...max]
  39355. var extent = data.getDataExtent(valueDim);
  39356. extent[0] = 0;
  39357. // In the case some sector angle is smaller than minAngle
  39358. var restAngle = PI2$4;
  39359. var valueSumLargerThanMinAngle = 0;
  39360. var currentAngle = startAngle;
  39361. var dir = clockwise ? 1 : -1;
  39362. data.each(valueDim, function (value, idx) {
  39363. var angle;
  39364. if (isNaN(value)) {
  39365. data.setItemLayout(idx, {
  39366. angle: NaN,
  39367. startAngle: NaN,
  39368. endAngle: NaN,
  39369. clockwise: clockwise,
  39370. cx: cx,
  39371. cy: cy,
  39372. r0: r0,
  39373. r: roseType
  39374. ? NaN
  39375. : r,
  39376. viewRect: viewRect
  39377. });
  39378. return;
  39379. }
  39380. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39381. if (roseType !== 'area') {
  39382. angle = (sum === 0 && stillShowZeroSum)
  39383. ? unitRadian : (value * unitRadian);
  39384. }
  39385. else {
  39386. angle = PI2$4 / validDataCount;
  39387. }
  39388. if (angle < minAngle) {
  39389. angle = minAngle;
  39390. restAngle -= minAngle;
  39391. }
  39392. else {
  39393. valueSumLargerThanMinAngle += value;
  39394. }
  39395. var endAngle = currentAngle + dir * angle;
  39396. data.setItemLayout(idx, {
  39397. angle: angle,
  39398. startAngle: currentAngle,
  39399. endAngle: endAngle,
  39400. clockwise: clockwise,
  39401. cx: cx,
  39402. cy: cy,
  39403. r0: r0,
  39404. r: roseType
  39405. ? linearMap(value, extent, [r0, r])
  39406. : r,
  39407. viewRect: viewRect
  39408. });
  39409. currentAngle = endAngle;
  39410. });
  39411. // Some sector is constrained by minAngle
  39412. // Rest sectors needs recalculate angle
  39413. if (restAngle < PI2$4 && validDataCount) {
  39414. // Average the angle if rest angle is not enough after all angles is
  39415. // Constrained by minAngle
  39416. if (restAngle <= 1e-3) {
  39417. var angle = PI2$4 / validDataCount;
  39418. data.each(valueDim, function (value, idx) {
  39419. if (!isNaN(value)) {
  39420. var layout = data.getItemLayout(idx);
  39421. layout.angle = angle;
  39422. layout.startAngle = startAngle + dir * idx * angle;
  39423. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39424. }
  39425. });
  39426. }
  39427. else {
  39428. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39429. currentAngle = startAngle;
  39430. data.each(valueDim, function (value, idx) {
  39431. if (!isNaN(value)) {
  39432. var layout = data.getItemLayout(idx);
  39433. var angle = layout.angle === minAngle
  39434. ? minAngle : value * unitRadian;
  39435. layout.startAngle = currentAngle;
  39436. layout.endAngle = currentAngle + dir * angle;
  39437. currentAngle += dir * angle;
  39438. }
  39439. });
  39440. }
  39441. }
  39442. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39443. });
  39444. };
  39445. /*
  39446. * Licensed to the Apache Software Foundation (ASF) under one
  39447. * or more contributor license agreements. See the NOTICE file
  39448. * distributed with this work for additional information
  39449. * regarding copyright ownership. The ASF licenses this file
  39450. * to you under the Apache License, Version 2.0 (the
  39451. * "License"); you may not use this file except in compliance
  39452. * with the License. You may obtain a copy of the License at
  39453. *
  39454. * http://www.apache.org/licenses/LICENSE-2.0
  39455. *
  39456. * Unless required by applicable law or agreed to in writing,
  39457. * software distributed under the License is distributed on an
  39458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39459. * KIND, either express or implied. See the License for the
  39460. * specific language governing permissions and limitations
  39461. * under the License.
  39462. */
  39463. var dataFilter = function (seriesType) {
  39464. return {
  39465. seriesType: seriesType,
  39466. reset: function (seriesModel, ecModel) {
  39467. var legendModels = ecModel.findComponents({
  39468. mainType: 'legend'
  39469. });
  39470. if (!legendModels || !legendModels.length) {
  39471. return;
  39472. }
  39473. var data = seriesModel.getData();
  39474. data.filterSelf(function (idx) {
  39475. var name = data.getName(idx);
  39476. // If in any legend component the status is not selected.
  39477. for (var i = 0; i < legendModels.length; i++) {
  39478. if (!legendModels[i].isSelected(name)) {
  39479. return false;
  39480. }
  39481. }
  39482. return true;
  39483. });
  39484. }
  39485. };
  39486. };
  39487. /*
  39488. * Licensed to the Apache Software Foundation (ASF) under one
  39489. * or more contributor license agreements. See the NOTICE file
  39490. * distributed with this work for additional information
  39491. * regarding copyright ownership. The ASF licenses this file
  39492. * to you under the Apache License, Version 2.0 (the
  39493. * "License"); you may not use this file except in compliance
  39494. * with the License. You may obtain a copy of the License at
  39495. *
  39496. * http://www.apache.org/licenses/LICENSE-2.0
  39497. *
  39498. * Unless required by applicable law or agreed to in writing,
  39499. * software distributed under the License is distributed on an
  39500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39501. * KIND, either express or implied. See the License for the
  39502. * specific language governing permissions and limitations
  39503. * under the License.
  39504. */
  39505. createDataSelectAction('pie', [{
  39506. type: 'pieToggleSelect',
  39507. event: 'pieselectchanged',
  39508. method: 'toggleSelected'
  39509. }, {
  39510. type: 'pieSelect',
  39511. event: 'pieselected',
  39512. method: 'select'
  39513. }, {
  39514. type: 'pieUnSelect',
  39515. event: 'pieunselected',
  39516. method: 'unSelect'
  39517. }]);
  39518. registerVisual(dataColor('pie'));
  39519. registerLayout(curry(pieLayout, 'pie'));
  39520. registerProcessor(dataFilter('pie'));
  39521. /*
  39522. * Licensed to the Apache Software Foundation (ASF) under one
  39523. * or more contributor license agreements. See the NOTICE file
  39524. * distributed with this work for additional information
  39525. * regarding copyright ownership. The ASF licenses this file
  39526. * to you under the Apache License, Version 2.0 (the
  39527. * "License"); you may not use this file except in compliance
  39528. * with the License. You may obtain a copy of the License at
  39529. *
  39530. * http://www.apache.org/licenses/LICENSE-2.0
  39531. *
  39532. * Unless required by applicable law or agreed to in writing,
  39533. * software distributed under the License is distributed on an
  39534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39535. * KIND, either express or implied. See the License for the
  39536. * specific language governing permissions and limitations
  39537. * under the License.
  39538. */
  39539. SeriesModel.extend({
  39540. type: 'series.scatter',
  39541. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39542. getInitialData: function (option, ecModel) {
  39543. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39544. },
  39545. brushSelector: 'point',
  39546. getProgressive: function () {
  39547. var progressive = this.option.progressive;
  39548. if (progressive == null) {
  39549. // PENDING
  39550. return this.option.large ? 5e3 : this.get('progressive');
  39551. }
  39552. return progressive;
  39553. },
  39554. getProgressiveThreshold: function () {
  39555. var progressiveThreshold = this.option.progressiveThreshold;
  39556. if (progressiveThreshold == null) {
  39557. // PENDING
  39558. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39559. }
  39560. return progressiveThreshold;
  39561. },
  39562. defaultOption: {
  39563. coordinateSystem: 'cartesian2d',
  39564. zlevel: 0,
  39565. z: 2,
  39566. legendHoverLink: true,
  39567. hoverAnimation: true,
  39568. // Cartesian coordinate system
  39569. // xAxisIndex: 0,
  39570. // yAxisIndex: 0,
  39571. // Polar coordinate system
  39572. // polarIndex: 0,
  39573. // Geo coordinate system
  39574. // geoIndex: 0,
  39575. // symbol: null, // 图形类型
  39576. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39577. // symbolRotate: null, // 图形旋转控制
  39578. large: false,
  39579. // Available when large is true
  39580. largeThreshold: 2000,
  39581. // cursor: null,
  39582. // label: {
  39583. // show: false
  39584. // distance: 5,
  39585. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39586. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39587. // 'inside'|'left'|'right'|'top'|'bottom'
  39588. // 默认使用全局文本样式,详见TEXTSTYLE
  39589. // },
  39590. itemStyle: {
  39591. opacity: 0.8
  39592. // color: 各异
  39593. },
  39594. // If clip the overflow graphics
  39595. // Works on cartesian / polar series
  39596. clip: true
  39597. // progressive: null
  39598. }
  39599. });
  39600. /*
  39601. * Licensed to the Apache Software Foundation (ASF) under one
  39602. * or more contributor license agreements. See the NOTICE file
  39603. * distributed with this work for additional information
  39604. * regarding copyright ownership. The ASF licenses this file
  39605. * to you under the Apache License, Version 2.0 (the
  39606. * "License"); you may not use this file except in compliance
  39607. * with the License. You may obtain a copy of the License at
  39608. *
  39609. * http://www.apache.org/licenses/LICENSE-2.0
  39610. *
  39611. * Unless required by applicable law or agreed to in writing,
  39612. * software distributed under the License is distributed on an
  39613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39614. * KIND, either express or implied. See the License for the
  39615. * specific language governing permissions and limitations
  39616. * under the License.
  39617. */
  39618. /* global Float32Array */
  39619. // TODO Batch by color
  39620. var BOOST_SIZE_THRESHOLD = 4;
  39621. var LargeSymbolPath = extendShape({
  39622. shape: {
  39623. points: null
  39624. },
  39625. symbolProxy: null,
  39626. softClipShape: null,
  39627. buildPath: function (path, shape) {
  39628. var points = shape.points;
  39629. var size = shape.size;
  39630. var symbolProxy = this.symbolProxy;
  39631. var symbolProxyShape = symbolProxy.shape;
  39632. var ctx = path.getContext ? path.getContext() : path;
  39633. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39634. // Do draw in afterBrush.
  39635. if (canBoost) {
  39636. return;
  39637. }
  39638. for (var i = 0; i < points.length;) {
  39639. var x = points[i++];
  39640. var y = points[i++];
  39641. if (isNaN(x) || isNaN(y)) {
  39642. continue;
  39643. }
  39644. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39645. continue;
  39646. }
  39647. symbolProxyShape.x = x - size[0] / 2;
  39648. symbolProxyShape.y = y - size[1] / 2;
  39649. symbolProxyShape.width = size[0];
  39650. symbolProxyShape.height = size[1];
  39651. symbolProxy.buildPath(path, symbolProxyShape, true);
  39652. }
  39653. },
  39654. afterBrush: function (ctx) {
  39655. var shape = this.shape;
  39656. var points = shape.points;
  39657. var size = shape.size;
  39658. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39659. if (!canBoost) {
  39660. return;
  39661. }
  39662. this.setTransform(ctx);
  39663. // PENDING If style or other canvas status changed?
  39664. for (var i = 0; i < points.length;) {
  39665. var x = points[i++];
  39666. var y = points[i++];
  39667. if (isNaN(x) || isNaN(y)) {
  39668. continue;
  39669. }
  39670. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39671. continue;
  39672. }
  39673. // fillRect is faster than building a rect path and draw.
  39674. // And it support light globalCompositeOperation.
  39675. ctx.fillRect(
  39676. x - size[0] / 2, y - size[1] / 2,
  39677. size[0], size[1]
  39678. );
  39679. }
  39680. this.restoreTransform(ctx);
  39681. },
  39682. findDataIndex: function (x, y) {
  39683. // TODO ???
  39684. // Consider transform
  39685. var shape = this.shape;
  39686. var points = shape.points;
  39687. var size = shape.size;
  39688. var w = Math.max(size[0], 4);
  39689. var h = Math.max(size[1], 4);
  39690. // Not consider transform
  39691. // Treat each element as a rect
  39692. // top down traverse
  39693. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  39694. var i = idx * 2;
  39695. var x0 = points[i] - w / 2;
  39696. var y0 = points[i + 1] - h / 2;
  39697. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  39698. return idx;
  39699. }
  39700. }
  39701. return -1;
  39702. }
  39703. });
  39704. function LargeSymbolDraw() {
  39705. this.group = new Group();
  39706. }
  39707. var largeSymbolProto = LargeSymbolDraw.prototype;
  39708. largeSymbolProto.isPersistent = function () {
  39709. return !this._incremental;
  39710. };
  39711. /**
  39712. * Update symbols draw by new data
  39713. * @param {module:echarts/data/List} data
  39714. * @param {Object} opt
  39715. * @param {Object} [opt.clipShape]
  39716. */
  39717. largeSymbolProto.updateData = function (data, opt) {
  39718. this.group.removeAll();
  39719. var symbolEl = new LargeSymbolPath({
  39720. rectHover: true,
  39721. cursor: 'default'
  39722. });
  39723. symbolEl.setShape({
  39724. points: data.getLayout('symbolPoints')
  39725. });
  39726. this._setCommon(symbolEl, data, false, opt);
  39727. this.group.add(symbolEl);
  39728. this._incremental = null;
  39729. };
  39730. largeSymbolProto.updateLayout = function (data) {
  39731. if (this._incremental) {
  39732. return;
  39733. }
  39734. var points = data.getLayout('symbolPoints');
  39735. this.group.eachChild(function (child) {
  39736. if (child.startIndex != null) {
  39737. var len = (child.endIndex - child.startIndex) * 2;
  39738. var byteOffset = child.startIndex * 4 * 2;
  39739. points = new Float32Array(points.buffer, byteOffset, len);
  39740. }
  39741. child.setShape('points', points);
  39742. });
  39743. };
  39744. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  39745. this.group.removeAll();
  39746. this._clearIncremental();
  39747. // Only use incremental displayables when data amount is larger than 2 million.
  39748. // PENDING Incremental data?
  39749. if (data.count() > 2e6) {
  39750. if (!this._incremental) {
  39751. this._incremental = new IncrementalDisplayble({
  39752. silent: true
  39753. });
  39754. }
  39755. this.group.add(this._incremental);
  39756. }
  39757. else {
  39758. this._incremental = null;
  39759. }
  39760. };
  39761. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  39762. var symbolEl;
  39763. if (this._incremental) {
  39764. symbolEl = new LargeSymbolPath();
  39765. this._incremental.addDisplayable(symbolEl, true);
  39766. }
  39767. else {
  39768. symbolEl = new LargeSymbolPath({
  39769. rectHover: true,
  39770. cursor: 'default',
  39771. startIndex: taskParams.start,
  39772. endIndex: taskParams.end
  39773. });
  39774. symbolEl.incremental = true;
  39775. this.group.add(symbolEl);
  39776. }
  39777. symbolEl.setShape({
  39778. points: data.getLayout('symbolPoints')
  39779. });
  39780. this._setCommon(symbolEl, data, !!this._incremental, opt);
  39781. };
  39782. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  39783. var hostModel = data.hostModel;
  39784. opt = opt || {};
  39785. // TODO
  39786. // if (data.hasItemVisual.symbolSize) {
  39787. // // TODO typed array?
  39788. // symbolEl.setShape('sizes', data.mapArray(
  39789. // function (idx) {
  39790. // var size = data.getItemVisual(idx, 'symbolSize');
  39791. // return (size instanceof Array) ? size : [size, size];
  39792. // }
  39793. // ));
  39794. // }
  39795. // else {
  39796. var size = data.getVisual('symbolSize');
  39797. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  39798. // }
  39799. symbolEl.softClipShape = opt.clipShape || null;
  39800. // Create symbolProxy to build path for each data
  39801. symbolEl.symbolProxy = createSymbol(
  39802. data.getVisual('symbol'), 0, 0, 0, 0
  39803. );
  39804. // Use symbolProxy setColor method
  39805. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  39806. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  39807. symbolEl.useStyle(
  39808. // Draw shadow when doing fillRect is extremely slow.
  39809. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  39810. );
  39811. var visualColor = data.getVisual('color');
  39812. if (visualColor) {
  39813. symbolEl.setColor(visualColor);
  39814. }
  39815. if (!isIncremental) {
  39816. // Enable tooltip
  39817. // PENDING May have performance issue when path is extremely large
  39818. symbolEl.seriesIndex = hostModel.seriesIndex;
  39819. symbolEl.on('mousemove', function (e) {
  39820. symbolEl.dataIndex = null;
  39821. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  39822. if (dataIndex >= 0) {
  39823. // Provide dataIndex for tooltip
  39824. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  39825. }
  39826. });
  39827. }
  39828. };
  39829. largeSymbolProto.remove = function () {
  39830. this._clearIncremental();
  39831. this._incremental = null;
  39832. this.group.removeAll();
  39833. };
  39834. largeSymbolProto._clearIncremental = function () {
  39835. var incremental = this._incremental;
  39836. if (incremental) {
  39837. incremental.clearDisplaybles();
  39838. }
  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. extendChartView({
  39859. type: 'scatter',
  39860. render: function (seriesModel, ecModel, api) {
  39861. var data = seriesModel.getData();
  39862. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39863. symbolDraw.updateData(data, {
  39864. // TODO
  39865. // If this parameter should be a shape or a bounding volume
  39866. // shape will be more general.
  39867. // But bounding volume like bounding rect will be much faster in the contain calculation
  39868. clipShape: this._getClipShape(seriesModel)
  39869. });
  39870. this._finished = true;
  39871. },
  39872. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  39873. var data = seriesModel.getData();
  39874. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39875. symbolDraw.incrementalPrepareUpdate(data);
  39876. this._finished = false;
  39877. },
  39878. incrementalRender: function (taskParams, seriesModel, ecModel) {
  39879. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  39880. clipShape: this._getClipShape(seriesModel)
  39881. });
  39882. this._finished = taskParams.end === seriesModel.getData().count();
  39883. },
  39884. updateTransform: function (seriesModel, ecModel, api) {
  39885. var data = seriesModel.getData();
  39886. // Must mark group dirty and make sure the incremental layer will be cleared
  39887. // PENDING
  39888. this.group.dirty();
  39889. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  39890. return {
  39891. update: true
  39892. };
  39893. }
  39894. else {
  39895. var res = pointsLayout().reset(seriesModel);
  39896. if (res.progress) {
  39897. res.progress({ start: 0, end: data.count() }, data);
  39898. }
  39899. this._symbolDraw.updateLayout(data);
  39900. }
  39901. },
  39902. _getClipShape: function (seriesModel) {
  39903. var coordSys = seriesModel.coordinateSystem;
  39904. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  39905. return seriesModel.get('clip', true) ? clipArea : null;
  39906. },
  39907. _updateSymbolDraw: function (data, seriesModel) {
  39908. var symbolDraw = this._symbolDraw;
  39909. var pipelineContext = seriesModel.pipelineContext;
  39910. var isLargeDraw = pipelineContext.large;
  39911. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  39912. symbolDraw && symbolDraw.remove();
  39913. symbolDraw = this._symbolDraw = isLargeDraw
  39914. ? new LargeSymbolDraw()
  39915. : new SymbolDraw();
  39916. this._isLargeDraw = isLargeDraw;
  39917. this.group.removeAll();
  39918. }
  39919. this.group.add(symbolDraw.group);
  39920. return symbolDraw;
  39921. },
  39922. remove: function (ecModel, api) {
  39923. this._symbolDraw && this._symbolDraw.remove(true);
  39924. this._symbolDraw = null;
  39925. },
  39926. dispose: function () {}
  39927. });
  39928. /*
  39929. * Licensed to the Apache Software Foundation (ASF) under one
  39930. * or more contributor license agreements. See the NOTICE file
  39931. * distributed with this work for additional information
  39932. * regarding copyright ownership. The ASF licenses this file
  39933. * to you under the Apache License, Version 2.0 (the
  39934. * "License"); you may not use this file except in compliance
  39935. * with the License. You may obtain a copy of the License at
  39936. *
  39937. * http://www.apache.org/licenses/LICENSE-2.0
  39938. *
  39939. * Unless required by applicable law or agreed to in writing,
  39940. * software distributed under the License is distributed on an
  39941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39942. * KIND, either express or implied. See the License for the
  39943. * specific language governing permissions and limitations
  39944. * under the License.
  39945. */
  39946. // import * as zrUtil from 'zrender/src/core/util';
  39947. // In case developer forget to include grid component
  39948. registerVisual(visualSymbol('scatter', 'circle'));
  39949. registerLayout(pointsLayout('scatter'));
  39950. // echarts.registerProcessor(function (ecModel, api) {
  39951. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  39952. // var data = seriesModel.getData();
  39953. // var coordSys = seriesModel.coordinateSystem;
  39954. // if (coordSys.type !== 'geo') {
  39955. // return;
  39956. // }
  39957. // var startPt = coordSys.pointToData([0, 0]);
  39958. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  39959. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  39960. // return data.mapDimension(dim);
  39961. // });
  39962. // var range = {};
  39963. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  39964. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  39965. // data.selectRange(range);
  39966. // });
  39967. // });
  39968. /*
  39969. * Licensed to the Apache Software Foundation (ASF) under one
  39970. * or more contributor license agreements. See the NOTICE file
  39971. * distributed with this work for additional information
  39972. * regarding copyright ownership. The ASF licenses this file
  39973. * to you under the Apache License, Version 2.0 (the
  39974. * "License"); you may not use this file except in compliance
  39975. * with the License. You may obtain a copy of the License at
  39976. *
  39977. * http://www.apache.org/licenses/LICENSE-2.0
  39978. *
  39979. * Unless required by applicable law or agreed to in writing,
  39980. * software distributed under the License is distributed on an
  39981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39982. * KIND, either express or implied. See the License for the
  39983. * specific language governing permissions and limitations
  39984. * under the License.
  39985. */
  39986. function IndicatorAxis(dim, scale, radiusExtent) {
  39987. Axis.call(this, dim, scale, radiusExtent);
  39988. /**
  39989. * Axis type
  39990. * - 'category'
  39991. * - 'value'
  39992. * - 'time'
  39993. * - 'log'
  39994. * @type {string}
  39995. */
  39996. this.type = 'value';
  39997. this.angle = 0;
  39998. /**
  39999. * Indicator name
  40000. * @type {string}
  40001. */
  40002. this.name = '';
  40003. /**
  40004. * @type {module:echarts/model/Model}
  40005. */
  40006. this.model;
  40007. }
  40008. inherits(IndicatorAxis, Axis);
  40009. /*
  40010. * Licensed to the Apache Software Foundation (ASF) under one
  40011. * or more contributor license agreements. See the NOTICE file
  40012. * distributed with this work for additional information
  40013. * regarding copyright ownership. The ASF licenses this file
  40014. * to you under the Apache License, Version 2.0 (the
  40015. * "License"); you may not use this file except in compliance
  40016. * with the License. You may obtain a copy of the License at
  40017. *
  40018. * http://www.apache.org/licenses/LICENSE-2.0
  40019. *
  40020. * Unless required by applicable law or agreed to in writing,
  40021. * software distributed under the License is distributed on an
  40022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40023. * KIND, either express or implied. See the License for the
  40024. * specific language governing permissions and limitations
  40025. * under the License.
  40026. */
  40027. // TODO clockwise
  40028. function Radar(radarModel, ecModel, api) {
  40029. this._model = radarModel;
  40030. /**
  40031. * Radar dimensions
  40032. * @type {Array.<string>}
  40033. */
  40034. this.dimensions = [];
  40035. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  40036. var dim = 'indicator_' + idx;
  40037. var indicatorAxis = new IndicatorAxis(dim,
  40038. (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale());
  40039. indicatorAxis.name = indicatorModel.get('name');
  40040. // Inject model and axis
  40041. indicatorAxis.model = indicatorModel;
  40042. indicatorModel.axis = indicatorAxis;
  40043. this.dimensions.push(dim);
  40044. return indicatorAxis;
  40045. }, this);
  40046. this.resize(radarModel, api);
  40047. /**
  40048. * @type {number}
  40049. * @readOnly
  40050. */
  40051. this.cx;
  40052. /**
  40053. * @type {number}
  40054. * @readOnly
  40055. */
  40056. this.cy;
  40057. /**
  40058. * @type {number}
  40059. * @readOnly
  40060. */
  40061. this.r;
  40062. /**
  40063. * @type {number}
  40064. * @readOnly
  40065. */
  40066. this.r0;
  40067. /**
  40068. * @type {number}
  40069. * @readOnly
  40070. */
  40071. this.startAngle;
  40072. }
  40073. Radar.prototype.getIndicatorAxes = function () {
  40074. return this._indicatorAxes;
  40075. };
  40076. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  40077. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40078. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  40079. };
  40080. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  40081. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  40082. var angle = indicatorAxis.angle;
  40083. var x = this.cx + coord * Math.cos(angle);
  40084. var y = this.cy - coord * Math.sin(angle);
  40085. return [x, y];
  40086. };
  40087. Radar.prototype.pointToData = function (pt) {
  40088. var dx = pt[0] - this.cx;
  40089. var dy = pt[1] - this.cy;
  40090. var radius = Math.sqrt(dx * dx + dy * dy);
  40091. dx /= radius;
  40092. dy /= radius;
  40093. var radian = Math.atan2(-dy, dx);
  40094. // Find the closest angle
  40095. // FIXME index can calculated directly
  40096. var minRadianDiff = Infinity;
  40097. var closestAxis;
  40098. var closestAxisIdx = -1;
  40099. for (var i = 0; i < this._indicatorAxes.length; i++) {
  40100. var indicatorAxis = this._indicatorAxes[i];
  40101. var diff = Math.abs(radian - indicatorAxis.angle);
  40102. if (diff < minRadianDiff) {
  40103. closestAxis = indicatorAxis;
  40104. closestAxisIdx = i;
  40105. minRadianDiff = diff;
  40106. }
  40107. }
  40108. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  40109. };
  40110. Radar.prototype.resize = function (radarModel, api) {
  40111. var center = radarModel.get('center');
  40112. var viewWidth = api.getWidth();
  40113. var viewHeight = api.getHeight();
  40114. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  40115. this.cx = parsePercent$1(center[0], viewWidth);
  40116. this.cy = parsePercent$1(center[1], viewHeight);
  40117. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  40118. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  40119. var radius = radarModel.get('radius');
  40120. if (typeof radius === 'string' || typeof radius === 'number') {
  40121. radius = [0, radius];
  40122. }
  40123. this.r0 = parsePercent$1(radius[0], viewSize);
  40124. this.r = parsePercent$1(radius[1], viewSize);
  40125. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  40126. indicatorAxis.setExtent(this.r0, this.r);
  40127. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  40128. // Normalize to [-PI, PI]
  40129. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  40130. indicatorAxis.angle = angle;
  40131. }, this);
  40132. };
  40133. Radar.prototype.update = function (ecModel, api) {
  40134. var indicatorAxes = this._indicatorAxes;
  40135. var radarModel = this._model;
  40136. each$1(indicatorAxes, function (indicatorAxis) {
  40137. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  40138. });
  40139. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  40140. if (radarSeries.get('coordinateSystem') !== 'radar'
  40141. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  40142. ) {
  40143. return;
  40144. }
  40145. var data = radarSeries.getData();
  40146. each$1(indicatorAxes, function (indicatorAxis) {
  40147. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  40148. });
  40149. }, this);
  40150. var splitNumber = radarModel.get('splitNumber');
  40151. function increaseInterval(interval) {
  40152. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  40153. // Increase interval
  40154. var f = interval / exp10;
  40155. if (f === 2) {
  40156. f = 5;
  40157. }
  40158. else { // f is 2 or 5
  40159. f *= 2;
  40160. }
  40161. return f * exp10;
  40162. }
  40163. // Force all the axis fixing the maxSplitNumber.
  40164. each$1(indicatorAxes, function (indicatorAxis, idx) {
  40165. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  40166. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  40167. var axisModel = indicatorAxis.model;
  40168. var scale = indicatorAxis.scale;
  40169. var fixedMin = axisModel.getMin();
  40170. var fixedMax = axisModel.getMax();
  40171. var interval = scale.getInterval();
  40172. if (fixedMin != null && fixedMax != null) {
  40173. // User set min, max, divide to get new interval
  40174. scale.setExtent(+fixedMin, +fixedMax);
  40175. scale.setInterval(
  40176. (fixedMax - fixedMin) / splitNumber
  40177. );
  40178. }
  40179. else if (fixedMin != null) {
  40180. var max;
  40181. // User set min, expand extent on the other side
  40182. do {
  40183. max = fixedMin + interval * splitNumber;
  40184. scale.setExtent(+fixedMin, max);
  40185. // Interval must been set after extent
  40186. // FIXME
  40187. scale.setInterval(interval);
  40188. interval = increaseInterval(interval);
  40189. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  40190. }
  40191. else if (fixedMax != null) {
  40192. var min;
  40193. // User set min, expand extent on the other side
  40194. do {
  40195. min = fixedMax - interval * splitNumber;
  40196. scale.setExtent(min, +fixedMax);
  40197. scale.setInterval(interval);
  40198. interval = increaseInterval(interval);
  40199. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  40200. }
  40201. else {
  40202. var nicedSplitNumber = scale.getTicks().length - 1;
  40203. if (nicedSplitNumber > splitNumber) {
  40204. interval = increaseInterval(interval);
  40205. }
  40206. // PENDING
  40207. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  40208. var halfSplitNumber = Math.round(splitNumber / 2);
  40209. scale.setExtent(
  40210. round$1(center - halfSplitNumber * interval),
  40211. round$1(center + (splitNumber - halfSplitNumber) * interval)
  40212. );
  40213. scale.setInterval(interval);
  40214. }
  40215. });
  40216. };
  40217. /**
  40218. * Radar dimensions is based on the data
  40219. * @type {Array}
  40220. */
  40221. Radar.dimensions = [];
  40222. Radar.create = function (ecModel, api) {
  40223. var radarList = [];
  40224. ecModel.eachComponent('radar', function (radarModel) {
  40225. var radar = new Radar(radarModel, ecModel, api);
  40226. radarList.push(radar);
  40227. radarModel.coordinateSystem = radar;
  40228. });
  40229. ecModel.eachSeriesByType('radar', function (radarSeries) {
  40230. if (radarSeries.get('coordinateSystem') === 'radar') {
  40231. // Inject coordinate system
  40232. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  40233. }
  40234. });
  40235. return radarList;
  40236. };
  40237. CoordinateSystemManager.register('radar', Radar);
  40238. /*
  40239. * Licensed to the Apache Software Foundation (ASF) under one
  40240. * or more contributor license agreements. See the NOTICE file
  40241. * distributed with this work for additional information
  40242. * regarding copyright ownership. The ASF licenses this file
  40243. * to you under the Apache License, Version 2.0 (the
  40244. * "License"); you may not use this file except in compliance
  40245. * with the License. You may obtain a copy of the License at
  40246. *
  40247. * http://www.apache.org/licenses/LICENSE-2.0
  40248. *
  40249. * Unless required by applicable law or agreed to in writing,
  40250. * software distributed under the License is distributed on an
  40251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40252. * KIND, either express or implied. See the License for the
  40253. * specific language governing permissions and limitations
  40254. * under the License.
  40255. */
  40256. var valueAxisDefault = axisDefault.valueAxis;
  40257. function defaultsShow(opt, show) {
  40258. return defaults({
  40259. show: show
  40260. }, opt);
  40261. }
  40262. var RadarModel = extendComponentModel({
  40263. type: 'radar',
  40264. optionUpdated: function () {
  40265. var boundaryGap = this.get('boundaryGap');
  40266. var splitNumber = this.get('splitNumber');
  40267. var scale = this.get('scale');
  40268. var axisLine = this.get('axisLine');
  40269. var axisTick = this.get('axisTick');
  40270. var axisType = this.get('axisType');
  40271. var axisLabel = this.get('axisLabel');
  40272. var nameTextStyle = this.get('name');
  40273. var showName = this.get('name.show');
  40274. var nameFormatter = this.get('name.formatter');
  40275. var nameGap = this.get('nameGap');
  40276. var triggerEvent = this.get('triggerEvent');
  40277. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  40278. // PENDING
  40279. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  40280. indicatorOpt.min = 0;
  40281. }
  40282. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  40283. indicatorOpt.max = 0;
  40284. }
  40285. var iNameTextStyle = nameTextStyle;
  40286. if (indicatorOpt.color != null) {
  40287. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  40288. }
  40289. // Use same configuration
  40290. indicatorOpt = merge(clone(indicatorOpt), {
  40291. boundaryGap: boundaryGap,
  40292. splitNumber: splitNumber,
  40293. scale: scale,
  40294. axisLine: axisLine,
  40295. axisTick: axisTick,
  40296. axisType: axisType,
  40297. axisLabel: axisLabel,
  40298. // Compatible with 2 and use text
  40299. name: indicatorOpt.text,
  40300. nameLocation: 'end',
  40301. nameGap: nameGap,
  40302. // min: 0,
  40303. nameTextStyle: iNameTextStyle,
  40304. triggerEvent: triggerEvent
  40305. }, false);
  40306. if (!showName) {
  40307. indicatorOpt.name = '';
  40308. }
  40309. if (typeof nameFormatter === 'string') {
  40310. var indName = indicatorOpt.name;
  40311. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  40312. }
  40313. else if (typeof nameFormatter === 'function') {
  40314. indicatorOpt.name = nameFormatter(
  40315. indicatorOpt.name, indicatorOpt
  40316. );
  40317. }
  40318. var model = extend(
  40319. new Model(indicatorOpt, null, this.ecModel),
  40320. axisModelCommonMixin
  40321. );
  40322. // For triggerEvent.
  40323. model.mainType = 'radar';
  40324. model.componentIndex = this.componentIndex;
  40325. return model;
  40326. }, this);
  40327. this.getIndicatorModels = function () {
  40328. return indicatorModels;
  40329. };
  40330. },
  40331. defaultOption: {
  40332. zlevel: 0,
  40333. z: 0,
  40334. center: ['50%', '50%'],
  40335. radius: '75%',
  40336. startAngle: 90,
  40337. name: {
  40338. show: true
  40339. // formatter: null
  40340. // textStyle: {}
  40341. },
  40342. boundaryGap: [0, 0],
  40343. splitNumber: 5,
  40344. nameGap: 15,
  40345. scale: false,
  40346. // Polygon or circle
  40347. shape: 'polygon',
  40348. axisLine: merge(
  40349. {
  40350. lineStyle: {
  40351. color: '#bbb'
  40352. }
  40353. },
  40354. valueAxisDefault.axisLine
  40355. ),
  40356. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  40357. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  40358. axisType: 'interval',
  40359. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  40360. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  40361. // {text, min, max}
  40362. indicator: []
  40363. }
  40364. });
  40365. /*
  40366. * Licensed to the Apache Software Foundation (ASF) under one
  40367. * or more contributor license agreements. See the NOTICE file
  40368. * distributed with this work for additional information
  40369. * regarding copyright ownership. The ASF licenses this file
  40370. * to you under the Apache License, Version 2.0 (the
  40371. * "License"); you may not use this file except in compliance
  40372. * with the License. You may obtain a copy of the License at
  40373. *
  40374. * http://www.apache.org/licenses/LICENSE-2.0
  40375. *
  40376. * Unless required by applicable law or agreed to in writing,
  40377. * software distributed under the License is distributed on an
  40378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40379. * KIND, either express or implied. See the License for the
  40380. * specific language governing permissions and limitations
  40381. * under the License.
  40382. */
  40383. var axisBuilderAttrs$1 = [
  40384. 'axisLine', 'axisTickLabel', 'axisName'
  40385. ];
  40386. extendComponentView({
  40387. type: 'radar',
  40388. render: function (radarModel, ecModel, api) {
  40389. var group = this.group;
  40390. group.removeAll();
  40391. this._buildAxes(radarModel);
  40392. this._buildSplitLineAndArea(radarModel);
  40393. },
  40394. _buildAxes: function (radarModel) {
  40395. var radar = radarModel.coordinateSystem;
  40396. var indicatorAxes = radar.getIndicatorAxes();
  40397. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  40398. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  40399. position: [radar.cx, radar.cy],
  40400. rotation: indicatorAxis.angle,
  40401. labelDirection: -1,
  40402. tickDirection: -1,
  40403. nameDirection: 1
  40404. });
  40405. return axisBuilder;
  40406. });
  40407. each$1(axisBuilders, function (axisBuilder) {
  40408. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  40409. this.group.add(axisBuilder.getGroup());
  40410. }, this);
  40411. },
  40412. _buildSplitLineAndArea: function (radarModel) {
  40413. var radar = radarModel.coordinateSystem;
  40414. var indicatorAxes = radar.getIndicatorAxes();
  40415. if (!indicatorAxes.length) {
  40416. return;
  40417. }
  40418. var shape = radarModel.get('shape');
  40419. var splitLineModel = radarModel.getModel('splitLine');
  40420. var splitAreaModel = radarModel.getModel('splitArea');
  40421. var lineStyleModel = splitLineModel.getModel('lineStyle');
  40422. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40423. var showSplitLine = splitLineModel.get('show');
  40424. var showSplitArea = splitAreaModel.get('show');
  40425. var splitLineColors = lineStyleModel.get('color');
  40426. var splitAreaColors = areaStyleModel.get('color');
  40427. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  40428. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  40429. var splitLines = [];
  40430. var splitAreas = [];
  40431. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  40432. var colorIndex = idx % areaOrLineColorList.length;
  40433. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  40434. return colorIndex;
  40435. }
  40436. if (shape === 'circle') {
  40437. var ticksRadius = indicatorAxes[0].getTicksCoords();
  40438. var cx = radar.cx;
  40439. var cy = radar.cy;
  40440. for (var i = 0; i < ticksRadius.length; i++) {
  40441. if (showSplitLine) {
  40442. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40443. splitLines[colorIndex].push(new Circle({
  40444. shape: {
  40445. cx: cx,
  40446. cy: cy,
  40447. r: ticksRadius[i].coord
  40448. }
  40449. }));
  40450. }
  40451. if (showSplitArea && i < ticksRadius.length - 1) {
  40452. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  40453. splitAreas[colorIndex].push(new Ring({
  40454. shape: {
  40455. cx: cx,
  40456. cy: cy,
  40457. r0: ticksRadius[i].coord,
  40458. r: ticksRadius[i + 1].coord
  40459. }
  40460. }));
  40461. }
  40462. }
  40463. }
  40464. // Polyyon
  40465. else {
  40466. var realSplitNumber;
  40467. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  40468. var ticksCoords = indicatorAxis.getTicksCoords();
  40469. realSplitNumber = realSplitNumber == null
  40470. ? ticksCoords.length - 1
  40471. : Math.min(ticksCoords.length - 1, realSplitNumber);
  40472. return map(ticksCoords, function (tickCoord) {
  40473. return radar.coordToPoint(tickCoord.coord, idx);
  40474. });
  40475. });
  40476. var prevPoints = [];
  40477. for (var i = 0; i <= realSplitNumber; i++) {
  40478. var points = [];
  40479. for (var j = 0; j < indicatorAxes.length; j++) {
  40480. points.push(axesTicksPoints[j][i]);
  40481. }
  40482. // Close
  40483. if (points[0]) {
  40484. points.push(points[0].slice());
  40485. }
  40486. else {
  40487. if (__DEV__) {
  40488. console.error('Can\'t draw value axis ' + i);
  40489. }
  40490. }
  40491. if (showSplitLine) {
  40492. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  40493. splitLines[colorIndex].push(new Polyline({
  40494. shape: {
  40495. points: points
  40496. }
  40497. }));
  40498. }
  40499. if (showSplitArea && prevPoints) {
  40500. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  40501. splitAreas[colorIndex].push(new Polygon({
  40502. shape: {
  40503. points: points.concat(prevPoints)
  40504. }
  40505. }));
  40506. }
  40507. prevPoints = points.slice().reverse();
  40508. }
  40509. }
  40510. var lineStyle = lineStyleModel.getLineStyle();
  40511. var areaStyle = areaStyleModel.getAreaStyle();
  40512. // Add splitArea before splitLine
  40513. each$1(splitAreas, function (splitAreas, idx) {
  40514. this.group.add(mergePath(
  40515. splitAreas, {
  40516. style: defaults({
  40517. stroke: 'none',
  40518. fill: splitAreaColors[idx % splitAreaColors.length]
  40519. }, areaStyle),
  40520. silent: true
  40521. }
  40522. ));
  40523. }, this);
  40524. each$1(splitLines, function (splitLines, idx) {
  40525. this.group.add(mergePath(
  40526. splitLines, {
  40527. style: defaults({
  40528. fill: 'none',
  40529. stroke: splitLineColors[idx % splitLineColors.length]
  40530. }, lineStyle),
  40531. silent: true
  40532. }
  40533. ));
  40534. }, this);
  40535. }
  40536. });
  40537. /*
  40538. * Licensed to the Apache Software Foundation (ASF) under one
  40539. * or more contributor license agreements. See the NOTICE file
  40540. * distributed with this work for additional information
  40541. * regarding copyright ownership. The ASF licenses this file
  40542. * to you under the Apache License, Version 2.0 (the
  40543. * "License"); you may not use this file except in compliance
  40544. * with the License. You may obtain a copy of the License at
  40545. *
  40546. * http://www.apache.org/licenses/LICENSE-2.0
  40547. *
  40548. * Unless required by applicable law or agreed to in writing,
  40549. * software distributed under the License is distributed on an
  40550. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40551. * KIND, either express or implied. See the License for the
  40552. * specific language governing permissions and limitations
  40553. * under the License.
  40554. */
  40555. /*
  40556. * Licensed to the Apache Software Foundation (ASF) under one
  40557. * or more contributor license agreements. See the NOTICE file
  40558. * distributed with this work for additional information
  40559. * regarding copyright ownership. The ASF licenses this file
  40560. * to you under the Apache License, Version 2.0 (the
  40561. * "License"); you may not use this file except in compliance
  40562. * with the License. You may obtain a copy of the License at
  40563. *
  40564. * http://www.apache.org/licenses/LICENSE-2.0
  40565. *
  40566. * Unless required by applicable law or agreed to in writing,
  40567. * software distributed under the License is distributed on an
  40568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40569. * KIND, either express or implied. See the License for the
  40570. * specific language governing permissions and limitations
  40571. * under the License.
  40572. */
  40573. var RadarSeries = SeriesModel.extend({
  40574. type: 'series.radar',
  40575. dependencies: ['radar'],
  40576. // Overwrite
  40577. init: function (option) {
  40578. RadarSeries.superApply(this, 'init', arguments);
  40579. // Enable legend selection for each data item
  40580. // Use a function instead of direct access because data reference may changed
  40581. this.legendVisualProvider = new LegendVisualProvider(
  40582. bind(this.getData, this), bind(this.getRawData, this)
  40583. );
  40584. },
  40585. getInitialData: function (option, ecModel) {
  40586. return createListSimply(this, {
  40587. generateCoord: 'indicator_',
  40588. generateCoordCount: Infinity
  40589. });
  40590. },
  40591. formatTooltip: function (dataIndex) {
  40592. var data = this.getData();
  40593. var coordSys = this.coordinateSystem;
  40594. var indicatorAxes = coordSys.getIndicatorAxes();
  40595. var name = this.getData().getName(dataIndex);
  40596. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  40597. + map(indicatorAxes, function (axis, idx) {
  40598. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  40599. return encodeHTML(axis.name + ' : ' + val);
  40600. }).join('<br />');
  40601. },
  40602. defaultOption: {
  40603. zlevel: 0,
  40604. z: 2,
  40605. coordinateSystem: 'radar',
  40606. legendHoverLink: true,
  40607. radarIndex: 0,
  40608. lineStyle: {
  40609. width: 2,
  40610. type: 'solid'
  40611. },
  40612. label: {
  40613. position: 'top'
  40614. },
  40615. // areaStyle: {
  40616. // },
  40617. // itemStyle: {}
  40618. symbol: 'emptyCircle',
  40619. symbolSize: 4
  40620. // symbolRotate: null
  40621. }
  40622. });
  40623. /*
  40624. * Licensed to the Apache Software Foundation (ASF) under one
  40625. * or more contributor license agreements. See the NOTICE file
  40626. * distributed with this work for additional information
  40627. * regarding copyright ownership. The ASF licenses this file
  40628. * to you under the Apache License, Version 2.0 (the
  40629. * "License"); you may not use this file except in compliance
  40630. * with the License. You may obtain a copy of the License at
  40631. *
  40632. * http://www.apache.org/licenses/LICENSE-2.0
  40633. *
  40634. * Unless required by applicable law or agreed to in writing,
  40635. * software distributed under the License is distributed on an
  40636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40637. * KIND, either express or implied. See the License for the
  40638. * specific language governing permissions and limitations
  40639. * under the License.
  40640. */
  40641. function normalizeSymbolSize(symbolSize) {
  40642. if (!isArray(symbolSize)) {
  40643. symbolSize = [+symbolSize, +symbolSize];
  40644. }
  40645. return symbolSize;
  40646. }
  40647. extendChartView({
  40648. type: 'radar',
  40649. render: function (seriesModel, ecModel, api) {
  40650. var polar = seriesModel.coordinateSystem;
  40651. var group = this.group;
  40652. var data = seriesModel.getData();
  40653. var oldData = this._data;
  40654. function createSymbol$$1(data, idx) {
  40655. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  40656. var color = data.getItemVisual(idx, 'color');
  40657. if (symbolType === 'none') {
  40658. return;
  40659. }
  40660. var symbolSize = normalizeSymbolSize(
  40661. data.getItemVisual(idx, 'symbolSize')
  40662. );
  40663. var symbolPath = createSymbol(
  40664. symbolType, -1, -1, 2, 2, color
  40665. );
  40666. symbolPath.attr({
  40667. style: {
  40668. strokeNoScale: true
  40669. },
  40670. z2: 100,
  40671. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  40672. });
  40673. return symbolPath;
  40674. }
  40675. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  40676. // Simply rerender all
  40677. symbolGroup.removeAll();
  40678. for (var i = 0; i < newPoints.length - 1; i++) {
  40679. var symbolPath = createSymbol$$1(data, idx);
  40680. if (symbolPath) {
  40681. symbolPath.__dimIdx = i;
  40682. if (oldPoints[i]) {
  40683. symbolPath.attr('position', oldPoints[i]);
  40684. graphic[isInit ? 'initProps' : 'updateProps'](
  40685. symbolPath, {
  40686. position: newPoints[i]
  40687. }, seriesModel, idx
  40688. );
  40689. }
  40690. else {
  40691. symbolPath.attr('position', newPoints[i]);
  40692. }
  40693. symbolGroup.add(symbolPath);
  40694. }
  40695. }
  40696. }
  40697. function getInitialPoints(points) {
  40698. return map(points, function (pt) {
  40699. return [polar.cx, polar.cy];
  40700. });
  40701. }
  40702. data.diff(oldData)
  40703. .add(function (idx) {
  40704. var points = data.getItemLayout(idx);
  40705. if (!points) {
  40706. return;
  40707. }
  40708. var polygon = new Polygon();
  40709. var polyline = new Polyline();
  40710. var target = {
  40711. shape: {
  40712. points: points
  40713. }
  40714. };
  40715. polygon.shape.points = getInitialPoints(points);
  40716. polyline.shape.points = getInitialPoints(points);
  40717. initProps(polygon, target, seriesModel, idx);
  40718. initProps(polyline, target, seriesModel, idx);
  40719. var itemGroup = new Group();
  40720. var symbolGroup = new Group();
  40721. itemGroup.add(polyline);
  40722. itemGroup.add(polygon);
  40723. itemGroup.add(symbolGroup);
  40724. updateSymbols(
  40725. polyline.shape.points, points, symbolGroup, data, idx, true
  40726. );
  40727. data.setItemGraphicEl(idx, itemGroup);
  40728. })
  40729. .update(function (newIdx, oldIdx) {
  40730. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  40731. var polyline = itemGroup.childAt(0);
  40732. var polygon = itemGroup.childAt(1);
  40733. var symbolGroup = itemGroup.childAt(2);
  40734. var target = {
  40735. shape: {
  40736. points: data.getItemLayout(newIdx)
  40737. }
  40738. };
  40739. if (!target.shape.points) {
  40740. return;
  40741. }
  40742. updateSymbols(
  40743. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  40744. );
  40745. updateProps(polyline, target, seriesModel);
  40746. updateProps(polygon, target, seriesModel);
  40747. data.setItemGraphicEl(newIdx, itemGroup);
  40748. })
  40749. .remove(function (idx) {
  40750. group.remove(oldData.getItemGraphicEl(idx));
  40751. })
  40752. .execute();
  40753. data.eachItemGraphicEl(function (itemGroup, idx) {
  40754. var itemModel = data.getItemModel(idx);
  40755. var polyline = itemGroup.childAt(0);
  40756. var polygon = itemGroup.childAt(1);
  40757. var symbolGroup = itemGroup.childAt(2);
  40758. var color = data.getItemVisual(idx, 'color');
  40759. group.add(itemGroup);
  40760. polyline.useStyle(
  40761. defaults(
  40762. itemModel.getModel('lineStyle').getLineStyle(),
  40763. {
  40764. fill: 'none',
  40765. stroke: color
  40766. }
  40767. )
  40768. );
  40769. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  40770. var areaStyleModel = itemModel.getModel('areaStyle');
  40771. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  40772. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  40773. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  40774. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  40775. polygon.ignore = polygonIgnore;
  40776. polygon.useStyle(
  40777. defaults(
  40778. areaStyleModel.getAreaStyle(),
  40779. {
  40780. fill: color,
  40781. opacity: 0.7
  40782. }
  40783. )
  40784. );
  40785. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  40786. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  40787. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  40788. var labelModel = itemModel.getModel('label');
  40789. var labelHoverModel = itemModel.getModel('emphasis.label');
  40790. symbolGroup.eachChild(function (symbolPath) {
  40791. symbolPath.setStyle(itemStyle);
  40792. symbolPath.hoverStyle = clone(itemHoverStyle);
  40793. var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx);
  40794. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  40795. setLabelStyle(
  40796. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  40797. {
  40798. labelFetcher: data.hostModel,
  40799. labelDataIndex: idx,
  40800. labelDimIndex: symbolPath.__dimIdx,
  40801. defaultText: defaultText,
  40802. autoColor: color,
  40803. isRectText: true
  40804. }
  40805. );
  40806. });
  40807. itemGroup.highDownOnUpdate = function (fromState, toState) {
  40808. polygon.attr('ignore', toState === 'emphasis' ? hoverPolygonIgnore : polygonIgnore);
  40809. };
  40810. setHoverStyle(itemGroup);
  40811. });
  40812. this._data = data;
  40813. },
  40814. remove: function () {
  40815. this.group.removeAll();
  40816. this._data = null;
  40817. },
  40818. dispose: function () {}
  40819. });
  40820. /*
  40821. * Licensed to the Apache Software Foundation (ASF) under one
  40822. * or more contributor license agreements. See the NOTICE file
  40823. * distributed with this work for additional information
  40824. * regarding copyright ownership. The ASF licenses this file
  40825. * to you under the Apache License, Version 2.0 (the
  40826. * "License"); you may not use this file except in compliance
  40827. * with the License. You may obtain a copy of the License at
  40828. *
  40829. * http://www.apache.org/licenses/LICENSE-2.0
  40830. *
  40831. * Unless required by applicable law or agreed to in writing,
  40832. * software distributed under the License is distributed on an
  40833. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40834. * KIND, either express or implied. See the License for the
  40835. * specific language governing permissions and limitations
  40836. * under the License.
  40837. */
  40838. var radarLayout = function (ecModel) {
  40839. ecModel.eachSeriesByType('radar', function (seriesModel) {
  40840. var data = seriesModel.getData();
  40841. var points = [];
  40842. var coordSys = seriesModel.coordinateSystem;
  40843. if (!coordSys) {
  40844. return;
  40845. }
  40846. var axes = coordSys.getIndicatorAxes();
  40847. each$1(axes, function (axis, axisIndex) {
  40848. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  40849. points[dataIndex] = points[dataIndex] || [];
  40850. var point = coordSys.dataToPoint(val, axisIndex);
  40851. points[dataIndex][axisIndex] = isValidPoint(point)
  40852. ? point : getValueMissingPoint(coordSys);
  40853. });
  40854. });
  40855. // Close polygon
  40856. data.each(function (idx) {
  40857. // TODO
  40858. // Is it appropriate to connect to the next data when some data is missing?
  40859. // Or, should trade it like `connectNull` in line chart?
  40860. var firstPoint = find(points[idx], function (point) {
  40861. return isValidPoint(point);
  40862. }) || getValueMissingPoint(coordSys);
  40863. // Copy the first actual point to the end of the array
  40864. points[idx].push(firstPoint.slice());
  40865. data.setItemLayout(idx, points[idx]);
  40866. });
  40867. });
  40868. };
  40869. function isValidPoint(point) {
  40870. return !isNaN(point[0]) && !isNaN(point[1]);
  40871. }
  40872. function getValueMissingPoint(coordSys) {
  40873. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  40874. // (probably cause problem when refreshing or animating)
  40875. return [coordSys.cx, coordSys.cy];
  40876. }
  40877. /*
  40878. * Licensed to the Apache Software Foundation (ASF) under one
  40879. * or more contributor license agreements. See the NOTICE file
  40880. * distributed with this work for additional information
  40881. * regarding copyright ownership. The ASF licenses this file
  40882. * to you under the Apache License, Version 2.0 (the
  40883. * "License"); you may not use this file except in compliance
  40884. * with the License. You may obtain a copy of the License at
  40885. *
  40886. * http://www.apache.org/licenses/LICENSE-2.0
  40887. *
  40888. * Unless required by applicable law or agreed to in writing,
  40889. * software distributed under the License is distributed on an
  40890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40891. * KIND, either express or implied. See the License for the
  40892. * specific language governing permissions and limitations
  40893. * under the License.
  40894. */
  40895. // Backward compat for radar chart in 2
  40896. var backwardCompat$1 = function (option) {
  40897. var polarOptArr = option.polar;
  40898. if (polarOptArr) {
  40899. if (!isArray(polarOptArr)) {
  40900. polarOptArr = [polarOptArr];
  40901. }
  40902. var polarNotRadar = [];
  40903. each$1(polarOptArr, function (polarOpt, idx) {
  40904. if (polarOpt.indicator) {
  40905. if (polarOpt.type && !polarOpt.shape) {
  40906. polarOpt.shape = polarOpt.type;
  40907. }
  40908. option.radar = option.radar || [];
  40909. if (!isArray(option.radar)) {
  40910. option.radar = [option.radar];
  40911. }
  40912. option.radar.push(polarOpt);
  40913. }
  40914. else {
  40915. polarNotRadar.push(polarOpt);
  40916. }
  40917. });
  40918. option.polar = polarNotRadar;
  40919. }
  40920. each$1(option.series, function (seriesOpt) {
  40921. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  40922. seriesOpt.radarIndex = seriesOpt.polarIndex;
  40923. }
  40924. });
  40925. };
  40926. /*
  40927. * Licensed to the Apache Software Foundation (ASF) under one
  40928. * or more contributor license agreements. See the NOTICE file
  40929. * distributed with this work for additional information
  40930. * regarding copyright ownership. The ASF licenses this file
  40931. * to you under the Apache License, Version 2.0 (the
  40932. * "License"); you may not use this file except in compliance
  40933. * with the License. You may obtain a copy of the License at
  40934. *
  40935. * http://www.apache.org/licenses/LICENSE-2.0
  40936. *
  40937. * Unless required by applicable law or agreed to in writing,
  40938. * software distributed under the License is distributed on an
  40939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40940. * KIND, either express or implied. See the License for the
  40941. * specific language governing permissions and limitations
  40942. * under the License.
  40943. */
  40944. // Must use radar component
  40945. registerVisual(dataColor('radar'));
  40946. registerVisual(visualSymbol('radar', 'circle'));
  40947. registerLayout(radarLayout);
  40948. registerProcessor(dataFilter('radar'));
  40949. registerPreprocessor(backwardCompat$1);
  40950. /*
  40951. * Licensed to the Apache Software Foundation (ASF) under one
  40952. * or more contributor license agreements. See the NOTICE file
  40953. * distributed with this work for additional information
  40954. * regarding copyright ownership. The ASF licenses this file
  40955. * to you under the Apache License, Version 2.0 (the
  40956. * "License"); you may not use this file except in compliance
  40957. * with the License. You may obtain a copy of the License at
  40958. *
  40959. * http://www.apache.org/licenses/LICENSE-2.0
  40960. *
  40961. * Unless required by applicable law or agreed to in writing,
  40962. * software distributed under the License is distributed on an
  40963. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40964. * KIND, either express or implied. See the License for the
  40965. * specific language governing permissions and limitations
  40966. * under the License.
  40967. */
  40968. // Fix for 南海诸岛
  40969. var geoCoord = [126, 25];
  40970. var points$1 = [
  40971. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  40972. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  40973. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  40974. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  40975. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  40976. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  40977. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  40978. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  40979. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  40980. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  40981. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  40982. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  40983. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  40984. [1, 92.4], [1, 3.5], [0, 3.5]]
  40985. ];
  40986. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  40987. for (var k = 0; k < points$1[i$1].length; k++) {
  40988. points$1[i$1][k][0] /= 10.5;
  40989. points$1[i$1][k][1] /= -10.5 / 0.75;
  40990. points$1[i$1][k][0] += geoCoord[0];
  40991. points$1[i$1][k][1] += geoCoord[1];
  40992. }
  40993. }
  40994. var fixNanhai = function (mapType, regions) {
  40995. if (mapType === 'china') {
  40996. regions.push(new Region(
  40997. '南海诸岛',
  40998. map(points$1, function (exterior) {
  40999. return {
  41000. type: 'polygon',
  41001. exterior: exterior
  41002. };
  41003. }), geoCoord
  41004. ));
  41005. }
  41006. };
  41007. /*
  41008. * Licensed to the Apache Software Foundation (ASF) under one
  41009. * or more contributor license agreements. See the NOTICE file
  41010. * distributed with this work for additional information
  41011. * regarding copyright ownership. The ASF licenses this file
  41012. * to you under the Apache License, Version 2.0 (the
  41013. * "License"); you may not use this file except in compliance
  41014. * with the License. You may obtain a copy of the License at
  41015. *
  41016. * http://www.apache.org/licenses/LICENSE-2.0
  41017. *
  41018. * Unless required by applicable law or agreed to in writing,
  41019. * software distributed under the License is distributed on an
  41020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41021. * KIND, either express or implied. See the License for the
  41022. * specific language governing permissions and limitations
  41023. * under the License.
  41024. */
  41025. var coordsOffsetMap = {
  41026. '南海诸岛': [32, 80],
  41027. // 全国
  41028. '广东': [0, -10],
  41029. '香港': [10, 5],
  41030. '澳门': [-10, 10],
  41031. //'北京': [-10, 0],
  41032. '天津': [5, 5]
  41033. };
  41034. var fixTextCoord = function (mapType, region) {
  41035. if (mapType === 'china') {
  41036. var coordFix = coordsOffsetMap[region.name];
  41037. if (coordFix) {
  41038. var cp = region.center;
  41039. cp[0] += coordFix[0] / 10.5;
  41040. cp[1] += -coordFix[1] / (10.5 / 0.75);
  41041. }
  41042. }
  41043. };
  41044. /*
  41045. * Licensed to the Apache Software Foundation (ASF) under one
  41046. * or more contributor license agreements. See the NOTICE file
  41047. * distributed with this work for additional information
  41048. * regarding copyright ownership. The ASF licenses this file
  41049. * to you under the Apache License, Version 2.0 (the
  41050. * "License"); you may not use this file except in compliance
  41051. * with the License. You may obtain a copy of the License at
  41052. *
  41053. * http://www.apache.org/licenses/LICENSE-2.0
  41054. *
  41055. * Unless required by applicable law or agreed to in writing,
  41056. * software distributed under the License is distributed on an
  41057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41058. * KIND, either express or implied. See the License for the
  41059. * specific language governing permissions and limitations
  41060. * under the License.
  41061. */
  41062. var geoCoordMap = {
  41063. 'Russia': [100, 60],
  41064. 'United States': [-99, 38],
  41065. 'United States of America': [-99, 38]
  41066. };
  41067. var fixGeoCoord = function (mapType, region) {
  41068. if (mapType === 'world') {
  41069. var geoCoord = geoCoordMap[region.name];
  41070. if (geoCoord) {
  41071. var cp = region.center;
  41072. cp[0] = geoCoord[0];
  41073. cp[1] = geoCoord[1];
  41074. }
  41075. }
  41076. };
  41077. /*
  41078. * Licensed to the Apache Software Foundation (ASF) under one
  41079. * or more contributor license agreements. See the NOTICE file
  41080. * distributed with this work for additional information
  41081. * regarding copyright ownership. The ASF licenses this file
  41082. * to you under the Apache License, Version 2.0 (the
  41083. * "License"); you may not use this file except in compliance
  41084. * with the License. You may obtain a copy of the License at
  41085. *
  41086. * http://www.apache.org/licenses/LICENSE-2.0
  41087. *
  41088. * Unless required by applicable law or agreed to in writing,
  41089. * software distributed under the License is distributed on an
  41090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41091. * KIND, either express or implied. See the License for the
  41092. * specific language governing permissions and limitations
  41093. * under the License.
  41094. */
  41095. // Fix for 钓鱼岛
  41096. // var Region = require('../Region');
  41097. // var zrUtil = require('zrender/src/core/util');
  41098. // var geoCoord = [126, 25];
  41099. var points$2 = [
  41100. [
  41101. [123.45165252685547, 25.73527164402261],
  41102. [123.49731445312499, 25.73527164402261],
  41103. [123.49731445312499, 25.750734064600884],
  41104. [123.45165252685547, 25.750734064600884],
  41105. [123.45165252685547, 25.73527164402261]
  41106. ]
  41107. ];
  41108. var fixDiaoyuIsland = function (mapType, region) {
  41109. if (mapType === 'china' && region.name === '台湾') {
  41110. region.geometries.push({
  41111. type: 'polygon',
  41112. exterior: points$2[0]
  41113. });
  41114. }
  41115. };
  41116. /*
  41117. * Licensed to the Apache Software Foundation (ASF) under one
  41118. * or more contributor license agreements. See the NOTICE file
  41119. * distributed with this work for additional information
  41120. * regarding copyright ownership. The ASF licenses this file
  41121. * to you under the Apache License, Version 2.0 (the
  41122. * "License"); you may not use this file except in compliance
  41123. * with the License. You may obtain a copy of the License at
  41124. *
  41125. * http://www.apache.org/licenses/LICENSE-2.0
  41126. *
  41127. * Unless required by applicable law or agreed to in writing,
  41128. * software distributed under the License is distributed on an
  41129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41130. * KIND, either express or implied. See the License for the
  41131. * specific language governing permissions and limitations
  41132. * under the License.
  41133. */
  41134. // Built-in GEO fixer.
  41135. var inner$7 = makeInner();
  41136. var geoJSONLoader = {
  41137. /**
  41138. * @param {string} mapName
  41139. * @param {Object} mapRecord {specialAreas, geoJSON}
  41140. * @return {Object} {regions, boundingRect}
  41141. */
  41142. load: function (mapName, mapRecord) {
  41143. var parsed = inner$7(mapRecord).parsed;
  41144. if (parsed) {
  41145. return parsed;
  41146. }
  41147. var specialAreas = mapRecord.specialAreas || {};
  41148. var geoJSON = mapRecord.geoJSON;
  41149. var regions;
  41150. // https://jsperf.com/try-catch-performance-overhead
  41151. try {
  41152. regions = geoJSON ? parseGeoJson$1(geoJSON) : [];
  41153. }
  41154. catch (e) {
  41155. throw new Error('Invalid geoJson format\n' + e.message);
  41156. }
  41157. fixNanhai(mapName, regions);
  41158. each$1(regions, function (region) {
  41159. var regionName = region.name;
  41160. fixTextCoord(mapName, region);
  41161. fixGeoCoord(mapName, region);
  41162. fixDiaoyuIsland(mapName, region);
  41163. // Some area like Alaska in USA map needs to be tansformed
  41164. // to look better
  41165. var specialArea = specialAreas[regionName];
  41166. if (specialArea) {
  41167. region.transformTo(
  41168. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  41169. );
  41170. }
  41171. });
  41172. return (inner$7(mapRecord).parsed = {
  41173. regions: regions,
  41174. boundingRect: getBoundingRect$1(regions)
  41175. });
  41176. }
  41177. };
  41178. function getBoundingRect$1(regions) {
  41179. var rect;
  41180. for (var i = 0; i < regions.length; i++) {
  41181. var regionRect = regions[i].getBoundingRect();
  41182. rect = rect || regionRect.clone();
  41183. rect.union(regionRect);
  41184. }
  41185. return rect;
  41186. }
  41187. /*
  41188. * Licensed to the Apache Software Foundation (ASF) under one
  41189. * or more contributor license agreements. See the NOTICE file
  41190. * distributed with this work for additional information
  41191. * regarding copyright ownership. The ASF licenses this file
  41192. * to you under the Apache License, Version 2.0 (the
  41193. * "License"); you may not use this file except in compliance
  41194. * with the License. You may obtain a copy of the License at
  41195. *
  41196. * http://www.apache.org/licenses/LICENSE-2.0
  41197. *
  41198. * Unless required by applicable law or agreed to in writing,
  41199. * software distributed under the License is distributed on an
  41200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41201. * KIND, either express or implied. See the License for the
  41202. * specific language governing permissions and limitations
  41203. * under the License.
  41204. */
  41205. var inner$8 = makeInner();
  41206. var geoSVGLoader = {
  41207. /**
  41208. * @param {string} mapName
  41209. * @param {Object} mapRecord {specialAreas, geoJSON}
  41210. * @return {Object} {root, boundingRect}
  41211. */
  41212. load: function (mapName, mapRecord) {
  41213. var originRoot = inner$8(mapRecord).originRoot;
  41214. if (originRoot) {
  41215. return {
  41216. root: originRoot,
  41217. boundingRect: inner$8(mapRecord).boundingRect
  41218. };
  41219. }
  41220. var graphic = buildGraphic(mapRecord);
  41221. inner$8(mapRecord).originRoot = graphic.root;
  41222. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  41223. return graphic;
  41224. },
  41225. makeGraphic: function (mapName, mapRecord, hostKey) {
  41226. // For performance consideration (in large SVG), graphic only maked
  41227. // when necessary and reuse them according to hostKey.
  41228. var field = inner$8(mapRecord);
  41229. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  41230. var root = rootMap.get(hostKey);
  41231. if (root) {
  41232. return root;
  41233. }
  41234. var originRoot = field.originRoot;
  41235. var boundingRect = field.boundingRect;
  41236. // For performance, if originRoot is not used by a view,
  41237. // assign it to a view, but not reproduce graphic elements.
  41238. if (!field.originRootHostKey) {
  41239. field.originRootHostKey = hostKey;
  41240. root = originRoot;
  41241. }
  41242. else {
  41243. root = buildGraphic(mapRecord, boundingRect).root;
  41244. }
  41245. return rootMap.set(hostKey, root);
  41246. },
  41247. removeGraphic: function (mapName, mapRecord, hostKey) {
  41248. var field = inner$8(mapRecord);
  41249. var rootMap = field.rootMap;
  41250. rootMap && rootMap.removeKey(hostKey);
  41251. if (hostKey === field.originRootHostKey) {
  41252. field.originRootHostKey = null;
  41253. }
  41254. }
  41255. };
  41256. function buildGraphic(mapRecord, boundingRect) {
  41257. var svgXML = mapRecord.svgXML;
  41258. var result;
  41259. var root;
  41260. try {
  41261. result = svgXML && parseSVG(svgXML, {
  41262. ignoreViewBox: true,
  41263. ignoreRootClip: true
  41264. }) || {};
  41265. root = result.root;
  41266. assert$1(root != null);
  41267. }
  41268. catch (e) {
  41269. throw new Error('Invalid svg format\n' + e.message);
  41270. }
  41271. var svgWidth = result.width;
  41272. var svgHeight = result.height;
  41273. var viewBoxRect = result.viewBoxRect;
  41274. if (!boundingRect) {
  41275. boundingRect = (svgWidth == null || svgHeight == null)
  41276. // If svg width / height not specified, calculate
  41277. // bounding rect as the width / height
  41278. ? root.getBoundingRect()
  41279. : new BoundingRect(0, 0, 0, 0);
  41280. if (svgWidth != null) {
  41281. boundingRect.width = svgWidth;
  41282. }
  41283. if (svgHeight != null) {
  41284. boundingRect.height = svgHeight;
  41285. }
  41286. }
  41287. if (viewBoxRect) {
  41288. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  41289. var elRoot = root;
  41290. root = new Group();
  41291. root.add(elRoot);
  41292. elRoot.scale = viewBoxTransform.scale;
  41293. elRoot.position = viewBoxTransform.position;
  41294. }
  41295. root.setClipPath(new Rect({
  41296. shape: boundingRect.plain()
  41297. }));
  41298. return {
  41299. root: root,
  41300. boundingRect: boundingRect
  41301. };
  41302. }
  41303. /*
  41304. * Licensed to the Apache Software Foundation (ASF) under one
  41305. * or more contributor license agreements. See the NOTICE file
  41306. * distributed with this work for additional information
  41307. * regarding copyright ownership. The ASF licenses this file
  41308. * to you under the Apache License, Version 2.0 (the
  41309. * "License"); you may not use this file except in compliance
  41310. * with the License. You may obtain a copy of the License at
  41311. *
  41312. * http://www.apache.org/licenses/LICENSE-2.0
  41313. *
  41314. * Unless required by applicable law or agreed to in writing,
  41315. * software distributed under the License is distributed on an
  41316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41317. * KIND, either express or implied. See the License for the
  41318. * specific language governing permissions and limitations
  41319. * under the License.
  41320. */
  41321. var loaders = {
  41322. geoJSON: geoJSONLoader,
  41323. svg: geoSVGLoader
  41324. };
  41325. var geoSourceManager = {
  41326. /**
  41327. * @param {string} mapName
  41328. * @param {Object} nameMap
  41329. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  41330. */
  41331. load: function (mapName, nameMap) {
  41332. var regions = [];
  41333. var regionsMap = createHashMap();
  41334. var nameCoordMap = createHashMap();
  41335. var boundingRect;
  41336. var mapRecords = retrieveMap(mapName);
  41337. each$1(mapRecords, function (record) {
  41338. var singleSource = loaders[record.type].load(mapName, record);
  41339. each$1(singleSource.regions, function (region) {
  41340. var regionName = region.name;
  41341. // Try use the alias in geoNameMap
  41342. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  41343. region = region.cloneShallow(regionName = nameMap[regionName]);
  41344. }
  41345. regions.push(region);
  41346. regionsMap.set(regionName, region);
  41347. nameCoordMap.set(regionName, region.center);
  41348. });
  41349. var rect = singleSource.boundingRect;
  41350. if (rect) {
  41351. boundingRect
  41352. ? boundingRect.union(rect)
  41353. : (boundingRect = rect.clone());
  41354. }
  41355. });
  41356. return {
  41357. regions: regions,
  41358. regionsMap: regionsMap,
  41359. nameCoordMap: nameCoordMap,
  41360. // FIXME Always return new ?
  41361. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  41362. };
  41363. },
  41364. /**
  41365. * @param {string} mapName
  41366. * @param {string} hostKey For cache.
  41367. * @return {Array.<module:zrender/Element>} Roots.
  41368. */
  41369. makeGraphic: makeInvoker('makeGraphic'),
  41370. /**
  41371. * @param {string} mapName
  41372. * @param {string} hostKey For cache.
  41373. */
  41374. removeGraphic: makeInvoker('removeGraphic')
  41375. };
  41376. function makeInvoker(methodName) {
  41377. return function (mapName, hostKey) {
  41378. var mapRecords = retrieveMap(mapName);
  41379. var results = [];
  41380. each$1(mapRecords, function (record) {
  41381. var method = loaders[record.type][methodName];
  41382. method && results.push(method(mapName, record, hostKey));
  41383. });
  41384. return results;
  41385. };
  41386. }
  41387. function mapNotExistsError(mapName) {
  41388. if (__DEV__) {
  41389. console.error(
  41390. 'Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.'
  41391. );
  41392. }
  41393. }
  41394. function retrieveMap(mapName) {
  41395. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  41396. if (__DEV__) {
  41397. if (!mapRecords.length) {
  41398. mapNotExistsError(mapName);
  41399. }
  41400. }
  41401. return mapRecords;
  41402. }
  41403. /*
  41404. * Licensed to the Apache Software Foundation (ASF) under one
  41405. * or more contributor license agreements. See the NOTICE file
  41406. * distributed with this work for additional information
  41407. * regarding copyright ownership. The ASF licenses this file
  41408. * to you under the Apache License, Version 2.0 (the
  41409. * "License"); you may not use this file except in compliance
  41410. * with the License. You may obtain a copy of the License at
  41411. *
  41412. * http://www.apache.org/licenses/LICENSE-2.0
  41413. *
  41414. * Unless required by applicable law or agreed to in writing,
  41415. * software distributed under the License is distributed on an
  41416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41417. * KIND, either express or implied. See the License for the
  41418. * specific language governing permissions and limitations
  41419. * under the License.
  41420. */
  41421. var MapSeries = SeriesModel.extend({
  41422. type: 'series.map',
  41423. dependencies: ['geo'],
  41424. layoutMode: 'box',
  41425. /**
  41426. * Only first map series of same mapType will drawMap
  41427. * @type {boolean}
  41428. */
  41429. needsDrawMap: false,
  41430. /**
  41431. * Group of all map series with same mapType
  41432. * @type {boolean}
  41433. */
  41434. seriesGroup: [],
  41435. getInitialData: function (option) {
  41436. var data = createListSimply(this, {
  41437. coordDimensions: ['value'],
  41438. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41439. });
  41440. var valueDim = data.mapDimension('value');
  41441. var dataNameMap = createHashMap();
  41442. var selectTargetList = [];
  41443. var toAppendNames = [];
  41444. for (var i = 0, len = data.count(); i < len; i++) {
  41445. var name = data.getName(i);
  41446. dataNameMap.set(name, true);
  41447. selectTargetList.push({
  41448. name: name,
  41449. value: data.get(valueDim, i),
  41450. selected: retrieveRawAttr(data, i, 'selected')
  41451. });
  41452. }
  41453. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap);
  41454. each$1(geoSource.regions, function (region) {
  41455. var name = region.name;
  41456. if (!dataNameMap.get(name)) {
  41457. selectTargetList.push({name: name});
  41458. toAppendNames.push(name);
  41459. }
  41460. });
  41461. this.updateSelectedMap(selectTargetList);
  41462. // Complete data with missing regions. The consequent processes (like visual
  41463. // map and render) can not be performed without a "full data". For example,
  41464. // find `dataIndex` by name.
  41465. data.appendValues([], toAppendNames);
  41466. return data;
  41467. },
  41468. /**
  41469. * If no host geo model, return null, which means using a
  41470. * inner exclusive geo model.
  41471. */
  41472. getHostGeoModel: function () {
  41473. var geoIndex = this.option.geoIndex;
  41474. return geoIndex != null
  41475. ? this.dependentModels.geo[geoIndex]
  41476. : null;
  41477. },
  41478. getMapType: function () {
  41479. return (this.getHostGeoModel() || this).option.map;
  41480. },
  41481. // _fillOption: function (option, mapName) {
  41482. // Shallow clone
  41483. // option = zrUtil.extend({}, option);
  41484. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  41485. // return option;
  41486. // },
  41487. getRawValue: function (dataIndex) {
  41488. // Use value stored in data instead because it is calculated from multiple series
  41489. // FIXME Provide all value of multiple series ?
  41490. var data = this.getData();
  41491. return data.get(data.mapDimension('value'), dataIndex);
  41492. },
  41493. /**
  41494. * Get model of region
  41495. * @param {string} name
  41496. * @return {module:echarts/model/Model}
  41497. */
  41498. getRegionModel: function (regionName) {
  41499. var data = this.getData();
  41500. return data.getItemModel(data.indexOfName(regionName));
  41501. },
  41502. /**
  41503. * Map tooltip formatter
  41504. *
  41505. * @param {number} dataIndex
  41506. */
  41507. formatTooltip: function (dataIndex) {
  41508. // FIXME orignalData and data is a bit confusing
  41509. var data = this.getData();
  41510. var formattedValue = addCommas(this.getRawValue(dataIndex));
  41511. var name = data.getName(dataIndex);
  41512. var seriesGroup = this.seriesGroup;
  41513. var seriesNames = [];
  41514. for (var i = 0; i < seriesGroup.length; i++) {
  41515. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  41516. var valueDim = data.mapDimension('value');
  41517. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  41518. seriesNames.push(
  41519. encodeHTML(seriesGroup[i].name)
  41520. );
  41521. }
  41522. }
  41523. return seriesNames.join(', ') + '<br />'
  41524. + encodeHTML(name + ' : ' + formattedValue);
  41525. },
  41526. /**
  41527. * @implement
  41528. */
  41529. getTooltipPosition: function (dataIndex) {
  41530. if (dataIndex != null) {
  41531. var name = this.getData().getName(dataIndex);
  41532. var geo = this.coordinateSystem;
  41533. var region = geo.getRegion(name);
  41534. return region && geo.dataToPoint(region.center);
  41535. }
  41536. },
  41537. setZoom: function (zoom) {
  41538. this.option.zoom = zoom;
  41539. },
  41540. setCenter: function (center) {
  41541. this.option.center = center;
  41542. },
  41543. defaultOption: {
  41544. // 一级层叠
  41545. zlevel: 0,
  41546. // 二级层叠
  41547. z: 2,
  41548. coordinateSystem: 'geo',
  41549. // map should be explicitly specified since ec3.
  41550. map: '',
  41551. // If `geoIndex` is not specified, a exclusive geo will be
  41552. // created. Otherwise use the specified geo component, and
  41553. // `map` and `mapType` are ignored.
  41554. // geoIndex: 0,
  41555. // 'center' | 'left' | 'right' | 'x%' | {number}
  41556. left: 'center',
  41557. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  41558. top: 'center',
  41559. // right
  41560. // bottom
  41561. // width:
  41562. // height
  41563. // Aspect is width / height. Inited to be geoJson bbox aspect
  41564. // This parameter is used for scale this aspect
  41565. aspectScale: 0.75,
  41566. ///// Layout with center and size
  41567. // If you wan't to put map in a fixed size box with right aspect ratio
  41568. // This two properties may more conveninet
  41569. // layoutCenter: [50%, 50%]
  41570. // layoutSize: 100
  41571. // 数值合并方式,默认加和,可选为:
  41572. // 'sum' | 'average' | 'max' | 'min'
  41573. // mapValueCalculation: 'sum',
  41574. // 地图数值计算结果小数精度
  41575. // mapValuePrecision: 0,
  41576. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  41577. showLegendSymbol: true,
  41578. // 选择模式,默认关闭,可选single,multiple
  41579. // selectedMode: false,
  41580. dataRangeHoverLink: true,
  41581. // 是否开启缩放及漫游模式
  41582. // roam: false,
  41583. // Define left-top, right-bottom coords to control view
  41584. // For example, [ [180, 90], [-180, -90] ],
  41585. // higher priority than center and zoom
  41586. boundingCoords: null,
  41587. // Default on center of map
  41588. center: null,
  41589. zoom: 1,
  41590. scaleLimit: null,
  41591. label: {
  41592. show: false,
  41593. color: '#000'
  41594. },
  41595. // scaleLimit: null,
  41596. itemStyle: {
  41597. borderWidth: 0.5,
  41598. borderColor: '#444',
  41599. areaColor: '#eee'
  41600. },
  41601. emphasis: {
  41602. label: {
  41603. show: true,
  41604. color: 'rgb(100,0,0)'
  41605. },
  41606. itemStyle: {
  41607. areaColor: 'rgba(255,215,0,0.8)'
  41608. }
  41609. }
  41610. }
  41611. });
  41612. mixin(MapSeries, selectableMixin);
  41613. /*
  41614. * Licensed to the Apache Software Foundation (ASF) under one
  41615. * or more contributor license agreements. See the NOTICE file
  41616. * distributed with this work for additional information
  41617. * regarding copyright ownership. The ASF licenses this file
  41618. * to you under the Apache License, Version 2.0 (the
  41619. * "License"); you may not use this file except in compliance
  41620. * with the License. You may obtain a copy of the License at
  41621. *
  41622. * http://www.apache.org/licenses/LICENSE-2.0
  41623. *
  41624. * Unless required by applicable law or agreed to in writing,
  41625. * software distributed under the License is distributed on an
  41626. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41627. * KIND, either express or implied. See the License for the
  41628. * specific language governing permissions and limitations
  41629. * under the License.
  41630. */
  41631. var ATTR = '\0_ec_interaction_mutex';
  41632. function take(zr, resourceKey, userKey) {
  41633. var store = getStore(zr);
  41634. store[resourceKey] = userKey;
  41635. }
  41636. function release(zr, resourceKey, userKey) {
  41637. var store = getStore(zr);
  41638. var uKey = store[resourceKey];
  41639. if (uKey === userKey) {
  41640. store[resourceKey] = null;
  41641. }
  41642. }
  41643. function isTaken(zr, resourceKey) {
  41644. return !!getStore(zr)[resourceKey];
  41645. }
  41646. function getStore(zr) {
  41647. return zr[ATTR] || (zr[ATTR] = {});
  41648. }
  41649. /**
  41650. * payload: {
  41651. * type: 'takeGlobalCursor',
  41652. * key: 'dataZoomSelect', or 'brush', or ...,
  41653. * If no userKey, release global cursor.
  41654. * }
  41655. */
  41656. registerAction(
  41657. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  41658. function () {}
  41659. );
  41660. /*
  41661. * Licensed to the Apache Software Foundation (ASF) under one
  41662. * or more contributor license agreements. See the NOTICE file
  41663. * distributed with this work for additional information
  41664. * regarding copyright ownership. The ASF licenses this file
  41665. * to you under the Apache License, Version 2.0 (the
  41666. * "License"); you may not use this file except in compliance
  41667. * with the License. You may obtain a copy of the License at
  41668. *
  41669. * http://www.apache.org/licenses/LICENSE-2.0
  41670. *
  41671. * Unless required by applicable law or agreed to in writing,
  41672. * software distributed under the License is distributed on an
  41673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41674. * KIND, either express or implied. See the License for the
  41675. * specific language governing permissions and limitations
  41676. * under the License.
  41677. */
  41678. /**
  41679. * @alias module:echarts/component/helper/RoamController
  41680. * @constructor
  41681. * @mixin {module:zrender/mixin/Eventful}
  41682. *
  41683. * @param {module:zrender/zrender~ZRender} zr
  41684. */
  41685. function RoamController(zr) {
  41686. /**
  41687. * @type {Function}
  41688. */
  41689. this.pointerChecker;
  41690. /**
  41691. * @type {module:zrender}
  41692. */
  41693. this._zr = zr;
  41694. /**
  41695. * @type {Object}
  41696. */
  41697. this._opt = {};
  41698. // Avoid two roamController bind the same handler
  41699. var bind$$1 = bind;
  41700. var mousedownHandler = bind$$1(mousedown, this);
  41701. var mousemoveHandler = bind$$1(mousemove, this);
  41702. var mouseupHandler = bind$$1(mouseup, this);
  41703. var mousewheelHandler = bind$$1(mousewheel, this);
  41704. var pinchHandler = bind$$1(pinch, this);
  41705. Eventful.call(this);
  41706. /**
  41707. * @param {Function} pointerChecker
  41708. * input: x, y
  41709. * output: boolean
  41710. */
  41711. this.setPointerChecker = function (pointerChecker) {
  41712. this.pointerChecker = pointerChecker;
  41713. };
  41714. /**
  41715. * Notice: only enable needed types. For example, if 'zoom'
  41716. * is not needed, 'zoom' should not be enabled, otherwise
  41717. * default mousewheel behaviour (scroll page) will be disabled.
  41718. *
  41719. * @param {boolean|string} [controlType=true] Specify the control type,
  41720. * which can be null/undefined or true/false
  41721. * or 'pan/move' or 'zoom'/'scale'
  41722. * @param {Object} [opt]
  41723. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41724. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41725. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41726. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  41727. */
  41728. this.enable = function (controlType, opt) {
  41729. // Disable previous first
  41730. this.disable();
  41731. this._opt = defaults(clone(opt) || {}, {
  41732. zoomOnMouseWheel: true,
  41733. moveOnMouseMove: true,
  41734. // By default, wheel do not trigger move.
  41735. moveOnMouseWheel: false,
  41736. preventDefaultMouseMove: true
  41737. });
  41738. if (controlType == null) {
  41739. controlType = true;
  41740. }
  41741. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  41742. zr.on('mousedown', mousedownHandler);
  41743. zr.on('mousemove', mousemoveHandler);
  41744. zr.on('mouseup', mouseupHandler);
  41745. }
  41746. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  41747. zr.on('mousewheel', mousewheelHandler);
  41748. zr.on('pinch', pinchHandler);
  41749. }
  41750. };
  41751. this.disable = function () {
  41752. zr.off('mousedown', mousedownHandler);
  41753. zr.off('mousemove', mousemoveHandler);
  41754. zr.off('mouseup', mouseupHandler);
  41755. zr.off('mousewheel', mousewheelHandler);
  41756. zr.off('pinch', pinchHandler);
  41757. };
  41758. this.dispose = this.disable;
  41759. this.isDragging = function () {
  41760. return this._dragging;
  41761. };
  41762. this.isPinching = function () {
  41763. return this._pinching;
  41764. };
  41765. }
  41766. mixin(RoamController, Eventful);
  41767. function mousedown(e) {
  41768. if (isMiddleOrRightButtonOnMouseUpDown(e)
  41769. || (e.target && e.target.draggable)
  41770. ) {
  41771. return;
  41772. }
  41773. var x = e.offsetX;
  41774. var y = e.offsetY;
  41775. // Only check on mosedown, but not mousemove.
  41776. // Mouse can be out of target when mouse moving.
  41777. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  41778. this._x = x;
  41779. this._y = y;
  41780. this._dragging = true;
  41781. }
  41782. }
  41783. function mousemove(e) {
  41784. if (!this._dragging
  41785. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  41786. || e.gestureEvent === 'pinch'
  41787. || isTaken(this._zr, 'globalPan')
  41788. ) {
  41789. return;
  41790. }
  41791. var x = e.offsetX;
  41792. var y = e.offsetY;
  41793. var oldX = this._x;
  41794. var oldY = this._y;
  41795. var dx = x - oldX;
  41796. var dy = y - oldY;
  41797. this._x = x;
  41798. this._y = y;
  41799. this._opt.preventDefaultMouseMove && stop(e.event);
  41800. trigger(this, 'pan', 'moveOnMouseMove', e, {
  41801. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  41802. });
  41803. }
  41804. function mouseup(e) {
  41805. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  41806. this._dragging = false;
  41807. }
  41808. }
  41809. function mousewheel(e) {
  41810. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  41811. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  41812. var wheelDelta = e.wheelDelta;
  41813. var absWheelDeltaDelta = Math.abs(wheelDelta);
  41814. var originX = e.offsetX;
  41815. var originY = e.offsetY;
  41816. // wheelDelta maybe -0 in chrome mac.
  41817. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  41818. return;
  41819. }
  41820. // If both `shouldZoom` and `shouldMove` is true, trigger
  41821. // their event both, and the final behavior is determined
  41822. // by event listener themselves.
  41823. if (shouldZoom) {
  41824. // Convenience:
  41825. // Mac and VM Windows on Mac: scroll up: zoom out.
  41826. // Windows: scroll up: zoom in.
  41827. // FIXME: Should do more test in different environment.
  41828. // wheelDelta is too complicated in difference nvironment
  41829. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  41830. // although it has been normallized by zrender.
  41831. // wheelDelta of mouse wheel is bigger than touch pad.
  41832. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  41833. var scale = wheelDelta > 0 ? factor : 1 / factor;
  41834. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  41835. scale: scale, originX: originX, originY: originY
  41836. });
  41837. }
  41838. if (shouldMove) {
  41839. // FIXME: Should do more test in different environment.
  41840. var absDelta = Math.abs(wheelDelta);
  41841. // wheelDelta of mouse wheel is bigger than touch pad.
  41842. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  41843. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  41844. scrollDelta: scrollDelta, originX: originX, originY: originY
  41845. });
  41846. }
  41847. }
  41848. function pinch(e) {
  41849. if (isTaken(this._zr, 'globalPan')) {
  41850. return;
  41851. }
  41852. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  41853. checkPointerAndTrigger(this, 'zoom', null, e, {
  41854. scale: scale, originX: e.pinchX, originY: e.pinchY
  41855. });
  41856. }
  41857. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  41858. if (controller.pointerChecker
  41859. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  41860. ) {
  41861. // When mouse is out of roamController rect,
  41862. // default befavoius should not be be disabled, otherwise
  41863. // page sliding is disabled, contrary to expectation.
  41864. stop(e.event);
  41865. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  41866. }
  41867. }
  41868. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  41869. // Also provide behavior checker for event listener, for some case that
  41870. // multiple components share one listener.
  41871. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  41872. controller.trigger(eventName, contollerEvent);
  41873. }
  41874. // settings: {
  41875. // zoomOnMouseWheel
  41876. // moveOnMouseMove
  41877. // moveOnMouseWheel
  41878. // }
  41879. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  41880. function isAvailableBehavior(behaviorToCheck, e, settings) {
  41881. var setting = settings[behaviorToCheck];
  41882. return !behaviorToCheck || (
  41883. setting && (!isString(setting) || e.event[setting + 'Key'])
  41884. );
  41885. }
  41886. /*
  41887. * Licensed to the Apache Software Foundation (ASF) under one
  41888. * or more contributor license agreements. See the NOTICE file
  41889. * distributed with this work for additional information
  41890. * regarding copyright ownership. The ASF licenses this file
  41891. * to you under the Apache License, Version 2.0 (the
  41892. * "License"); you may not use this file except in compliance
  41893. * with the License. You may obtain a copy of the License at
  41894. *
  41895. * http://www.apache.org/licenses/LICENSE-2.0
  41896. *
  41897. * Unless required by applicable law or agreed to in writing,
  41898. * software distributed under the License is distributed on an
  41899. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41900. * KIND, either express or implied. See the License for the
  41901. * specific language governing permissions and limitations
  41902. * under the License.
  41903. */
  41904. /**
  41905. * For geo and graph.
  41906. *
  41907. * @param {Object} controllerHost
  41908. * @param {module:zrender/Element} controllerHost.target
  41909. */
  41910. function updateViewOnPan(controllerHost, dx, dy) {
  41911. var target = controllerHost.target;
  41912. var pos = target.position;
  41913. pos[0] += dx;
  41914. pos[1] += dy;
  41915. target.dirty();
  41916. }
  41917. /**
  41918. * For geo and graph.
  41919. *
  41920. * @param {Object} controllerHost
  41921. * @param {module:zrender/Element} controllerHost.target
  41922. * @param {number} controllerHost.zoom
  41923. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  41924. */
  41925. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  41926. var target = controllerHost.target;
  41927. var zoomLimit = controllerHost.zoomLimit;
  41928. var pos = target.position;
  41929. var scale = target.scale;
  41930. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  41931. newZoom *= zoomDelta;
  41932. if (zoomLimit) {
  41933. var zoomMin = zoomLimit.min || 0;
  41934. var zoomMax = zoomLimit.max || Infinity;
  41935. newZoom = Math.max(
  41936. Math.min(zoomMax, newZoom),
  41937. zoomMin
  41938. );
  41939. }
  41940. var zoomScale = newZoom / controllerHost.zoom;
  41941. controllerHost.zoom = newZoom;
  41942. // Keep the mouse center when scaling
  41943. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  41944. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  41945. scale[0] *= zoomScale;
  41946. scale[1] *= zoomScale;
  41947. target.dirty();
  41948. }
  41949. /*
  41950. * Licensed to the Apache Software Foundation (ASF) under one
  41951. * or more contributor license agreements. See the NOTICE file
  41952. * distributed with this work for additional information
  41953. * regarding copyright ownership. The ASF licenses this file
  41954. * to you under the Apache License, Version 2.0 (the
  41955. * "License"); you may not use this file except in compliance
  41956. * with the License. You may obtain a copy of the License at
  41957. *
  41958. * http://www.apache.org/licenses/LICENSE-2.0
  41959. *
  41960. * Unless required by applicable law or agreed to in writing,
  41961. * software distributed under the License is distributed on an
  41962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41963. * KIND, either express or implied. See the License for the
  41964. * specific language governing permissions and limitations
  41965. * under the License.
  41966. */
  41967. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  41968. /**
  41969. * Avoid that: mouse click on a elements that is over geo or graph,
  41970. * but roam is triggered.
  41971. */
  41972. function onIrrelevantElement(e, api, targetCoordSysModel) {
  41973. var model = api.getComponentByElement(e.topTarget);
  41974. // If model is axisModel, it works only if it is injected with coordinateSystem.
  41975. var coordSys = model && model.coordinateSystem;
  41976. return model
  41977. && model !== targetCoordSysModel
  41978. && !IRRELEVANT_EXCLUDES[model.mainType]
  41979. && (coordSys && coordSys.model !== targetCoordSysModel);
  41980. }
  41981. /*
  41982. * Licensed to the Apache Software Foundation (ASF) under one
  41983. * or more contributor license agreements. See the NOTICE file
  41984. * distributed with this work for additional information
  41985. * regarding copyright ownership. The ASF licenses this file
  41986. * to you under the Apache License, Version 2.0 (the
  41987. * "License"); you may not use this file except in compliance
  41988. * with the License. You may obtain a copy of the License at
  41989. *
  41990. * http://www.apache.org/licenses/LICENSE-2.0
  41991. *
  41992. * Unless required by applicable law or agreed to in writing,
  41993. * software distributed under the License is distributed on an
  41994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41995. * KIND, either express or implied. See the License for the
  41996. * specific language governing permissions and limitations
  41997. * under the License.
  41998. */
  41999. function getFixedItemStyle(model) {
  42000. var itemStyle = model.getItemStyle();
  42001. var areaColor = model.get('areaColor');
  42002. // If user want the color not to be changed when hover,
  42003. // they should both set areaColor and color to be null.
  42004. if (areaColor != null) {
  42005. itemStyle.fill = areaColor;
  42006. }
  42007. return itemStyle;
  42008. }
  42009. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  42010. regionsGroup.off('click');
  42011. regionsGroup.off('mousedown');
  42012. if (mapOrGeoModel.get('selectedMode')) {
  42013. regionsGroup.on('mousedown', function () {
  42014. mapDraw._mouseDownFlag = true;
  42015. });
  42016. regionsGroup.on('click', function (e) {
  42017. if (!mapDraw._mouseDownFlag) {
  42018. return;
  42019. }
  42020. mapDraw._mouseDownFlag = false;
  42021. var el = e.target;
  42022. while (!el.__regions) {
  42023. el = el.parent;
  42024. }
  42025. if (!el) {
  42026. return;
  42027. }
  42028. var action = {
  42029. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  42030. batch: map(el.__regions, function (region) {
  42031. return {
  42032. name: region.name,
  42033. from: fromView.uid
  42034. };
  42035. })
  42036. };
  42037. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  42038. api.dispatchAction(action);
  42039. updateMapSelected(mapOrGeoModel, regionsGroup);
  42040. });
  42041. }
  42042. }
  42043. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  42044. // FIXME
  42045. regionsGroup.eachChild(function (otherRegionEl) {
  42046. each$1(otherRegionEl.__regions, function (region) {
  42047. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  42048. });
  42049. });
  42050. }
  42051. /**
  42052. * @alias module:echarts/component/helper/MapDraw
  42053. * @param {module:echarts/ExtensionAPI} api
  42054. * @param {boolean} updateGroup
  42055. */
  42056. function MapDraw(api, updateGroup) {
  42057. var group = new Group();
  42058. /**
  42059. * @type {string}
  42060. * @private
  42061. */
  42062. this.uid = getUID('ec_map_draw');
  42063. /**
  42064. * @type {module:echarts/component/helper/RoamController}
  42065. * @private
  42066. */
  42067. this._controller = new RoamController(api.getZr());
  42068. /**
  42069. * @type {Object} {target, zoom, zoomLimit}
  42070. * @private
  42071. */
  42072. this._controllerHost = {target: updateGroup ? group : null};
  42073. /**
  42074. * @type {module:zrender/container/Group}
  42075. * @readOnly
  42076. */
  42077. this.group = group;
  42078. /**
  42079. * @type {boolean}
  42080. * @private
  42081. */
  42082. this._updateGroup = updateGroup;
  42083. /**
  42084. * This flag is used to make sure that only one among
  42085. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  42086. * action may be triggered when `pan`, which is unexpected.
  42087. * @type {booelan}
  42088. */
  42089. this._mouseDownFlag;
  42090. /**
  42091. * @type {string}
  42092. */
  42093. this._mapName;
  42094. /**
  42095. * @type {boolean}
  42096. */
  42097. this._initialized;
  42098. /**
  42099. * @type {module:zrender/container/Group}
  42100. */
  42101. group.add(this._regionsGroup = new Group());
  42102. /**
  42103. * @type {module:zrender/container/Group}
  42104. */
  42105. group.add(this._backgroundGroup = new Group());
  42106. }
  42107. MapDraw.prototype = {
  42108. constructor: MapDraw,
  42109. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  42110. var isGeo = mapOrGeoModel.mainType === 'geo';
  42111. // Map series has data. GEO model that controlled by map series
  42112. // will be assigned with map data. Other GEO model has no data.
  42113. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  42114. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  42115. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  42116. data = mapSeries.getData();
  42117. }
  42118. });
  42119. var geo = mapOrGeoModel.coordinateSystem;
  42120. this._updateBackground(geo);
  42121. var regionsGroup = this._regionsGroup;
  42122. var group = this.group;
  42123. if (geo._roamTransformable.transform) {
  42124. group.transform = geo._roamTransformable.transform.slice();
  42125. group.decomposeTransform();
  42126. }
  42127. var scale = geo._rawTransformable.scale;
  42128. var position = geo._rawTransformable.position;
  42129. regionsGroup.removeAll();
  42130. var itemStyleAccessPath = ['itemStyle'];
  42131. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  42132. var labelAccessPath = ['label'];
  42133. var hoverLabelAccessPath = ['emphasis', 'label'];
  42134. var nameMap = createHashMap();
  42135. each$1(geo.regions, function (region) {
  42136. // Consider in GeoJson properties.name may be duplicated, for example,
  42137. // there is multiple region named "United Kindom" or "France" (so many
  42138. // colonies). And it is not appropriate to merge them in geo, which
  42139. // will make them share the same label and bring trouble in label
  42140. // location calculation.
  42141. var regionGroup = nameMap.get(region.name)
  42142. || nameMap.set(region.name, new Group());
  42143. var compoundPath = new CompoundPath({
  42144. segmentIgnoreThreshold: 1,
  42145. shape: {
  42146. paths: []
  42147. }
  42148. });
  42149. regionGroup.add(compoundPath);
  42150. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  42151. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  42152. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  42153. var itemStyle = getFixedItemStyle(itemStyleModel);
  42154. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel);
  42155. var labelModel = regionModel.getModel(labelAccessPath);
  42156. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  42157. var dataIdx;
  42158. // Use the itemStyle in data if has data
  42159. if (data) {
  42160. dataIdx = data.indexOfName(region.name);
  42161. // Only visual color of each item will be used. It can be encoded by dataRange
  42162. // But visual color of series is used in symbol drawing
  42163. //
  42164. // Visual color for each series is for the symbol draw
  42165. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  42166. if (visualColor) {
  42167. itemStyle.fill = visualColor;
  42168. }
  42169. }
  42170. var transformPoint = function (point) {
  42171. return [
  42172. point[0] * scale[0] + position[0],
  42173. point[1] * scale[1] + position[1]
  42174. ];
  42175. };
  42176. each$1(region.geometries, function (geometry) {
  42177. if (geometry.type !== 'polygon') {
  42178. return;
  42179. }
  42180. var points = [];
  42181. for (var i = 0; i < geometry.exterior.length; ++i) {
  42182. points.push(transformPoint(geometry.exterior[i]));
  42183. }
  42184. compoundPath.shape.paths.push(new Polygon({
  42185. segmentIgnoreThreshold: 1,
  42186. shape: {
  42187. points: points
  42188. }
  42189. }));
  42190. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  42191. var interior = geometry.interiors[i];
  42192. var points = [];
  42193. for (var j = 0; j < interior.length; ++j) {
  42194. points.push(transformPoint(interior[j]));
  42195. }
  42196. compoundPath.shape.paths.push(new Polygon({
  42197. segmentIgnoreThreshold: 1,
  42198. shape: {
  42199. points: points
  42200. }
  42201. }));
  42202. }
  42203. });
  42204. compoundPath.setStyle(itemStyle);
  42205. compoundPath.style.strokeNoScale = true;
  42206. compoundPath.culling = true;
  42207. // Label
  42208. var showLabel = labelModel.get('show');
  42209. var hoverShowLabel = hoverLabelModel.get('show');
  42210. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  42211. var itemLayout = data && data.getItemLayout(dataIdx);
  42212. // In the following cases label will be drawn
  42213. // 1. In map series and data value is NaN
  42214. // 2. In geo component
  42215. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  42216. if (
  42217. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  42218. || (itemLayout && itemLayout.showLabel)
  42219. ) {
  42220. var query = !isGeo ? dataIdx : region.name;
  42221. var labelFetcher;
  42222. // Consider dataIdx not found.
  42223. if (!data || dataIdx >= 0) {
  42224. labelFetcher = mapOrGeoModel;
  42225. }
  42226. var textEl = new Text({
  42227. position: transformPoint(region.center.slice()),
  42228. // FIXME
  42229. // label rotation is not support yet in geo or regions of series-map
  42230. // that has no data. The rotation will be effected by this `scale`.
  42231. // So needed to change to RectText?
  42232. scale: [1 / group.scale[0], 1 / group.scale[1]],
  42233. z2: 10,
  42234. silent: true
  42235. });
  42236. setLabelStyle(
  42237. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  42238. {
  42239. labelFetcher: labelFetcher,
  42240. labelDataIndex: query,
  42241. defaultText: region.name,
  42242. useInsideStyle: false
  42243. },
  42244. {
  42245. textAlign: 'center',
  42246. textVerticalAlign: 'middle'
  42247. }
  42248. );
  42249. regionGroup.add(textEl);
  42250. }
  42251. // setItemGraphicEl, setHoverStyle after all polygons and labels
  42252. // are added to the rigionGroup
  42253. if (data) {
  42254. data.setItemGraphicEl(dataIdx, regionGroup);
  42255. }
  42256. else {
  42257. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  42258. // Package custom mouse event for geo component
  42259. compoundPath.eventData = {
  42260. componentType: 'geo',
  42261. componentIndex: mapOrGeoModel.componentIndex,
  42262. geoIndex: mapOrGeoModel.componentIndex,
  42263. name: region.name,
  42264. region: (regionModel && regionModel.option) || {}
  42265. };
  42266. }
  42267. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  42268. groupRegions.push(region);
  42269. regionGroup.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
  42270. setHoverStyle(regionGroup, hoverItemStyle);
  42271. regionsGroup.add(regionGroup);
  42272. });
  42273. this._updateController(mapOrGeoModel, ecModel, api);
  42274. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  42275. updateMapSelected(mapOrGeoModel, regionsGroup);
  42276. },
  42277. remove: function () {
  42278. this._regionsGroup.removeAll();
  42279. this._backgroundGroup.removeAll();
  42280. this._controller.dispose();
  42281. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  42282. this._mapName = null;
  42283. this._controllerHost = {};
  42284. },
  42285. _updateBackground: function (geo) {
  42286. var mapName = geo.map;
  42287. if (this._mapName !== mapName) {
  42288. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  42289. this._backgroundGroup.add(root);
  42290. }, this);
  42291. }
  42292. this._mapName = mapName;
  42293. },
  42294. _updateController: function (mapOrGeoModel, ecModel, api) {
  42295. var geo = mapOrGeoModel.coordinateSystem;
  42296. var controller = this._controller;
  42297. var controllerHost = this._controllerHost;
  42298. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  42299. controllerHost.zoom = geo.getZoom();
  42300. // roamType is will be set default true if it is null
  42301. controller.enable(mapOrGeoModel.get('roam') || false);
  42302. var mainType = mapOrGeoModel.mainType;
  42303. function makeActionBase() {
  42304. var action = {
  42305. type: 'geoRoam',
  42306. componentType: mainType
  42307. };
  42308. action[mainType + 'Id'] = mapOrGeoModel.id;
  42309. return action;
  42310. }
  42311. controller.off('pan').on('pan', function (e) {
  42312. this._mouseDownFlag = false;
  42313. updateViewOnPan(controllerHost, e.dx, e.dy);
  42314. api.dispatchAction(extend(makeActionBase(), {
  42315. dx: e.dx,
  42316. dy: e.dy
  42317. }));
  42318. }, this);
  42319. controller.off('zoom').on('zoom', function (e) {
  42320. this._mouseDownFlag = false;
  42321. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42322. api.dispatchAction(extend(makeActionBase(), {
  42323. zoom: e.scale,
  42324. originX: e.originX,
  42325. originY: e.originY
  42326. }));
  42327. if (this._updateGroup) {
  42328. var scale = this.group.scale;
  42329. this._regionsGroup.traverse(function (el) {
  42330. if (el.type === 'text') {
  42331. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  42332. }
  42333. });
  42334. }
  42335. }, this);
  42336. controller.setPointerChecker(function (e, x, y) {
  42337. return geo.getViewRectAfterRoam().contain(x, y)
  42338. && !onIrrelevantElement(e, api, mapOrGeoModel);
  42339. });
  42340. }
  42341. };
  42342. /*
  42343. * Licensed to the Apache Software Foundation (ASF) under one
  42344. * or more contributor license agreements. See the NOTICE file
  42345. * distributed with this work for additional information
  42346. * regarding copyright ownership. The ASF licenses this file
  42347. * to you under the Apache License, Version 2.0 (the
  42348. * "License"); you may not use this file except in compliance
  42349. * with the License. You may obtain a copy of the License at
  42350. *
  42351. * http://www.apache.org/licenses/LICENSE-2.0
  42352. *
  42353. * Unless required by applicable law or agreed to in writing,
  42354. * software distributed under the License is distributed on an
  42355. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42356. * KIND, either express or implied. See the License for the
  42357. * specific language governing permissions and limitations
  42358. * under the License.
  42359. */
  42360. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  42361. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  42362. extendChartView({
  42363. type: 'map',
  42364. render: function (mapModel, ecModel, api, payload) {
  42365. // Not render if it is an toggleSelect action from self
  42366. if (payload && payload.type === 'mapToggleSelect'
  42367. && payload.from === this.uid
  42368. ) {
  42369. return;
  42370. }
  42371. var group = this.group;
  42372. group.removeAll();
  42373. if (mapModel.getHostGeoModel()) {
  42374. return;
  42375. }
  42376. // Not update map if it is an roam action from self
  42377. if (!(payload && payload.type === 'geoRoam'
  42378. && payload.componentType === 'series'
  42379. && payload.seriesId === mapModel.id
  42380. )
  42381. ) {
  42382. if (mapModel.needsDrawMap) {
  42383. var mapDraw = this._mapDraw || new MapDraw(api, true);
  42384. group.add(mapDraw.group);
  42385. mapDraw.draw(mapModel, ecModel, api, this, payload);
  42386. this._mapDraw = mapDraw;
  42387. }
  42388. else {
  42389. // Remove drawed map
  42390. this._mapDraw && this._mapDraw.remove();
  42391. this._mapDraw = null;
  42392. }
  42393. }
  42394. else {
  42395. var mapDraw = this._mapDraw;
  42396. mapDraw && group.add(mapDraw.group);
  42397. }
  42398. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  42399. && this._renderSymbols(mapModel, ecModel, api);
  42400. },
  42401. remove: function () {
  42402. this._mapDraw && this._mapDraw.remove();
  42403. this._mapDraw = null;
  42404. this.group.removeAll();
  42405. },
  42406. dispose: function () {
  42407. this._mapDraw && this._mapDraw.remove();
  42408. this._mapDraw = null;
  42409. },
  42410. _renderSymbols: function (mapModel, ecModel, api) {
  42411. var originalData = mapModel.originalData;
  42412. var group = this.group;
  42413. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  42414. if (isNaN(value)) {
  42415. return;
  42416. }
  42417. var layout = originalData.getItemLayout(originalDataIndex);
  42418. if (!layout || !layout.point) {
  42419. // Not exists in map
  42420. return;
  42421. }
  42422. var point = layout.point;
  42423. var offset = layout.offset;
  42424. var circle = new Circle({
  42425. style: {
  42426. // Because the special of map draw.
  42427. // Which needs statistic of multiple series and draw on one map.
  42428. // And each series also need a symbol with legend color
  42429. //
  42430. // Layout and visual are put one the different data
  42431. fill: mapModel.getData().getVisual('color')
  42432. },
  42433. shape: {
  42434. cx: point[0] + offset * 9,
  42435. cy: point[1],
  42436. r: 3
  42437. },
  42438. silent: true,
  42439. // Do not overlap the first series, on which labels are displayed.
  42440. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  42441. });
  42442. // Only the series that has the first value on the same region is in charge of rendering the label.
  42443. // But consider the case:
  42444. // series: [
  42445. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  42446. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  42447. // ]
  42448. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  42449. // For backward compatibility, we follow the rule that render label `A` by the
  42450. // settings on series `X` but render label `C` by the settings on series `Y`.
  42451. if (!offset) {
  42452. var fullData = mapModel.mainSeries.getData();
  42453. var name = originalData.getName(originalDataIndex);
  42454. var fullIndex = fullData.indexOfName(name);
  42455. var itemModel = originalData.getItemModel(originalDataIndex);
  42456. var labelModel = itemModel.getModel('label');
  42457. var hoverLabelModel = itemModel.getModel('emphasis.label');
  42458. var regionGroup = fullData.getItemGraphicEl(fullIndex);
  42459. // `getFormattedLabel` needs to use `getData` inside. Here
  42460. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  42461. // FIXME
  42462. // If this is not the `mainSeries`, the item model (like label formatter)
  42463. // set on original data item will never get. But it has been working
  42464. // like that from the begining, and this scenario is rarely encountered.
  42465. // So it won't be fixed until have to.
  42466. var normalText = retrieve2(
  42467. mapModel.getFormattedLabel(fullIndex, 'normal'),
  42468. name
  42469. );
  42470. var emphasisText = retrieve2(
  42471. mapModel.getFormattedLabel(fullIndex, 'emphasis'),
  42472. normalText
  42473. );
  42474. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  42475. var recordVersion = Math.random();
  42476. // Prevent from register listeners duplicatedly when roaming.
  42477. if (!highDownRecord) {
  42478. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  42479. var onEmphasis = curry(onRegionHighDown, true);
  42480. var onNormal = curry(onRegionHighDown, false);
  42481. regionGroup.on('mouseover', onEmphasis)
  42482. .on('mouseout', onNormal)
  42483. .on('emphasis', onEmphasis)
  42484. .on('normal', onNormal);
  42485. }
  42486. // Prevent removed regions effect current grapics.
  42487. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  42488. extend(highDownRecord, {
  42489. recordVersion: recordVersion,
  42490. circle: circle,
  42491. labelModel: labelModel,
  42492. hoverLabelModel: hoverLabelModel,
  42493. emphasisText: emphasisText,
  42494. normalText: normalText
  42495. });
  42496. // FIXME
  42497. // Consider set option when emphasis.
  42498. enterRegionHighDown(highDownRecord, false);
  42499. }
  42500. group.add(circle);
  42501. });
  42502. }
  42503. });
  42504. function onRegionHighDown(toHighOrDown) {
  42505. var highDownRecord = this[HIGH_DOWN_PROP];
  42506. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  42507. enterRegionHighDown(highDownRecord, toHighOrDown);
  42508. }
  42509. }
  42510. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  42511. var circle = highDownRecord.circle;
  42512. var labelModel = highDownRecord.labelModel;
  42513. var hoverLabelModel = highDownRecord.hoverLabelModel;
  42514. var emphasisText = highDownRecord.emphasisText;
  42515. var normalText = highDownRecord.normalText;
  42516. if (toHighOrDown) {
  42517. circle.style.extendFrom(
  42518. setTextStyle({}, hoverLabelModel, {
  42519. text: hoverLabelModel.get('show') ? emphasisText : null
  42520. }, {isRectText: true, useInsideStyle: false}, true)
  42521. );
  42522. // Make label upper than others if overlaps.
  42523. circle.__mapOriginalZ2 = circle.z2;
  42524. circle.z2 += Z2_EMPHASIS_LIFT;
  42525. }
  42526. else {
  42527. setTextStyle(circle.style, labelModel, {
  42528. text: labelModel.get('show') ? normalText : null,
  42529. textPosition: labelModel.getShallow('position') || 'bottom'
  42530. }, {isRectText: true, useInsideStyle: false});
  42531. // Trigger normalize style like padding.
  42532. circle.dirty(false);
  42533. if (circle.__mapOriginalZ2 != null) {
  42534. circle.z2 = circle.__mapOriginalZ2;
  42535. circle.__mapOriginalZ2 = null;
  42536. }
  42537. }
  42538. }
  42539. /*
  42540. * Licensed to the Apache Software Foundation (ASF) under one
  42541. * or more contributor license agreements. See the NOTICE file
  42542. * distributed with this work for additional information
  42543. * regarding copyright ownership. The ASF licenses this file
  42544. * to you under the Apache License, Version 2.0 (the
  42545. * "License"); you may not use this file except in compliance
  42546. * with the License. You may obtain a copy of the License at
  42547. *
  42548. * http://www.apache.org/licenses/LICENSE-2.0
  42549. *
  42550. * Unless required by applicable law or agreed to in writing,
  42551. * software distributed under the License is distributed on an
  42552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42553. * KIND, either express or implied. See the License for the
  42554. * specific language governing permissions and limitations
  42555. * under the License.
  42556. */
  42557. /**
  42558. * @param {module:echarts/coord/View} view
  42559. * @param {Object} payload
  42560. * @param {Object} [zoomLimit]
  42561. */
  42562. function updateCenterAndZoom(
  42563. view, payload, zoomLimit
  42564. ) {
  42565. var previousZoom = view.getZoom();
  42566. var center = view.getCenter();
  42567. var zoom = payload.zoom;
  42568. var point = view.dataToPoint(center);
  42569. if (payload.dx != null && payload.dy != null) {
  42570. point[0] -= payload.dx;
  42571. point[1] -= payload.dy;
  42572. var center = view.pointToData(point);
  42573. view.setCenter(center);
  42574. }
  42575. if (zoom != null) {
  42576. if (zoomLimit) {
  42577. var zoomMin = zoomLimit.min || 0;
  42578. var zoomMax = zoomLimit.max || Infinity;
  42579. zoom = Math.max(
  42580. Math.min(previousZoom * zoom, zoomMax),
  42581. zoomMin
  42582. ) / previousZoom;
  42583. }
  42584. // Zoom on given point(originX, originY)
  42585. view.scale[0] *= zoom;
  42586. view.scale[1] *= zoom;
  42587. var position = view.position;
  42588. var fixX = (payload.originX - position[0]) * (zoom - 1);
  42589. var fixY = (payload.originY - position[1]) * (zoom - 1);
  42590. position[0] -= fixX;
  42591. position[1] -= fixY;
  42592. view.updateTransform();
  42593. // Get the new center
  42594. var center = view.pointToData(point);
  42595. view.setCenter(center);
  42596. view.setZoom(zoom * previousZoom);
  42597. }
  42598. return {
  42599. center: view.getCenter(),
  42600. zoom: view.getZoom()
  42601. };
  42602. }
  42603. /*
  42604. * Licensed to the Apache Software Foundation (ASF) under one
  42605. * or more contributor license agreements. See the NOTICE file
  42606. * distributed with this work for additional information
  42607. * regarding copyright ownership. The ASF licenses this file
  42608. * to you under the Apache License, Version 2.0 (the
  42609. * "License"); you may not use this file except in compliance
  42610. * with the License. You may obtain a copy of the License at
  42611. *
  42612. * http://www.apache.org/licenses/LICENSE-2.0
  42613. *
  42614. * Unless required by applicable law or agreed to in writing,
  42615. * software distributed under the License is distributed on an
  42616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42617. * KIND, either express or implied. See the License for the
  42618. * specific language governing permissions and limitations
  42619. * under the License.
  42620. */
  42621. /**
  42622. * @payload
  42623. * @property {string} [componentType=series]
  42624. * @property {number} [dx]
  42625. * @property {number} [dy]
  42626. * @property {number} [zoom]
  42627. * @property {number} [originX]
  42628. * @property {number} [originY]
  42629. */
  42630. registerAction({
  42631. type: 'geoRoam',
  42632. event: 'geoRoam',
  42633. update: 'updateTransform'
  42634. }, function (payload, ecModel) {
  42635. var componentType = payload.componentType || 'series';
  42636. ecModel.eachComponent(
  42637. { mainType: componentType, query: payload },
  42638. function (componentModel) {
  42639. var geo = componentModel.coordinateSystem;
  42640. if (geo.type !== 'geo') {
  42641. return;
  42642. }
  42643. var res = updateCenterAndZoom(
  42644. geo, payload, componentModel.get('scaleLimit')
  42645. );
  42646. componentModel.setCenter
  42647. && componentModel.setCenter(res.center);
  42648. componentModel.setZoom
  42649. && componentModel.setZoom(res.zoom);
  42650. // All map series with same `map` use the same geo coordinate system
  42651. // So the center and zoom must be in sync. Include the series not selected by legend
  42652. if (componentType === 'series') {
  42653. each$1(componentModel.seriesGroup, function (seriesModel) {
  42654. seriesModel.setCenter(res.center);
  42655. seriesModel.setZoom(res.zoom);
  42656. });
  42657. }
  42658. }
  42659. );
  42660. });
  42661. /*
  42662. * Licensed to the Apache Software Foundation (ASF) under one
  42663. * or more contributor license agreements. See the NOTICE file
  42664. * distributed with this work for additional information
  42665. * regarding copyright ownership. The ASF licenses this file
  42666. * to you under the Apache License, Version 2.0 (the
  42667. * "License"); you may not use this file except in compliance
  42668. * with the License. You may obtain a copy of the License at
  42669. *
  42670. * http://www.apache.org/licenses/LICENSE-2.0
  42671. *
  42672. * Unless required by applicable law or agreed to in writing,
  42673. * software distributed under the License is distributed on an
  42674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42675. * KIND, either express or implied. See the License for the
  42676. * specific language governing permissions and limitations
  42677. * under the License.
  42678. */
  42679. /**
  42680. * Simple view coordinate system
  42681. * Mapping given x, y to transformd view x, y
  42682. */
  42683. var v2ApplyTransform$1 = applyTransform;
  42684. // Dummy transform node
  42685. function TransformDummy() {
  42686. Transformable.call(this);
  42687. }
  42688. mixin(TransformDummy, Transformable);
  42689. function View(name) {
  42690. /**
  42691. * @type {string}
  42692. */
  42693. this.name = name;
  42694. /**
  42695. * @type {Object}
  42696. */
  42697. this.zoomLimit;
  42698. Transformable.call(this);
  42699. this._roamTransformable = new TransformDummy();
  42700. this._rawTransformable = new TransformDummy();
  42701. this._center;
  42702. this._zoom;
  42703. }
  42704. View.prototype = {
  42705. constructor: View,
  42706. type: 'view',
  42707. /**
  42708. * @param {Array.<string>}
  42709. * @readOnly
  42710. */
  42711. dimensions: ['x', 'y'],
  42712. /**
  42713. * Set bounding rect
  42714. * @param {number} x
  42715. * @param {number} y
  42716. * @param {number} width
  42717. * @param {number} height
  42718. */
  42719. // PENDING to getRect
  42720. setBoundingRect: function (x, y, width, height) {
  42721. this._rect = new BoundingRect(x, y, width, height);
  42722. return this._rect;
  42723. },
  42724. /**
  42725. * @return {module:zrender/core/BoundingRect}
  42726. */
  42727. // PENDING to getRect
  42728. getBoundingRect: function () {
  42729. return this._rect;
  42730. },
  42731. /**
  42732. * @param {number} x
  42733. * @param {number} y
  42734. * @param {number} width
  42735. * @param {number} height
  42736. */
  42737. setViewRect: function (x, y, width, height) {
  42738. this.transformTo(x, y, width, height);
  42739. this._viewRect = new BoundingRect(x, y, width, height);
  42740. },
  42741. /**
  42742. * Transformed to particular position and size
  42743. * @param {number} x
  42744. * @param {number} y
  42745. * @param {number} width
  42746. * @param {number} height
  42747. */
  42748. transformTo: function (x, y, width, height) {
  42749. var rect = this.getBoundingRect();
  42750. var rawTransform = this._rawTransformable;
  42751. rawTransform.transform = rect.calculateTransform(
  42752. new BoundingRect(x, y, width, height)
  42753. );
  42754. rawTransform.decomposeTransform();
  42755. this._updateTransform();
  42756. },
  42757. /**
  42758. * Set center of view
  42759. * @param {Array.<number>} [centerCoord]
  42760. */
  42761. setCenter: function (centerCoord) {
  42762. if (!centerCoord) {
  42763. return;
  42764. }
  42765. this._center = centerCoord;
  42766. this._updateCenterAndZoom();
  42767. },
  42768. /**
  42769. * @param {number} zoom
  42770. */
  42771. setZoom: function (zoom) {
  42772. zoom = zoom || 1;
  42773. var zoomLimit = this.zoomLimit;
  42774. if (zoomLimit) {
  42775. if (zoomLimit.max != null) {
  42776. zoom = Math.min(zoomLimit.max, zoom);
  42777. }
  42778. if (zoomLimit.min != null) {
  42779. zoom = Math.max(zoomLimit.min, zoom);
  42780. }
  42781. }
  42782. this._zoom = zoom;
  42783. this._updateCenterAndZoom();
  42784. },
  42785. /**
  42786. * Get default center without roam
  42787. */
  42788. getDefaultCenter: function () {
  42789. // Rect before any transform
  42790. var rawRect = this.getBoundingRect();
  42791. var cx = rawRect.x + rawRect.width / 2;
  42792. var cy = rawRect.y + rawRect.height / 2;
  42793. return [cx, cy];
  42794. },
  42795. getCenter: function () {
  42796. return this._center || this.getDefaultCenter();
  42797. },
  42798. getZoom: function () {
  42799. return this._zoom || 1;
  42800. },
  42801. /**
  42802. * @return {Array.<number}
  42803. */
  42804. getRoamTransform: function () {
  42805. return this._roamTransformable.getLocalTransform();
  42806. },
  42807. /**
  42808. * Remove roam
  42809. */
  42810. _updateCenterAndZoom: function () {
  42811. // Must update after view transform updated
  42812. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  42813. var roamTransform = this._roamTransformable;
  42814. var defaultCenter = this.getDefaultCenter();
  42815. var center = this.getCenter();
  42816. var zoom = this.getZoom();
  42817. center = applyTransform([], center, rawTransformMatrix);
  42818. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  42819. roamTransform.origin = center;
  42820. roamTransform.position = [
  42821. defaultCenter[0] - center[0],
  42822. defaultCenter[1] - center[1]
  42823. ];
  42824. roamTransform.scale = [zoom, zoom];
  42825. this._updateTransform();
  42826. },
  42827. /**
  42828. * Update transform from roam and mapLocation
  42829. * @private
  42830. */
  42831. _updateTransform: function () {
  42832. var roamTransformable = this._roamTransformable;
  42833. var rawTransformable = this._rawTransformable;
  42834. rawTransformable.parent = roamTransformable;
  42835. roamTransformable.updateTransform();
  42836. rawTransformable.updateTransform();
  42837. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  42838. this._rawTransform = rawTransformable.getLocalTransform();
  42839. this.invTransform = this.invTransform || [];
  42840. invert(this.invTransform, this.transform);
  42841. this.decomposeTransform();
  42842. },
  42843. /**
  42844. * @return {module:zrender/core/BoundingRect}
  42845. */
  42846. getViewRect: function () {
  42847. return this._viewRect;
  42848. },
  42849. /**
  42850. * Get view rect after roam transform
  42851. * @return {module:zrender/core/BoundingRect}
  42852. */
  42853. getViewRectAfterRoam: function () {
  42854. var rect = this.getBoundingRect().clone();
  42855. rect.applyTransform(this.transform);
  42856. return rect;
  42857. },
  42858. /**
  42859. * Convert a single (lon, lat) data item to (x, y) point.
  42860. * @param {Array.<number>} data
  42861. * @param {boolean} noRoam
  42862. * @param {Array.<number>} [out]
  42863. * @return {Array.<number>}
  42864. */
  42865. dataToPoint: function (data, noRoam, out) {
  42866. var transform = noRoam ? this._rawTransform : this.transform;
  42867. out = out || [];
  42868. return transform
  42869. ? v2ApplyTransform$1(out, data, transform)
  42870. : copy(out, data);
  42871. },
  42872. /**
  42873. * Convert a (x, y) point to (lon, lat) data
  42874. * @param {Array.<number>} point
  42875. * @return {Array.<number>}
  42876. */
  42877. pointToData: function (point) {
  42878. var invTransform = this.invTransform;
  42879. return invTransform
  42880. ? v2ApplyTransform$1([], point, invTransform)
  42881. : [point[0], point[1]];
  42882. },
  42883. /**
  42884. * @implements
  42885. * see {module:echarts/CoodinateSystem}
  42886. */
  42887. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  42888. /**
  42889. * @implements
  42890. * see {module:echarts/CoodinateSystem}
  42891. */
  42892. convertFromPixel: curry(doConvert$1, 'pointToData'),
  42893. /**
  42894. * @implements
  42895. * see {module:echarts/CoodinateSystem}
  42896. */
  42897. containPoint: function (point) {
  42898. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  42899. }
  42900. /**
  42901. * @return {number}
  42902. */
  42903. // getScalarScale: function () {
  42904. // // Use determinant square root of transform to mutiply scalar
  42905. // var m = this.transform;
  42906. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  42907. // return det;
  42908. // }
  42909. };
  42910. mixin(View, Transformable);
  42911. function doConvert$1(methodName, ecModel, finder, value) {
  42912. var seriesModel = finder.seriesModel;
  42913. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  42914. return coordSys === this ? coordSys[methodName](value) : null;
  42915. }
  42916. /*
  42917. * Licensed to the Apache Software Foundation (ASF) under one
  42918. * or more contributor license agreements. See the NOTICE file
  42919. * distributed with this work for additional information
  42920. * regarding copyright ownership. The ASF licenses this file
  42921. * to you under the Apache License, Version 2.0 (the
  42922. * "License"); you may not use this file except in compliance
  42923. * with the License. You may obtain a copy of the License at
  42924. *
  42925. * http://www.apache.org/licenses/LICENSE-2.0
  42926. *
  42927. * Unless required by applicable law or agreed to in writing,
  42928. * software distributed under the License is distributed on an
  42929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42930. * KIND, either express or implied. See the License for the
  42931. * specific language governing permissions and limitations
  42932. * under the License.
  42933. */
  42934. /**
  42935. * [Geo description]
  42936. * For backward compatibility, the orginal interface:
  42937. * `name, map, geoJson, specialAreas, nameMap` is kept.
  42938. *
  42939. * @param {string|Object} name
  42940. * @param {string} map Map type
  42941. * Specify the positioned areas by left, top, width, height
  42942. * @param {Object.<string, string>} [nameMap]
  42943. * Specify name alias
  42944. * @param {boolean} [invertLongitute=true]
  42945. */
  42946. function Geo(name, map$$1, nameMap, invertLongitute) {
  42947. View.call(this, name);
  42948. /**
  42949. * Map type
  42950. * @type {string}
  42951. */
  42952. this.map = map$$1;
  42953. var source = geoSourceManager.load(map$$1, nameMap);
  42954. this._nameCoordMap = source.nameCoordMap;
  42955. this._regionsMap = source.regionsMap;
  42956. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  42957. /**
  42958. * @readOnly
  42959. */
  42960. this.regions = source.regions;
  42961. /**
  42962. * @type {module:zrender/src/core/BoundingRect}
  42963. */
  42964. this._rect = source.boundingRect;
  42965. }
  42966. Geo.prototype = {
  42967. constructor: Geo,
  42968. type: 'geo',
  42969. /**
  42970. * @param {Array.<string>}
  42971. * @readOnly
  42972. */
  42973. dimensions: ['lng', 'lat'],
  42974. /**
  42975. * If contain given lng,lat coord
  42976. * @param {Array.<number>}
  42977. * @readOnly
  42978. */
  42979. containCoord: function (coord) {
  42980. var regions = this.regions;
  42981. for (var i = 0; i < regions.length; i++) {
  42982. if (regions[i].contain(coord)) {
  42983. return true;
  42984. }
  42985. }
  42986. return false;
  42987. },
  42988. /**
  42989. * @override
  42990. */
  42991. transformTo: function (x, y, width, height) {
  42992. var rect = this.getBoundingRect();
  42993. var invertLongitute = this._invertLongitute;
  42994. rect = rect.clone();
  42995. if (invertLongitute) {
  42996. // Longitute is inverted
  42997. rect.y = -rect.y - rect.height;
  42998. }
  42999. var rawTransformable = this._rawTransformable;
  43000. rawTransformable.transform = rect.calculateTransform(
  43001. new BoundingRect(x, y, width, height)
  43002. );
  43003. rawTransformable.decomposeTransform();
  43004. if (invertLongitute) {
  43005. var scale = rawTransformable.scale;
  43006. scale[1] = -scale[1];
  43007. }
  43008. rawTransformable.updateTransform();
  43009. this._updateTransform();
  43010. },
  43011. /**
  43012. * @param {string} name
  43013. * @return {module:echarts/coord/geo/Region}
  43014. */
  43015. getRegion: function (name) {
  43016. return this._regionsMap.get(name);
  43017. },
  43018. getRegionByCoord: function (coord) {
  43019. var regions = this.regions;
  43020. for (var i = 0; i < regions.length; i++) {
  43021. if (regions[i].contain(coord)) {
  43022. return regions[i];
  43023. }
  43024. }
  43025. },
  43026. /**
  43027. * Add geoCoord for indexing by name
  43028. * @param {string} name
  43029. * @param {Array.<number>} geoCoord
  43030. */
  43031. addGeoCoord: function (name, geoCoord) {
  43032. this._nameCoordMap.set(name, geoCoord);
  43033. },
  43034. /**
  43035. * Get geoCoord by name
  43036. * @param {string} name
  43037. * @return {Array.<number>}
  43038. */
  43039. getGeoCoord: function (name) {
  43040. return this._nameCoordMap.get(name);
  43041. },
  43042. /**
  43043. * @override
  43044. */
  43045. getBoundingRect: function () {
  43046. return this._rect;
  43047. },
  43048. /**
  43049. * @param {string|Array.<number>} data
  43050. * @param {boolean} noRoam
  43051. * @param {Array.<number>} [out]
  43052. * @return {Array.<number>}
  43053. */
  43054. dataToPoint: function (data, noRoam, out) {
  43055. if (typeof data === 'string') {
  43056. // Map area name to geoCoord
  43057. data = this.getGeoCoord(data);
  43058. }
  43059. if (data) {
  43060. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  43061. }
  43062. },
  43063. /**
  43064. * @override
  43065. */
  43066. convertToPixel: curry(doConvert, 'dataToPoint'),
  43067. /**
  43068. * @override
  43069. */
  43070. convertFromPixel: curry(doConvert, 'pointToData')
  43071. };
  43072. mixin(Geo, View);
  43073. function doConvert(methodName, ecModel, finder, value) {
  43074. var geoModel = finder.geoModel;
  43075. var seriesModel = finder.seriesModel;
  43076. var coordSys = geoModel
  43077. ? geoModel.coordinateSystem
  43078. : seriesModel
  43079. ? (
  43080. seriesModel.coordinateSystem // For map.
  43081. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  43082. )
  43083. : null;
  43084. return coordSys === this ? coordSys[methodName](value) : null;
  43085. }
  43086. /*
  43087. * Licensed to the Apache Software Foundation (ASF) under one
  43088. * or more contributor license agreements. See the NOTICE file
  43089. * distributed with this work for additional information
  43090. * regarding copyright ownership. The ASF licenses this file
  43091. * to you under the Apache License, Version 2.0 (the
  43092. * "License"); you may not use this file except in compliance
  43093. * with the License. You may obtain a copy of the License at
  43094. *
  43095. * http://www.apache.org/licenses/LICENSE-2.0
  43096. *
  43097. * Unless required by applicable law or agreed to in writing,
  43098. * software distributed under the License is distributed on an
  43099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43100. * KIND, either express or implied. See the License for the
  43101. * specific language governing permissions and limitations
  43102. * under the License.
  43103. */
  43104. /**
  43105. * Resize method bound to the geo
  43106. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  43107. * @param {module:echarts/ExtensionAPI} api
  43108. */
  43109. function resizeGeo(geoModel, api) {
  43110. var boundingCoords = geoModel.get('boundingCoords');
  43111. if (boundingCoords != null) {
  43112. var leftTop = boundingCoords[0];
  43113. var rightBottom = boundingCoords[1];
  43114. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  43115. if (__DEV__) {
  43116. console.error('Invalid boundingCoords');
  43117. }
  43118. }
  43119. else {
  43120. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  43121. }
  43122. }
  43123. var rect = this.getBoundingRect();
  43124. var boxLayoutOption;
  43125. var center = geoModel.get('layoutCenter');
  43126. var size = geoModel.get('layoutSize');
  43127. var viewWidth = api.getWidth();
  43128. var viewHeight = api.getHeight();
  43129. var aspect = rect.width / rect.height * this.aspectScale;
  43130. var useCenterAndSize = false;
  43131. if (center && size) {
  43132. center = [
  43133. parsePercent$1(center[0], viewWidth),
  43134. parsePercent$1(center[1], viewHeight)
  43135. ];
  43136. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  43137. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  43138. useCenterAndSize = true;
  43139. }
  43140. else {
  43141. if (__DEV__) {
  43142. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  43143. }
  43144. }
  43145. }
  43146. var viewRect;
  43147. if (useCenterAndSize) {
  43148. var viewRect = {};
  43149. if (aspect > 1) {
  43150. // Width is same with size
  43151. viewRect.width = size;
  43152. viewRect.height = size / aspect;
  43153. }
  43154. else {
  43155. viewRect.height = size;
  43156. viewRect.width = size * aspect;
  43157. }
  43158. viewRect.y = center[1] - viewRect.height / 2;
  43159. viewRect.x = center[0] - viewRect.width / 2;
  43160. }
  43161. else {
  43162. // Use left/top/width/height
  43163. boxLayoutOption = geoModel.getBoxLayoutParams();
  43164. // 0.75 rate
  43165. boxLayoutOption.aspect = aspect;
  43166. viewRect = getLayoutRect(boxLayoutOption, {
  43167. width: viewWidth,
  43168. height: viewHeight
  43169. });
  43170. }
  43171. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  43172. this.setCenter(geoModel.get('center'));
  43173. this.setZoom(geoModel.get('zoom'));
  43174. }
  43175. /**
  43176. * @param {module:echarts/coord/Geo} geo
  43177. * @param {module:echarts/model/Model} model
  43178. * @inner
  43179. */
  43180. function setGeoCoords(geo, model) {
  43181. each$1(model.get('geoCoord'), function (geoCoord, name) {
  43182. geo.addGeoCoord(name, geoCoord);
  43183. });
  43184. }
  43185. var geoCreator = {
  43186. // For deciding which dimensions to use when creating list data
  43187. dimensions: Geo.prototype.dimensions,
  43188. create: function (ecModel, api) {
  43189. var geoList = [];
  43190. // FIXME Create each time may be slow
  43191. ecModel.eachComponent('geo', function (geoModel, idx) {
  43192. var name = geoModel.get('map');
  43193. var aspectScale = geoModel.get('aspectScale');
  43194. var invertLongitute = true;
  43195. var mapRecords = mapDataStorage.retrieveMap(name);
  43196. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  43197. aspectScale == null && (aspectScale = 1);
  43198. invertLongitute = false;
  43199. }
  43200. else {
  43201. aspectScale == null && (aspectScale = 0.75);
  43202. }
  43203. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  43204. geo.aspectScale = aspectScale;
  43205. geo.zoomLimit = geoModel.get('scaleLimit');
  43206. geoList.push(geo);
  43207. setGeoCoords(geo, geoModel);
  43208. geoModel.coordinateSystem = geo;
  43209. geo.model = geoModel;
  43210. // Inject resize method
  43211. geo.resize = resizeGeo;
  43212. geo.resize(geoModel, api);
  43213. });
  43214. ecModel.eachSeries(function (seriesModel) {
  43215. var coordSys = seriesModel.get('coordinateSystem');
  43216. if (coordSys === 'geo') {
  43217. var geoIndex = seriesModel.get('geoIndex') || 0;
  43218. seriesModel.coordinateSystem = geoList[geoIndex];
  43219. }
  43220. });
  43221. // If has map series
  43222. var mapModelGroupBySeries = {};
  43223. ecModel.eachSeriesByType('map', function (seriesModel) {
  43224. if (!seriesModel.getHostGeoModel()) {
  43225. var mapType = seriesModel.getMapType();
  43226. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  43227. mapModelGroupBySeries[mapType].push(seriesModel);
  43228. }
  43229. });
  43230. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  43231. var nameMapList = map(mapSeries, function (singleMapSeries) {
  43232. return singleMapSeries.get('nameMap');
  43233. });
  43234. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  43235. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  43236. return singleMapSeries.get('scaleLimit');
  43237. }));
  43238. geoList.push(geo);
  43239. // Inject resize method
  43240. geo.resize = resizeGeo;
  43241. geo.aspectScale = mapSeries[0].get('aspectScale');
  43242. geo.resize(mapSeries[0], api);
  43243. each$1(mapSeries, function (singleMapSeries) {
  43244. singleMapSeries.coordinateSystem = geo;
  43245. setGeoCoords(geo, singleMapSeries);
  43246. });
  43247. });
  43248. return geoList;
  43249. },
  43250. /**
  43251. * Fill given regions array
  43252. * @param {Array.<Object>} originRegionArr
  43253. * @param {string} mapName
  43254. * @param {Object} [nameMap]
  43255. * @return {Array}
  43256. */
  43257. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  43258. // Not use the original
  43259. var regionsArr = (originRegionArr || []).slice();
  43260. var dataNameMap = createHashMap();
  43261. for (var i = 0; i < regionsArr.length; i++) {
  43262. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  43263. }
  43264. var source = geoSourceManager.load(mapName, nameMap);
  43265. each$1(source.regions, function (region) {
  43266. var name = region.name;
  43267. !dataNameMap.get(name) && regionsArr.push({name: name});
  43268. });
  43269. return regionsArr;
  43270. }
  43271. };
  43272. registerCoordinateSystem('geo', geoCreator);
  43273. /*
  43274. * Licensed to the Apache Software Foundation (ASF) under one
  43275. * or more contributor license agreements. See the NOTICE file
  43276. * distributed with this work for additional information
  43277. * regarding copyright ownership. The ASF licenses this file
  43278. * to you under the Apache License, Version 2.0 (the
  43279. * "License"); you may not use this file except in compliance
  43280. * with the License. You may obtain a copy of the License at
  43281. *
  43282. * http://www.apache.org/licenses/LICENSE-2.0
  43283. *
  43284. * Unless required by applicable law or agreed to in writing,
  43285. * software distributed under the License is distributed on an
  43286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43287. * KIND, either express or implied. See the License for the
  43288. * specific language governing permissions and limitations
  43289. * under the License.
  43290. */
  43291. var mapSymbolLayout = function (ecModel) {
  43292. var processedMapType = {};
  43293. ecModel.eachSeriesByType('map', function (mapSeries) {
  43294. var mapType = mapSeries.getMapType();
  43295. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  43296. return;
  43297. }
  43298. var mapSymbolOffsets = {};
  43299. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  43300. var geo = subMapSeries.coordinateSystem;
  43301. var data = subMapSeries.originalData;
  43302. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  43303. data.each(data.mapDimension('value'), function (value, idx) {
  43304. var name = data.getName(idx);
  43305. var region = geo.getRegion(name);
  43306. // If input series.data is [11, 22, '-'/null/undefined, 44],
  43307. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  43308. // not be drawn. So here must validate if value is NaN.
  43309. if (!region || isNaN(value)) {
  43310. return;
  43311. }
  43312. var offset = mapSymbolOffsets[name] || 0;
  43313. var point = geo.dataToPoint(region.center);
  43314. mapSymbolOffsets[name] = offset + 1;
  43315. data.setItemLayout(idx, {
  43316. point: point,
  43317. offset: offset
  43318. });
  43319. });
  43320. }
  43321. });
  43322. // Show label of those region not has legendSymbol(which is offset 0)
  43323. var data = mapSeries.getData();
  43324. data.each(function (idx) {
  43325. var name = data.getName(idx);
  43326. var layout = data.getItemLayout(idx) || {};
  43327. layout.showLabel = !mapSymbolOffsets[name];
  43328. data.setItemLayout(idx, layout);
  43329. });
  43330. processedMapType[mapType] = true;
  43331. });
  43332. };
  43333. /*
  43334. * Licensed to the Apache Software Foundation (ASF) under one
  43335. * or more contributor license agreements. See the NOTICE file
  43336. * distributed with this work for additional information
  43337. * regarding copyright ownership. The ASF licenses this file
  43338. * to you under the Apache License, Version 2.0 (the
  43339. * "License"); you may not use this file except in compliance
  43340. * with the License. You may obtain a copy of the License at
  43341. *
  43342. * http://www.apache.org/licenses/LICENSE-2.0
  43343. *
  43344. * Unless required by applicable law or agreed to in writing,
  43345. * software distributed under the License is distributed on an
  43346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43347. * KIND, either express or implied. See the License for the
  43348. * specific language governing permissions and limitations
  43349. * under the License.
  43350. */
  43351. var mapVisual = function (ecModel) {
  43352. ecModel.eachSeriesByType('map', function (seriesModel) {
  43353. var colorList = seriesModel.get('color');
  43354. var itemStyleModel = seriesModel.getModel('itemStyle');
  43355. var areaColor = itemStyleModel.get('areaColor');
  43356. var color = itemStyleModel.get('color')
  43357. || colorList[seriesModel.seriesIndex % colorList.length];
  43358. seriesModel.getData().setVisual({
  43359. 'areaColor': areaColor,
  43360. 'color': color
  43361. });
  43362. });
  43363. };
  43364. /*
  43365. * Licensed to the Apache Software Foundation (ASF) under one
  43366. * or more contributor license agreements. See the NOTICE file
  43367. * distributed with this work for additional information
  43368. * regarding copyright ownership. The ASF licenses this file
  43369. * to you under the Apache License, Version 2.0 (the
  43370. * "License"); you may not use this file except in compliance
  43371. * with the License. You may obtain a copy of the License at
  43372. *
  43373. * http://www.apache.org/licenses/LICENSE-2.0
  43374. *
  43375. * Unless required by applicable law or agreed to in writing,
  43376. * software distributed under the License is distributed on an
  43377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43378. * KIND, either express or implied. See the License for the
  43379. * specific language governing permissions and limitations
  43380. * under the License.
  43381. */
  43382. // FIXME 公用?
  43383. /**
  43384. * @param {Array.<module:echarts/data/List>} datas
  43385. * @param {string} statisticType 'average' 'sum'
  43386. * @inner
  43387. */
  43388. function dataStatistics(datas, statisticType) {
  43389. var dataNameMap = {};
  43390. each$1(datas, function (data) {
  43391. data.each(data.mapDimension('value'), function (value, idx) {
  43392. // Add prefix to avoid conflict with Object.prototype.
  43393. var mapKey = 'ec-' + data.getName(idx);
  43394. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  43395. if (!isNaN(value)) {
  43396. dataNameMap[mapKey].push(value);
  43397. }
  43398. });
  43399. });
  43400. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  43401. var mapKey = 'ec-' + datas[0].getName(idx);
  43402. var sum = 0;
  43403. var min = Infinity;
  43404. var max = -Infinity;
  43405. var len = dataNameMap[mapKey].length;
  43406. for (var i = 0; i < len; i++) {
  43407. min = Math.min(min, dataNameMap[mapKey][i]);
  43408. max = Math.max(max, dataNameMap[mapKey][i]);
  43409. sum += dataNameMap[mapKey][i];
  43410. }
  43411. var result;
  43412. if (statisticType === 'min') {
  43413. result = min;
  43414. }
  43415. else if (statisticType === 'max') {
  43416. result = max;
  43417. }
  43418. else if (statisticType === 'average') {
  43419. result = sum / len;
  43420. }
  43421. else {
  43422. result = sum;
  43423. }
  43424. return len === 0 ? NaN : result;
  43425. });
  43426. }
  43427. var mapDataStatistic = function (ecModel) {
  43428. var seriesGroups = {};
  43429. ecModel.eachSeriesByType('map', function (seriesModel) {
  43430. var hostGeoModel = seriesModel.getHostGeoModel();
  43431. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  43432. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  43433. });
  43434. each$1(seriesGroups, function (seriesList, key) {
  43435. var data = dataStatistics(
  43436. map(seriesList, function (seriesModel) {
  43437. return seriesModel.getData();
  43438. }),
  43439. seriesList[0].get('mapValueCalculation')
  43440. );
  43441. for (var i = 0; i < seriesList.length; i++) {
  43442. seriesList[i].originalData = seriesList[i].getData();
  43443. }
  43444. // FIXME Put where?
  43445. for (var i = 0; i < seriesList.length; i++) {
  43446. seriesList[i].seriesGroup = seriesList;
  43447. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  43448. seriesList[i].setData(data.cloneShallow());
  43449. seriesList[i].mainSeries = seriesList[0];
  43450. }
  43451. });
  43452. };
  43453. /*
  43454. * Licensed to the Apache Software Foundation (ASF) under one
  43455. * or more contributor license agreements. See the NOTICE file
  43456. * distributed with this work for additional information
  43457. * regarding copyright ownership. The ASF licenses this file
  43458. * to you under the Apache License, Version 2.0 (the
  43459. * "License"); you may not use this file except in compliance
  43460. * with the License. You may obtain a copy of the License at
  43461. *
  43462. * http://www.apache.org/licenses/LICENSE-2.0
  43463. *
  43464. * Unless required by applicable law or agreed to in writing,
  43465. * software distributed under the License is distributed on an
  43466. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43467. * KIND, either express or implied. See the License for the
  43468. * specific language governing permissions and limitations
  43469. * under the License.
  43470. */
  43471. var backwardCompat$2 = function (option) {
  43472. // Save geoCoord
  43473. var mapSeries = [];
  43474. each$1(option.series, function (seriesOpt) {
  43475. if (seriesOpt && seriesOpt.type === 'map') {
  43476. mapSeries.push(seriesOpt);
  43477. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  43478. // Put x, y, width, height, x2, y2 in the top level
  43479. defaults(seriesOpt, seriesOpt.mapLocation);
  43480. }
  43481. });
  43482. };
  43483. /*
  43484. * Licensed to the Apache Software Foundation (ASF) under one
  43485. * or more contributor license agreements. See the NOTICE file
  43486. * distributed with this work for additional information
  43487. * regarding copyright ownership. The ASF licenses this file
  43488. * to you under the Apache License, Version 2.0 (the
  43489. * "License"); you may not use this file except in compliance
  43490. * with the License. You may obtain a copy of the License at
  43491. *
  43492. * http://www.apache.org/licenses/LICENSE-2.0
  43493. *
  43494. * Unless required by applicable law or agreed to in writing,
  43495. * software distributed under the License is distributed on an
  43496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43497. * KIND, either express or implied. See the License for the
  43498. * specific language governing permissions and limitations
  43499. * under the License.
  43500. */
  43501. registerLayout(mapSymbolLayout);
  43502. registerVisual(mapVisual);
  43503. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  43504. registerPreprocessor(backwardCompat$2);
  43505. createDataSelectAction('map', [{
  43506. type: 'mapToggleSelect',
  43507. event: 'mapselectchanged',
  43508. method: 'toggleSelected'
  43509. }, {
  43510. type: 'mapSelect',
  43511. event: 'mapselected',
  43512. method: 'select'
  43513. }, {
  43514. type: 'mapUnSelect',
  43515. event: 'mapunselected',
  43516. method: 'unSelect'
  43517. }]);
  43518. /*
  43519. * Licensed to the Apache Software Foundation (ASF) under one
  43520. * or more contributor license agreements. See the NOTICE file
  43521. * distributed with this work for additional information
  43522. * regarding copyright ownership. The ASF licenses this file
  43523. * to you under the Apache License, Version 2.0 (the
  43524. * "License"); you may not use this file except in compliance
  43525. * with the License. You may obtain a copy of the License at
  43526. *
  43527. * http://www.apache.org/licenses/LICENSE-2.0
  43528. *
  43529. * Unless required by applicable law or agreed to in writing,
  43530. * software distributed under the License is distributed on an
  43531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43532. * KIND, either express or implied. See the License for the
  43533. * specific language governing permissions and limitations
  43534. * under the License.
  43535. */
  43536. /**
  43537. * Link lists and struct (graph or tree)
  43538. */
  43539. var each$7 = each$1;
  43540. var DATAS = '\0__link_datas';
  43541. var MAIN_DATA = '\0__link_mainData';
  43542. // Caution:
  43543. // In most case, either list or its shallow clones (see list.cloneShallow)
  43544. // is active in echarts process. So considering heap memory consumption,
  43545. // we do not clone tree or graph, but share them among list and its shallow clones.
  43546. // But in some rare case, we have to keep old list (like do animation in chart). So
  43547. // please take care that both the old list and the new list share the same tree/graph.
  43548. /**
  43549. * @param {Object} opt
  43550. * @param {module:echarts/data/List} opt.mainData
  43551. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  43552. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  43553. * @param {Object} [opt.datas] {dataType: data},
  43554. * like: {node: nodeList, edge: edgeList}.
  43555. * Should contain mainData.
  43556. * @param {Object} [opt.datasAttr] {dataType: attr},
  43557. * designation: struct[datasAttr[dataType]] = list;
  43558. */
  43559. function linkList(opt) {
  43560. var mainData = opt.mainData;
  43561. var datas = opt.datas;
  43562. if (!datas) {
  43563. datas = {main: mainData};
  43564. opt.datasAttr = {main: 'data'};
  43565. }
  43566. opt.datas = opt.mainData = null;
  43567. linkAll(mainData, datas, opt);
  43568. // Porxy data original methods.
  43569. each$7(datas, function (data) {
  43570. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  43571. data.wrapMethod(methodName, curry(transferInjection, opt));
  43572. });
  43573. });
  43574. // Beyond transfer, additional features should be added to `cloneShallow`.
  43575. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  43576. // Only mainData trigger change, because struct.update may trigger
  43577. // another changable methods, which may bring about dead lock.
  43578. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  43579. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  43580. });
  43581. // Make sure datas contains mainData.
  43582. assert$1(datas[mainData.dataType] === mainData);
  43583. }
  43584. function transferInjection(opt, res) {
  43585. if (isMainData(this)) {
  43586. // Transfer datas to new main data.
  43587. var datas = extend({}, this[DATAS]);
  43588. datas[this.dataType] = res;
  43589. linkAll(res, datas, opt);
  43590. }
  43591. else {
  43592. // Modify the reference in main data to point newData.
  43593. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  43594. }
  43595. return res;
  43596. }
  43597. function changeInjection(opt, res) {
  43598. opt.struct && opt.struct.update(this);
  43599. return res;
  43600. }
  43601. function cloneShallowInjection(opt, res) {
  43602. // cloneShallow, which brings about some fragilities, may be inappropriate
  43603. // to be exposed as an API. So for implementation simplicity we can make
  43604. // the restriction that cloneShallow of not-mainData should not be invoked
  43605. // outside, but only be invoked here.
  43606. each$7(res[DATAS], function (data, dataType) {
  43607. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  43608. });
  43609. return res;
  43610. }
  43611. /**
  43612. * Supplement method to List.
  43613. *
  43614. * @public
  43615. * @param {string} [dataType] If not specified, return mainData.
  43616. * @return {module:echarts/data/List}
  43617. */
  43618. function getLinkedData(dataType) {
  43619. var mainData = this[MAIN_DATA];
  43620. return (dataType == null || mainData == null)
  43621. ? mainData
  43622. : mainData[DATAS][dataType];
  43623. }
  43624. function isMainData(data) {
  43625. return data[MAIN_DATA] === data;
  43626. }
  43627. function linkAll(mainData, datas, opt) {
  43628. mainData[DATAS] = {};
  43629. each$7(datas, function (data, dataType) {
  43630. linkSingle(data, dataType, mainData, opt);
  43631. });
  43632. }
  43633. function linkSingle(data, dataType, mainData, opt) {
  43634. mainData[DATAS][dataType] = data;
  43635. data[MAIN_DATA] = mainData;
  43636. data.dataType = dataType;
  43637. if (opt.struct) {
  43638. data[opt.structAttr] = opt.struct;
  43639. opt.struct[opt.datasAttr[dataType]] = data;
  43640. }
  43641. // Supplement method.
  43642. data.getLinkedData = getLinkedData;
  43643. }
  43644. /*
  43645. * Licensed to the Apache Software Foundation (ASF) under one
  43646. * or more contributor license agreements. See the NOTICE file
  43647. * distributed with this work for additional information
  43648. * regarding copyright ownership. The ASF licenses this file
  43649. * to you under the Apache License, Version 2.0 (the
  43650. * "License"); you may not use this file except in compliance
  43651. * with the License. You may obtain a copy of the License at
  43652. *
  43653. * http://www.apache.org/licenses/LICENSE-2.0
  43654. *
  43655. * Unless required by applicable law or agreed to in writing,
  43656. * software distributed under the License is distributed on an
  43657. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43658. * KIND, either express or implied. See the License for the
  43659. * specific language governing permissions and limitations
  43660. * under the License.
  43661. */
  43662. /**
  43663. * Tree data structure
  43664. *
  43665. * @module echarts/data/Tree
  43666. */
  43667. /**
  43668. * @constructor module:echarts/data/Tree~TreeNode
  43669. * @param {string} name
  43670. * @param {module:echarts/data/Tree} hostTree
  43671. */
  43672. var TreeNode = function (name, hostTree) {
  43673. /**
  43674. * @type {string}
  43675. */
  43676. this.name = name || '';
  43677. /**
  43678. * Depth of node
  43679. *
  43680. * @type {number}
  43681. * @readOnly
  43682. */
  43683. this.depth = 0;
  43684. /**
  43685. * Height of the subtree rooted at this node.
  43686. * @type {number}
  43687. * @readOnly
  43688. */
  43689. this.height = 0;
  43690. /**
  43691. * @type {module:echarts/data/Tree~TreeNode}
  43692. * @readOnly
  43693. */
  43694. this.parentNode = null;
  43695. /**
  43696. * Reference to list item.
  43697. * Do not persistent dataIndex outside,
  43698. * besause it may be changed by list.
  43699. * If dataIndex -1,
  43700. * this node is logical deleted (filtered) in list.
  43701. *
  43702. * @type {Object}
  43703. * @readOnly
  43704. */
  43705. this.dataIndex = -1;
  43706. /**
  43707. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  43708. * @readOnly
  43709. */
  43710. this.children = [];
  43711. /**
  43712. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  43713. * @pubilc
  43714. */
  43715. this.viewChildren = [];
  43716. /**
  43717. * @type {moduel:echarts/data/Tree}
  43718. * @readOnly
  43719. */
  43720. this.hostTree = hostTree;
  43721. };
  43722. TreeNode.prototype = {
  43723. constructor: TreeNode,
  43724. /**
  43725. * The node is removed.
  43726. * @return {boolean} is removed.
  43727. */
  43728. isRemoved: function () {
  43729. return this.dataIndex < 0;
  43730. },
  43731. /**
  43732. * Travel this subtree (include this node).
  43733. * Usage:
  43734. * node.eachNode(function () { ... }); // preorder
  43735. * node.eachNode('preorder', function () { ... }); // preorder
  43736. * node.eachNode('postorder', function () { ... }); // postorder
  43737. * node.eachNode(
  43738. * {order: 'postorder', attr: 'viewChildren'},
  43739. * function () { ... }
  43740. * ); // postorder
  43741. *
  43742. * @param {(Object|string)} options If string, means order.
  43743. * @param {string=} options.order 'preorder' or 'postorder'
  43744. * @param {string=} options.attr 'children' or 'viewChildren'
  43745. * @param {Function} cb If in preorder and return false,
  43746. * its subtree will not be visited.
  43747. * @param {Object} [context]
  43748. */
  43749. eachNode: function (options, cb, context) {
  43750. if (typeof options === 'function') {
  43751. context = cb;
  43752. cb = options;
  43753. options = null;
  43754. }
  43755. options = options || {};
  43756. if (isString(options)) {
  43757. options = {order: options};
  43758. }
  43759. var order = options.order || 'preorder';
  43760. var children = this[options.attr || 'children'];
  43761. var suppressVisitSub;
  43762. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  43763. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  43764. children[i].eachNode(options, cb, context);
  43765. }
  43766. order === 'postorder' && cb.call(context, this);
  43767. },
  43768. /**
  43769. * Update depth and height of this subtree.
  43770. *
  43771. * @param {number} depth
  43772. */
  43773. updateDepthAndHeight: function (depth) {
  43774. var height = 0;
  43775. this.depth = depth;
  43776. for (var i = 0; i < this.children.length; i++) {
  43777. var child = this.children[i];
  43778. child.updateDepthAndHeight(depth + 1);
  43779. if (child.height > height) {
  43780. height = child.height;
  43781. }
  43782. }
  43783. this.height = height + 1;
  43784. },
  43785. /**
  43786. * @param {string} id
  43787. * @return {module:echarts/data/Tree~TreeNode}
  43788. */
  43789. getNodeById: function (id) {
  43790. if (this.getId() === id) {
  43791. return this;
  43792. }
  43793. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  43794. var res = children[i].getNodeById(id);
  43795. if (res) {
  43796. return res;
  43797. }
  43798. }
  43799. },
  43800. /**
  43801. * @param {module:echarts/data/Tree~TreeNode} node
  43802. * @return {boolean}
  43803. */
  43804. contains: function (node) {
  43805. if (node === this) {
  43806. return true;
  43807. }
  43808. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  43809. var res = children[i].contains(node);
  43810. if (res) {
  43811. return res;
  43812. }
  43813. }
  43814. },
  43815. /**
  43816. * @param {boolean} includeSelf Default false.
  43817. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  43818. */
  43819. getAncestors: function (includeSelf) {
  43820. var ancestors = [];
  43821. var node = includeSelf ? this : this.parentNode;
  43822. while (node) {
  43823. ancestors.push(node);
  43824. node = node.parentNode;
  43825. }
  43826. ancestors.reverse();
  43827. return ancestors;
  43828. },
  43829. /**
  43830. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  43831. * @return {number} Value.
  43832. */
  43833. getValue: function (dimension) {
  43834. var data = this.hostTree.data;
  43835. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  43836. },
  43837. /**
  43838. * @param {Object} layout
  43839. * @param {boolean=} [merge=false]
  43840. */
  43841. setLayout: function (layout, merge$$1) {
  43842. this.dataIndex >= 0
  43843. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  43844. },
  43845. /**
  43846. * @return {Object} layout
  43847. */
  43848. getLayout: function () {
  43849. return this.hostTree.data.getItemLayout(this.dataIndex);
  43850. },
  43851. /**
  43852. * @param {string} [path]
  43853. * @return {module:echarts/model/Model}
  43854. */
  43855. getModel: function (path) {
  43856. if (this.dataIndex < 0) {
  43857. return;
  43858. }
  43859. var hostTree = this.hostTree;
  43860. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  43861. var levelModel = this.getLevelModel();
  43862. var leavesModel;
  43863. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  43864. leavesModel = this.getLeavesModel();
  43865. }
  43866. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  43867. },
  43868. /**
  43869. * @return {module:echarts/model/Model}
  43870. */
  43871. getLevelModel: function () {
  43872. return (this.hostTree.levelModels || [])[this.depth];
  43873. },
  43874. /**
  43875. * @return {module:echarts/model/Model}
  43876. */
  43877. getLeavesModel: function () {
  43878. return this.hostTree.leavesModel;
  43879. },
  43880. /**
  43881. * @example
  43882. * setItemVisual('color', color);
  43883. * setItemVisual({
  43884. * 'color': color
  43885. * });
  43886. */
  43887. setVisual: function (key, value) {
  43888. this.dataIndex >= 0
  43889. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  43890. },
  43891. /**
  43892. * Get item visual
  43893. */
  43894. getVisual: function (key, ignoreParent) {
  43895. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  43896. },
  43897. /**
  43898. * @public
  43899. * @return {number}
  43900. */
  43901. getRawIndex: function () {
  43902. return this.hostTree.data.getRawIndex(this.dataIndex);
  43903. },
  43904. /**
  43905. * @public
  43906. * @return {string}
  43907. */
  43908. getId: function () {
  43909. return this.hostTree.data.getId(this.dataIndex);
  43910. },
  43911. /**
  43912. * if this is an ancestor of another node
  43913. *
  43914. * @public
  43915. * @param {TreeNode} node another node
  43916. * @return {boolean} if is ancestor
  43917. */
  43918. isAncestorOf: function (node) {
  43919. var parent = node.parentNode;
  43920. while (parent) {
  43921. if (parent === this) {
  43922. return true;
  43923. }
  43924. parent = parent.parentNode;
  43925. }
  43926. return false;
  43927. },
  43928. /**
  43929. * if this is an descendant of another node
  43930. *
  43931. * @public
  43932. * @param {TreeNode} node another node
  43933. * @return {boolean} if is descendant
  43934. */
  43935. isDescendantOf: function (node) {
  43936. return node !== this && node.isAncestorOf(this);
  43937. }
  43938. };
  43939. /**
  43940. * @constructor
  43941. * @alias module:echarts/data/Tree
  43942. * @param {module:echarts/model/Model} hostModel
  43943. * @param {Array.<Object>} levelOptions
  43944. * @param {Object} leavesOption
  43945. */
  43946. function Tree(hostModel, levelOptions, leavesOption) {
  43947. /**
  43948. * @type {module:echarts/data/Tree~TreeNode}
  43949. * @readOnly
  43950. */
  43951. this.root;
  43952. /**
  43953. * @type {module:echarts/data/List}
  43954. * @readOnly
  43955. */
  43956. this.data;
  43957. /**
  43958. * Index of each item is the same as the raw index of coresponding list item.
  43959. * @private
  43960. * @type {Array.<module:echarts/data/Tree~TreeNode}
  43961. */
  43962. this._nodes = [];
  43963. /**
  43964. * @private
  43965. * @readOnly
  43966. * @type {module:echarts/model/Model}
  43967. */
  43968. this.hostModel = hostModel;
  43969. /**
  43970. * @private
  43971. * @readOnly
  43972. * @type {Array.<module:echarts/model/Model}
  43973. */
  43974. this.levelModels = map(levelOptions || [], function (levelDefine) {
  43975. return new Model(levelDefine, hostModel, hostModel.ecModel);
  43976. });
  43977. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  43978. }
  43979. Tree.prototype = {
  43980. constructor: Tree,
  43981. type: 'tree',
  43982. /**
  43983. * Travel this subtree (include this node).
  43984. * Usage:
  43985. * node.eachNode(function () { ... }); // preorder
  43986. * node.eachNode('preorder', function () { ... }); // preorder
  43987. * node.eachNode('postorder', function () { ... }); // postorder
  43988. * node.eachNode(
  43989. * {order: 'postorder', attr: 'viewChildren'},
  43990. * function () { ... }
  43991. * ); // postorder
  43992. *
  43993. * @param {(Object|string)} options If string, means order.
  43994. * @param {string=} options.order 'preorder' or 'postorder'
  43995. * @param {string=} options.attr 'children' or 'viewChildren'
  43996. * @param {Function} cb
  43997. * @param {Object} [context]
  43998. */
  43999. eachNode: function (options, cb, context) {
  44000. this.root.eachNode(options, cb, context);
  44001. },
  44002. /**
  44003. * @param {number} dataIndex
  44004. * @return {module:echarts/data/Tree~TreeNode}
  44005. */
  44006. getNodeByDataIndex: function (dataIndex) {
  44007. var rawIndex = this.data.getRawIndex(dataIndex);
  44008. return this._nodes[rawIndex];
  44009. },
  44010. /**
  44011. * @param {string} name
  44012. * @return {module:echarts/data/Tree~TreeNode}
  44013. */
  44014. getNodeByName: function (name) {
  44015. return this.root.getNodeByName(name);
  44016. },
  44017. /**
  44018. * Update item available by list,
  44019. * when list has been performed options like 'filterSelf' or 'map'.
  44020. */
  44021. update: function () {
  44022. var data = this.data;
  44023. var nodes = this._nodes;
  44024. for (var i = 0, len = nodes.length; i < len; i++) {
  44025. nodes[i].dataIndex = -1;
  44026. }
  44027. for (var i = 0, len = data.count(); i < len; i++) {
  44028. nodes[data.getRawIndex(i)].dataIndex = i;
  44029. }
  44030. },
  44031. /**
  44032. * Clear all layouts
  44033. */
  44034. clearLayouts: function () {
  44035. this.data.clearItemLayouts();
  44036. }
  44037. };
  44038. /**
  44039. * data node format:
  44040. * {
  44041. * name: ...
  44042. * value: ...
  44043. * children: [
  44044. * {
  44045. * name: ...
  44046. * value: ...
  44047. * children: ...
  44048. * },
  44049. * ...
  44050. * ]
  44051. * }
  44052. *
  44053. * @static
  44054. * @param {Object} dataRoot Root node.
  44055. * @param {module:echarts/model/Model} hostModel
  44056. * @param {Object} treeOptions
  44057. * @param {Array.<Object>} treeOptions.levels
  44058. * @param {Array.<Object>} treeOptions.leaves
  44059. * @return module:echarts/data/Tree
  44060. */
  44061. Tree.createTree = function (dataRoot, hostModel, treeOptions, beforeLink) {
  44062. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  44063. var listData = [];
  44064. var dimMax = 1;
  44065. buildHierarchy(dataRoot);
  44066. function buildHierarchy(dataNode, parentNode) {
  44067. var value = dataNode.value;
  44068. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  44069. listData.push(dataNode);
  44070. var node = new TreeNode(dataNode.name, tree);
  44071. parentNode
  44072. ? addChild(node, parentNode)
  44073. : (tree.root = node);
  44074. tree._nodes.push(node);
  44075. var children = dataNode.children;
  44076. if (children) {
  44077. for (var i = 0; i < children.length; i++) {
  44078. buildHierarchy(children[i], node);
  44079. }
  44080. }
  44081. }
  44082. tree.root.updateDepthAndHeight(0);
  44083. var dimensionsInfo = createDimensions(listData, {
  44084. coordDimensions: ['value'],
  44085. dimensionsCount: dimMax
  44086. });
  44087. var list = new List(dimensionsInfo, hostModel);
  44088. list.initData(listData);
  44089. linkList({
  44090. mainData: list,
  44091. struct: tree,
  44092. structAttr: 'tree'
  44093. });
  44094. tree.update();
  44095. beforeLink && beforeLink(list);
  44096. return tree;
  44097. };
  44098. /**
  44099. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  44100. * so this function is not ready and not necessary to be public.
  44101. *
  44102. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  44103. */
  44104. function addChild(child, node) {
  44105. var children = node.children;
  44106. if (child.parentNode === node) {
  44107. return;
  44108. }
  44109. children.push(child);
  44110. child.parentNode = node;
  44111. }
  44112. /*
  44113. * Licensed to the Apache Software Foundation (ASF) under one
  44114. * or more contributor license agreements. See the NOTICE file
  44115. * distributed with this work for additional information
  44116. * regarding copyright ownership. The ASF licenses this file
  44117. * to you under the Apache License, Version 2.0 (the
  44118. * "License"); you may not use this file except in compliance
  44119. * with the License. You may obtain a copy of the License at
  44120. *
  44121. * http://www.apache.org/licenses/LICENSE-2.0
  44122. *
  44123. * Unless required by applicable law or agreed to in writing,
  44124. * software distributed under the License is distributed on an
  44125. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44126. * KIND, either express or implied. See the License for the
  44127. * specific language governing permissions and limitations
  44128. * under the License.
  44129. */
  44130. SeriesModel.extend({
  44131. type: 'series.tree',
  44132. layoutInfo: null,
  44133. // can support the position parameters 'left', 'top','right','bottom', 'width',
  44134. // 'height' in the setOption() with 'merge' mode normal.
  44135. layoutMode: 'box',
  44136. /**
  44137. * Init a tree data structure from data in option series
  44138. * @param {Object} option the object used to config echarts view
  44139. * @return {module:echarts/data/List} storage initial data
  44140. */
  44141. getInitialData: function (option) {
  44142. //create an virtual root
  44143. var root = {name: option.name, children: option.data};
  44144. var leaves = option.leaves || {};
  44145. var treeOption = {};
  44146. treeOption.leaves = leaves;
  44147. var tree = Tree.createTree(root, this, treeOption, beforeLink);
  44148. function beforeLink(nodeData) {
  44149. nodeData.wrapMethod('getItemModel', function (model, idx) {
  44150. var node = tree.getNodeByDataIndex(idx);
  44151. var leavesModel = node.getLeavesModel();
  44152. if (!node.children.length || !node.isExpand) {
  44153. model.parentModel = leavesModel;
  44154. }
  44155. return model;
  44156. });
  44157. }
  44158. var treeDepth = 0;
  44159. tree.eachNode('preorder', function (node) {
  44160. if (node.depth > treeDepth) {
  44161. treeDepth = node.depth;
  44162. }
  44163. });
  44164. var expandAndCollapse = option.expandAndCollapse;
  44165. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  44166. ? option.initialTreeDepth : treeDepth;
  44167. tree.root.eachNode('preorder', function (node) {
  44168. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  44169. // Add item.collapsed != null, because users can collapse node original in the series.data.
  44170. node.isExpand = (item && item.collapsed != null)
  44171. ? !item.collapsed
  44172. : node.depth <= expandTreeDepth;
  44173. });
  44174. return tree.data;
  44175. },
  44176. /**
  44177. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  44178. * @returns {string} orient
  44179. */
  44180. getOrient: function () {
  44181. var orient = this.get('orient');
  44182. if (orient === 'horizontal') {
  44183. orient = 'LR';
  44184. }
  44185. else if (orient === 'vertical') {
  44186. orient = 'TB';
  44187. }
  44188. return orient;
  44189. },
  44190. setZoom: function (zoom) {
  44191. this.option.zoom = zoom;
  44192. },
  44193. setCenter: function (center) {
  44194. this.option.center = center;
  44195. },
  44196. /**
  44197. * @override
  44198. * @param {number} dataIndex
  44199. */
  44200. formatTooltip: function (dataIndex) {
  44201. var tree = this.getData().tree;
  44202. var realRoot = tree.root.children[0];
  44203. var node = tree.getNodeByDataIndex(dataIndex);
  44204. var value = node.getValue();
  44205. var name = node.name;
  44206. while (node && (node !== realRoot)) {
  44207. name = node.parentNode.name + '.' + name;
  44208. node = node.parentNode;
  44209. }
  44210. return encodeHTML(name + (
  44211. (isNaN(value) || value == null) ? '' : ' : ' + value
  44212. ));
  44213. },
  44214. defaultOption: {
  44215. zlevel: 0,
  44216. z: 2,
  44217. coordinateSystem: 'view',
  44218. // the position of the whole view
  44219. left: '12%',
  44220. top: '12%',
  44221. right: '12%',
  44222. bottom: '12%',
  44223. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  44224. layout: 'orthogonal',
  44225. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  44226. roam: false,
  44227. // Symbol size scale ratio in roam
  44228. nodeScaleRatio: 0.4,
  44229. // Default on center of graph
  44230. center: null,
  44231. zoom: 1,
  44232. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  44233. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  44234. orient: 'LR',
  44235. symbol: 'emptyCircle',
  44236. symbolSize: 7,
  44237. expandAndCollapse: true,
  44238. initialTreeDepth: 2,
  44239. lineStyle: {
  44240. color: '#ccc',
  44241. width: 1.5,
  44242. curveness: 0.5
  44243. },
  44244. itemStyle: {
  44245. color: 'lightsteelblue',
  44246. borderColor: '#c23531',
  44247. borderWidth: 1.5
  44248. },
  44249. label: {
  44250. show: true,
  44251. color: '#555'
  44252. },
  44253. leaves: {
  44254. label: {
  44255. show: true
  44256. }
  44257. },
  44258. animationEasing: 'linear',
  44259. animationDuration: 700,
  44260. animationDurationUpdate: 1000
  44261. }
  44262. });
  44263. /*
  44264. * Licensed to the Apache Software Foundation (ASF) under one
  44265. * or more contributor license agreements. See the NOTICE file
  44266. * distributed with this work for additional information
  44267. * regarding copyright ownership. The ASF licenses this file
  44268. * to you under the Apache License, Version 2.0 (the
  44269. * "License"); you may not use this file except in compliance
  44270. * with the License. You may obtain a copy of the License at
  44271. *
  44272. * http://www.apache.org/licenses/LICENSE-2.0
  44273. *
  44274. * Unless required by applicable law or agreed to in writing,
  44275. * software distributed under the License is distributed on an
  44276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44277. * KIND, either express or implied. See the License for the
  44278. * specific language governing permissions and limitations
  44279. * under the License.
  44280. */
  44281. /*
  44282. * A third-party license is embeded for some of the code in this file:
  44283. * The tree layoutHelper implementation was originally copied from
  44284. * "d3.js"(https://github.com/d3/d3-hierarchy) with
  44285. * some modifications made for this project.
  44286. * (see more details in the comment of the specific method below.)
  44287. * The use of the source code of this file is also subject to the terms
  44288. * and consitions of the licence of "d3.js" (BSD-3Clause, see
  44289. * </licenses/LICENSE-d3>).
  44290. */
  44291. /**
  44292. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  44293. * the tree.
  44294. */
  44295. /**
  44296. * Initialize all computational message for following algorithm.
  44297. *
  44298. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree.
  44299. */
  44300. function init$2(root) {
  44301. root.hierNode = {
  44302. defaultAncestor: null,
  44303. ancestor: root,
  44304. prelim: 0,
  44305. modifier: 0,
  44306. change: 0,
  44307. shift: 0,
  44308. i: 0,
  44309. thread: null
  44310. };
  44311. var nodes = [root];
  44312. var node;
  44313. var children;
  44314. while (node = nodes.pop()) { // jshint ignore:line
  44315. children = node.children;
  44316. if (node.isExpand && children.length) {
  44317. var n = children.length;
  44318. for (var i = n - 1; i >= 0; i--) {
  44319. var child = children[i];
  44320. child.hierNode = {
  44321. defaultAncestor: null,
  44322. ancestor: child,
  44323. prelim: 0,
  44324. modifier: 0,
  44325. change: 0,
  44326. shift: 0,
  44327. i: i,
  44328. thread: null
  44329. };
  44330. nodes.push(child);
  44331. }
  44332. }
  44333. }
  44334. }
  44335. /**
  44336. * The implementation of this function was originally copied from "d3.js"
  44337. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44338. * with some modifications made for this program.
  44339. * See the license statement at the head of this file.
  44340. *
  44341. * Computes a preliminary x coordinate for node. Before that, this function is
  44342. * applied recursively to the children of node, as well as the function
  44343. * apportion(). After spacing out the children by calling executeShifts(), the
  44344. * node is placed to the midpoint of its outermost children.
  44345. *
  44346. * @param {module:echarts/data/Tree~TreeNode} node
  44347. * @param {Function} separation
  44348. */
  44349. function firstWalk(node, separation) {
  44350. var children = node.isExpand ? node.children : [];
  44351. var siblings = node.parentNode.children;
  44352. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  44353. if (children.length) {
  44354. executeShifts(node);
  44355. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  44356. if (subtreeW) {
  44357. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44358. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  44359. }
  44360. else {
  44361. node.hierNode.prelim = midPoint;
  44362. }
  44363. }
  44364. else if (subtreeW) {
  44365. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44366. }
  44367. node.parentNode.hierNode.defaultAncestor = apportion(
  44368. node,
  44369. subtreeW,
  44370. node.parentNode.hierNode.defaultAncestor || siblings[0],
  44371. separation
  44372. );
  44373. }
  44374. /**
  44375. * The implementation of this function was originally copied from "d3.js"
  44376. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44377. * with some modifications made for this program.
  44378. * See the license statement at the head of this file.
  44379. *
  44380. * Computes all real x-coordinates by summing up the modifiers recursively.
  44381. *
  44382. * @param {module:echarts/data/Tree~TreeNode} node
  44383. */
  44384. function secondWalk(node) {
  44385. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  44386. node.setLayout({x: nodeX}, true);
  44387. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  44388. }
  44389. function separation(cb) {
  44390. return arguments.length ? cb : defaultSeparation;
  44391. }
  44392. /**
  44393. * Transform the common coordinate to radial coordinate.
  44394. *
  44395. * @param {number} x
  44396. * @param {number} y
  44397. * @return {Object}
  44398. */
  44399. function radialCoordinate(x, y) {
  44400. var radialCoor = {};
  44401. x -= Math.PI / 2;
  44402. radialCoor.x = y * Math.cos(x);
  44403. radialCoor.y = y * Math.sin(x);
  44404. return radialCoor;
  44405. }
  44406. /**
  44407. * Get the layout position of the whole view.
  44408. *
  44409. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  44410. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  44411. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  44412. */
  44413. function getViewRect$1(seriesModel, api) {
  44414. return getLayoutRect(
  44415. seriesModel.getBoxLayoutParams(), {
  44416. width: api.getWidth(),
  44417. height: api.getHeight()
  44418. }
  44419. );
  44420. }
  44421. /**
  44422. * All other shifts, applied to the smaller subtrees between w- and w+, are
  44423. * performed by this function.
  44424. *
  44425. * The implementation of this function was originally copied from "d3.js"
  44426. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44427. * with some modifications made for this program.
  44428. * See the license statement at the head of this file.
  44429. *
  44430. * @param {module:echarts/data/Tree~TreeNode} node
  44431. */
  44432. function executeShifts(node) {
  44433. var children = node.children;
  44434. var n = children.length;
  44435. var shift = 0;
  44436. var change = 0;
  44437. while (--n >= 0) {
  44438. var child = children[n];
  44439. child.hierNode.prelim += shift;
  44440. child.hierNode.modifier += shift;
  44441. change += child.hierNode.change;
  44442. shift += child.hierNode.shift + change;
  44443. }
  44444. }
  44445. /**
  44446. * The implementation of this function was originally copied from "d3.js"
  44447. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44448. * with some modifications made for this program.
  44449. * See the license statement at the head of this file.
  44450. *
  44451. * The core of the algorithm. Here, a new subtree is combined with the
  44452. * previous subtrees. Threads are used to traverse the inside and outside
  44453. * contours of the left and right subtree up to the highest common level.
  44454. * Whenever two nodes of the inside contours conflict, we compute the left
  44455. * one of the greatest uncommon ancestors using the function nextAncestor()
  44456. * and call moveSubtree() to shift the subtree and prepare the shifts of
  44457. * smaller subtrees. Finally, we add a new thread (if necessary).
  44458. *
  44459. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  44460. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  44461. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44462. * @param {Function} separation
  44463. * @return {module:echarts/data/Tree~TreeNode}
  44464. */
  44465. function apportion(subtreeV, subtreeW, ancestor, separation) {
  44466. if (subtreeW) {
  44467. var nodeOutRight = subtreeV;
  44468. var nodeInRight = subtreeV;
  44469. var nodeOutLeft = nodeInRight.parentNode.children[0];
  44470. var nodeInLeft = subtreeW;
  44471. var sumOutRight = nodeOutRight.hierNode.modifier;
  44472. var sumInRight = nodeInRight.hierNode.modifier;
  44473. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  44474. var sumInLeft = nodeInLeft.hierNode.modifier;
  44475. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  44476. nodeOutRight = nextRight(nodeOutRight);
  44477. nodeOutLeft = nextLeft(nodeOutLeft);
  44478. nodeOutRight.hierNode.ancestor = subtreeV;
  44479. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  44480. - sumInRight + separation(nodeInLeft, nodeInRight);
  44481. if (shift > 0) {
  44482. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  44483. sumInRight += shift;
  44484. sumOutRight += shift;
  44485. }
  44486. sumInLeft += nodeInLeft.hierNode.modifier;
  44487. sumInRight += nodeInRight.hierNode.modifier;
  44488. sumOutRight += nodeOutRight.hierNode.modifier;
  44489. sumOutLeft += nodeOutLeft.hierNode.modifier;
  44490. }
  44491. if (nodeInLeft && !nextRight(nodeOutRight)) {
  44492. nodeOutRight.hierNode.thread = nodeInLeft;
  44493. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  44494. }
  44495. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  44496. nodeOutLeft.hierNode.thread = nodeInRight;
  44497. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  44498. ancestor = subtreeV;
  44499. }
  44500. }
  44501. return ancestor;
  44502. }
  44503. /**
  44504. * This function is used to traverse the right contour of a subtree.
  44505. * It returns the rightmost child of node or the thread of node. The function
  44506. * returns null if and only if node is on the highest depth of its subtree.
  44507. *
  44508. * @param {module:echarts/data/Tree~TreeNode} node
  44509. * @return {module:echarts/data/Tree~TreeNode}
  44510. */
  44511. function nextRight(node) {
  44512. var children = node.children;
  44513. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  44514. }
  44515. /**
  44516. * This function is used to traverse the left contour of a subtree (or a subforest).
  44517. * It returns the leftmost child of node or the thread of node. The function
  44518. * returns null if and only if node is on the highest depth of its subtree.
  44519. *
  44520. * @param {module:echarts/data/Tree~TreeNode} node
  44521. * @return {module:echarts/data/Tree~TreeNode}
  44522. */
  44523. function nextLeft(node) {
  44524. var children = node.children;
  44525. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  44526. }
  44527. /**
  44528. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  44529. * Otherwise, returns the specified ancestor.
  44530. *
  44531. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  44532. * @param {module:echarts/data/Tree~TreeNode} node
  44533. * @param {module:echarts/data/Tree~TreeNode} ancestor
  44534. * @return {module:echarts/data/Tree~TreeNode}
  44535. */
  44536. function nextAncestor(nodeInLeft, node, ancestor) {
  44537. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  44538. ? nodeInLeft.hierNode.ancestor : ancestor;
  44539. }
  44540. /**
  44541. * The implementation of this function was originally copied from "d3.js"
  44542. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44543. * with some modifications made for this program.
  44544. * See the license statement at the head of this file.
  44545. *
  44546. * Shifts the current subtree rooted at wr.
  44547. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  44548. *
  44549. * @param {module:echarts/data/Tree~TreeNode} wl
  44550. * @param {module:echarts/data/Tree~TreeNode} wr
  44551. * @param {number} shift [description]
  44552. */
  44553. function moveSubtree(wl, wr, shift) {
  44554. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  44555. wr.hierNode.change -= change;
  44556. wr.hierNode.shift += shift;
  44557. wr.hierNode.modifier += shift;
  44558. wr.hierNode.prelim += shift;
  44559. wl.hierNode.change += change;
  44560. }
  44561. /**
  44562. * The implementation of this function was originally copied from "d3.js"
  44563. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44564. * with some modifications made for this program.
  44565. * See the license statement at the head of this file.
  44566. */
  44567. function defaultSeparation(node1, node2) {
  44568. return node1.parentNode === node2.parentNode ? 1 : 2;
  44569. }
  44570. /*
  44571. * Licensed to the Apache Software Foundation (ASF) under one
  44572. * or more contributor license agreements. See the NOTICE file
  44573. * distributed with this work for additional information
  44574. * regarding copyright ownership. The ASF licenses this file
  44575. * to you under the Apache License, Version 2.0 (the
  44576. * "License"); you may not use this file except in compliance
  44577. * with the License. You may obtain a copy of the License at
  44578. *
  44579. * http://www.apache.org/licenses/LICENSE-2.0
  44580. *
  44581. * Unless required by applicable law or agreed to in writing,
  44582. * software distributed under the License is distributed on an
  44583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44584. * KIND, either express or implied. See the License for the
  44585. * specific language governing permissions and limitations
  44586. * under the License.
  44587. */
  44588. extendChartView({
  44589. type: 'tree',
  44590. /**
  44591. * Init the chart
  44592. * @override
  44593. * @param {module:echarts/model/Global} ecModel
  44594. * @param {module:echarts/ExtensionAPI} api
  44595. */
  44596. init: function (ecModel, api) {
  44597. /**
  44598. * @private
  44599. * @type {module:echarts/data/Tree}
  44600. */
  44601. this._oldTree;
  44602. /**
  44603. * @private
  44604. * @type {module:zrender/container/Group}
  44605. */
  44606. this._mainGroup = new Group();
  44607. /**
  44608. * @private
  44609. * @type {module:echarts/componet/helper/RoamController}
  44610. */
  44611. this._controller = new RoamController(api.getZr());
  44612. this._controllerHost = {target: this.group};
  44613. this.group.add(this._mainGroup);
  44614. },
  44615. render: function (seriesModel, ecModel, api, payload) {
  44616. var data = seriesModel.getData();
  44617. var layoutInfo = seriesModel.layoutInfo;
  44618. var group = this._mainGroup;
  44619. var layout = seriesModel.get('layout');
  44620. if (layout === 'radial') {
  44621. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  44622. }
  44623. else {
  44624. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  44625. }
  44626. this._updateViewCoordSys(seriesModel, layoutInfo, layout);
  44627. this._updateController(seriesModel, ecModel, api);
  44628. var oldData = this._data;
  44629. var seriesScope = {
  44630. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  44631. layout: layout,
  44632. orient: seriesModel.getOrient(),
  44633. curvature: seriesModel.get('lineStyle.curveness'),
  44634. symbolRotate: seriesModel.get('symbolRotate'),
  44635. symbolOffset: seriesModel.get('symbolOffset'),
  44636. hoverAnimation: seriesModel.get('hoverAnimation'),
  44637. useNameLabel: true,
  44638. fadeIn: true
  44639. };
  44640. data.diff(oldData)
  44641. .add(function (newIdx) {
  44642. if (symbolNeedsDraw$1(data, newIdx)) {
  44643. // Create node and edge
  44644. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  44645. }
  44646. })
  44647. .update(function (newIdx, oldIdx) {
  44648. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  44649. if (!symbolNeedsDraw$1(data, newIdx)) {
  44650. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  44651. return;
  44652. }
  44653. // Update node and edge
  44654. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  44655. })
  44656. .remove(function (oldIdx) {
  44657. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  44658. // When remove a collapsed node of subtree, since the collapsed
  44659. // node haven't been initialized with a symbol element,
  44660. // you can't found it's symbol element through index.
  44661. // so if we want to remove the symbol element we should insure
  44662. // that the symbol element is not null.
  44663. if (symbolEl) {
  44664. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  44665. }
  44666. })
  44667. .execute();
  44668. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  44669. this._updateNodeAndLinkScale(seriesModel);
  44670. if (seriesScope.expandAndCollapse === true) {
  44671. data.eachItemGraphicEl(function (el, dataIndex) {
  44672. el.off('click').on('click', function () {
  44673. api.dispatchAction({
  44674. type: 'treeExpandAndCollapse',
  44675. seriesId: seriesModel.id,
  44676. dataIndex: dataIndex
  44677. });
  44678. });
  44679. });
  44680. }
  44681. this._data = data;
  44682. },
  44683. _updateViewCoordSys: function (seriesModel) {
  44684. var data = seriesModel.getData();
  44685. var points = [];
  44686. data.each(function (idx) {
  44687. var layout = data.getItemLayout(idx);
  44688. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  44689. points.push([+layout.x, +layout.y]);
  44690. }
  44691. });
  44692. var min = [];
  44693. var max = [];
  44694. fromPoints(points, min, max);
  44695. // If don't Store min max when collapse the root node after roam,
  44696. // the root node will disappear.
  44697. var oldMin = this._min;
  44698. var oldMax = this._max;
  44699. // If width or height is 0
  44700. if (max[0] - min[0] === 0) {
  44701. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  44702. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  44703. }
  44704. if (max[1] - min[1] === 0) {
  44705. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  44706. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  44707. }
  44708. var viewCoordSys = seriesModel.coordinateSystem = new View();
  44709. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  44710. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  44711. viewCoordSys.setCenter(seriesModel.get('center'));
  44712. viewCoordSys.setZoom(seriesModel.get('zoom'));
  44713. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  44714. this.group.attr({
  44715. position: viewCoordSys.position,
  44716. scale: viewCoordSys.scale
  44717. });
  44718. this._viewCoordSys = viewCoordSys;
  44719. this._min = min;
  44720. this._max = max;
  44721. },
  44722. _updateController: function (seriesModel, ecModel, api) {
  44723. var controller = this._controller;
  44724. var controllerHost = this._controllerHost;
  44725. var group = this.group;
  44726. controller.setPointerChecker(function (e, x, y) {
  44727. var rect = group.getBoundingRect();
  44728. rect.applyTransform(group.transform);
  44729. return rect.contain(x, y)
  44730. && !onIrrelevantElement(e, api, seriesModel);
  44731. });
  44732. controller.enable(seriesModel.get('roam'));
  44733. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  44734. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  44735. controller
  44736. .off('pan')
  44737. .off('zoom')
  44738. .on('pan', function (e) {
  44739. updateViewOnPan(controllerHost, e.dx, e.dy);
  44740. api.dispatchAction({
  44741. seriesId: seriesModel.id,
  44742. type: 'treeRoam',
  44743. dx: e.dx,
  44744. dy: e.dy
  44745. });
  44746. }, this)
  44747. .on('zoom', function (e) {
  44748. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  44749. api.dispatchAction({
  44750. seriesId: seriesModel.id,
  44751. type: 'treeRoam',
  44752. zoom: e.scale,
  44753. originX: e.originX,
  44754. originY: e.originY
  44755. });
  44756. this._updateNodeAndLinkScale(seriesModel);
  44757. }, this);
  44758. },
  44759. _updateNodeAndLinkScale: function (seriesModel) {
  44760. var data = seriesModel.getData();
  44761. var nodeScale = this._getNodeGlobalScale(seriesModel);
  44762. var invScale = [nodeScale, nodeScale];
  44763. data.eachItemGraphicEl(function (el, idx) {
  44764. el.attr('scale', invScale);
  44765. });
  44766. },
  44767. _getNodeGlobalScale: function (seriesModel) {
  44768. var coordSys = seriesModel.coordinateSystem;
  44769. if (coordSys.type !== 'view') {
  44770. return 1;
  44771. }
  44772. var nodeScaleRatio = this._nodeScaleRatio;
  44773. var groupScale = coordSys.scale;
  44774. var groupZoom = (groupScale && groupScale[0]) || 1;
  44775. // Scale node when zoom changes
  44776. var roamZoom = coordSys.getZoom();
  44777. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  44778. return nodeScale / groupZoom;
  44779. },
  44780. dispose: function () {
  44781. this._controller && this._controller.dispose();
  44782. this._controllerHost = {};
  44783. },
  44784. remove: function () {
  44785. this._mainGroup.removeAll();
  44786. this._data = null;
  44787. }
  44788. });
  44789. function symbolNeedsDraw$1(data, dataIndex) {
  44790. var layout = data.getItemLayout(dataIndex);
  44791. return layout
  44792. && !isNaN(layout.x) && !isNaN(layout.y)
  44793. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  44794. }
  44795. function getTreeNodeStyle(node, itemModel, seriesScope) {
  44796. seriesScope.itemModel = itemModel;
  44797. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  44798. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  44799. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  44800. seriesScope.labelModel = itemModel.getModel('label');
  44801. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  44802. if (node.isExpand === false && node.children.length !== 0) {
  44803. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  44804. }
  44805. else {
  44806. seriesScope.symbolInnerColor = '#fff';
  44807. }
  44808. return seriesScope;
  44809. }
  44810. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  44811. var isInit = !symbolEl;
  44812. var node = data.tree.getNodeByDataIndex(dataIndex);
  44813. var itemModel = node.getModel();
  44814. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  44815. var virtualRoot = data.tree.root;
  44816. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  44817. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  44818. var sourceLayout = source.getLayout();
  44819. var sourceOldLayout = sourceSymbolEl
  44820. ? {
  44821. x: sourceSymbolEl.position[0],
  44822. y: sourceSymbolEl.position[1],
  44823. rawX: sourceSymbolEl.__radialOldRawX,
  44824. rawY: sourceSymbolEl.__radialOldRawY
  44825. }
  44826. : sourceLayout;
  44827. var targetLayout = node.getLayout();
  44828. if (isInit) {
  44829. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  44830. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  44831. }
  44832. else {
  44833. symbolEl.updateData(data, dataIndex, seriesScope);
  44834. }
  44835. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  44836. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  44837. symbolEl.__radialRawX = targetLayout.rawX;
  44838. symbolEl.__radialRawY = targetLayout.rawY;
  44839. group.add(symbolEl);
  44840. data.setItemGraphicEl(dataIndex, symbolEl);
  44841. updateProps(symbolEl, {
  44842. position: [targetLayout.x, targetLayout.y]
  44843. }, seriesModel);
  44844. var symbolPath = symbolEl.getSymbolPath();
  44845. if (seriesScope.layout === 'radial') {
  44846. var realRoot = virtualRoot.children[0];
  44847. var rootLayout = realRoot.getLayout();
  44848. var length = realRoot.children.length;
  44849. var rad;
  44850. var isLeft;
  44851. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  44852. var center = {};
  44853. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  44854. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  44855. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  44856. if (rad < 0) {
  44857. rad = Math.PI * 2 + rad;
  44858. }
  44859. isLeft = center.x < rootLayout.x;
  44860. if (isLeft) {
  44861. rad = rad - Math.PI;
  44862. }
  44863. }
  44864. else {
  44865. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  44866. if (rad < 0) {
  44867. rad = Math.PI * 2 + rad;
  44868. }
  44869. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  44870. isLeft = targetLayout.x < rootLayout.x;
  44871. if (isLeft) {
  44872. rad = rad - Math.PI;
  44873. }
  44874. }
  44875. else {
  44876. isLeft = targetLayout.x > rootLayout.x;
  44877. if (!isLeft) {
  44878. rad = rad - Math.PI;
  44879. }
  44880. }
  44881. }
  44882. var textPosition = isLeft ? 'left' : 'right';
  44883. var rotate = seriesScope.labelModel.get('rotate');
  44884. var labelRotateRadian = rotate * (Math.PI / 180);
  44885. symbolPath.setStyle({
  44886. textPosition: seriesScope.labelModel.get('position') || textPosition,
  44887. textRotation: rotate == null ? -rad : labelRotateRadian,
  44888. textOrigin: 'center',
  44889. verticalAlign: 'middle'
  44890. });
  44891. }
  44892. if (node.parentNode && node.parentNode !== virtualRoot) {
  44893. var edge = symbolEl.__edge;
  44894. if (!edge) {
  44895. edge = symbolEl.__edge = new BezierCurve({
  44896. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  44897. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  44898. });
  44899. }
  44900. updateProps(edge, {
  44901. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  44902. style: {opacity: 1}
  44903. }, seriesModel);
  44904. group.add(edge);
  44905. }
  44906. }
  44907. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  44908. var node = data.tree.getNodeByDataIndex(dataIndex);
  44909. var virtualRoot = data.tree.root;
  44910. var itemModel = node.getModel();
  44911. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  44912. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  44913. var sourceLayout;
  44914. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  44915. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  44916. }
  44917. updateProps(symbolEl, {
  44918. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  44919. }, seriesModel, function () {
  44920. group.remove(symbolEl);
  44921. data.setItemGraphicEl(dataIndex, null);
  44922. });
  44923. symbolEl.fadeOut(null, {keepLabel: true});
  44924. var edge = symbolEl.__edge;
  44925. if (edge) {
  44926. updateProps(edge, {
  44927. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  44928. style: {
  44929. opacity: 0
  44930. }
  44931. }, seriesModel, function () {
  44932. group.remove(edge);
  44933. });
  44934. }
  44935. }
  44936. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  44937. var cpx1;
  44938. var cpy1;
  44939. var cpx2;
  44940. var cpy2;
  44941. var orient = seriesScope.orient;
  44942. var x1;
  44943. var x2;
  44944. var y1;
  44945. var y2;
  44946. if (seriesScope.layout === 'radial') {
  44947. x1 = sourceLayout.rawX;
  44948. y1 = sourceLayout.rawY;
  44949. x2 = targetLayout.rawX;
  44950. y2 = targetLayout.rawY;
  44951. var radialCoor1 = radialCoordinate(x1, y1);
  44952. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  44953. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  44954. var radialCoor4 = radialCoordinate(x2, y2);
  44955. return {
  44956. x1: radialCoor1.x,
  44957. y1: radialCoor1.y,
  44958. x2: radialCoor4.x,
  44959. y2: radialCoor4.y,
  44960. cpx1: radialCoor2.x,
  44961. cpy1: radialCoor2.y,
  44962. cpx2: radialCoor3.x,
  44963. cpy2: radialCoor3.y
  44964. };
  44965. }
  44966. else {
  44967. x1 = sourceLayout.x;
  44968. y1 = sourceLayout.y;
  44969. x2 = targetLayout.x;
  44970. y2 = targetLayout.y;
  44971. if (orient === 'LR' || orient === 'RL') {
  44972. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  44973. cpy1 = y1;
  44974. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  44975. cpy2 = y2;
  44976. }
  44977. if (orient === 'TB' || orient === 'BT') {
  44978. cpx1 = x1;
  44979. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  44980. cpx2 = x2;
  44981. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  44982. }
  44983. }
  44984. return {
  44985. x1: x1,
  44986. y1: y1,
  44987. x2: x2,
  44988. y2: y2,
  44989. cpx1: cpx1,
  44990. cpy1: cpy1,
  44991. cpx2: cpx2,
  44992. cpy2: cpy2
  44993. };
  44994. }
  44995. /*
  44996. * Licensed to the Apache Software Foundation (ASF) under one
  44997. * or more contributor license agreements. See the NOTICE file
  44998. * distributed with this work for additional information
  44999. * regarding copyright ownership. The ASF licenses this file
  45000. * to you under the Apache License, Version 2.0 (the
  45001. * "License"); you may not use this file except in compliance
  45002. * with the License. You may obtain a copy of the License at
  45003. *
  45004. * http://www.apache.org/licenses/LICENSE-2.0
  45005. *
  45006. * Unless required by applicable law or agreed to in writing,
  45007. * software distributed under the License is distributed on an
  45008. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45009. * KIND, either express or implied. See the License for the
  45010. * specific language governing permissions and limitations
  45011. * under the License.
  45012. */
  45013. registerAction({
  45014. type: 'treeExpandAndCollapse',
  45015. event: 'treeExpandAndCollapse',
  45016. update: 'update'
  45017. }, function (payload, ecModel) {
  45018. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  45019. var dataIndex = payload.dataIndex;
  45020. var tree = seriesModel.getData().tree;
  45021. var node = tree.getNodeByDataIndex(dataIndex);
  45022. node.isExpand = !node.isExpand;
  45023. });
  45024. });
  45025. registerAction({
  45026. type: 'treeRoam',
  45027. event: 'treeRoam',
  45028. // Here we set 'none' instead of 'update', because roam action
  45029. // just need to update the transform matrix without having to recalculate
  45030. // the layout. So don't need to go through the whole update process, such
  45031. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  45032. update: 'none'
  45033. }, function (payload, ecModel) {
  45034. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  45035. var coordSys = seriesModel.coordinateSystem;
  45036. var res = updateCenterAndZoom(coordSys, payload);
  45037. seriesModel.setCenter
  45038. && seriesModel.setCenter(res.center);
  45039. seriesModel.setZoom
  45040. && seriesModel.setZoom(res.zoom);
  45041. });
  45042. });
  45043. /*
  45044. * Licensed to the Apache Software Foundation (ASF) under one
  45045. * or more contributor license agreements. See the NOTICE file
  45046. * distributed with this work for additional information
  45047. * regarding copyright ownership. The ASF licenses this file
  45048. * to you under the Apache License, Version 2.0 (the
  45049. * "License"); you may not use this file except in compliance
  45050. * with the License. You may obtain a copy of the License at
  45051. *
  45052. * http://www.apache.org/licenses/LICENSE-2.0
  45053. *
  45054. * Unless required by applicable law or agreed to in writing,
  45055. * software distributed under the License is distributed on an
  45056. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45057. * KIND, either express or implied. See the License for the
  45058. * specific language governing permissions and limitations
  45059. * under the License.
  45060. */
  45061. /**
  45062. * Traverse the tree from bottom to top and do something
  45063. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45064. * @param {Function} callback
  45065. */
  45066. function eachAfter(root, callback, separation) {
  45067. var nodes = [root];
  45068. var next = [];
  45069. var node;
  45070. while (node = nodes.pop()) { // jshint ignore:line
  45071. next.push(node);
  45072. if (node.isExpand) {
  45073. var children = node.children;
  45074. if (children.length) {
  45075. for (var i = 0; i < children.length; i++) {
  45076. nodes.push(children[i]);
  45077. }
  45078. }
  45079. }
  45080. }
  45081. while (node = next.pop()) { // jshint ignore:line
  45082. callback(node, separation);
  45083. }
  45084. }
  45085. /**
  45086. * Traverse the tree from top to bottom and do something
  45087. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  45088. * @param {Function} callback
  45089. */
  45090. function eachBefore(root, callback) {
  45091. var nodes = [root];
  45092. var node;
  45093. while (node = nodes.pop()) { // jshint ignore:line
  45094. callback(node);
  45095. if (node.isExpand) {
  45096. var children = node.children;
  45097. if (children.length) {
  45098. for (var i = children.length - 1; i >= 0; i--) {
  45099. nodes.push(children[i]);
  45100. }
  45101. }
  45102. }
  45103. }
  45104. }
  45105. /*
  45106. * Licensed to the Apache Software Foundation (ASF) under one
  45107. * or more contributor license agreements. See the NOTICE file
  45108. * distributed with this work for additional information
  45109. * regarding copyright ownership. The ASF licenses this file
  45110. * to you under the Apache License, Version 2.0 (the
  45111. * "License"); you may not use this file except in compliance
  45112. * with the License. You may obtain a copy of the License at
  45113. *
  45114. * http://www.apache.org/licenses/LICENSE-2.0
  45115. *
  45116. * Unless required by applicable law or agreed to in writing,
  45117. * software distributed under the License is distributed on an
  45118. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45119. * KIND, either express or implied. See the License for the
  45120. * specific language governing permissions and limitations
  45121. * under the License.
  45122. */
  45123. var treeLayout = function (ecModel, api) {
  45124. ecModel.eachSeriesByType('tree', function (seriesModel) {
  45125. commonLayout(seriesModel, api);
  45126. });
  45127. };
  45128. function commonLayout(seriesModel, api) {
  45129. var layoutInfo = getViewRect$1(seriesModel, api);
  45130. seriesModel.layoutInfo = layoutInfo;
  45131. var layout = seriesModel.get('layout');
  45132. var width = 0;
  45133. var height = 0;
  45134. var separation$$1 = null;
  45135. if (layout === 'radial') {
  45136. width = 2 * Math.PI;
  45137. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  45138. separation$$1 = separation(function (node1, node2) {
  45139. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  45140. });
  45141. }
  45142. else {
  45143. width = layoutInfo.width;
  45144. height = layoutInfo.height;
  45145. separation$$1 = separation();
  45146. }
  45147. var virtualRoot = seriesModel.getData().tree.root;
  45148. var realRoot = virtualRoot.children[0];
  45149. if (realRoot) {
  45150. init$2(virtualRoot);
  45151. eachAfter(realRoot, firstWalk, separation$$1);
  45152. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  45153. eachBefore(realRoot, secondWalk);
  45154. var left = realRoot;
  45155. var right = realRoot;
  45156. var bottom = realRoot;
  45157. eachBefore(realRoot, function (node) {
  45158. var x = node.getLayout().x;
  45159. if (x < left.getLayout().x) {
  45160. left = node;
  45161. }
  45162. if (x > right.getLayout().x) {
  45163. right = node;
  45164. }
  45165. if (node.depth > bottom.depth) {
  45166. bottom = node;
  45167. }
  45168. });
  45169. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  45170. var tx = delta - left.getLayout().x;
  45171. var kx = 0;
  45172. var ky = 0;
  45173. var coorX = 0;
  45174. var coorY = 0;
  45175. if (layout === 'radial') {
  45176. kx = width / (right.getLayout().x + delta + tx);
  45177. // here we use (node.depth - 1), bucause the real root's depth is 1
  45178. ky = height / ((bottom.depth - 1) || 1);
  45179. eachBefore(realRoot, function (node) {
  45180. coorX = (node.getLayout().x + tx) * kx;
  45181. coorY = (node.depth - 1) * ky;
  45182. var finalCoor = radialCoordinate(coorX, coorY);
  45183. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  45184. });
  45185. }
  45186. else {
  45187. var orient = seriesModel.getOrient();
  45188. if (orient === 'RL' || orient === 'LR') {
  45189. ky = height / (right.getLayout().x + delta + tx);
  45190. kx = width / ((bottom.depth - 1) || 1);
  45191. eachBefore(realRoot, function (node) {
  45192. coorY = (node.getLayout().x + tx) * ky;
  45193. coorX = orient === 'LR'
  45194. ? (node.depth - 1) * kx
  45195. : width - (node.depth - 1) * kx;
  45196. node.setLayout({x: coorX, y: coorY}, true);
  45197. });
  45198. }
  45199. else if (orient === 'TB' || orient === 'BT') {
  45200. kx = width / (right.getLayout().x + delta + tx);
  45201. ky = height / ((bottom.depth - 1) || 1);
  45202. eachBefore(realRoot, function (node) {
  45203. coorX = (node.getLayout().x + tx) * kx;
  45204. coorY = orient === 'TB'
  45205. ? (node.depth - 1) * ky
  45206. : height - (node.depth - 1) * ky;
  45207. node.setLayout({x: coorX, y: coorY}, true);
  45208. });
  45209. }
  45210. }
  45211. }
  45212. }
  45213. /*
  45214. * Licensed to the Apache Software Foundation (ASF) under one
  45215. * or more contributor license agreements. See the NOTICE file
  45216. * distributed with this work for additional information
  45217. * regarding copyright ownership. The ASF licenses this file
  45218. * to you under the Apache License, Version 2.0 (the
  45219. * "License"); you may not use this file except in compliance
  45220. * with the License. You may obtain a copy of the License at
  45221. *
  45222. * http://www.apache.org/licenses/LICENSE-2.0
  45223. *
  45224. * Unless required by applicable law or agreed to in writing,
  45225. * software distributed under the License is distributed on an
  45226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45227. * KIND, either express or implied. See the License for the
  45228. * specific language governing permissions and limitations
  45229. * under the License.
  45230. */
  45231. registerVisual(visualSymbol('tree', 'circle'));
  45232. registerLayout(treeLayout);
  45233. /*
  45234. * Licensed to the Apache Software Foundation (ASF) under one
  45235. * or more contributor license agreements. See the NOTICE file
  45236. * distributed with this work for additional information
  45237. * regarding copyright ownership. The ASF licenses this file
  45238. * to you under the Apache License, Version 2.0 (the
  45239. * "License"); you may not use this file except in compliance
  45240. * with the License. You may obtain a copy of the License at
  45241. *
  45242. * http://www.apache.org/licenses/LICENSE-2.0
  45243. *
  45244. * Unless required by applicable law or agreed to in writing,
  45245. * software distributed under the License is distributed on an
  45246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45247. * KIND, either express or implied. See the License for the
  45248. * specific language governing permissions and limitations
  45249. * under the License.
  45250. */
  45251. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  45252. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  45253. var root = seriesModel.getData().tree.root;
  45254. var targetNode = payload.targetNode;
  45255. if (typeof targetNode === 'string') {
  45256. targetNode = root.getNodeById(targetNode);
  45257. }
  45258. if (targetNode && root.contains(targetNode)) {
  45259. return {node: targetNode};
  45260. }
  45261. var targetNodeId = payload.targetNodeId;
  45262. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  45263. return {node: targetNode};
  45264. }
  45265. }
  45266. }
  45267. // Not includes the given node at the last item.
  45268. function getPathToRoot(node) {
  45269. var path = [];
  45270. while (node) {
  45271. node = node.parentNode;
  45272. node && path.push(node);
  45273. }
  45274. return path.reverse();
  45275. }
  45276. function aboveViewRoot(viewRoot, node) {
  45277. var viewPath = getPathToRoot(viewRoot);
  45278. return indexOf(viewPath, node) >= 0;
  45279. }
  45280. // From root to the input node (the input node will be included).
  45281. function wrapTreePathInfo(node, seriesModel) {
  45282. var treePathInfo = [];
  45283. while (node) {
  45284. var nodeDataIndex = node.dataIndex;
  45285. treePathInfo.push({
  45286. name: node.name,
  45287. dataIndex: nodeDataIndex,
  45288. value: seriesModel.getRawValue(nodeDataIndex)
  45289. });
  45290. node = node.parentNode;
  45291. }
  45292. treePathInfo.reverse();
  45293. return treePathInfo;
  45294. }
  45295. /*
  45296. * Licensed to the Apache Software Foundation (ASF) under one
  45297. * or more contributor license agreements. See the NOTICE file
  45298. * distributed with this work for additional information
  45299. * regarding copyright ownership. The ASF licenses this file
  45300. * to you under the Apache License, Version 2.0 (the
  45301. * "License"); you may not use this file except in compliance
  45302. * with the License. You may obtain a copy of the License at
  45303. *
  45304. * http://www.apache.org/licenses/LICENSE-2.0
  45305. *
  45306. * Unless required by applicable law or agreed to in writing,
  45307. * software distributed under the License is distributed on an
  45308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45309. * KIND, either express or implied. See the License for the
  45310. * specific language governing permissions and limitations
  45311. * under the License.
  45312. */
  45313. SeriesModel.extend({
  45314. type: 'series.treemap',
  45315. layoutMode: 'box',
  45316. dependencies: ['grid', 'polar'],
  45317. preventUsingHoverLayer: true,
  45318. /**
  45319. * @type {module:echarts/data/Tree~Node}
  45320. */
  45321. _viewRoot: null,
  45322. defaultOption: {
  45323. // Disable progressive rendering
  45324. progressive: 0,
  45325. // center: ['50%', '50%'], // not supported in ec3.
  45326. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  45327. left: 'center',
  45328. top: 'middle',
  45329. right: null,
  45330. bottom: null,
  45331. width: '80%',
  45332. height: '80%',
  45333. sort: true, // Can be null or false or true
  45334. // (order by desc default, asc not supported yet (strange effect))
  45335. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  45336. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  45337. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  45338. // Count from zero (zero represents only view root).
  45339. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  45340. // to align specialized icon. ▷▶❒❐▼✚
  45341. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  45342. // target node area in the view area.
  45343. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  45344. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  45345. // If leafDepth is set and clicking a node which has children but
  45346. // be on left depth, the behaviour would be changing root. Otherwise
  45347. // use behavious defined above.
  45348. animation: true,
  45349. animationDurationUpdate: 900,
  45350. animationEasing: 'quinticInOut',
  45351. breadcrumb: {
  45352. show: true,
  45353. height: 22,
  45354. left: 'center',
  45355. top: 'bottom',
  45356. // right
  45357. // bottom
  45358. emptyItemWidth: 25, // Width of empty node.
  45359. itemStyle: {
  45360. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  45361. borderColor: 'rgba(255,255,255,0.7)',
  45362. borderWidth: 1,
  45363. shadowColor: 'rgba(150,150,150,1)',
  45364. shadowBlur: 3,
  45365. shadowOffsetX: 0,
  45366. shadowOffsetY: 0,
  45367. textStyle: {
  45368. color: '#fff'
  45369. }
  45370. },
  45371. emphasis: {
  45372. textStyle: {}
  45373. }
  45374. },
  45375. label: {
  45376. show: true,
  45377. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  45378. distance: 0,
  45379. padding: 5,
  45380. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  45381. // formatter: null,
  45382. color: '#fff',
  45383. ellipsis: true
  45384. // align
  45385. // verticalAlign
  45386. },
  45387. upperLabel: { // Label when node is parent.
  45388. show: false,
  45389. position: [0, '50%'],
  45390. height: 20,
  45391. // formatter: null,
  45392. color: '#fff',
  45393. ellipsis: true,
  45394. // align: null,
  45395. verticalAlign: 'middle'
  45396. },
  45397. itemStyle: {
  45398. color: null, // Can be 'none' if not necessary.
  45399. colorAlpha: null, // Can be 'none' if not necessary.
  45400. colorSaturation: null, // Can be 'none' if not necessary.
  45401. borderWidth: 0,
  45402. gapWidth: 0,
  45403. borderColor: '#fff',
  45404. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  45405. // border color is evaluated by color of current node and
  45406. // borderColorSaturation.
  45407. },
  45408. emphasis: {
  45409. upperLabel: {
  45410. show: true,
  45411. position: [0, '50%'],
  45412. color: '#fff',
  45413. ellipsis: true,
  45414. verticalAlign: 'middle'
  45415. }
  45416. },
  45417. visualDimension: 0, // Can be 0, 1, 2, 3.
  45418. visualMin: null,
  45419. visualMax: null,
  45420. color: [], // + treemapSeries.color should not be modified. Please only modified
  45421. // level[n].color (if necessary).
  45422. // + Specify color list of each level. level[0].color would be global
  45423. // color list if not specified. (see method `setDefault`).
  45424. // + But set as a empty array to forbid fetch color from global palette
  45425. // when using nodeModel.get('color'), otherwise nodes on deep level
  45426. // will always has color palette set and are not able to inherit color
  45427. // from parent node.
  45428. // + TreemapSeries.color can not be set as 'none', otherwise effect
  45429. // legend color fetching (see seriesColor.js).
  45430. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  45431. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  45432. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  45433. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  45434. // be rendered. Only works when sort is 'asc' or 'desc'.
  45435. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  45436. // grandchildren will not show.
  45437. // Why grandchildren? If not grandchildren but children,
  45438. // some siblings show children and some not,
  45439. // the appearance may be mess and not consistent,
  45440. levels: [] // Each item: {
  45441. // visibleMin, itemStyle, visualDimension, label
  45442. // }
  45443. // data: {
  45444. // value: [],
  45445. // children: [],
  45446. // link: 'http://xxx.xxx.xxx',
  45447. // target: 'blank' or 'self'
  45448. // }
  45449. },
  45450. /**
  45451. * @override
  45452. */
  45453. getInitialData: function (option, ecModel) {
  45454. // Create a virtual root.
  45455. var root = {name: option.name, children: option.data};
  45456. completeTreeValue(root);
  45457. var levels = option.levels || [];
  45458. levels = option.levels = setDefault(levels, ecModel);
  45459. var treeOption = {};
  45460. treeOption.levels = levels;
  45461. // Make sure always a new tree is created when setOption,
  45462. // in TreemapView, we check whether oldTree === newTree
  45463. // to choose mappings approach among old shapes and new shapes.
  45464. return Tree.createTree(root, this, treeOption).data;
  45465. },
  45466. optionUpdated: function () {
  45467. this.resetViewRoot();
  45468. },
  45469. /**
  45470. * @override
  45471. * @param {number} dataIndex
  45472. * @param {boolean} [mutipleSeries=false]
  45473. */
  45474. formatTooltip: function (dataIndex) {
  45475. var data = this.getData();
  45476. var value = this.getRawValue(dataIndex);
  45477. var formattedValue = isArray(value)
  45478. ? addCommas(value[0]) : addCommas(value);
  45479. var name = data.getName(dataIndex);
  45480. return encodeHTML(name + ': ' + formattedValue);
  45481. },
  45482. /**
  45483. * Add tree path to tooltip param
  45484. *
  45485. * @override
  45486. * @param {number} dataIndex
  45487. * @return {Object}
  45488. */
  45489. getDataParams: function (dataIndex) {
  45490. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  45491. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  45492. params.treePathInfo = wrapTreePathInfo(node, this);
  45493. return params;
  45494. },
  45495. /**
  45496. * @public
  45497. * @param {Object} layoutInfo {
  45498. * x: containerGroup x
  45499. * y: containerGroup y
  45500. * width: containerGroup width
  45501. * height: containerGroup height
  45502. * }
  45503. */
  45504. setLayoutInfo: function (layoutInfo) {
  45505. /**
  45506. * @readOnly
  45507. * @type {Object}
  45508. */
  45509. this.layoutInfo = this.layoutInfo || {};
  45510. extend(this.layoutInfo, layoutInfo);
  45511. },
  45512. /**
  45513. * @param {string} id
  45514. * @return {number} index
  45515. */
  45516. mapIdToIndex: function (id) {
  45517. // A feature is implemented:
  45518. // index is monotone increasing with the sequence of
  45519. // input id at the first time.
  45520. // This feature can make sure that each data item and its
  45521. // mapped color have the same index between data list and
  45522. // color list at the beginning, which is useful for user
  45523. // to adjust data-color mapping.
  45524. /**
  45525. * @private
  45526. * @type {Object}
  45527. */
  45528. var idIndexMap = this._idIndexMap;
  45529. if (!idIndexMap) {
  45530. idIndexMap = this._idIndexMap = createHashMap();
  45531. /**
  45532. * @private
  45533. * @type {number}
  45534. */
  45535. this._idIndexMapCount = 0;
  45536. }
  45537. var index = idIndexMap.get(id);
  45538. if (index == null) {
  45539. idIndexMap.set(id, index = this._idIndexMapCount++);
  45540. }
  45541. return index;
  45542. },
  45543. getViewRoot: function () {
  45544. return this._viewRoot;
  45545. },
  45546. /**
  45547. * @param {module:echarts/data/Tree~Node} [viewRoot]
  45548. */
  45549. resetViewRoot: function (viewRoot) {
  45550. viewRoot
  45551. ? (this._viewRoot = viewRoot)
  45552. : (viewRoot = this._viewRoot);
  45553. var root = this.getRawData().tree.root;
  45554. if (!viewRoot
  45555. || (viewRoot !== root && !root.contains(viewRoot))
  45556. ) {
  45557. this._viewRoot = root;
  45558. }
  45559. }
  45560. });
  45561. /**
  45562. * @param {Object} dataNode
  45563. */
  45564. function completeTreeValue(dataNode) {
  45565. // Postorder travel tree.
  45566. // If value of none-leaf node is not set,
  45567. // calculate it by suming up the value of all children.
  45568. var sum = 0;
  45569. each$1(dataNode.children, function (child) {
  45570. completeTreeValue(child);
  45571. var childValue = child.value;
  45572. isArray(childValue) && (childValue = childValue[0]);
  45573. sum += childValue;
  45574. });
  45575. var thisValue = dataNode.value;
  45576. if (isArray(thisValue)) {
  45577. thisValue = thisValue[0];
  45578. }
  45579. if (thisValue == null || isNaN(thisValue)) {
  45580. thisValue = sum;
  45581. }
  45582. // Value should not less than 0.
  45583. if (thisValue < 0) {
  45584. thisValue = 0;
  45585. }
  45586. isArray(dataNode.value)
  45587. ? (dataNode.value[0] = thisValue)
  45588. : (dataNode.value = thisValue);
  45589. }
  45590. /**
  45591. * set default to level configuration
  45592. */
  45593. function setDefault(levels, ecModel) {
  45594. var globalColorList = ecModel.get('color');
  45595. if (!globalColorList) {
  45596. return;
  45597. }
  45598. levels = levels || [];
  45599. var hasColorDefine;
  45600. each$1(levels, function (levelDefine) {
  45601. var model = new Model(levelDefine);
  45602. var modelColor = model.get('color');
  45603. if (model.get('itemStyle.color')
  45604. || (modelColor && modelColor !== 'none')
  45605. ) {
  45606. hasColorDefine = true;
  45607. }
  45608. });
  45609. if (!hasColorDefine) {
  45610. var level0 = levels[0] || (levels[0] = {});
  45611. level0.color = globalColorList.slice();
  45612. }
  45613. return levels;
  45614. }
  45615. /*
  45616. * Licensed to the Apache Software Foundation (ASF) under one
  45617. * or more contributor license agreements. See the NOTICE file
  45618. * distributed with this work for additional information
  45619. * regarding copyright ownership. The ASF licenses this file
  45620. * to you under the Apache License, Version 2.0 (the
  45621. * "License"); you may not use this file except in compliance
  45622. * with the License. You may obtain a copy of the License at
  45623. *
  45624. * http://www.apache.org/licenses/LICENSE-2.0
  45625. *
  45626. * Unless required by applicable law or agreed to in writing,
  45627. * software distributed under the License is distributed on an
  45628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45629. * KIND, either express or implied. See the License for the
  45630. * specific language governing permissions and limitations
  45631. * under the License.
  45632. */
  45633. var TEXT_PADDING = 8;
  45634. var ITEM_GAP = 8;
  45635. var ARRAY_LENGTH = 5;
  45636. function Breadcrumb(containerGroup) {
  45637. /**
  45638. * @private
  45639. * @type {module:zrender/container/Group}
  45640. */
  45641. this.group = new Group();
  45642. containerGroup.add(this.group);
  45643. }
  45644. Breadcrumb.prototype = {
  45645. constructor: Breadcrumb,
  45646. render: function (seriesModel, api, targetNode, onSelect) {
  45647. var model = seriesModel.getModel('breadcrumb');
  45648. var thisGroup = this.group;
  45649. thisGroup.removeAll();
  45650. if (!model.get('show') || !targetNode) {
  45651. return;
  45652. }
  45653. var normalStyleModel = model.getModel('itemStyle');
  45654. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  45655. var textStyleModel = normalStyleModel.getModel('textStyle');
  45656. var layoutParam = {
  45657. pos: {
  45658. left: model.get('left'),
  45659. right: model.get('right'),
  45660. top: model.get('top'),
  45661. bottom: model.get('bottom')
  45662. },
  45663. box: {
  45664. width: api.getWidth(),
  45665. height: api.getHeight()
  45666. },
  45667. emptyItemWidth: model.get('emptyItemWidth'),
  45668. totalWidth: 0,
  45669. renderList: []
  45670. };
  45671. this._prepare(targetNode, layoutParam, textStyleModel);
  45672. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  45673. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  45674. },
  45675. /**
  45676. * Prepare render list and total width
  45677. * @private
  45678. */
  45679. _prepare: function (targetNode, layoutParam, textStyleModel) {
  45680. for (var node = targetNode; node; node = node.parentNode) {
  45681. var text = node.getModel().get('name');
  45682. var textRect = textStyleModel.getTextRect(text);
  45683. var itemWidth = Math.max(
  45684. textRect.width + TEXT_PADDING * 2,
  45685. layoutParam.emptyItemWidth
  45686. );
  45687. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  45688. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  45689. }
  45690. },
  45691. /**
  45692. * @private
  45693. */
  45694. _renderContent: function (
  45695. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  45696. ) {
  45697. // Start rendering.
  45698. var lastX = 0;
  45699. var emptyItemWidth = layoutParam.emptyItemWidth;
  45700. var height = seriesModel.get('breadcrumb.height');
  45701. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  45702. var totalWidth = layoutParam.totalWidth;
  45703. var renderList = layoutParam.renderList;
  45704. for (var i = renderList.length - 1; i >= 0; i--) {
  45705. var item = renderList[i];
  45706. var itemNode = item.node;
  45707. var itemWidth = item.width;
  45708. var text = item.text;
  45709. // Hdie text and shorten width if necessary.
  45710. if (totalWidth > availableSize.width) {
  45711. totalWidth -= itemWidth - emptyItemWidth;
  45712. itemWidth = emptyItemWidth;
  45713. text = null;
  45714. }
  45715. var el = new Polygon({
  45716. shape: {
  45717. points: makeItemPoints(
  45718. lastX, 0, itemWidth, height,
  45719. i === renderList.length - 1, i === 0
  45720. )
  45721. },
  45722. style: defaults(
  45723. normalStyleModel.getItemStyle(),
  45724. {
  45725. lineJoin: 'bevel',
  45726. text: text,
  45727. textFill: textStyleModel.getTextColor(),
  45728. textFont: textStyleModel.getFont()
  45729. }
  45730. ),
  45731. z: 10,
  45732. onclick: curry(onSelect, itemNode)
  45733. });
  45734. this.group.add(el);
  45735. packEventData(el, seriesModel, itemNode);
  45736. lastX += itemWidth + ITEM_GAP;
  45737. }
  45738. },
  45739. /**
  45740. * @override
  45741. */
  45742. remove: function () {
  45743. this.group.removeAll();
  45744. }
  45745. };
  45746. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  45747. var points = [
  45748. [head ? x : x - ARRAY_LENGTH, y],
  45749. [x + itemWidth, y],
  45750. [x + itemWidth, y + itemHeight],
  45751. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  45752. ];
  45753. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  45754. !head && points.push([x, y + itemHeight / 2]);
  45755. return points;
  45756. }
  45757. // Package custom mouse event.
  45758. function packEventData(el, seriesModel, itemNode) {
  45759. el.eventData = {
  45760. componentType: 'series',
  45761. componentSubType: 'treemap',
  45762. componentIndex: seriesModel.componentIndex,
  45763. seriesIndex: seriesModel.componentIndex,
  45764. seriesName: seriesModel.name,
  45765. seriesType: 'treemap',
  45766. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  45767. nodeData: {
  45768. dataIndex: itemNode && itemNode.dataIndex,
  45769. name: itemNode && itemNode.name
  45770. },
  45771. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  45772. };
  45773. }
  45774. /*
  45775. * Licensed to the Apache Software Foundation (ASF) under one
  45776. * or more contributor license agreements. See the NOTICE file
  45777. * distributed with this work for additional information
  45778. * regarding copyright ownership. The ASF licenses this file
  45779. * to you under the Apache License, Version 2.0 (the
  45780. * "License"); you may not use this file except in compliance
  45781. * with the License. You may obtain a copy of the License at
  45782. *
  45783. * http://www.apache.org/licenses/LICENSE-2.0
  45784. *
  45785. * Unless required by applicable law or agreed to in writing,
  45786. * software distributed under the License is distributed on an
  45787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45788. * KIND, either express or implied. See the License for the
  45789. * specific language governing permissions and limitations
  45790. * under the License.
  45791. */
  45792. /**
  45793. * @param {number} [time=500] Time in ms
  45794. * @param {string} [easing='linear']
  45795. * @param {number} [delay=0]
  45796. * @param {Function} [callback]
  45797. *
  45798. * @example
  45799. * // Animate position
  45800. * animation
  45801. * .createWrap()
  45802. * .add(el1, {position: [10, 10]})
  45803. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  45804. * .done(function () { // done })
  45805. * .start('cubicOut');
  45806. */
  45807. function createWrap() {
  45808. var storage = [];
  45809. var elExistsMap = {};
  45810. var doneCallback;
  45811. return {
  45812. /**
  45813. * Caution: a el can only be added once, otherwise 'done'
  45814. * might not be called. This method checks this (by el.id),
  45815. * suppresses adding and returns false when existing el found.
  45816. *
  45817. * @param {modele:zrender/Element} el
  45818. * @param {Object} target
  45819. * @param {number} [time=500]
  45820. * @param {number} [delay=0]
  45821. * @param {string} [easing='linear']
  45822. * @return {boolean} Whether adding succeeded.
  45823. *
  45824. * @example
  45825. * add(el, target, time, delay, easing);
  45826. * add(el, target, time, easing);
  45827. * add(el, target, time);
  45828. * add(el, target);
  45829. */
  45830. add: function (el, target, time, delay, easing) {
  45831. if (isString(delay)) {
  45832. easing = delay;
  45833. delay = 0;
  45834. }
  45835. if (elExistsMap[el.id]) {
  45836. return false;
  45837. }
  45838. elExistsMap[el.id] = 1;
  45839. storage.push(
  45840. {el: el, target: target, time: time, delay: delay, easing: easing}
  45841. );
  45842. return true;
  45843. },
  45844. /**
  45845. * Only execute when animation finished. Will not execute when any
  45846. * of 'stop' or 'stopAnimation' called.
  45847. *
  45848. * @param {Function} callback
  45849. */
  45850. done: function (callback) {
  45851. doneCallback = callback;
  45852. return this;
  45853. },
  45854. /**
  45855. * Will stop exist animation firstly.
  45856. */
  45857. start: function () {
  45858. var count = storage.length;
  45859. for (var i = 0, len = storage.length; i < len; i++) {
  45860. var item = storage[i];
  45861. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  45862. }
  45863. return this;
  45864. function done() {
  45865. count--;
  45866. if (!count) {
  45867. storage.length = 0;
  45868. elExistsMap = {};
  45869. doneCallback && doneCallback();
  45870. }
  45871. }
  45872. }
  45873. };
  45874. }
  45875. /*
  45876. * Licensed to the Apache Software Foundation (ASF) under one
  45877. * or more contributor license agreements. See the NOTICE file
  45878. * distributed with this work for additional information
  45879. * regarding copyright ownership. The ASF licenses this file
  45880. * to you under the Apache License, Version 2.0 (the
  45881. * "License"); you may not use this file except in compliance
  45882. * with the License. You may obtain a copy of the License at
  45883. *
  45884. * http://www.apache.org/licenses/LICENSE-2.0
  45885. *
  45886. * Unless required by applicable law or agreed to in writing,
  45887. * software distributed under the License is distributed on an
  45888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45889. * KIND, either express or implied. See the License for the
  45890. * specific language governing permissions and limitations
  45891. * under the License.
  45892. */
  45893. var bind$1 = bind;
  45894. var Group$2 = Group;
  45895. var Rect$1 = Rect;
  45896. var each$8 = each$1;
  45897. var DRAG_THRESHOLD = 3;
  45898. var PATH_LABEL_NOAMAL = ['label'];
  45899. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  45900. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  45901. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  45902. var Z_BASE = 10; // Should bigger than every z.
  45903. var Z_BG = 1;
  45904. var Z_CONTENT = 2;
  45905. var getItemStyleEmphasis = makeStyleMapper([
  45906. ['fill', 'color'],
  45907. // `borderColor` and `borderWidth` has been occupied,
  45908. // so use `stroke` to indicate the stroke of the rect.
  45909. ['stroke', 'strokeColor'],
  45910. ['lineWidth', 'strokeWidth'],
  45911. ['shadowBlur'],
  45912. ['shadowOffsetX'],
  45913. ['shadowOffsetY'],
  45914. ['shadowColor']
  45915. ]);
  45916. var getItemStyleNormal = function (model) {
  45917. // Normal style props should include emphasis style props.
  45918. var itemStyle = getItemStyleEmphasis(model);
  45919. // Clear styles set by emphasis.
  45920. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  45921. return itemStyle;
  45922. };
  45923. extendChartView({
  45924. type: 'treemap',
  45925. /**
  45926. * @override
  45927. */
  45928. init: function (o, api) {
  45929. /**
  45930. * @private
  45931. * @type {module:zrender/container/Group}
  45932. */
  45933. this._containerGroup;
  45934. /**
  45935. * @private
  45936. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  45937. */
  45938. this._storage = createStorage();
  45939. /**
  45940. * @private
  45941. * @type {module:echarts/data/Tree}
  45942. */
  45943. this._oldTree;
  45944. /**
  45945. * @private
  45946. * @type {module:echarts/chart/treemap/Breadcrumb}
  45947. */
  45948. this._breadcrumb;
  45949. /**
  45950. * @private
  45951. * @type {module:echarts/component/helper/RoamController}
  45952. */
  45953. this._controller;
  45954. /**
  45955. * 'ready', 'animating'
  45956. * @private
  45957. */
  45958. this._state = 'ready';
  45959. },
  45960. /**
  45961. * @override
  45962. */
  45963. render: function (seriesModel, ecModel, api, payload) {
  45964. var models = ecModel.findComponents({
  45965. mainType: 'series', subType: 'treemap', query: payload
  45966. });
  45967. if (indexOf(models, seriesModel) < 0) {
  45968. return;
  45969. }
  45970. this.seriesModel = seriesModel;
  45971. this.api = api;
  45972. this.ecModel = ecModel;
  45973. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  45974. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  45975. var payloadType = payload && payload.type;
  45976. var layoutInfo = seriesModel.layoutInfo;
  45977. var isInit = !this._oldTree;
  45978. var thisStorage = this._storage;
  45979. // Mark new root when action is treemapRootToNode.
  45980. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  45981. ? {
  45982. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  45983. direction: payload.direction
  45984. }
  45985. : null;
  45986. var containerGroup = this._giveContainerGroup(layoutInfo);
  45987. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  45988. (
  45989. !isInit && (
  45990. !payloadType
  45991. || payloadType === 'treemapZoomToNode'
  45992. || payloadType === 'treemapRootToNode'
  45993. )
  45994. )
  45995. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  45996. : renderResult.renderFinally();
  45997. this._resetController(api);
  45998. this._renderBreadcrumb(seriesModel, api, targetInfo);
  45999. },
  46000. /**
  46001. * @private
  46002. */
  46003. _giveContainerGroup: function (layoutInfo) {
  46004. var containerGroup = this._containerGroup;
  46005. if (!containerGroup) {
  46006. // FIXME
  46007. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  46008. containerGroup = this._containerGroup = new Group$2();
  46009. this._initEvents(containerGroup);
  46010. this.group.add(containerGroup);
  46011. }
  46012. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  46013. return containerGroup;
  46014. },
  46015. /**
  46016. * @private
  46017. */
  46018. _doRender: function (containerGroup, seriesModel, reRoot) {
  46019. var thisTree = seriesModel.getData().tree;
  46020. var oldTree = this._oldTree;
  46021. // Clear last shape records.
  46022. var lastsForAnimation = createStorage();
  46023. var thisStorage = createStorage();
  46024. var oldStorage = this._storage;
  46025. var willInvisibleEls = [];
  46026. var doRenderNode = curry(
  46027. renderNode, seriesModel,
  46028. thisStorage, oldStorage, reRoot,
  46029. lastsForAnimation, willInvisibleEls
  46030. );
  46031. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  46032. // the oldTree is actually losted, so we can not find all of the old graphic
  46033. // elements from tree. So we use this stragegy: make element storage, move
  46034. // from old storage to new storage, clear old storage.
  46035. dualTravel(
  46036. thisTree.root ? [thisTree.root] : [],
  46037. (oldTree && oldTree.root) ? [oldTree.root] : [],
  46038. containerGroup,
  46039. thisTree === oldTree || !oldTree,
  46040. 0
  46041. );
  46042. // Process all removing.
  46043. var willDeleteEls = clearStorage(oldStorage);
  46044. this._oldTree = thisTree;
  46045. this._storage = thisStorage;
  46046. return {
  46047. lastsForAnimation: lastsForAnimation,
  46048. willDeleteEls: willDeleteEls,
  46049. renderFinally: renderFinally
  46050. };
  46051. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  46052. // When 'render' is triggered by action,
  46053. // 'this' and 'old' may be the same tree,
  46054. // we use rawIndex in that case.
  46055. if (sameTree) {
  46056. oldViewChildren = thisViewChildren;
  46057. each$8(thisViewChildren, function (child, index) {
  46058. !child.isRemoved() && processNode(index, index);
  46059. });
  46060. }
  46061. // Diff hierarchically (diff only in each subtree, but not whole).
  46062. // because, consistency of view is important.
  46063. else {
  46064. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  46065. .add(processNode)
  46066. .update(processNode)
  46067. .remove(curry(processNode, null))
  46068. .execute();
  46069. }
  46070. function getKey(node) {
  46071. // Identify by name or raw index.
  46072. return node.getId();
  46073. }
  46074. function processNode(newIndex, oldIndex) {
  46075. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  46076. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  46077. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  46078. group && dualTravel(
  46079. thisNode && thisNode.viewChildren || [],
  46080. oldNode && oldNode.viewChildren || [],
  46081. group,
  46082. sameTree,
  46083. depth + 1
  46084. );
  46085. }
  46086. }
  46087. function clearStorage(storage) {
  46088. var willDeleteEls = createStorage();
  46089. storage && each$8(storage, function (store, storageName) {
  46090. var delEls = willDeleteEls[storageName];
  46091. each$8(store, function (el) {
  46092. el && (delEls.push(el), el.__tmWillDelete = 1);
  46093. });
  46094. });
  46095. return willDeleteEls;
  46096. }
  46097. function renderFinally() {
  46098. each$8(willDeleteEls, function (els) {
  46099. each$8(els, function (el) {
  46100. el.parent && el.parent.remove(el);
  46101. });
  46102. });
  46103. each$8(willInvisibleEls, function (el) {
  46104. el.invisible = true;
  46105. // Setting invisible is for optimizing, so no need to set dirty,
  46106. // just mark as invisible.
  46107. el.dirty();
  46108. });
  46109. }
  46110. },
  46111. /**
  46112. * @private
  46113. */
  46114. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  46115. if (!seriesModel.get('animation')) {
  46116. return;
  46117. }
  46118. var duration = seriesModel.get('animationDurationUpdate');
  46119. var easing = seriesModel.get('animationEasing');
  46120. var animationWrap = createWrap();
  46121. // Make delete animations.
  46122. each$8(renderResult.willDeleteEls, function (store, storageName) {
  46123. each$8(store, function (el, rawIndex) {
  46124. if (el.invisible) {
  46125. return;
  46126. }
  46127. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  46128. var target;
  46129. if (reRoot && reRoot.direction === 'drillDown') {
  46130. target = parent === reRoot.rootNodeGroup
  46131. // This is the content element of view root.
  46132. // Only `content` will enter this branch, because
  46133. // `background` and `nodeGroup` will not be deleted.
  46134. ? {
  46135. shape: {
  46136. x: 0,
  46137. y: 0,
  46138. width: parent.__tmNodeWidth,
  46139. height: parent.__tmNodeHeight
  46140. },
  46141. style: {
  46142. opacity: 0
  46143. }
  46144. }
  46145. // Others.
  46146. : {style: {opacity: 0}};
  46147. }
  46148. else {
  46149. var targetX = 0;
  46150. var targetY = 0;
  46151. if (!parent.__tmWillDelete) {
  46152. // Let node animate to right-bottom corner, cooperating with fadeout,
  46153. // which is appropriate for user understanding.
  46154. // Divided by 2 for reRoot rolling up effect.
  46155. targetX = parent.__tmNodeWidth / 2;
  46156. targetY = parent.__tmNodeHeight / 2;
  46157. }
  46158. target = storageName === 'nodeGroup'
  46159. ? {position: [targetX, targetY], style: {opacity: 0}}
  46160. : {
  46161. shape: {x: targetX, y: targetY, width: 0, height: 0},
  46162. style: {opacity: 0}
  46163. };
  46164. }
  46165. target && animationWrap.add(el, target, duration, easing);
  46166. });
  46167. });
  46168. // Make other animations
  46169. each$8(this._storage, function (store, storageName) {
  46170. each$8(store, function (el, rawIndex) {
  46171. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  46172. var target = {};
  46173. if (!last) {
  46174. return;
  46175. }
  46176. if (storageName === 'nodeGroup') {
  46177. if (last.old) {
  46178. target.position = el.position.slice();
  46179. el.attr('position', last.old);
  46180. }
  46181. }
  46182. else {
  46183. if (last.old) {
  46184. target.shape = extend({}, el.shape);
  46185. el.setShape(last.old);
  46186. }
  46187. if (last.fadein) {
  46188. el.setStyle('opacity', 0);
  46189. target.style = {opacity: 1};
  46190. }
  46191. // When animation is stopped for succedent animation starting,
  46192. // el.style.opacity might not be 1
  46193. else if (el.style.opacity !== 1) {
  46194. target.style = {opacity: 1};
  46195. }
  46196. }
  46197. animationWrap.add(el, target, duration, easing);
  46198. });
  46199. }, this);
  46200. this._state = 'animating';
  46201. animationWrap
  46202. .done(bind$1(function () {
  46203. this._state = 'ready';
  46204. renderResult.renderFinally();
  46205. }, this))
  46206. .start();
  46207. },
  46208. /**
  46209. * @private
  46210. */
  46211. _resetController: function (api) {
  46212. var controller = this._controller;
  46213. // Init controller.
  46214. if (!controller) {
  46215. controller = this._controller = new RoamController(api.getZr());
  46216. controller.enable(this.seriesModel.get('roam'));
  46217. controller.on('pan', bind$1(this._onPan, this));
  46218. controller.on('zoom', bind$1(this._onZoom, this));
  46219. }
  46220. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  46221. controller.setPointerChecker(function (e, x, y) {
  46222. return rect.contain(x, y);
  46223. });
  46224. },
  46225. /**
  46226. * @private
  46227. */
  46228. _clearController: function () {
  46229. var controller = this._controller;
  46230. if (controller) {
  46231. controller.dispose();
  46232. controller = null;
  46233. }
  46234. },
  46235. /**
  46236. * @private
  46237. */
  46238. _onPan: function (e) {
  46239. if (this._state !== 'animating'
  46240. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  46241. ) {
  46242. // These param must not be cached.
  46243. var root = this.seriesModel.getData().tree.root;
  46244. if (!root) {
  46245. return;
  46246. }
  46247. var rootLayout = root.getLayout();
  46248. if (!rootLayout) {
  46249. return;
  46250. }
  46251. this.api.dispatchAction({
  46252. type: 'treemapMove',
  46253. from: this.uid,
  46254. seriesId: this.seriesModel.id,
  46255. rootRect: {
  46256. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  46257. width: rootLayout.width, height: rootLayout.height
  46258. }
  46259. });
  46260. }
  46261. },
  46262. /**
  46263. * @private
  46264. */
  46265. _onZoom: function (e) {
  46266. var mouseX = e.originX;
  46267. var mouseY = e.originY;
  46268. if (this._state !== 'animating') {
  46269. // These param must not be cached.
  46270. var root = this.seriesModel.getData().tree.root;
  46271. if (!root) {
  46272. return;
  46273. }
  46274. var rootLayout = root.getLayout();
  46275. if (!rootLayout) {
  46276. return;
  46277. }
  46278. var rect = new BoundingRect(
  46279. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  46280. );
  46281. var layoutInfo = this.seriesModel.layoutInfo;
  46282. // Transform mouse coord from global to containerGroup.
  46283. mouseX -= layoutInfo.x;
  46284. mouseY -= layoutInfo.y;
  46285. // Scale root bounding rect.
  46286. var m = create$1();
  46287. translate(m, m, [-mouseX, -mouseY]);
  46288. scale$1(m, m, [e.scale, e.scale]);
  46289. translate(m, m, [mouseX, mouseY]);
  46290. rect.applyTransform(m);
  46291. this.api.dispatchAction({
  46292. type: 'treemapRender',
  46293. from: this.uid,
  46294. seriesId: this.seriesModel.id,
  46295. rootRect: {
  46296. x: rect.x, y: rect.y,
  46297. width: rect.width, height: rect.height
  46298. }
  46299. });
  46300. }
  46301. },
  46302. /**
  46303. * @private
  46304. */
  46305. _initEvents: function (containerGroup) {
  46306. containerGroup.on('click', function (e) {
  46307. if (this._state !== 'ready') {
  46308. return;
  46309. }
  46310. var nodeClick = this.seriesModel.get('nodeClick', true);
  46311. if (!nodeClick) {
  46312. return;
  46313. }
  46314. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  46315. if (!targetInfo) {
  46316. return;
  46317. }
  46318. var node = targetInfo.node;
  46319. if (node.getLayout().isLeafRoot) {
  46320. this._rootToNode(targetInfo);
  46321. }
  46322. else {
  46323. if (nodeClick === 'zoomToNode') {
  46324. this._zoomToNode(targetInfo);
  46325. }
  46326. else if (nodeClick === 'link') {
  46327. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  46328. var link = itemModel.get('link', true);
  46329. var linkTarget = itemModel.get('target', true) || 'blank';
  46330. link && window.open(link, linkTarget);
  46331. }
  46332. }
  46333. }, this);
  46334. },
  46335. /**
  46336. * @private
  46337. */
  46338. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  46339. if (!targetInfo) {
  46340. targetInfo = seriesModel.get('leafDepth', true) != null
  46341. ? {node: seriesModel.getViewRoot()}
  46342. // FIXME
  46343. // better way?
  46344. // Find breadcrumb tail on center of containerGroup.
  46345. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  46346. if (!targetInfo) {
  46347. targetInfo = {node: seriesModel.getData().tree.root};
  46348. }
  46349. }
  46350. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  46351. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  46352. function onSelect(node) {
  46353. if (this._state !== 'animating') {
  46354. aboveViewRoot(seriesModel.getViewRoot(), node)
  46355. ? this._rootToNode({node: node})
  46356. : this._zoomToNode({node: node});
  46357. }
  46358. }
  46359. },
  46360. /**
  46361. * @override
  46362. */
  46363. remove: function () {
  46364. this._clearController();
  46365. this._containerGroup && this._containerGroup.removeAll();
  46366. this._storage = createStorage();
  46367. this._state = 'ready';
  46368. this._breadcrumb && this._breadcrumb.remove();
  46369. },
  46370. dispose: function () {
  46371. this._clearController();
  46372. },
  46373. /**
  46374. * @private
  46375. */
  46376. _zoomToNode: function (targetInfo) {
  46377. this.api.dispatchAction({
  46378. type: 'treemapZoomToNode',
  46379. from: this.uid,
  46380. seriesId: this.seriesModel.id,
  46381. targetNode: targetInfo.node
  46382. });
  46383. },
  46384. /**
  46385. * @private
  46386. */
  46387. _rootToNode: function (targetInfo) {
  46388. this.api.dispatchAction({
  46389. type: 'treemapRootToNode',
  46390. from: this.uid,
  46391. seriesId: this.seriesModel.id,
  46392. targetNode: targetInfo.node
  46393. });
  46394. },
  46395. /**
  46396. * @public
  46397. * @param {number} x Global coord x.
  46398. * @param {number} y Global coord y.
  46399. * @return {Object} info If not found, return undefined;
  46400. * @return {number} info.node Target node.
  46401. * @return {number} info.offsetX x refer to target node.
  46402. * @return {number} info.offsetY y refer to target node.
  46403. */
  46404. findTarget: function (x, y) {
  46405. var targetInfo;
  46406. var viewRoot = this.seriesModel.getViewRoot();
  46407. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  46408. var bgEl = this._storage.background[node.getRawIndex()];
  46409. // If invisible, there might be no element.
  46410. if (bgEl) {
  46411. var point = bgEl.transformCoordToLocal(x, y);
  46412. var shape = bgEl.shape;
  46413. // For performance consideration, dont use 'getBoundingRect'.
  46414. if (shape.x <= point[0]
  46415. && point[0] <= shape.x + shape.width
  46416. && shape.y <= point[1]
  46417. && point[1] <= shape.y + shape.height
  46418. ) {
  46419. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  46420. }
  46421. else {
  46422. return false; // Suppress visit subtree.
  46423. }
  46424. }
  46425. }, this);
  46426. return targetInfo;
  46427. }
  46428. });
  46429. /**
  46430. * @inner
  46431. */
  46432. function createStorage() {
  46433. return {nodeGroup: [], background: [], content: []};
  46434. }
  46435. /**
  46436. * @inner
  46437. * @return Return undefined means do not travel further.
  46438. */
  46439. function renderNode(
  46440. seriesModel, thisStorage, oldStorage, reRoot,
  46441. lastsForAnimation, willInvisibleEls,
  46442. thisNode, oldNode, parentGroup, depth
  46443. ) {
  46444. // Whether under viewRoot.
  46445. if (!thisNode) {
  46446. // Deleting nodes will be performed finally. This method just find
  46447. // element from old storage, or create new element, set them to new
  46448. // storage, and set styles.
  46449. return;
  46450. }
  46451. // -------------------------------------------------------------------
  46452. // Start of closure variables available in "Procedures in renderNode".
  46453. var thisLayout = thisNode.getLayout();
  46454. if (!thisLayout || !thisLayout.isInView) {
  46455. return;
  46456. }
  46457. var thisWidth = thisLayout.width;
  46458. var thisHeight = thisLayout.height;
  46459. var borderWidth = thisLayout.borderWidth;
  46460. var thisInvisible = thisLayout.invisible;
  46461. var thisRawIndex = thisNode.getRawIndex();
  46462. var oldRawIndex = oldNode && oldNode.getRawIndex();
  46463. var thisViewChildren = thisNode.viewChildren;
  46464. var upperHeight = thisLayout.upperHeight;
  46465. var isParent = thisViewChildren && thisViewChildren.length;
  46466. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  46467. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  46468. // End of closure ariables available in "Procedures in renderNode".
  46469. // -----------------------------------------------------------------
  46470. // Node group
  46471. var group = giveGraphic('nodeGroup', Group$2);
  46472. if (!group) {
  46473. return;
  46474. }
  46475. parentGroup.add(group);
  46476. // x,y are not set when el is above view root.
  46477. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  46478. group.__tmNodeWidth = thisWidth;
  46479. group.__tmNodeHeight = thisHeight;
  46480. if (thisLayout.isAboveViewRoot) {
  46481. return group;
  46482. }
  46483. // Background
  46484. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  46485. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  46486. // No children, render content.
  46487. if (!isParent) {
  46488. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  46489. content && renderContent(group, content);
  46490. }
  46491. return group;
  46492. // ----------------------------
  46493. // | Procedures in renderNode |
  46494. // ----------------------------
  46495. function renderBackground(group, bg, useUpperLabel) {
  46496. // For tooltip.
  46497. bg.dataIndex = thisNode.dataIndex;
  46498. bg.seriesIndex = seriesModel.seriesIndex;
  46499. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  46500. var visualBorderColor = thisNode.getVisual('borderColor', true);
  46501. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  46502. updateStyle(bg, function () {
  46503. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  46504. normalStyle.fill = visualBorderColor;
  46505. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  46506. emphasisStyle.fill = emphasisBorderColor;
  46507. if (useUpperLabel) {
  46508. var upperLabelWidth = thisWidth - 2 * borderWidth;
  46509. prepareText(
  46510. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  46511. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  46512. );
  46513. }
  46514. // For old bg.
  46515. else {
  46516. normalStyle.text = emphasisStyle.text = null;
  46517. }
  46518. bg.setStyle(normalStyle);
  46519. setHoverStyle(bg, emphasisStyle);
  46520. });
  46521. group.add(bg);
  46522. }
  46523. function renderContent(group, content) {
  46524. // For tooltip.
  46525. content.dataIndex = thisNode.dataIndex;
  46526. content.seriesIndex = seriesModel.seriesIndex;
  46527. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  46528. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  46529. content.culling = true;
  46530. content.setShape({
  46531. x: borderWidth,
  46532. y: borderWidth,
  46533. width: contentWidth,
  46534. height: contentHeight
  46535. });
  46536. var visualColor = thisNode.getVisual('color', true);
  46537. updateStyle(content, function () {
  46538. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  46539. normalStyle.fill = visualColor;
  46540. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  46541. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  46542. content.setStyle(normalStyle);
  46543. setHoverStyle(content, emphasisStyle);
  46544. });
  46545. group.add(content);
  46546. }
  46547. function updateStyle(element, cb) {
  46548. if (!thisInvisible) {
  46549. // If invisible, do not set visual, otherwise the element will
  46550. // change immediately before animation. We think it is OK to
  46551. // remain its origin color when moving out of the view window.
  46552. cb();
  46553. if (!element.__tmWillVisible) {
  46554. element.invisible = false;
  46555. }
  46556. }
  46557. else {
  46558. // Delay invisible setting utill animation finished,
  46559. // avoid element vanish suddenly before animation.
  46560. !element.invisible && willInvisibleEls.push(element);
  46561. }
  46562. }
  46563. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  46564. var nodeModel = thisNode.getModel();
  46565. var text = retrieve(
  46566. seriesModel.getFormattedLabel(
  46567. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  46568. ),
  46569. nodeModel.get('name')
  46570. );
  46571. if (!upperLabelRect && thisLayout.isLeafRoot) {
  46572. var iconChar = seriesModel.get('drillDownIcon', true);
  46573. text = iconChar ? iconChar + ' ' + text : text;
  46574. }
  46575. var normalLabelModel = nodeModel.getModel(
  46576. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  46577. );
  46578. var emphasisLabelModel = nodeModel.getModel(
  46579. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  46580. );
  46581. var isShow = normalLabelModel.getShallow('show');
  46582. setLabelStyle(
  46583. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  46584. {
  46585. defaultText: isShow ? text : null,
  46586. autoColor: visualColor,
  46587. isRectText: true
  46588. }
  46589. );
  46590. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  46591. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  46592. ? {
  46593. outerWidth: width,
  46594. outerHeight: height,
  46595. minChar: 2
  46596. }
  46597. : null;
  46598. }
  46599. function giveGraphic(storageName, Ctor, depth, z) {
  46600. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  46601. var lasts = lastsForAnimation[storageName];
  46602. if (element) {
  46603. // Remove from oldStorage
  46604. oldStorage[storageName][oldRawIndex] = null;
  46605. prepareAnimationWhenHasOld(lasts, element, storageName);
  46606. }
  46607. // If invisible and no old element, do not create new element (for optimizing).
  46608. else if (!thisInvisible) {
  46609. element = new Ctor({z: calculateZ(depth, z)});
  46610. element.__tmDepth = depth;
  46611. element.__tmStorageName = storageName;
  46612. prepareAnimationWhenNoOld(lasts, element, storageName);
  46613. }
  46614. // Set to thisStorage
  46615. return (thisStorage[storageName][thisRawIndex] = element);
  46616. }
  46617. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  46618. var lastCfg = lasts[thisRawIndex] = {};
  46619. lastCfg.old = storageName === 'nodeGroup'
  46620. ? element.position.slice()
  46621. : extend({}, element.shape);
  46622. }
  46623. // If a element is new, we need to find the animation start point carefully,
  46624. // otherwise it will looks strange when 'zoomToNode'.
  46625. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  46626. var lastCfg = lasts[thisRawIndex] = {};
  46627. var parentNode = thisNode.parentNode;
  46628. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  46629. var parentOldX = 0;
  46630. var parentOldY = 0;
  46631. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  46632. // For convenience, get old bounding rect from background.
  46633. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  46634. if (!reRoot && parentOldBg && parentOldBg.old) {
  46635. parentOldX = parentOldBg.old.width;
  46636. parentOldY = parentOldBg.old.height;
  46637. }
  46638. // When no parent old shape found, its parent is new too,
  46639. // so we can just use {x:0, y:0}.
  46640. lastCfg.old = storageName === 'nodeGroup'
  46641. ? [0, parentOldY]
  46642. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  46643. }
  46644. // Fade in, user can be aware that these nodes are new.
  46645. lastCfg.fadein = storageName !== 'nodeGroup';
  46646. }
  46647. }
  46648. // We can not set all backgroud with the same z, Because the behaviour of
  46649. // drill down and roll up differ background creation sequence from tree
  46650. // hierarchy sequence, which cause that lowser background element overlap
  46651. // upper ones. So we calculate z based on depth.
  46652. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  46653. // treemap with large z overlaps other components.
  46654. function calculateZ(depth, zInLevel) {
  46655. var zb = depth * Z_BASE + zInLevel;
  46656. return (zb - 1) / zb;
  46657. }
  46658. /*
  46659. * Licensed to the Apache Software Foundation (ASF) under one
  46660. * or more contributor license agreements. See the NOTICE file
  46661. * distributed with this work for additional information
  46662. * regarding copyright ownership. The ASF licenses this file
  46663. * to you under the Apache License, Version 2.0 (the
  46664. * "License"); you may not use this file except in compliance
  46665. * with the License. You may obtain a copy of the License at
  46666. *
  46667. * http://www.apache.org/licenses/LICENSE-2.0
  46668. *
  46669. * Unless required by applicable law or agreed to in writing,
  46670. * software distributed under the License is distributed on an
  46671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46672. * KIND, either express or implied. See the License for the
  46673. * specific language governing permissions and limitations
  46674. * under the License.
  46675. */
  46676. /**
  46677. * @file Treemap action
  46678. */
  46679. var noop$1 = function () {};
  46680. var actionTypes = [
  46681. 'treemapZoomToNode',
  46682. 'treemapRender',
  46683. 'treemapMove'
  46684. ];
  46685. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  46686. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  46687. }
  46688. registerAction(
  46689. {type: 'treemapRootToNode', update: 'updateView'},
  46690. function (payload, ecModel) {
  46691. ecModel.eachComponent(
  46692. {mainType: 'series', subType: 'treemap', query: payload},
  46693. handleRootToNode
  46694. );
  46695. function handleRootToNode(model, index) {
  46696. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  46697. var targetInfo = retrieveTargetInfo(payload, types, model);
  46698. if (targetInfo) {
  46699. var originViewRoot = model.getViewRoot();
  46700. if (originViewRoot) {
  46701. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  46702. ? 'rollUp' : 'drillDown';
  46703. }
  46704. model.resetViewRoot(targetInfo.node);
  46705. }
  46706. }
  46707. }
  46708. );
  46709. /*
  46710. * Licensed to the Apache Software Foundation (ASF) under one
  46711. * or more contributor license agreements. See the NOTICE file
  46712. * distributed with this work for additional information
  46713. * regarding copyright ownership. The ASF licenses this file
  46714. * to you under the Apache License, Version 2.0 (the
  46715. * "License"); you may not use this file except in compliance
  46716. * with the License. You may obtain a copy of the License at
  46717. *
  46718. * http://www.apache.org/licenses/LICENSE-2.0
  46719. *
  46720. * Unless required by applicable law or agreed to in writing,
  46721. * software distributed under the License is distributed on an
  46722. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46723. * KIND, either express or implied. See the License for the
  46724. * specific language governing permissions and limitations
  46725. * under the License.
  46726. */
  46727. var each$9 = each$1;
  46728. var isObject$5 = isObject$1;
  46729. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  46730. /**
  46731. * @param {Object} option
  46732. * @param {string} [option.type] See visualHandlers.
  46733. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  46734. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  46735. * required when mappingMethod is 'linear'
  46736. * @param {Array.<Object>=} [option.pieceList] [
  46737. * {value: someValue},
  46738. * {interval: [min1, max1], visual: {...}},
  46739. * {interval: [min2, max2]}
  46740. * ],
  46741. * required when mappingMethod is 'piecewise'.
  46742. * Visual for only each piece can be specified.
  46743. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  46744. * required when mappingMethod is 'category'.
  46745. * If no option.categories, categories is set
  46746. * as [0, 1, 2, ...].
  46747. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  46748. * @param {(Array|Object|*)} [option.visual] Visual data.
  46749. * when mappingMethod is 'category',
  46750. * visual data can be array or object
  46751. * (like: {cate1: '#222', none: '#fff'})
  46752. * or primary types (which represents
  46753. * defualt category visual), otherwise visual
  46754. * can be array or primary (which will be
  46755. * normalized to array).
  46756. *
  46757. */
  46758. var VisualMapping = function (option) {
  46759. var mappingMethod = option.mappingMethod;
  46760. var visualType = option.type;
  46761. /**
  46762. * @readOnly
  46763. * @type {Object}
  46764. */
  46765. var thisOption = this.option = clone(option);
  46766. /**
  46767. * @readOnly
  46768. * @type {string}
  46769. */
  46770. this.type = visualType;
  46771. /**
  46772. * @readOnly
  46773. * @type {string}
  46774. */
  46775. this.mappingMethod = mappingMethod;
  46776. /**
  46777. * @private
  46778. * @type {Function}
  46779. */
  46780. this._normalizeData = normalizers[mappingMethod];
  46781. var visualHandler = visualHandlers[visualType];
  46782. /**
  46783. * @public
  46784. * @type {Function}
  46785. */
  46786. this.applyVisual = visualHandler.applyVisual;
  46787. /**
  46788. * @public
  46789. * @type {Function}
  46790. */
  46791. this.getColorMapper = visualHandler.getColorMapper;
  46792. /**
  46793. * @private
  46794. * @type {Function}
  46795. */
  46796. this._doMap = visualHandler._doMap[mappingMethod];
  46797. if (mappingMethod === 'piecewise') {
  46798. normalizeVisualRange(thisOption);
  46799. preprocessForPiecewise(thisOption);
  46800. }
  46801. else if (mappingMethod === 'category') {
  46802. thisOption.categories
  46803. ? preprocessForSpecifiedCategory(thisOption)
  46804. // categories is ordinal when thisOption.categories not specified,
  46805. // which need no more preprocess except normalize visual.
  46806. : normalizeVisualRange(thisOption, true);
  46807. }
  46808. else { // mappingMethod === 'linear' or 'fixed'
  46809. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  46810. normalizeVisualRange(thisOption);
  46811. }
  46812. };
  46813. VisualMapping.prototype = {
  46814. constructor: VisualMapping,
  46815. mapValueToVisual: function (value) {
  46816. var normalized = this._normalizeData(value);
  46817. return this._doMap(normalized, value);
  46818. },
  46819. getNormalizer: function () {
  46820. return bind(this._normalizeData, this);
  46821. }
  46822. };
  46823. var visualHandlers = VisualMapping.visualHandlers = {
  46824. color: {
  46825. applyVisual: makeApplyVisual('color'),
  46826. /**
  46827. * Create a mapper function
  46828. * @return {Function}
  46829. */
  46830. getColorMapper: function () {
  46831. var thisOption = this.option;
  46832. return bind(
  46833. thisOption.mappingMethod === 'category'
  46834. ? function (value, isNormalized) {
  46835. !isNormalized && (value = this._normalizeData(value));
  46836. return doMapCategory.call(this, value);
  46837. }
  46838. : function (value, isNormalized, out) {
  46839. // If output rgb array
  46840. // which will be much faster and useful in pixel manipulation
  46841. var returnRGBArray = !!out;
  46842. !isNormalized && (value = this._normalizeData(value));
  46843. out = fastLerp(value, thisOption.parsedVisual, out);
  46844. return returnRGBArray ? out : stringify(out, 'rgba');
  46845. },
  46846. this
  46847. );
  46848. },
  46849. _doMap: {
  46850. linear: function (normalized) {
  46851. return stringify(
  46852. fastLerp(normalized, this.option.parsedVisual),
  46853. 'rgba'
  46854. );
  46855. },
  46856. category: doMapCategory,
  46857. piecewise: function (normalized, value) {
  46858. var result = getSpecifiedVisual.call(this, value);
  46859. if (result == null) {
  46860. result = stringify(
  46861. fastLerp(normalized, this.option.parsedVisual),
  46862. 'rgba'
  46863. );
  46864. }
  46865. return result;
  46866. },
  46867. fixed: doMapFixed
  46868. }
  46869. },
  46870. colorHue: makePartialColorVisualHandler(function (color, value) {
  46871. return modifyHSL(color, value);
  46872. }),
  46873. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  46874. return modifyHSL(color, null, value);
  46875. }),
  46876. colorLightness: makePartialColorVisualHandler(function (color, value) {
  46877. return modifyHSL(color, null, null, value);
  46878. }),
  46879. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  46880. return modifyAlpha(color, value);
  46881. }),
  46882. opacity: {
  46883. applyVisual: makeApplyVisual('opacity'),
  46884. _doMap: makeDoMap([0, 1])
  46885. },
  46886. liftZ: {
  46887. applyVisual: makeApplyVisual('liftZ'),
  46888. _doMap: {
  46889. linear: doMapFixed,
  46890. category: doMapFixed,
  46891. piecewise: doMapFixed,
  46892. fixed: doMapFixed
  46893. }
  46894. },
  46895. symbol: {
  46896. applyVisual: function (value, getter, setter) {
  46897. var symbolCfg = this.mapValueToVisual(value);
  46898. if (isString(symbolCfg)) {
  46899. setter('symbol', symbolCfg);
  46900. }
  46901. else if (isObject$5(symbolCfg)) {
  46902. for (var name in symbolCfg) {
  46903. if (symbolCfg.hasOwnProperty(name)) {
  46904. setter(name, symbolCfg[name]);
  46905. }
  46906. }
  46907. }
  46908. },
  46909. _doMap: {
  46910. linear: doMapToArray,
  46911. category: doMapCategory,
  46912. piecewise: function (normalized, value) {
  46913. var result = getSpecifiedVisual.call(this, value);
  46914. if (result == null) {
  46915. result = doMapToArray.call(this, normalized);
  46916. }
  46917. return result;
  46918. },
  46919. fixed: doMapFixed
  46920. }
  46921. },
  46922. symbolSize: {
  46923. applyVisual: makeApplyVisual('symbolSize'),
  46924. _doMap: makeDoMap([0, 1])
  46925. }
  46926. };
  46927. function preprocessForPiecewise(thisOption) {
  46928. var pieceList = thisOption.pieceList;
  46929. thisOption.hasSpecialVisual = false;
  46930. each$1(pieceList, function (piece, index) {
  46931. piece.originIndex = index;
  46932. // piece.visual is "result visual value" but not
  46933. // a visual range, so it does not need to be normalized.
  46934. if (piece.visual != null) {
  46935. thisOption.hasSpecialVisual = true;
  46936. }
  46937. });
  46938. }
  46939. function preprocessForSpecifiedCategory(thisOption) {
  46940. // Hash categories.
  46941. var categories = thisOption.categories;
  46942. var visual = thisOption.visual;
  46943. var categoryMap = thisOption.categoryMap = {};
  46944. each$9(categories, function (cate, index) {
  46945. categoryMap[cate] = index;
  46946. });
  46947. // Process visual map input.
  46948. if (!isArray(visual)) {
  46949. var visualArr = [];
  46950. if (isObject$1(visual)) {
  46951. each$9(visual, function (v, cate) {
  46952. var index = categoryMap[cate];
  46953. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  46954. });
  46955. }
  46956. else { // Is primary type, represents default visual.
  46957. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  46958. }
  46959. visual = setVisualToOption(thisOption, visualArr);
  46960. }
  46961. // Remove categories that has no visual,
  46962. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  46963. for (var i = categories.length - 1; i >= 0; i--) {
  46964. if (visual[i] == null) {
  46965. delete categoryMap[categories[i]];
  46966. categories.pop();
  46967. }
  46968. }
  46969. }
  46970. function normalizeVisualRange(thisOption, isCategory) {
  46971. var visual = thisOption.visual;
  46972. var visualArr = [];
  46973. if (isObject$1(visual)) {
  46974. each$9(visual, function (v) {
  46975. visualArr.push(v);
  46976. });
  46977. }
  46978. else if (visual != null) {
  46979. visualArr.push(visual);
  46980. }
  46981. var doNotNeedPair = {color: 1, symbol: 1};
  46982. if (!isCategory
  46983. && visualArr.length === 1
  46984. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  46985. ) {
  46986. // Do not care visualArr.length === 0, which is illegal.
  46987. visualArr[1] = visualArr[0];
  46988. }
  46989. setVisualToOption(thisOption, visualArr);
  46990. }
  46991. function makePartialColorVisualHandler(applyValue) {
  46992. return {
  46993. applyVisual: function (value, getter, setter) {
  46994. value = this.mapValueToVisual(value);
  46995. // Must not be array value
  46996. setter('color', applyValue(getter('color'), value));
  46997. },
  46998. _doMap: makeDoMap([0, 1])
  46999. };
  47000. }
  47001. function doMapToArray(normalized) {
  47002. var visual = this.option.visual;
  47003. return visual[
  47004. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  47005. ] || {};
  47006. }
  47007. function makeApplyVisual(visualType) {
  47008. return function (value, getter, setter) {
  47009. setter(visualType, this.mapValueToVisual(value));
  47010. };
  47011. }
  47012. function doMapCategory(normalized) {
  47013. var visual = this.option.visual;
  47014. return visual[
  47015. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  47016. ? normalized % visual.length
  47017. : normalized
  47018. ];
  47019. }
  47020. function doMapFixed() {
  47021. return this.option.visual[0];
  47022. }
  47023. function makeDoMap(sourceExtent) {
  47024. return {
  47025. linear: function (normalized) {
  47026. return linearMap(normalized, sourceExtent, this.option.visual, true);
  47027. },
  47028. category: doMapCategory,
  47029. piecewise: function (normalized, value) {
  47030. var result = getSpecifiedVisual.call(this, value);
  47031. if (result == null) {
  47032. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  47033. }
  47034. return result;
  47035. },
  47036. fixed: doMapFixed
  47037. };
  47038. }
  47039. function getSpecifiedVisual(value) {
  47040. var thisOption = this.option;
  47041. var pieceList = thisOption.pieceList;
  47042. if (thisOption.hasSpecialVisual) {
  47043. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  47044. var piece = pieceList[pieceIndex];
  47045. if (piece && piece.visual) {
  47046. return piece.visual[this.type];
  47047. }
  47048. }
  47049. }
  47050. function setVisualToOption(thisOption, visualArr) {
  47051. thisOption.visual = visualArr;
  47052. if (thisOption.type === 'color') {
  47053. thisOption.parsedVisual = map(visualArr, function (item) {
  47054. return parse(item);
  47055. });
  47056. }
  47057. return visualArr;
  47058. }
  47059. /**
  47060. * Normalizers by mapping methods.
  47061. */
  47062. var normalizers = {
  47063. linear: function (value) {
  47064. return linearMap(value, this.option.dataExtent, [0, 1], true);
  47065. },
  47066. piecewise: function (value) {
  47067. var pieceList = this.option.pieceList;
  47068. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  47069. if (pieceIndex != null) {
  47070. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  47071. }
  47072. },
  47073. category: function (value) {
  47074. var index = this.option.categories
  47075. ? this.option.categoryMap[value]
  47076. : value; // ordinal
  47077. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  47078. },
  47079. fixed: noop
  47080. };
  47081. /**
  47082. * List available visual types.
  47083. *
  47084. * @public
  47085. * @return {Array.<string>}
  47086. */
  47087. VisualMapping.listVisualTypes = function () {
  47088. var visualTypes = [];
  47089. each$1(visualHandlers, function (handler, key) {
  47090. visualTypes.push(key);
  47091. });
  47092. return visualTypes;
  47093. };
  47094. /**
  47095. * @public
  47096. */
  47097. VisualMapping.addVisualHandler = function (name, handler) {
  47098. visualHandlers[name] = handler;
  47099. };
  47100. /**
  47101. * @public
  47102. */
  47103. VisualMapping.isValidType = function (visualType) {
  47104. return visualHandlers.hasOwnProperty(visualType);
  47105. };
  47106. /**
  47107. * Convinent method.
  47108. * Visual can be Object or Array or primary type.
  47109. *
  47110. * @public
  47111. */
  47112. VisualMapping.eachVisual = function (visual, callback, context) {
  47113. if (isObject$1(visual)) {
  47114. each$1(visual, callback, context);
  47115. }
  47116. else {
  47117. callback.call(context, visual);
  47118. }
  47119. };
  47120. VisualMapping.mapVisual = function (visual, callback, context) {
  47121. var isPrimary;
  47122. var newVisual = isArray(visual)
  47123. ? []
  47124. : isObject$1(visual)
  47125. ? {}
  47126. : (isPrimary = true, null);
  47127. VisualMapping.eachVisual(visual, function (v, key) {
  47128. var newVal = callback.call(context, v, key);
  47129. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  47130. });
  47131. return newVisual;
  47132. };
  47133. /**
  47134. * @public
  47135. * @param {Object} obj
  47136. * @return {Object} new object containers visual values.
  47137. * If no visuals, return null.
  47138. */
  47139. VisualMapping.retrieveVisuals = function (obj) {
  47140. var ret = {};
  47141. var hasVisual;
  47142. obj && each$9(visualHandlers, function (h, visualType) {
  47143. if (obj.hasOwnProperty(visualType)) {
  47144. ret[visualType] = obj[visualType];
  47145. hasVisual = true;
  47146. }
  47147. });
  47148. return hasVisual ? ret : null;
  47149. };
  47150. /**
  47151. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  47152. *
  47153. * @public
  47154. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  47155. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  47156. * @return {Array.<string>} Sorted visual types.
  47157. */
  47158. VisualMapping.prepareVisualTypes = function (visualTypes) {
  47159. if (isObject$5(visualTypes)) {
  47160. var types = [];
  47161. each$9(visualTypes, function (item, type) {
  47162. types.push(type);
  47163. });
  47164. visualTypes = types;
  47165. }
  47166. else if (isArray(visualTypes)) {
  47167. visualTypes = visualTypes.slice();
  47168. }
  47169. else {
  47170. return [];
  47171. }
  47172. visualTypes.sort(function (type1, type2) {
  47173. // color should be front of colorSaturation, colorAlpha, ...
  47174. // symbol and symbolSize do not matter.
  47175. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  47176. ? 1 : -1;
  47177. });
  47178. return visualTypes;
  47179. };
  47180. /**
  47181. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  47182. * Other visuals are only depends on themself.
  47183. *
  47184. * @public
  47185. * @param {string} visualType1
  47186. * @param {string} visualType2
  47187. * @return {boolean}
  47188. */
  47189. VisualMapping.dependsOn = function (visualType1, visualType2) {
  47190. return visualType2 === 'color'
  47191. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  47192. : visualType1 === visualType2;
  47193. };
  47194. /**
  47195. * @param {number} value
  47196. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  47197. * Always from small to big.
  47198. * @param {boolean} [findClosestWhenOutside=false]
  47199. * @return {number} index
  47200. */
  47201. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  47202. var possibleI;
  47203. var abs = Infinity;
  47204. // value has the higher priority.
  47205. for (var i = 0, len = pieceList.length; i < len; i++) {
  47206. var pieceValue = pieceList[i].value;
  47207. if (pieceValue != null) {
  47208. if (pieceValue === value
  47209. // FIXME
  47210. // It is supposed to compare value according to value type of dimension,
  47211. // but currently value type can exactly be string or number.
  47212. // Compromise for numeric-like string (like '12'), especially
  47213. // in the case that visualMap.categories is ['22', '33'].
  47214. || (typeof pieceValue === 'string' && pieceValue === value + '')
  47215. ) {
  47216. return i;
  47217. }
  47218. findClosestWhenOutside && updatePossible(pieceValue, i);
  47219. }
  47220. }
  47221. for (var i = 0, len = pieceList.length; i < len; i++) {
  47222. var piece = pieceList[i];
  47223. var interval = piece.interval;
  47224. var close = piece.close;
  47225. if (interval) {
  47226. if (interval[0] === -Infinity) {
  47227. if (littleThan(close[1], value, interval[1])) {
  47228. return i;
  47229. }
  47230. }
  47231. else if (interval[1] === Infinity) {
  47232. if (littleThan(close[0], interval[0], value)) {
  47233. return i;
  47234. }
  47235. }
  47236. else if (
  47237. littleThan(close[0], interval[0], value)
  47238. && littleThan(close[1], value, interval[1])
  47239. ) {
  47240. return i;
  47241. }
  47242. findClosestWhenOutside && updatePossible(interval[0], i);
  47243. findClosestWhenOutside && updatePossible(interval[1], i);
  47244. }
  47245. }
  47246. if (findClosestWhenOutside) {
  47247. return value === Infinity
  47248. ? pieceList.length - 1
  47249. : value === -Infinity
  47250. ? 0
  47251. : possibleI;
  47252. }
  47253. function updatePossible(val, index) {
  47254. var newAbs = Math.abs(val - value);
  47255. if (newAbs < abs) {
  47256. abs = newAbs;
  47257. possibleI = index;
  47258. }
  47259. }
  47260. };
  47261. function littleThan(close, a, b) {
  47262. return close ? a <= b : a < b;
  47263. }
  47264. /*
  47265. * Licensed to the Apache Software Foundation (ASF) under one
  47266. * or more contributor license agreements. See the NOTICE file
  47267. * distributed with this work for additional information
  47268. * regarding copyright ownership. The ASF licenses this file
  47269. * to you under the Apache License, Version 2.0 (the
  47270. * "License"); you may not use this file except in compliance
  47271. * with the License. You may obtain a copy of the License at
  47272. *
  47273. * http://www.apache.org/licenses/LICENSE-2.0
  47274. *
  47275. * Unless required by applicable law or agreed to in writing,
  47276. * software distributed under the License is distributed on an
  47277. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47278. * KIND, either express or implied. See the License for the
  47279. * specific language governing permissions and limitations
  47280. * under the License.
  47281. */
  47282. var isArray$2 = isArray;
  47283. var ITEM_STYLE_NORMAL = 'itemStyle';
  47284. var treemapVisual = {
  47285. seriesType: 'treemap',
  47286. reset: function (seriesModel, ecModel, api, payload) {
  47287. var tree = seriesModel.getData().tree;
  47288. var root = tree.root;
  47289. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  47290. if (root.isRemoved()) {
  47291. return;
  47292. }
  47293. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  47294. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  47295. });
  47296. travelTree(
  47297. root, // Visual should calculate from tree root but not view root.
  47298. {},
  47299. levelItemStyles,
  47300. seriesItemStyleModel,
  47301. seriesModel.getViewRoot().getAncestors(),
  47302. seriesModel
  47303. );
  47304. }
  47305. };
  47306. function travelTree(
  47307. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  47308. viewRootAncestors, seriesModel
  47309. ) {
  47310. var nodeModel = node.getModel();
  47311. var nodeLayout = node.getLayout();
  47312. // Optimize
  47313. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  47314. return;
  47315. }
  47316. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  47317. var levelItemStyle = levelItemStyles[node.depth];
  47318. var visuals = buildVisuals(
  47319. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47320. );
  47321. // calculate border color
  47322. var borderColor = nodeItemStyleModel.get('borderColor');
  47323. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  47324. var thisNodeColor;
  47325. if (borderColorSaturation != null) {
  47326. // For performance, do not always execute 'calculateColor'.
  47327. thisNodeColor = calculateColor(visuals, node);
  47328. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  47329. }
  47330. node.setVisual('borderColor', borderColor);
  47331. var viewChildren = node.viewChildren;
  47332. if (!viewChildren || !viewChildren.length) {
  47333. thisNodeColor = calculateColor(visuals, node);
  47334. // Apply visual to this node.
  47335. node.setVisual('color', thisNodeColor);
  47336. }
  47337. else {
  47338. var mapping = buildVisualMapping(
  47339. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47340. );
  47341. // Designate visual to children.
  47342. each$1(viewChildren, function (child, index) {
  47343. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  47344. if (child.depth >= viewRootAncestors.length
  47345. || child === viewRootAncestors[child.depth]
  47346. ) {
  47347. var childVisual = mapVisual$1(
  47348. nodeModel, visuals, child, index, mapping, seriesModel
  47349. );
  47350. travelTree(
  47351. child, childVisual, levelItemStyles, seriesItemStyleModel,
  47352. viewRootAncestors, seriesModel
  47353. );
  47354. }
  47355. });
  47356. }
  47357. }
  47358. function buildVisuals(
  47359. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  47360. ) {
  47361. var visuals = extend({}, designatedVisual);
  47362. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  47363. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  47364. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  47365. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  47366. val == null && (val = designatedVisual[visualName]);
  47367. val == null && (val = seriesItemStyleModel.get(visualName));
  47368. val != null && (visuals[visualName] = val);
  47369. });
  47370. return visuals;
  47371. }
  47372. function calculateColor(visuals) {
  47373. var color = getValueVisualDefine(visuals, 'color');
  47374. if (color) {
  47375. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  47376. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  47377. if (colorSaturation) {
  47378. color = modifyHSL(color, null, null, colorSaturation);
  47379. }
  47380. if (colorAlpha) {
  47381. color = modifyAlpha(color, colorAlpha);
  47382. }
  47383. return color;
  47384. }
  47385. }
  47386. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  47387. return thisNodeColor != null
  47388. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  47389. : null;
  47390. }
  47391. function getValueVisualDefine(visuals, name) {
  47392. var value = visuals[name];
  47393. if (value != null && value !== 'none') {
  47394. return value;
  47395. }
  47396. }
  47397. function buildVisualMapping(
  47398. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  47399. ) {
  47400. if (!viewChildren || !viewChildren.length) {
  47401. return;
  47402. }
  47403. var rangeVisual = getRangeVisual(nodeModel, 'color')
  47404. || (
  47405. visuals.color != null
  47406. && visuals.color !== 'none'
  47407. && (
  47408. getRangeVisual(nodeModel, 'colorAlpha')
  47409. || getRangeVisual(nodeModel, 'colorSaturation')
  47410. )
  47411. );
  47412. if (!rangeVisual) {
  47413. return;
  47414. }
  47415. var visualMin = nodeModel.get('visualMin');
  47416. var visualMax = nodeModel.get('visualMax');
  47417. var dataExtent = nodeLayout.dataExtent.slice();
  47418. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  47419. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  47420. var colorMappingBy = nodeModel.get('colorMappingBy');
  47421. var opt = {
  47422. type: rangeVisual.name,
  47423. dataExtent: dataExtent,
  47424. visual: rangeVisual.range
  47425. };
  47426. if (opt.type === 'color'
  47427. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  47428. ) {
  47429. opt.mappingMethod = 'category';
  47430. opt.loop = true;
  47431. // categories is ordinal, so do not set opt.categories.
  47432. }
  47433. else {
  47434. opt.mappingMethod = 'linear';
  47435. }
  47436. var mapping = new VisualMapping(opt);
  47437. mapping.__drColorMappingBy = colorMappingBy;
  47438. return mapping;
  47439. }
  47440. // Notice: If we dont have the attribute 'colorRange', but only use
  47441. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  47442. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  47443. // this problem will be encountered:
  47444. // If a level-1 node dont have children, and its siblings has children,
  47445. // and colorRange is set on level-1, then the node can not be colored.
  47446. // So we separate 'colorRange' and 'color' to different attributes.
  47447. function getRangeVisual(nodeModel, name) {
  47448. // 'colorRange', 'colorARange', 'colorSRange'.
  47449. // If not exsits on this node, fetch from levels and series.
  47450. var range = nodeModel.get(name);
  47451. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  47452. }
  47453. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  47454. var childVisuals = extend({}, visuals);
  47455. if (mapping) {
  47456. var mappingType = mapping.type;
  47457. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  47458. var value = colorMappingBy === 'index'
  47459. ? index
  47460. : colorMappingBy === 'id'
  47461. ? seriesModel.mapIdToIndex(child.getId())
  47462. : child.getValue(nodeModel.get('visualDimension'));
  47463. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  47464. }
  47465. return childVisuals;
  47466. }
  47467. /*
  47468. * Licensed to the Apache Software Foundation (ASF) under one
  47469. * or more contributor license agreements. See the NOTICE file
  47470. * distributed with this work for additional information
  47471. * regarding copyright ownership. The ASF licenses this file
  47472. * to you under the Apache License, Version 2.0 (the
  47473. * "License"); you may not use this file except in compliance
  47474. * with the License. You may obtain a copy of the License at
  47475. *
  47476. * http://www.apache.org/licenses/LICENSE-2.0
  47477. *
  47478. * Unless required by applicable law or agreed to in writing,
  47479. * software distributed under the License is distributed on an
  47480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47481. * KIND, either express or implied. See the License for the
  47482. * specific language governing permissions and limitations
  47483. * under the License.
  47484. */
  47485. /*
  47486. * A third-party license is embeded for some of the code in this file:
  47487. * The treemap layout implementation was originally copied from
  47488. * "d3.js" with some modifications made for this project.
  47489. * (See more details in the comment of the method "squarify" below.)
  47490. * The use of the source code of this file is also subject to the terms
  47491. * and consitions of the license of "d3.js" (BSD-3Clause, see
  47492. * </licenses/LICENSE-d3>).
  47493. */
  47494. var mathMax$5 = Math.max;
  47495. var mathMin$5 = Math.min;
  47496. var retrieveValue = retrieve;
  47497. var each$10 = each$1;
  47498. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  47499. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  47500. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  47501. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  47502. /**
  47503. * @public
  47504. */
  47505. var treemapLayout = {
  47506. seriesType: 'treemap',
  47507. reset: function (seriesModel, ecModel, api, payload) {
  47508. // Layout result in each node:
  47509. // {x, y, width, height, area, borderWidth}
  47510. var ecWidth = api.getWidth();
  47511. var ecHeight = api.getHeight();
  47512. var seriesOption = seriesModel.option;
  47513. var layoutInfo = getLayoutRect(
  47514. seriesModel.getBoxLayoutParams(),
  47515. {
  47516. width: api.getWidth(),
  47517. height: api.getHeight()
  47518. }
  47519. );
  47520. var size = seriesOption.size || []; // Compatible with ec2.
  47521. var containerWidth = parsePercent$1(
  47522. retrieveValue(layoutInfo.width, size[0]),
  47523. ecWidth
  47524. );
  47525. var containerHeight = parsePercent$1(
  47526. retrieveValue(layoutInfo.height, size[1]),
  47527. ecHeight
  47528. );
  47529. // Fetch payload info.
  47530. var payloadType = payload && payload.type;
  47531. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  47532. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  47533. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  47534. ? payload.rootRect : null;
  47535. var viewRoot = seriesModel.getViewRoot();
  47536. var viewAbovePath = getPathToRoot(viewRoot);
  47537. if (payloadType !== 'treemapMove') {
  47538. var rootSize = payloadType === 'treemapZoomToNode'
  47539. ? estimateRootSize(
  47540. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  47541. )
  47542. : rootRect
  47543. ? [rootRect.width, rootRect.height]
  47544. : [containerWidth, containerHeight];
  47545. var sort = seriesOption.sort;
  47546. if (sort && sort !== 'asc' && sort !== 'desc') {
  47547. sort = 'desc';
  47548. }
  47549. var options = {
  47550. squareRatio: seriesOption.squareRatio,
  47551. sort: sort,
  47552. leafDepth: seriesOption.leafDepth
  47553. };
  47554. // layout should be cleared because using updateView but not update.
  47555. viewRoot.hostTree.clearLayouts();
  47556. // TODO
  47557. // optimize: if out of view clip, do not layout.
  47558. // But take care that if do not render node out of view clip,
  47559. // how to calculate start po
  47560. var viewRootLayout = {
  47561. x: 0, y: 0,
  47562. width: rootSize[0], height: rootSize[1],
  47563. area: rootSize[0] * rootSize[1]
  47564. };
  47565. viewRoot.setLayout(viewRootLayout);
  47566. squarify(viewRoot, options, false, 0);
  47567. // Supplement layout.
  47568. var viewRootLayout = viewRoot.getLayout();
  47569. each$10(viewAbovePath, function (node, index) {
  47570. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  47571. node.setLayout(extend(
  47572. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  47573. viewRootLayout
  47574. ));
  47575. });
  47576. }
  47577. var treeRoot = seriesModel.getData().tree.root;
  47578. treeRoot.setLayout(
  47579. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  47580. true
  47581. );
  47582. seriesModel.setLayoutInfo(layoutInfo);
  47583. // FIXME
  47584. // 现在没有clip功能,暂时取ec高宽。
  47585. prunning(
  47586. treeRoot,
  47587. // Transform to base element coordinate system.
  47588. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  47589. viewAbovePath,
  47590. viewRoot,
  47591. 0
  47592. );
  47593. }
  47594. };
  47595. /**
  47596. * Layout treemap with squarify algorithm.
  47597. * The original presentation of this algorithm
  47598. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  47599. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  47600. * The implementation of this algorithm was originally copied from "d3.js"
  47601. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  47602. * with some modifications made for this program.
  47603. * See the license statement at the head of this file.
  47604. *
  47605. * @protected
  47606. * @param {module:echarts/data/Tree~TreeNode} node
  47607. * @param {Object} options
  47608. * @param {string} options.sort 'asc' or 'desc'
  47609. * @param {number} options.squareRatio
  47610. * @param {boolean} hideChildren
  47611. * @param {number} depth
  47612. */
  47613. function squarify(node, options, hideChildren, depth) {
  47614. var width;
  47615. var height;
  47616. if (node.isRemoved()) {
  47617. return;
  47618. }
  47619. var thisLayout = node.getLayout();
  47620. width = thisLayout.width;
  47621. height = thisLayout.height;
  47622. // Considering border and gap
  47623. var nodeModel = node.getModel();
  47624. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  47625. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  47626. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  47627. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  47628. var layoutOffset = borderWidth - halfGapWidth;
  47629. var layoutOffsetUpper = upperHeight - halfGapWidth;
  47630. var nodeModel = node.getModel();
  47631. node.setLayout({
  47632. borderWidth: borderWidth,
  47633. upperHeight: upperHeight,
  47634. upperLabelHeight: upperLabelHeight
  47635. }, true);
  47636. width = mathMax$5(width - 2 * layoutOffset, 0);
  47637. height = mathMax$5(height - layoutOffset - layoutOffsetUpper, 0);
  47638. var totalArea = width * height;
  47639. var viewChildren = initChildren(
  47640. node, nodeModel, totalArea, options, hideChildren, depth
  47641. );
  47642. if (!viewChildren.length) {
  47643. return;
  47644. }
  47645. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  47646. var rowFixedLength = mathMin$5(width, height);
  47647. var best = Infinity; // the best row score so far
  47648. var row = [];
  47649. row.area = 0;
  47650. for (var i = 0, len = viewChildren.length; i < len;) {
  47651. var child = viewChildren[i];
  47652. row.push(child);
  47653. row.area += child.getLayout().area;
  47654. var score = worst(row, rowFixedLength, options.squareRatio);
  47655. // continue with this orientation
  47656. if (score <= best) {
  47657. i++;
  47658. best = score;
  47659. }
  47660. // abort, and try a different orientation
  47661. else {
  47662. row.area -= row.pop().getLayout().area;
  47663. position(row, rowFixedLength, rect, halfGapWidth, false);
  47664. rowFixedLength = mathMin$5(rect.width, rect.height);
  47665. row.length = row.area = 0;
  47666. best = Infinity;
  47667. }
  47668. }
  47669. if (row.length) {
  47670. position(row, rowFixedLength, rect, halfGapWidth, true);
  47671. }
  47672. if (!hideChildren) {
  47673. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  47674. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  47675. hideChildren = true;
  47676. }
  47677. }
  47678. for (var i = 0, len = viewChildren.length; i < len; i++) {
  47679. squarify(viewChildren[i], options, hideChildren, depth + 1);
  47680. }
  47681. }
  47682. /**
  47683. * Set area to each child, and calculate data extent for visual coding.
  47684. */
  47685. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  47686. var viewChildren = node.children || [];
  47687. var orderBy = options.sort;
  47688. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  47689. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  47690. // leafDepth has higher priority.
  47691. if (hideChildren && !overLeafDepth) {
  47692. return (node.viewChildren = []);
  47693. }
  47694. // Sort children, order by desc.
  47695. viewChildren = filter(viewChildren, function (child) {
  47696. return !child.isRemoved();
  47697. });
  47698. sort$1(viewChildren, orderBy);
  47699. var info = statistic(nodeModel, viewChildren, orderBy);
  47700. if (info.sum === 0) {
  47701. return (node.viewChildren = []);
  47702. }
  47703. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  47704. if (info.sum === 0) {
  47705. return (node.viewChildren = []);
  47706. }
  47707. // Set area to each child.
  47708. for (var i = 0, len = viewChildren.length; i < len; i++) {
  47709. var area = viewChildren[i].getValue() / info.sum * totalArea;
  47710. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  47711. viewChildren[i].setLayout({area: area});
  47712. }
  47713. if (overLeafDepth) {
  47714. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  47715. viewChildren.length = 0;
  47716. }
  47717. node.viewChildren = viewChildren;
  47718. node.setLayout({dataExtent: info.dataExtent}, true);
  47719. return viewChildren;
  47720. }
  47721. /**
  47722. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  47723. */
  47724. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  47725. // visibleMin is not supported yet when no option.sort.
  47726. if (!orderBy) {
  47727. return sum;
  47728. }
  47729. var visibleMin = nodeModel.get('visibleMin');
  47730. var len = orderedChildren.length;
  47731. var deletePoint = len;
  47732. // Always travel from little value to big value.
  47733. for (var i = len - 1; i >= 0; i--) {
  47734. var value = orderedChildren[
  47735. orderBy === 'asc' ? len - i - 1 : i
  47736. ].getValue();
  47737. if (value / sum * totalArea < visibleMin) {
  47738. deletePoint = i;
  47739. sum -= value;
  47740. }
  47741. }
  47742. orderBy === 'asc'
  47743. ? orderedChildren.splice(0, len - deletePoint)
  47744. : orderedChildren.splice(deletePoint, len - deletePoint);
  47745. return sum;
  47746. }
  47747. /**
  47748. * Sort
  47749. */
  47750. function sort$1(viewChildren, orderBy) {
  47751. if (orderBy) {
  47752. viewChildren.sort(function (a, b) {
  47753. var diff = orderBy === 'asc'
  47754. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  47755. return diff === 0
  47756. ? (orderBy === 'asc'
  47757. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  47758. )
  47759. : diff;
  47760. });
  47761. }
  47762. return viewChildren;
  47763. }
  47764. /**
  47765. * Statistic
  47766. */
  47767. function statistic(nodeModel, children, orderBy) {
  47768. // Calculate sum.
  47769. var sum = 0;
  47770. for (var i = 0, len = children.length; i < len; i++) {
  47771. sum += children[i].getValue();
  47772. }
  47773. // Statistic data extent for latter visual coding.
  47774. // Notice: data extent should be calculate based on raw children
  47775. // but not filtered view children, otherwise visual mapping will not
  47776. // be stable when zoom (where children is filtered by visibleMin).
  47777. var dimension = nodeModel.get('visualDimension');
  47778. var dataExtent;
  47779. // The same as area dimension.
  47780. if (!children || !children.length) {
  47781. dataExtent = [NaN, NaN];
  47782. }
  47783. else if (dimension === 'value' && orderBy) {
  47784. dataExtent = [
  47785. children[children.length - 1].getValue(),
  47786. children[0].getValue()
  47787. ];
  47788. orderBy === 'asc' && dataExtent.reverse();
  47789. }
  47790. // Other dimension.
  47791. else {
  47792. var dataExtent = [Infinity, -Infinity];
  47793. each$10(children, function (child) {
  47794. var value = child.getValue(dimension);
  47795. value < dataExtent[0] && (dataExtent[0] = value);
  47796. value > dataExtent[1] && (dataExtent[1] = value);
  47797. });
  47798. }
  47799. return {sum: sum, dataExtent: dataExtent};
  47800. }
  47801. /**
  47802. * Computes the score for the specified row,
  47803. * as the worst aspect ratio.
  47804. */
  47805. function worst(row, rowFixedLength, ratio) {
  47806. var areaMax = 0;
  47807. var areaMin = Infinity;
  47808. for (var i = 0, area, len = row.length; i < len; i++) {
  47809. area = row[i].getLayout().area;
  47810. if (area) {
  47811. area < areaMin && (areaMin = area);
  47812. area > areaMax && (areaMax = area);
  47813. }
  47814. }
  47815. var squareArea = row.area * row.area;
  47816. var f = rowFixedLength * rowFixedLength * ratio;
  47817. return squareArea
  47818. ? mathMax$5(
  47819. (f * areaMax) / squareArea,
  47820. squareArea / (f * areaMin)
  47821. )
  47822. : Infinity;
  47823. }
  47824. /**
  47825. * Positions the specified row of nodes. Modifies `rect`.
  47826. */
  47827. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  47828. // When rowFixedLength === rect.width,
  47829. // it is horizontal subdivision,
  47830. // rowFixedLength is the width of the subdivision,
  47831. // rowOtherLength is the height of the subdivision,
  47832. // and nodes will be positioned from left to right.
  47833. // wh[idx0WhenH] means: when horizontal,
  47834. // wh[idx0WhenH] => wh[0] => 'width'.
  47835. // xy[idx1WhenH] => xy[1] => 'y'.
  47836. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  47837. var idx1WhenH = 1 - idx0WhenH;
  47838. var xy = ['x', 'y'];
  47839. var wh = ['width', 'height'];
  47840. var last = rect[xy[idx0WhenH]];
  47841. var rowOtherLength = rowFixedLength
  47842. ? row.area / rowFixedLength : 0;
  47843. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  47844. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  47845. }
  47846. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  47847. var node = row[i];
  47848. var nodeLayout = {};
  47849. var step = rowOtherLength
  47850. ? node.getLayout().area / rowOtherLength : 0;
  47851. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$5(rowOtherLength - 2 * halfGapWidth, 0);
  47852. // We use Math.max/min to avoid negative width/height when considering gap width.
  47853. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  47854. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  47855. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$5(modWH - 2 * halfGapWidth, 0);
  47856. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$5(halfGapWidth, wh1 / 2);
  47857. nodeLayout[xy[idx0WhenH]] = last + mathMin$5(halfGapWidth, wh0 / 2);
  47858. last += modWH;
  47859. node.setLayout(nodeLayout, true);
  47860. }
  47861. rect[xy[idx1WhenH]] += rowOtherLength;
  47862. rect[wh[idx1WhenH]] -= rowOtherLength;
  47863. }
  47864. // Return [containerWidth, containerHeight] as defualt.
  47865. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  47866. // If targetInfo.node exists, we zoom to the node,
  47867. // so estimate whold width and heigth by target node.
  47868. var currNode = (targetInfo || {}).node;
  47869. var defaultSize = [containerWidth, containerHeight];
  47870. if (!currNode || currNode === viewRoot) {
  47871. return defaultSize;
  47872. }
  47873. var parent;
  47874. var viewArea = containerWidth * containerHeight;
  47875. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  47876. while (parent = currNode.parentNode) { // jshint ignore:line
  47877. var sum = 0;
  47878. var siblings = parent.children;
  47879. for (var i = 0, len = siblings.length; i < len; i++) {
  47880. sum += siblings[i].getValue();
  47881. }
  47882. var currNodeValue = currNode.getValue();
  47883. if (currNodeValue === 0) {
  47884. return defaultSize;
  47885. }
  47886. area *= sum / currNodeValue;
  47887. // Considering border, suppose aspect ratio is 1.
  47888. var parentModel = parent.getModel();
  47889. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  47890. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  47891. area += 4 * borderWidth * borderWidth
  47892. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  47893. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  47894. currNode = parent;
  47895. }
  47896. area < viewArea && (area = viewArea);
  47897. var scale = Math.pow(area / viewArea, 0.5);
  47898. return [containerWidth * scale, containerHeight * scale];
  47899. }
  47900. // Root postion base on coord of containerGroup
  47901. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  47902. if (rootRect) {
  47903. return {x: rootRect.x, y: rootRect.y};
  47904. }
  47905. var defaultPosition = {x: 0, y: 0};
  47906. if (!targetInfo) {
  47907. return defaultPosition;
  47908. }
  47909. // If targetInfo is fetched by 'retrieveTargetInfo',
  47910. // old tree and new tree are the same tree,
  47911. // so the node still exists and we can visit it.
  47912. var targetNode = targetInfo.node;
  47913. var layout = targetNode.getLayout();
  47914. if (!layout) {
  47915. return defaultPosition;
  47916. }
  47917. // Transform coord from local to container.
  47918. var targetCenter = [layout.width / 2, layout.height / 2];
  47919. var node = targetNode;
  47920. while (node) {
  47921. var nodeLayout = node.getLayout();
  47922. targetCenter[0] += nodeLayout.x;
  47923. targetCenter[1] += nodeLayout.y;
  47924. node = node.parentNode;
  47925. }
  47926. return {
  47927. x: layoutInfo.width / 2 - targetCenter[0],
  47928. y: layoutInfo.height / 2 - targetCenter[1]
  47929. };
  47930. }
  47931. // Mark nodes visible for prunning when visual coding and rendering.
  47932. // Prunning depends on layout and root position, so we have to do it after layout.
  47933. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  47934. var nodeLayout = node.getLayout();
  47935. var nodeInViewAbovePath = viewAbovePath[depth];
  47936. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  47937. if (
  47938. (nodeInViewAbovePath && !isAboveViewRoot)
  47939. || (depth === viewAbovePath.length && node !== viewRoot)
  47940. ) {
  47941. return;
  47942. }
  47943. node.setLayout({
  47944. // isInView means: viewRoot sub tree + viewAbovePath
  47945. isInView: true,
  47946. // invisible only means: outside view clip so that the node can not
  47947. // see but still layout for animation preparation but not render.
  47948. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  47949. isAboveViewRoot: isAboveViewRoot
  47950. }, true);
  47951. // Transform to child coordinate.
  47952. var childClipRect = new BoundingRect(
  47953. clipRect.x - nodeLayout.x,
  47954. clipRect.y - nodeLayout.y,
  47955. clipRect.width,
  47956. clipRect.height
  47957. );
  47958. each$10(node.viewChildren || [], function (child) {
  47959. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  47960. });
  47961. }
  47962. function getUpperLabelHeight(model) {
  47963. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  47964. }
  47965. /*
  47966. * Licensed to the Apache Software Foundation (ASF) under one
  47967. * or more contributor license agreements. See the NOTICE file
  47968. * distributed with this work for additional information
  47969. * regarding copyright ownership. The ASF licenses this file
  47970. * to you under the Apache License, Version 2.0 (the
  47971. * "License"); you may not use this file except in compliance
  47972. * with the License. You may obtain a copy of the License at
  47973. *
  47974. * http://www.apache.org/licenses/LICENSE-2.0
  47975. *
  47976. * Unless required by applicable law or agreed to in writing,
  47977. * software distributed under the License is distributed on an
  47978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47979. * KIND, either express or implied. See the License for the
  47980. * specific language governing permissions and limitations
  47981. * under the License.
  47982. */
  47983. registerVisual(treemapVisual);
  47984. registerLayout(treemapLayout);
  47985. /*
  47986. * Licensed to the Apache Software Foundation (ASF) under one
  47987. * or more contributor license agreements. See the NOTICE file
  47988. * distributed with this work for additional information
  47989. * regarding copyright ownership. The ASF licenses this file
  47990. * to you under the Apache License, Version 2.0 (the
  47991. * "License"); you may not use this file except in compliance
  47992. * with the License. You may obtain a copy of the License at
  47993. *
  47994. * http://www.apache.org/licenses/LICENSE-2.0
  47995. *
  47996. * Unless required by applicable law or agreed to in writing,
  47997. * software distributed under the License is distributed on an
  47998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47999. * KIND, either express or implied. See the License for the
  48000. * specific language governing permissions and limitations
  48001. * under the License.
  48002. */
  48003. // id may be function name of Object, add a prefix to avoid this problem.
  48004. function generateNodeKey(id) {
  48005. return '_EC_' + id;
  48006. }
  48007. /**
  48008. * @alias module:echarts/data/Graph
  48009. * @constructor
  48010. * @param {boolean} directed
  48011. */
  48012. var Graph = function (directed) {
  48013. /**
  48014. * 是否是有向图
  48015. * @type {boolean}
  48016. * @private
  48017. */
  48018. this._directed = directed || false;
  48019. /**
  48020. * @type {Array.<module:echarts/data/Graph.Node>}
  48021. * @readOnly
  48022. */
  48023. this.nodes = [];
  48024. /**
  48025. * @type {Array.<module:echarts/data/Graph.Edge>}
  48026. * @readOnly
  48027. */
  48028. this.edges = [];
  48029. /**
  48030. * @type {Object.<string, module:echarts/data/Graph.Node>}
  48031. * @private
  48032. */
  48033. this._nodesMap = {};
  48034. /**
  48035. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  48036. * @private
  48037. */
  48038. this._edgesMap = {};
  48039. /**
  48040. * @type {module:echarts/data/List}
  48041. * @readOnly
  48042. */
  48043. this.data;
  48044. /**
  48045. * @type {module:echarts/data/List}
  48046. * @readOnly
  48047. */
  48048. this.edgeData;
  48049. };
  48050. var graphProto = Graph.prototype;
  48051. /**
  48052. * @type {string}
  48053. */
  48054. graphProto.type = 'graph';
  48055. /**
  48056. * If is directed graph
  48057. * @return {boolean}
  48058. */
  48059. graphProto.isDirected = function () {
  48060. return this._directed;
  48061. };
  48062. /**
  48063. * Add a new node
  48064. * @param {string} id
  48065. * @param {number} [dataIndex]
  48066. */
  48067. graphProto.addNode = function (id, dataIndex) {
  48068. id = id == null ? ('' + dataIndex) : ('' + id);
  48069. var nodesMap = this._nodesMap;
  48070. if (nodesMap[generateNodeKey(id)]) {
  48071. if (__DEV__) {
  48072. console.error('Graph nodes have duplicate name or id');
  48073. }
  48074. return;
  48075. }
  48076. var node = new Node(id, dataIndex);
  48077. node.hostGraph = this;
  48078. this.nodes.push(node);
  48079. nodesMap[generateNodeKey(id)] = node;
  48080. return node;
  48081. };
  48082. /**
  48083. * Get node by data index
  48084. * @param {number} dataIndex
  48085. * @return {module:echarts/data/Graph~Node}
  48086. */
  48087. graphProto.getNodeByIndex = function (dataIndex) {
  48088. var rawIdx = this.data.getRawIndex(dataIndex);
  48089. return this.nodes[rawIdx];
  48090. };
  48091. /**
  48092. * Get node by id
  48093. * @param {string} id
  48094. * @return {module:echarts/data/Graph.Node}
  48095. */
  48096. graphProto.getNodeById = function (id) {
  48097. return this._nodesMap[generateNodeKey(id)];
  48098. };
  48099. /**
  48100. * Add a new edge
  48101. * @param {number|string|module:echarts/data/Graph.Node} n1
  48102. * @param {number|string|module:echarts/data/Graph.Node} n2
  48103. * @param {number} [dataIndex=-1]
  48104. * @return {module:echarts/data/Graph.Edge}
  48105. */
  48106. graphProto.addEdge = function (n1, n2, dataIndex) {
  48107. var nodesMap = this._nodesMap;
  48108. var edgesMap = this._edgesMap;
  48109. // PNEDING
  48110. if (typeof n1 === 'number') {
  48111. n1 = this.nodes[n1];
  48112. }
  48113. if (typeof n2 === 'number') {
  48114. n2 = this.nodes[n2];
  48115. }
  48116. if (!Node.isInstance(n1)) {
  48117. n1 = nodesMap[generateNodeKey(n1)];
  48118. }
  48119. if (!Node.isInstance(n2)) {
  48120. n2 = nodesMap[generateNodeKey(n2)];
  48121. }
  48122. if (!n1 || !n2) {
  48123. return;
  48124. }
  48125. var key = n1.id + '-' + n2.id;
  48126. // PENDING
  48127. if (edgesMap[key]) {
  48128. return;
  48129. }
  48130. var edge = new Edge(n1, n2, dataIndex);
  48131. edge.hostGraph = this;
  48132. if (this._directed) {
  48133. n1.outEdges.push(edge);
  48134. n2.inEdges.push(edge);
  48135. }
  48136. n1.edges.push(edge);
  48137. if (n1 !== n2) {
  48138. n2.edges.push(edge);
  48139. }
  48140. this.edges.push(edge);
  48141. edgesMap[key] = edge;
  48142. return edge;
  48143. };
  48144. /**
  48145. * Get edge by data index
  48146. * @param {number} dataIndex
  48147. * @return {module:echarts/data/Graph~Node}
  48148. */
  48149. graphProto.getEdgeByIndex = function (dataIndex) {
  48150. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  48151. return this.edges[rawIdx];
  48152. };
  48153. /**
  48154. * Get edge by two linked nodes
  48155. * @param {module:echarts/data/Graph.Node|string} n1
  48156. * @param {module:echarts/data/Graph.Node|string} n2
  48157. * @return {module:echarts/data/Graph.Edge}
  48158. */
  48159. graphProto.getEdge = function (n1, n2) {
  48160. if (Node.isInstance(n1)) {
  48161. n1 = n1.id;
  48162. }
  48163. if (Node.isInstance(n2)) {
  48164. n2 = n2.id;
  48165. }
  48166. var edgesMap = this._edgesMap;
  48167. if (this._directed) {
  48168. return edgesMap[n1 + '-' + n2];
  48169. }
  48170. else {
  48171. return edgesMap[n1 + '-' + n2]
  48172. || edgesMap[n2 + '-' + n1];
  48173. }
  48174. };
  48175. /**
  48176. * Iterate all nodes
  48177. * @param {Function} cb
  48178. * @param {*} [context]
  48179. */
  48180. graphProto.eachNode = function (cb, context) {
  48181. var nodes = this.nodes;
  48182. var len = nodes.length;
  48183. for (var i = 0; i < len; i++) {
  48184. if (nodes[i].dataIndex >= 0) {
  48185. cb.call(context, nodes[i], i);
  48186. }
  48187. }
  48188. };
  48189. /**
  48190. * Iterate all edges
  48191. * @param {Function} cb
  48192. * @param {*} [context]
  48193. */
  48194. graphProto.eachEdge = function (cb, context) {
  48195. var edges = this.edges;
  48196. var len = edges.length;
  48197. for (var i = 0; i < len; i++) {
  48198. if (edges[i].dataIndex >= 0
  48199. && edges[i].node1.dataIndex >= 0
  48200. && edges[i].node2.dataIndex >= 0
  48201. ) {
  48202. cb.call(context, edges[i], i);
  48203. }
  48204. }
  48205. };
  48206. /**
  48207. * Breadth first traverse
  48208. * @param {Function} cb
  48209. * @param {module:echarts/data/Graph.Node} startNode
  48210. * @param {string} [direction='none'] 'none'|'in'|'out'
  48211. * @param {*} [context]
  48212. */
  48213. graphProto.breadthFirstTraverse = function (
  48214. cb, startNode, direction, context
  48215. ) {
  48216. if (!Node.isInstance(startNode)) {
  48217. startNode = this._nodesMap[generateNodeKey(startNode)];
  48218. }
  48219. if (!startNode) {
  48220. return;
  48221. }
  48222. var edgeType = direction === 'out'
  48223. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  48224. for (var i = 0; i < this.nodes.length; i++) {
  48225. this.nodes[i].__visited = false;
  48226. }
  48227. if (cb.call(context, startNode, null)) {
  48228. return;
  48229. }
  48230. var queue = [startNode];
  48231. while (queue.length) {
  48232. var currentNode = queue.shift();
  48233. var edges = currentNode[edgeType];
  48234. for (var i = 0; i < edges.length; i++) {
  48235. var e = edges[i];
  48236. var otherNode = e.node1 === currentNode
  48237. ? e.node2 : e.node1;
  48238. if (!otherNode.__visited) {
  48239. if (cb.call(context, otherNode, currentNode)) {
  48240. // Stop traversing
  48241. return;
  48242. }
  48243. queue.push(otherNode);
  48244. otherNode.__visited = true;
  48245. }
  48246. }
  48247. }
  48248. };
  48249. // TODO
  48250. // graphProto.depthFirstTraverse = function (
  48251. // cb, startNode, direction, context
  48252. // ) {
  48253. // };
  48254. // Filter update
  48255. graphProto.update = function () {
  48256. var data = this.data;
  48257. var edgeData = this.edgeData;
  48258. var nodes = this.nodes;
  48259. var edges = this.edges;
  48260. for (var i = 0, len = nodes.length; i < len; i++) {
  48261. nodes[i].dataIndex = -1;
  48262. }
  48263. for (var i = 0, len = data.count(); i < len; i++) {
  48264. nodes[data.getRawIndex(i)].dataIndex = i;
  48265. }
  48266. edgeData.filterSelf(function (idx) {
  48267. var edge = edges[edgeData.getRawIndex(idx)];
  48268. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  48269. });
  48270. // Update edge
  48271. for (var i = 0, len = edges.length; i < len; i++) {
  48272. edges[i].dataIndex = -1;
  48273. }
  48274. for (var i = 0, len = edgeData.count(); i < len; i++) {
  48275. edges[edgeData.getRawIndex(i)].dataIndex = i;
  48276. }
  48277. };
  48278. /**
  48279. * @return {module:echarts/data/Graph}
  48280. */
  48281. graphProto.clone = function () {
  48282. var graph = new Graph(this._directed);
  48283. var nodes = this.nodes;
  48284. var edges = this.edges;
  48285. for (var i = 0; i < nodes.length; i++) {
  48286. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  48287. }
  48288. for (var i = 0; i < edges.length; i++) {
  48289. var e = edges[i];
  48290. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  48291. }
  48292. return graph;
  48293. };
  48294. /**
  48295. * @alias module:echarts/data/Graph.Node
  48296. */
  48297. function Node(id, dataIndex) {
  48298. /**
  48299. * @type {string}
  48300. */
  48301. this.id = id == null ? '' : id;
  48302. /**
  48303. * @type {Array.<module:echarts/data/Graph.Edge>}
  48304. */
  48305. this.inEdges = [];
  48306. /**
  48307. * @type {Array.<module:echarts/data/Graph.Edge>}
  48308. */
  48309. this.outEdges = [];
  48310. /**
  48311. * @type {Array.<module:echarts/data/Graph.Edge>}
  48312. */
  48313. this.edges = [];
  48314. /**
  48315. * @type {module:echarts/data/Graph}
  48316. */
  48317. this.hostGraph;
  48318. /**
  48319. * @type {number}
  48320. */
  48321. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48322. }
  48323. Node.prototype = {
  48324. constructor: Node,
  48325. /**
  48326. * @return {number}
  48327. */
  48328. degree: function () {
  48329. return this.edges.length;
  48330. },
  48331. /**
  48332. * @return {number}
  48333. */
  48334. inDegree: function () {
  48335. return this.inEdges.length;
  48336. },
  48337. /**
  48338. * @return {number}
  48339. */
  48340. outDegree: function () {
  48341. return this.outEdges.length;
  48342. },
  48343. /**
  48344. * @param {string} [path]
  48345. * @return {module:echarts/model/Model}
  48346. */
  48347. getModel: function (path) {
  48348. if (this.dataIndex < 0) {
  48349. return;
  48350. }
  48351. var graph = this.hostGraph;
  48352. var itemModel = graph.data.getItemModel(this.dataIndex);
  48353. return itemModel.getModel(path);
  48354. }
  48355. };
  48356. /**
  48357. * 图边
  48358. * @alias module:echarts/data/Graph.Edge
  48359. * @param {module:echarts/data/Graph.Node} n1
  48360. * @param {module:echarts/data/Graph.Node} n2
  48361. * @param {number} [dataIndex=-1]
  48362. */
  48363. function Edge(n1, n2, dataIndex) {
  48364. /**
  48365. * 节点1,如果是有向图则为源节点
  48366. * @type {module:echarts/data/Graph.Node}
  48367. */
  48368. this.node1 = n1;
  48369. /**
  48370. * 节点2,如果是有向图则为目标节点
  48371. * @type {module:echarts/data/Graph.Node}
  48372. */
  48373. this.node2 = n2;
  48374. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  48375. }
  48376. /**
  48377. * @param {string} [path]
  48378. * @return {module:echarts/model/Model}
  48379. */
  48380. Edge.prototype.getModel = function (path) {
  48381. if (this.dataIndex < 0) {
  48382. return;
  48383. }
  48384. var graph = this.hostGraph;
  48385. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  48386. return itemModel.getModel(path);
  48387. };
  48388. var createGraphDataProxyMixin = function (hostName, dataName) {
  48389. return {
  48390. /**
  48391. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  48392. * @return {number}
  48393. */
  48394. getValue: function (dimension) {
  48395. var data = this[hostName][dataName];
  48396. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  48397. },
  48398. /**
  48399. * @param {Object|string} key
  48400. * @param {*} [value]
  48401. */
  48402. setVisual: function (key, value) {
  48403. this.dataIndex >= 0
  48404. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  48405. },
  48406. /**
  48407. * @param {string} key
  48408. * @return {boolean}
  48409. */
  48410. getVisual: function (key, ignoreParent) {
  48411. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  48412. },
  48413. /**
  48414. * @param {Object} layout
  48415. * @return {boolean} [merge=false]
  48416. */
  48417. setLayout: function (layout, merge$$1) {
  48418. this.dataIndex >= 0
  48419. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  48420. },
  48421. /**
  48422. * @return {Object}
  48423. */
  48424. getLayout: function () {
  48425. return this[hostName][dataName].getItemLayout(this.dataIndex);
  48426. },
  48427. /**
  48428. * @return {module:zrender/Element}
  48429. */
  48430. getGraphicEl: function () {
  48431. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  48432. },
  48433. /**
  48434. * @return {number}
  48435. */
  48436. getRawIndex: function () {
  48437. return this[hostName][dataName].getRawIndex(this.dataIndex);
  48438. }
  48439. };
  48440. };
  48441. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  48442. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  48443. Graph.Node = Node;
  48444. Graph.Edge = Edge;
  48445. enableClassCheck(Node);
  48446. enableClassCheck(Edge);
  48447. /*
  48448. * Licensed to the Apache Software Foundation (ASF) under one
  48449. * or more contributor license agreements. See the NOTICE file
  48450. * distributed with this work for additional information
  48451. * regarding copyright ownership. The ASF licenses this file
  48452. * to you under the Apache License, Version 2.0 (the
  48453. * "License"); you may not use this file except in compliance
  48454. * with the License. You may obtain a copy of the License at
  48455. *
  48456. * http://www.apache.org/licenses/LICENSE-2.0
  48457. *
  48458. * Unless required by applicable law or agreed to in writing,
  48459. * software distributed under the License is distributed on an
  48460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48461. * KIND, either express or implied. See the License for the
  48462. * specific language governing permissions and limitations
  48463. * under the License.
  48464. */
  48465. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  48466. // ??? TODO
  48467. // support dataset?
  48468. var graph = new Graph(directed);
  48469. for (var i = 0; i < nodes.length; i++) {
  48470. graph.addNode(retrieve(
  48471. // Id, name, dataIndex
  48472. nodes[i].id, nodes[i].name, i
  48473. ), i);
  48474. }
  48475. var linkNameList = [];
  48476. var validEdges = [];
  48477. var linkCount = 0;
  48478. for (var i = 0; i < edges.length; i++) {
  48479. var link = edges[i];
  48480. var source = link.source;
  48481. var target = link.target;
  48482. // addEdge may fail when source or target not exists
  48483. if (graph.addEdge(source, target, linkCount)) {
  48484. validEdges.push(link);
  48485. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  48486. linkCount++;
  48487. }
  48488. }
  48489. var coordSys = seriesModel.get('coordinateSystem');
  48490. var nodeData;
  48491. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  48492. nodeData = createListFromArray(nodes, seriesModel);
  48493. }
  48494. else {
  48495. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  48496. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  48497. ? (coordSysCtor.dimensions || []) : [];
  48498. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  48499. // `value` dimension, but graph need `value` dimension. It's better to
  48500. // uniform this behavior.
  48501. if (indexOf(coordDimensions, 'value') < 0) {
  48502. coordDimensions.concat(['value']);
  48503. }
  48504. var dimensionNames = createDimensions(nodes, {
  48505. coordDimensions: coordDimensions
  48506. });
  48507. nodeData = new List(dimensionNames, seriesModel);
  48508. nodeData.initData(nodes);
  48509. }
  48510. var edgeData = new List(['value'], seriesModel);
  48511. edgeData.initData(validEdges, linkNameList);
  48512. beforeLink && beforeLink(nodeData, edgeData);
  48513. linkList({
  48514. mainData: nodeData,
  48515. struct: graph,
  48516. structAttr: 'graph',
  48517. datas: {node: nodeData, edge: edgeData},
  48518. datasAttr: {node: 'data', edge: 'edgeData'}
  48519. });
  48520. // Update dataIndex of nodes and edges because invalid edge may be removed
  48521. graph.update();
  48522. return graph;
  48523. };
  48524. /*
  48525. * Licensed to the Apache Software Foundation (ASF) under one
  48526. * or more contributor license agreements. See the NOTICE file
  48527. * distributed with this work for additional information
  48528. * regarding copyright ownership. The ASF licenses this file
  48529. * to you under the Apache License, Version 2.0 (the
  48530. * "License"); you may not use this file except in compliance
  48531. * with the License. You may obtain a copy of the License at
  48532. *
  48533. * http://www.apache.org/licenses/LICENSE-2.0
  48534. *
  48535. * Unless required by applicable law or agreed to in writing,
  48536. * software distributed under the License is distributed on an
  48537. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48538. * KIND, either express or implied. See the License for the
  48539. * specific language governing permissions and limitations
  48540. * under the License.
  48541. */
  48542. var GraphSeries = extendSeriesModel({
  48543. type: 'series.graph',
  48544. init: function (option) {
  48545. GraphSeries.superApply(this, 'init', arguments);
  48546. var self = this;
  48547. function getCategoriesData() {
  48548. return self._categoriesData;
  48549. }
  48550. // Provide data for legend select
  48551. this.legendVisualProvider = new LegendVisualProvider(
  48552. getCategoriesData, getCategoriesData
  48553. );
  48554. this.fillDataTextStyle(option.edges || option.links);
  48555. this._updateCategoriesData();
  48556. },
  48557. mergeOption: function (option) {
  48558. GraphSeries.superApply(this, 'mergeOption', arguments);
  48559. this.fillDataTextStyle(option.edges || option.links);
  48560. this._updateCategoriesData();
  48561. },
  48562. mergeDefaultAndTheme: function (option) {
  48563. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  48564. defaultEmphasis(option, ['edgeLabel'], ['show']);
  48565. },
  48566. getInitialData: function (option, ecModel) {
  48567. var edges = option.edges || option.links || [];
  48568. var nodes = option.data || option.nodes || [];
  48569. var self = this;
  48570. if (nodes && edges) {
  48571. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  48572. }
  48573. function beforeLink(nodeData, edgeData) {
  48574. // Overwrite nodeData.getItemModel to
  48575. nodeData.wrapMethod('getItemModel', function (model) {
  48576. var categoriesModels = self._categoriesModels;
  48577. var categoryIdx = model.getShallow('category');
  48578. var categoryModel = categoriesModels[categoryIdx];
  48579. if (categoryModel) {
  48580. categoryModel.parentModel = model.parentModel;
  48581. model.parentModel = categoryModel;
  48582. }
  48583. return model;
  48584. });
  48585. var edgeLabelModel = self.getModel('edgeLabel');
  48586. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  48587. var fakeSeriesModel = new Model(
  48588. {label: edgeLabelModel.option},
  48589. edgeLabelModel.parentModel,
  48590. ecModel
  48591. );
  48592. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  48593. var emphasisFakeSeriesModel = new Model(
  48594. {emphasis: {label: emphasisEdgeLabelModel.option}},
  48595. emphasisEdgeLabelModel.parentModel,
  48596. ecModel
  48597. );
  48598. edgeData.wrapMethod('getItemModel', function (model) {
  48599. model.customizeGetParent(edgeGetParent);
  48600. return model;
  48601. });
  48602. function edgeGetParent(path) {
  48603. path = this.parsePath(path);
  48604. return (path && path[0] === 'label')
  48605. ? fakeSeriesModel
  48606. : (path && path[0] === 'emphasis' && path[1] === 'label')
  48607. ? emphasisFakeSeriesModel
  48608. : this.parentModel;
  48609. }
  48610. }
  48611. },
  48612. /**
  48613. * @return {module:echarts/data/Graph}
  48614. */
  48615. getGraph: function () {
  48616. return this.getData().graph;
  48617. },
  48618. /**
  48619. * @return {module:echarts/data/List}
  48620. */
  48621. getEdgeData: function () {
  48622. return this.getGraph().edgeData;
  48623. },
  48624. /**
  48625. * @return {module:echarts/data/List}
  48626. */
  48627. getCategoriesData: function () {
  48628. return this._categoriesData;
  48629. },
  48630. /**
  48631. * @override
  48632. */
  48633. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  48634. if (dataType === 'edge') {
  48635. var nodeData = this.getData();
  48636. var params = this.getDataParams(dataIndex, dataType);
  48637. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  48638. var sourceName = nodeData.getName(edge.node1.dataIndex);
  48639. var targetName = nodeData.getName(edge.node2.dataIndex);
  48640. var html = [];
  48641. sourceName != null && html.push(sourceName);
  48642. targetName != null && html.push(targetName);
  48643. html = encodeHTML(html.join(' > '));
  48644. if (params.value) {
  48645. html += ' : ' + encodeHTML(params.value);
  48646. }
  48647. return html;
  48648. }
  48649. else { // dataType === 'node' or empty
  48650. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  48651. }
  48652. },
  48653. _updateCategoriesData: function () {
  48654. var categories = map(this.option.categories || [], function (category) {
  48655. // Data must has value
  48656. return category.value != null ? category : extend({
  48657. value: 0
  48658. }, category);
  48659. });
  48660. var categoriesData = new List(['value'], this);
  48661. categoriesData.initData(categories);
  48662. this._categoriesData = categoriesData;
  48663. this._categoriesModels = categoriesData.mapArray(function (idx) {
  48664. return categoriesData.getItemModel(idx, true);
  48665. });
  48666. },
  48667. setZoom: function (zoom) {
  48668. this.option.zoom = zoom;
  48669. },
  48670. setCenter: function (center) {
  48671. this.option.center = center;
  48672. },
  48673. isAnimationEnabled: function () {
  48674. return GraphSeries.superCall(this, 'isAnimationEnabled')
  48675. // Not enable animation when do force layout
  48676. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  48677. },
  48678. defaultOption: {
  48679. zlevel: 0,
  48680. z: 2,
  48681. coordinateSystem: 'view',
  48682. // Default option for all coordinate systems
  48683. // xAxisIndex: 0,
  48684. // yAxisIndex: 0,
  48685. // polarIndex: 0,
  48686. // geoIndex: 0,
  48687. legendHoverLink: true,
  48688. hoverAnimation: true,
  48689. layout: null,
  48690. focusNodeAdjacency: false,
  48691. // Configuration of circular layout
  48692. circular: {
  48693. rotateLabel: false
  48694. },
  48695. // Configuration of force directed layout
  48696. force: {
  48697. initLayout: null,
  48698. // Node repulsion. Can be an array to represent range.
  48699. repulsion: [0, 50],
  48700. gravity: 0.1,
  48701. // Initial friction
  48702. friction: 0.6,
  48703. // Edge length. Can be an array to represent range.
  48704. edgeLength: 30,
  48705. layoutAnimation: true
  48706. },
  48707. left: 'center',
  48708. top: 'center',
  48709. // right: null,
  48710. // bottom: null,
  48711. // width: '80%',
  48712. // height: '80%',
  48713. symbol: 'circle',
  48714. symbolSize: 10,
  48715. edgeSymbol: ['none', 'none'],
  48716. edgeSymbolSize: 10,
  48717. edgeLabel: {
  48718. position: 'middle'
  48719. },
  48720. draggable: false,
  48721. roam: false,
  48722. // Default on center of graph
  48723. center: null,
  48724. zoom: 1,
  48725. // Symbol size scale ratio in roam
  48726. nodeScaleRatio: 0.6,
  48727. // cursor: null,
  48728. // categories: [],
  48729. // data: []
  48730. // Or
  48731. // nodes: []
  48732. //
  48733. // links: []
  48734. // Or
  48735. // edges: []
  48736. label: {
  48737. show: false,
  48738. formatter: '{b}'
  48739. },
  48740. itemStyle: {},
  48741. lineStyle: {
  48742. color: '#aaa',
  48743. width: 1,
  48744. curveness: 0,
  48745. opacity: 0.5
  48746. },
  48747. emphasis: {
  48748. label: {
  48749. show: true
  48750. }
  48751. }
  48752. }
  48753. });
  48754. /*
  48755. * Licensed to the Apache Software Foundation (ASF) under one
  48756. * or more contributor license agreements. See the NOTICE file
  48757. * distributed with this work for additional information
  48758. * regarding copyright ownership. The ASF licenses this file
  48759. * to you under the Apache License, Version 2.0 (the
  48760. * "License"); you may not use this file except in compliance
  48761. * with the License. You may obtain a copy of the License at
  48762. *
  48763. * http://www.apache.org/licenses/LICENSE-2.0
  48764. *
  48765. * Unless required by applicable law or agreed to in writing,
  48766. * software distributed under the License is distributed on an
  48767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48768. * KIND, either express or implied. See the License for the
  48769. * specific language governing permissions and limitations
  48770. * under the License.
  48771. */
  48772. /**
  48773. * Line path for bezier and straight line draw
  48774. */
  48775. var straightLineProto = Line.prototype;
  48776. var bezierCurveProto = BezierCurve.prototype;
  48777. function isLine(shape) {
  48778. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  48779. }
  48780. var LinePath = extendShape({
  48781. type: 'ec-line',
  48782. style: {
  48783. stroke: '#000',
  48784. fill: null
  48785. },
  48786. shape: {
  48787. x1: 0,
  48788. y1: 0,
  48789. x2: 0,
  48790. y2: 0,
  48791. percent: 1,
  48792. cpx1: null,
  48793. cpy1: null
  48794. },
  48795. buildPath: function (ctx, shape) {
  48796. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  48797. },
  48798. _buildPathLine: straightLineProto.buildPath,
  48799. _buildPathCurve: bezierCurveProto.buildPath,
  48800. pointAt: function (t) {
  48801. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  48802. },
  48803. _pointAtLine: straightLineProto.pointAt,
  48804. _pointAtCurve: bezierCurveProto.pointAt,
  48805. tangentAt: function (t) {
  48806. var shape = this.shape;
  48807. var p = isLine(shape)
  48808. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  48809. : this._tangentAtCurve(t);
  48810. return normalize(p, p);
  48811. },
  48812. _tangentAtCurve: bezierCurveProto.tangentAt
  48813. });
  48814. /*
  48815. * Licensed to the Apache Software Foundation (ASF) under one
  48816. * or more contributor license agreements. See the NOTICE file
  48817. * distributed with this work for additional information
  48818. * regarding copyright ownership. The ASF licenses this file
  48819. * to you under the Apache License, Version 2.0 (the
  48820. * "License"); you may not use this file except in compliance
  48821. * with the License. You may obtain a copy of the License at
  48822. *
  48823. * http://www.apache.org/licenses/LICENSE-2.0
  48824. *
  48825. * Unless required by applicable law or agreed to in writing,
  48826. * software distributed under the License is distributed on an
  48827. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48828. * KIND, either express or implied. See the License for the
  48829. * specific language governing permissions and limitations
  48830. * under the License.
  48831. */
  48832. /**
  48833. * @module echarts/chart/helper/Line
  48834. */
  48835. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  48836. function makeSymbolTypeKey(symbolCategory) {
  48837. return '_' + symbolCategory + 'Type';
  48838. }
  48839. /**
  48840. * @inner
  48841. */
  48842. function createSymbol$1(name, lineData, idx) {
  48843. var color = lineData.getItemVisual(idx, 'color');
  48844. var symbolType = lineData.getItemVisual(idx, name);
  48845. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  48846. if (!symbolType || symbolType === 'none') {
  48847. return;
  48848. }
  48849. if (!isArray(symbolSize)) {
  48850. symbolSize = [symbolSize, symbolSize];
  48851. }
  48852. var symbolPath = createSymbol(
  48853. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  48854. symbolSize[0], symbolSize[1], color
  48855. );
  48856. symbolPath.name = name;
  48857. return symbolPath;
  48858. }
  48859. function createLine(points) {
  48860. var line = new LinePath({
  48861. name: 'line',
  48862. subPixelOptimize: true
  48863. });
  48864. setLinePoints(line.shape, points);
  48865. return line;
  48866. }
  48867. function setLinePoints(targetShape, points) {
  48868. targetShape.x1 = points[0][0];
  48869. targetShape.y1 = points[0][1];
  48870. targetShape.x2 = points[1][0];
  48871. targetShape.y2 = points[1][1];
  48872. targetShape.percent = 1;
  48873. var cp1 = points[2];
  48874. if (cp1) {
  48875. targetShape.cpx1 = cp1[0];
  48876. targetShape.cpy1 = cp1[1];
  48877. }
  48878. else {
  48879. targetShape.cpx1 = NaN;
  48880. targetShape.cpy1 = NaN;
  48881. }
  48882. }
  48883. function updateSymbolAndLabelBeforeLineUpdate() {
  48884. var lineGroup = this;
  48885. var symbolFrom = lineGroup.childOfName('fromSymbol');
  48886. var symbolTo = lineGroup.childOfName('toSymbol');
  48887. var label = lineGroup.childOfName('label');
  48888. // Quick reject
  48889. if (!symbolFrom && !symbolTo && label.ignore) {
  48890. return;
  48891. }
  48892. var invScale = 1;
  48893. var parentNode = this.parent;
  48894. while (parentNode) {
  48895. if (parentNode.scale) {
  48896. invScale /= parentNode.scale[0];
  48897. }
  48898. parentNode = parentNode.parent;
  48899. }
  48900. var line = lineGroup.childOfName('line');
  48901. // If line not changed
  48902. // FIXME Parent scale changed
  48903. if (!this.__dirty && !line.__dirty) {
  48904. return;
  48905. }
  48906. var percent = line.shape.percent;
  48907. var fromPos = line.pointAt(0);
  48908. var toPos = line.pointAt(percent);
  48909. var d = sub([], toPos, fromPos);
  48910. normalize(d, d);
  48911. if (symbolFrom) {
  48912. symbolFrom.attr('position', fromPos);
  48913. var tangent = line.tangentAt(0);
  48914. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  48915. tangent[1], tangent[0]
  48916. ));
  48917. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  48918. }
  48919. if (symbolTo) {
  48920. symbolTo.attr('position', toPos);
  48921. var tangent = line.tangentAt(1);
  48922. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  48923. tangent[1], tangent[0]
  48924. ));
  48925. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  48926. }
  48927. if (!label.ignore) {
  48928. label.attr('position', toPos);
  48929. var textPosition;
  48930. var textAlign;
  48931. var textVerticalAlign;
  48932. var distance$$1 = 5 * invScale;
  48933. // End
  48934. if (label.__position === 'end') {
  48935. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  48936. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  48937. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  48938. }
  48939. // Middle
  48940. else if (label.__position === 'middle') {
  48941. var halfPercent = percent / 2;
  48942. var tangent = line.tangentAt(halfPercent);
  48943. var n = [tangent[1], -tangent[0]];
  48944. var cp = line.pointAt(halfPercent);
  48945. if (n[1] > 0) {
  48946. n[0] = -n[0];
  48947. n[1] = -n[1];
  48948. }
  48949. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  48950. textAlign = 'center';
  48951. textVerticalAlign = 'bottom';
  48952. var rotation = -Math.atan2(tangent[1], tangent[0]);
  48953. if (toPos[0] < fromPos[0]) {
  48954. rotation = Math.PI + rotation;
  48955. }
  48956. label.attr('rotation', rotation);
  48957. }
  48958. // Start
  48959. else {
  48960. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  48961. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  48962. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  48963. }
  48964. label.attr({
  48965. style: {
  48966. // Use the user specified text align and baseline first
  48967. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  48968. textAlign: label.__textAlign || textAlign
  48969. },
  48970. position: textPosition,
  48971. scale: [invScale, invScale]
  48972. });
  48973. }
  48974. }
  48975. /**
  48976. * @constructor
  48977. * @extends {module:zrender/graphic/Group}
  48978. * @alias {module:echarts/chart/helper/Line}
  48979. */
  48980. function Line$1(lineData, idx, seriesScope) {
  48981. Group.call(this);
  48982. this._createLine(lineData, idx, seriesScope);
  48983. }
  48984. var lineProto = Line$1.prototype;
  48985. // Update symbol position and rotation
  48986. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  48987. lineProto._createLine = function (lineData, idx, seriesScope) {
  48988. var seriesModel = lineData.hostModel;
  48989. var linePoints = lineData.getItemLayout(idx);
  48990. var line = createLine(linePoints);
  48991. line.shape.percent = 0;
  48992. initProps(line, {
  48993. shape: {
  48994. percent: 1
  48995. }
  48996. }, seriesModel, idx);
  48997. this.add(line);
  48998. var label = new Text({
  48999. name: 'label',
  49000. // FIXME
  49001. // Temporary solution for `focusNodeAdjacency`.
  49002. // line label do not use the opacity of lineStyle.
  49003. lineLabelOriginalOpacity: 1
  49004. });
  49005. this.add(label);
  49006. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49007. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49008. // symbols must added after line to make sure
  49009. // it will be updated after line#update.
  49010. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  49011. this.add(symbol);
  49012. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  49013. }, this);
  49014. this._updateCommonStl(lineData, idx, seriesScope);
  49015. };
  49016. lineProto.updateData = function (lineData, idx, seriesScope) {
  49017. var seriesModel = lineData.hostModel;
  49018. var line = this.childOfName('line');
  49019. var linePoints = lineData.getItemLayout(idx);
  49020. var target = {
  49021. shape: {}
  49022. };
  49023. setLinePoints(target.shape, linePoints);
  49024. updateProps(line, target, seriesModel, idx);
  49025. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49026. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  49027. var key = makeSymbolTypeKey(symbolCategory);
  49028. // Symbol changed
  49029. if (this[key] !== symbolType) {
  49030. this.remove(this.childOfName(symbolCategory));
  49031. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49032. this.add(symbol);
  49033. }
  49034. this[key] = symbolType;
  49035. }, this);
  49036. this._updateCommonStl(lineData, idx, seriesScope);
  49037. };
  49038. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  49039. var seriesModel = lineData.hostModel;
  49040. var line = this.childOfName('line');
  49041. var lineStyle = seriesScope && seriesScope.lineStyle;
  49042. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  49043. var labelModel = seriesScope && seriesScope.labelModel;
  49044. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  49045. // Optimization for large dataset
  49046. if (!seriesScope || lineData.hasItemOption) {
  49047. var itemModel = lineData.getItemModel(idx);
  49048. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  49049. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  49050. labelModel = itemModel.getModel('label');
  49051. hoverLabelModel = itemModel.getModel('emphasis.label');
  49052. }
  49053. var visualColor = lineData.getItemVisual(idx, 'color');
  49054. var visualOpacity = retrieve3(
  49055. lineData.getItemVisual(idx, 'opacity'),
  49056. lineStyle.opacity,
  49057. 1
  49058. );
  49059. line.useStyle(defaults(
  49060. {
  49061. strokeNoScale: true,
  49062. fill: 'none',
  49063. stroke: visualColor,
  49064. opacity: visualOpacity
  49065. },
  49066. lineStyle
  49067. ));
  49068. line.hoverStyle = hoverLineStyle;
  49069. // Update symbol
  49070. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  49071. var symbol = this.childOfName(symbolCategory);
  49072. if (symbol) {
  49073. symbol.setColor(visualColor);
  49074. symbol.setStyle({
  49075. opacity: visualOpacity
  49076. });
  49077. }
  49078. }, this);
  49079. var showLabel = labelModel.getShallow('show');
  49080. var hoverShowLabel = hoverLabelModel.getShallow('show');
  49081. var label = this.childOfName('label');
  49082. var defaultLabelColor;
  49083. var baseText;
  49084. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  49085. if (showLabel || hoverShowLabel) {
  49086. defaultLabelColor = visualColor || '#000';
  49087. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  49088. if (baseText == null) {
  49089. var rawVal = seriesModel.getRawValue(idx);
  49090. baseText = rawVal == null
  49091. ? lineData.getName(idx)
  49092. : isFinite(rawVal)
  49093. ? round$1(rawVal)
  49094. : rawVal;
  49095. }
  49096. }
  49097. var normalText = showLabel ? baseText : null;
  49098. var emphasisText = hoverShowLabel
  49099. ? retrieve2(
  49100. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  49101. baseText
  49102. )
  49103. : null;
  49104. var labelStyle = label.style;
  49105. // Always set `textStyle` even if `normalStyle.text` is null, because default
  49106. // values have to be set on `normalStyle`.
  49107. if (normalText != null || emphasisText != null) {
  49108. setTextStyle(label.style, labelModel, {
  49109. text: normalText
  49110. }, {
  49111. autoColor: defaultLabelColor
  49112. });
  49113. label.__textAlign = labelStyle.textAlign;
  49114. label.__verticalAlign = labelStyle.textVerticalAlign;
  49115. // 'start', 'middle', 'end'
  49116. label.__position = labelModel.get('position') || 'middle';
  49117. }
  49118. if (emphasisText != null) {
  49119. // Only these properties supported in this emphasis style here.
  49120. label.hoverStyle = {
  49121. text: emphasisText,
  49122. textFill: hoverLabelModel.getTextColor(true),
  49123. // For merging hover style to normal style, do not use
  49124. // `hoverLabelModel.getFont()` here.
  49125. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  49126. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  49127. fontSize: hoverLabelModel.getShallow('fontSize'),
  49128. fontFamily: hoverLabelModel.getShallow('fontFamily')
  49129. };
  49130. }
  49131. else {
  49132. label.hoverStyle = {
  49133. text: null
  49134. };
  49135. }
  49136. label.ignore = !showLabel && !hoverShowLabel;
  49137. setHoverStyle(this);
  49138. };
  49139. lineProto.highlight = function () {
  49140. this.trigger('emphasis');
  49141. };
  49142. lineProto.downplay = function () {
  49143. this.trigger('normal');
  49144. };
  49145. lineProto.updateLayout = function (lineData, idx) {
  49146. this.setLinePoints(lineData.getItemLayout(idx));
  49147. };
  49148. lineProto.setLinePoints = function (points) {
  49149. var linePath = this.childOfName('line');
  49150. setLinePoints(linePath.shape, points);
  49151. linePath.dirty();
  49152. };
  49153. inherits(Line$1, Group);
  49154. /*
  49155. * Licensed to the Apache Software Foundation (ASF) under one
  49156. * or more contributor license agreements. See the NOTICE file
  49157. * distributed with this work for additional information
  49158. * regarding copyright ownership. The ASF licenses this file
  49159. * to you under the Apache License, Version 2.0 (the
  49160. * "License"); you may not use this file except in compliance
  49161. * with the License. You may obtain a copy of the License at
  49162. *
  49163. * http://www.apache.org/licenses/LICENSE-2.0
  49164. *
  49165. * Unless required by applicable law or agreed to in writing,
  49166. * software distributed under the License is distributed on an
  49167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49168. * KIND, either express or implied. See the License for the
  49169. * specific language governing permissions and limitations
  49170. * under the License.
  49171. */
  49172. /**
  49173. * @module echarts/chart/helper/LineDraw
  49174. */
  49175. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  49176. /**
  49177. * @alias module:echarts/component/marker/LineDraw
  49178. * @constructor
  49179. */
  49180. function LineDraw(ctor) {
  49181. this._ctor = ctor || Line$1;
  49182. this.group = new Group();
  49183. }
  49184. var lineDrawProto = LineDraw.prototype;
  49185. lineDrawProto.isPersistent = function () {
  49186. return true;
  49187. };
  49188. /**
  49189. * @param {module:echarts/data/List} lineData
  49190. */
  49191. lineDrawProto.updateData = function (lineData) {
  49192. var lineDraw = this;
  49193. var group = lineDraw.group;
  49194. var oldLineData = lineDraw._lineData;
  49195. lineDraw._lineData = lineData;
  49196. // There is no oldLineData only when first rendering or switching from
  49197. // stream mode to normal mode, where previous elements should be removed.
  49198. if (!oldLineData) {
  49199. group.removeAll();
  49200. }
  49201. var seriesScope = makeSeriesScope$1(lineData);
  49202. lineData.diff(oldLineData)
  49203. .add(function (idx) {
  49204. doAdd(lineDraw, lineData, idx, seriesScope);
  49205. })
  49206. .update(function (newIdx, oldIdx) {
  49207. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  49208. })
  49209. .remove(function (idx) {
  49210. group.remove(oldLineData.getItemGraphicEl(idx));
  49211. })
  49212. .execute();
  49213. };
  49214. function doAdd(lineDraw, lineData, idx, seriesScope) {
  49215. var itemLayout = lineData.getItemLayout(idx);
  49216. if (!lineNeedsDraw(itemLayout)) {
  49217. return;
  49218. }
  49219. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  49220. lineData.setItemGraphicEl(idx, el);
  49221. lineDraw.group.add(el);
  49222. }
  49223. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  49224. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  49225. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  49226. lineDraw.group.remove(itemEl);
  49227. return;
  49228. }
  49229. if (!itemEl) {
  49230. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  49231. }
  49232. else {
  49233. itemEl.updateData(newLineData, newIdx, seriesScope);
  49234. }
  49235. newLineData.setItemGraphicEl(newIdx, itemEl);
  49236. lineDraw.group.add(itemEl);
  49237. }
  49238. lineDrawProto.updateLayout = function () {
  49239. var lineData = this._lineData;
  49240. // Do not support update layout in incremental mode.
  49241. if (!lineData) {
  49242. return;
  49243. }
  49244. lineData.eachItemGraphicEl(function (el, idx) {
  49245. el.updateLayout(lineData, idx);
  49246. }, this);
  49247. };
  49248. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  49249. this._seriesScope = makeSeriesScope$1(lineData);
  49250. this._lineData = null;
  49251. this.group.removeAll();
  49252. };
  49253. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  49254. function updateIncrementalAndHover(el) {
  49255. if (!el.isGroup) {
  49256. el.incremental = el.useHoverLayer = true;
  49257. }
  49258. }
  49259. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  49260. var itemLayout = lineData.getItemLayout(idx);
  49261. if (lineNeedsDraw(itemLayout)) {
  49262. var el = new this._ctor(lineData, idx, this._seriesScope);
  49263. el.traverse(updateIncrementalAndHover);
  49264. this.group.add(el);
  49265. lineData.setItemGraphicEl(idx, el);
  49266. }
  49267. }
  49268. };
  49269. function makeSeriesScope$1(lineData) {
  49270. var hostModel = lineData.hostModel;
  49271. return {
  49272. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  49273. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  49274. labelModel: hostModel.getModel('label'),
  49275. hoverLabelModel: hostModel.getModel('emphasis.label')
  49276. };
  49277. }
  49278. lineDrawProto.remove = function () {
  49279. this._clearIncremental();
  49280. this._incremental = null;
  49281. this.group.removeAll();
  49282. };
  49283. lineDrawProto._clearIncremental = function () {
  49284. var incremental = this._incremental;
  49285. if (incremental) {
  49286. incremental.clearDisplaybles();
  49287. }
  49288. };
  49289. function isPointNaN(pt) {
  49290. return isNaN(pt[0]) || isNaN(pt[1]);
  49291. }
  49292. function lineNeedsDraw(pts) {
  49293. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  49294. }
  49295. /*
  49296. * Licensed to the Apache Software Foundation (ASF) under one
  49297. * or more contributor license agreements. See the NOTICE file
  49298. * distributed with this work for additional information
  49299. * regarding copyright ownership. The ASF licenses this file
  49300. * to you under the Apache License, Version 2.0 (the
  49301. * "License"); you may not use this file except in compliance
  49302. * with the License. You may obtain a copy of the License at
  49303. *
  49304. * http://www.apache.org/licenses/LICENSE-2.0
  49305. *
  49306. * Unless required by applicable law or agreed to in writing,
  49307. * software distributed under the License is distributed on an
  49308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49309. * KIND, either express or implied. See the License for the
  49310. * specific language governing permissions and limitations
  49311. * under the License.
  49312. */
  49313. function getNodeGlobalScale(seriesModel) {
  49314. var coordSys = seriesModel.coordinateSystem;
  49315. if (coordSys.type !== 'view') {
  49316. return 1;
  49317. }
  49318. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  49319. var groupScale = coordSys.scale;
  49320. var groupZoom = (groupScale && groupScale[0]) || 1;
  49321. // Scale node when zoom changes
  49322. var roamZoom = coordSys.getZoom();
  49323. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  49324. return nodeScale / groupZoom;
  49325. }
  49326. function getSymbolSize$1(node) {
  49327. var symbolSize = node.getVisual('symbolSize');
  49328. if (symbolSize instanceof Array) {
  49329. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  49330. }
  49331. return +symbolSize;
  49332. }
  49333. /*
  49334. * Licensed to the Apache Software Foundation (ASF) under one
  49335. * or more contributor license agreements. See the NOTICE file
  49336. * distributed with this work for additional information
  49337. * regarding copyright ownership. The ASF licenses this file
  49338. * to you under the Apache License, Version 2.0 (the
  49339. * "License"); you may not use this file except in compliance
  49340. * with the License. You may obtain a copy of the License at
  49341. *
  49342. * http://www.apache.org/licenses/LICENSE-2.0
  49343. *
  49344. * Unless required by applicable law or agreed to in writing,
  49345. * software distributed under the License is distributed on an
  49346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49347. * KIND, either express or implied. See the License for the
  49348. * specific language governing permissions and limitations
  49349. * under the License.
  49350. */
  49351. var v1 = [];
  49352. var v2 = [];
  49353. var v3 = [];
  49354. var quadraticAt$1 = quadraticAt;
  49355. var v2DistSquare = distSquare;
  49356. var mathAbs$1 = Math.abs;
  49357. function intersectCurveCircle(curvePoints, center, radius) {
  49358. var p0 = curvePoints[0];
  49359. var p1 = curvePoints[1];
  49360. var p2 = curvePoints[2];
  49361. var d = Infinity;
  49362. var t;
  49363. var radiusSquare = radius * radius;
  49364. var interval = 0.1;
  49365. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  49366. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  49367. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  49368. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  49369. if (diff < d) {
  49370. d = diff;
  49371. t = _t;
  49372. }
  49373. }
  49374. // Assume the segment is monotone,Find root through Bisection method
  49375. // At most 32 iteration
  49376. for (var i = 0; i < 32; i++) {
  49377. // var prev = t - interval;
  49378. var next = t + interval;
  49379. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  49380. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  49381. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  49382. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  49383. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  49384. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  49385. var diff = v2DistSquare(v2, center) - radiusSquare;
  49386. if (mathAbs$1(diff) < 1e-2) {
  49387. break;
  49388. }
  49389. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  49390. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  49391. interval /= 2;
  49392. if (diff < 0) {
  49393. if (nextDiff >= 0) {
  49394. t = t + interval;
  49395. }
  49396. else {
  49397. t = t - interval;
  49398. }
  49399. }
  49400. else {
  49401. if (nextDiff >= 0) {
  49402. t = t - interval;
  49403. }
  49404. else {
  49405. t = t + interval;
  49406. }
  49407. }
  49408. }
  49409. return t;
  49410. }
  49411. // Adjust edge to avoid
  49412. var adjustEdge = function (graph, scale$$1) {
  49413. var tmp0 = [];
  49414. var quadraticSubdivide$$1 = quadraticSubdivide;
  49415. var pts = [[], [], []];
  49416. var pts2 = [[], []];
  49417. var v = [];
  49418. scale$$1 /= 2;
  49419. graph.eachEdge(function (edge, idx) {
  49420. var linePoints = edge.getLayout();
  49421. var fromSymbol = edge.getVisual('fromSymbol');
  49422. var toSymbol = edge.getVisual('toSymbol');
  49423. if (!linePoints.__original) {
  49424. linePoints.__original = [
  49425. clone$1(linePoints[0]),
  49426. clone$1(linePoints[1])
  49427. ];
  49428. if (linePoints[2]) {
  49429. linePoints.__original.push(clone$1(linePoints[2]));
  49430. }
  49431. }
  49432. var originalPoints = linePoints.__original;
  49433. // Quadratic curve
  49434. if (linePoints[2] != null) {
  49435. copy(pts[0], originalPoints[0]);
  49436. copy(pts[1], originalPoints[2]);
  49437. copy(pts[2], originalPoints[1]);
  49438. if (fromSymbol && fromSymbol !== 'none') {
  49439. var symbolSize = getSymbolSize$1(edge.node1);
  49440. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  49441. // Subdivide and get the second
  49442. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49443. pts[0][0] = tmp0[3];
  49444. pts[1][0] = tmp0[4];
  49445. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49446. pts[0][1] = tmp0[3];
  49447. pts[1][1] = tmp0[4];
  49448. }
  49449. if (toSymbol && toSymbol !== 'none') {
  49450. var symbolSize = getSymbolSize$1(edge.node2);
  49451. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  49452. // Subdivide and get the first
  49453. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49454. pts[1][0] = tmp0[1];
  49455. pts[2][0] = tmp0[2];
  49456. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49457. pts[1][1] = tmp0[1];
  49458. pts[2][1] = tmp0[2];
  49459. }
  49460. // Copy back to layout
  49461. copy(linePoints[0], pts[0]);
  49462. copy(linePoints[1], pts[2]);
  49463. copy(linePoints[2], pts[1]);
  49464. }
  49465. // Line
  49466. else {
  49467. copy(pts2[0], originalPoints[0]);
  49468. copy(pts2[1], originalPoints[1]);
  49469. sub(v, pts2[1], pts2[0]);
  49470. normalize(v, v);
  49471. if (fromSymbol && fromSymbol !== 'none') {
  49472. var symbolSize = getSymbolSize$1(edge.node1);
  49473. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  49474. }
  49475. if (toSymbol && toSymbol !== 'none') {
  49476. var symbolSize = getSymbolSize$1(edge.node2);
  49477. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  49478. }
  49479. copy(linePoints[0], pts2[0]);
  49480. copy(linePoints[1], pts2[1]);
  49481. }
  49482. });
  49483. };
  49484. /*
  49485. * Licensed to the Apache Software Foundation (ASF) under one
  49486. * or more contributor license agreements. See the NOTICE file
  49487. * distributed with this work for additional information
  49488. * regarding copyright ownership. The ASF licenses this file
  49489. * to you under the Apache License, Version 2.0 (the
  49490. * "License"); you may not use this file except in compliance
  49491. * with the License. You may obtain a copy of the License at
  49492. *
  49493. * http://www.apache.org/licenses/LICENSE-2.0
  49494. *
  49495. * Unless required by applicable law or agreed to in writing,
  49496. * software distributed under the License is distributed on an
  49497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49498. * KIND, either express or implied. See the License for the
  49499. * specific language governing permissions and limitations
  49500. * under the License.
  49501. */
  49502. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  49503. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  49504. var nodeOpacityPath = ['itemStyle', 'opacity'];
  49505. var lineOpacityPath = ['lineStyle', 'opacity'];
  49506. function getItemOpacity(item, opacityPath) {
  49507. var opacity = item.getVisual('opacity');
  49508. return opacity != null ? opacity : item.getModel().get(opacityPath);
  49509. }
  49510. function fadeOutItem(item, opacityPath, opacityRatio) {
  49511. var el = item.getGraphicEl();
  49512. var opacity = getItemOpacity(item, opacityPath);
  49513. if (opacityRatio != null) {
  49514. opacity == null && (opacity = 1);
  49515. opacity *= opacityRatio;
  49516. }
  49517. el.downplay && el.downplay();
  49518. el.traverse(function (child) {
  49519. if (!child.isGroup) {
  49520. var opct = child.lineLabelOriginalOpacity;
  49521. if (opct == null || opacityRatio != null) {
  49522. opct = opacity;
  49523. }
  49524. child.setStyle('opacity', opct);
  49525. }
  49526. });
  49527. }
  49528. function fadeInItem(item, opacityPath) {
  49529. var opacity = getItemOpacity(item, opacityPath);
  49530. var el = item.getGraphicEl();
  49531. // Should go back to normal opacity first, consider hoverLayer,
  49532. // where current state is copied to elMirror, and support
  49533. // emphasis opacity here.
  49534. el.traverse(function (child) {
  49535. !child.isGroup && child.setStyle('opacity', opacity);
  49536. });
  49537. el.highlight && el.highlight();
  49538. }
  49539. extendChartView({
  49540. type: 'graph',
  49541. init: function (ecModel, api) {
  49542. var symbolDraw = new SymbolDraw();
  49543. var lineDraw = new LineDraw();
  49544. var group = this.group;
  49545. this._controller = new RoamController(api.getZr());
  49546. this._controllerHost = {target: group};
  49547. group.add(symbolDraw.group);
  49548. group.add(lineDraw.group);
  49549. this._symbolDraw = symbolDraw;
  49550. this._lineDraw = lineDraw;
  49551. this._firstRender = true;
  49552. },
  49553. render: function (seriesModel, ecModel, api) {
  49554. var graphView = this;
  49555. var coordSys = seriesModel.coordinateSystem;
  49556. this._model = seriesModel;
  49557. var symbolDraw = this._symbolDraw;
  49558. var lineDraw = this._lineDraw;
  49559. var group = this.group;
  49560. if (coordSys.type === 'view') {
  49561. var groupNewProp = {
  49562. position: coordSys.position,
  49563. scale: coordSys.scale
  49564. };
  49565. if (this._firstRender) {
  49566. group.attr(groupNewProp);
  49567. }
  49568. else {
  49569. updateProps(group, groupNewProp, seriesModel);
  49570. }
  49571. }
  49572. // Fix edge contact point with node
  49573. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49574. var data = seriesModel.getData();
  49575. symbolDraw.updateData(data);
  49576. var edgeData = seriesModel.getEdgeData();
  49577. lineDraw.updateData(edgeData);
  49578. this._updateNodeAndLinkScale();
  49579. this._updateController(seriesModel, ecModel, api);
  49580. clearTimeout(this._layoutTimeout);
  49581. var forceLayout = seriesModel.forceLayout;
  49582. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  49583. if (forceLayout) {
  49584. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49585. }
  49586. data.eachItemGraphicEl(function (el, idx) {
  49587. var itemModel = data.getItemModel(idx);
  49588. // Update draggable
  49589. el.off('drag').off('dragend');
  49590. var draggable = itemModel.get('draggable');
  49591. if (draggable) {
  49592. el.on('drag', function () {
  49593. if (forceLayout) {
  49594. forceLayout.warmUp();
  49595. !this._layouting
  49596. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49597. forceLayout.setFixed(idx);
  49598. // Write position back to layout
  49599. data.setItemLayout(idx, el.position);
  49600. }
  49601. }, this).on('dragend', function () {
  49602. if (forceLayout) {
  49603. forceLayout.setUnfixed(idx);
  49604. }
  49605. }, this);
  49606. }
  49607. el.setDraggable(draggable && forceLayout);
  49608. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49609. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49610. if (itemModel.get('focusNodeAdjacency')) {
  49611. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49612. graphView._clearTimer();
  49613. api.dispatchAction({
  49614. type: 'focusNodeAdjacency',
  49615. seriesId: seriesModel.id,
  49616. dataIndex: el.dataIndex
  49617. });
  49618. });
  49619. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49620. graphView._dispatchUnfocus(api);
  49621. });
  49622. }
  49623. }, this);
  49624. data.graph.eachEdge(function (edge) {
  49625. var el = edge.getGraphicEl();
  49626. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49627. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49628. if (edge.getModel().get('focusNodeAdjacency')) {
  49629. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49630. graphView._clearTimer();
  49631. api.dispatchAction({
  49632. type: 'focusNodeAdjacency',
  49633. seriesId: seriesModel.id,
  49634. edgeDataIndex: edge.dataIndex
  49635. });
  49636. });
  49637. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49638. graphView._dispatchUnfocus(api);
  49639. });
  49640. }
  49641. });
  49642. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  49643. && seriesModel.get('circular.rotateLabel');
  49644. var cx = data.getLayout('cx');
  49645. var cy = data.getLayout('cy');
  49646. data.eachItemGraphicEl(function (el, idx) {
  49647. var itemModel = data.getItemModel(idx);
  49648. var labelRotate = itemModel.get('label.rotate') || 0;
  49649. var symbolPath = el.getSymbolPath();
  49650. if (circularRotateLabel) {
  49651. var pos = data.getItemLayout(idx);
  49652. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  49653. if (rad < 0) {
  49654. rad = Math.PI * 2 + rad;
  49655. }
  49656. var isLeft = pos[0] < cx;
  49657. if (isLeft) {
  49658. rad = rad - Math.PI;
  49659. }
  49660. var textPosition = isLeft ? 'left' : 'right';
  49661. modifyLabelStyle(
  49662. symbolPath,
  49663. {
  49664. textRotation: -rad,
  49665. textPosition: textPosition,
  49666. textOrigin: 'center'
  49667. },
  49668. {
  49669. textPosition: textPosition
  49670. }
  49671. );
  49672. }
  49673. else {
  49674. modifyLabelStyle(
  49675. symbolPath,
  49676. {
  49677. textRotation: labelRotate *= Math.PI / 180
  49678. }
  49679. );
  49680. }
  49681. });
  49682. this._firstRender = false;
  49683. },
  49684. dispose: function () {
  49685. this._controller && this._controller.dispose();
  49686. this._controllerHost = {};
  49687. this._clearTimer();
  49688. },
  49689. _dispatchUnfocus: function (api, opt) {
  49690. var self = this;
  49691. this._clearTimer();
  49692. this._unfocusDelayTimer = setTimeout(function () {
  49693. self._unfocusDelayTimer = null;
  49694. api.dispatchAction({
  49695. type: 'unfocusNodeAdjacency',
  49696. seriesId: self._model.id
  49697. });
  49698. }, 500);
  49699. },
  49700. _clearTimer: function () {
  49701. if (this._unfocusDelayTimer) {
  49702. clearTimeout(this._unfocusDelayTimer);
  49703. this._unfocusDelayTimer = null;
  49704. }
  49705. },
  49706. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49707. var data = this._model.getData();
  49708. var graph = data.graph;
  49709. var dataIndex = payload.dataIndex;
  49710. var edgeDataIndex = payload.edgeDataIndex;
  49711. var node = graph.getNodeByIndex(dataIndex);
  49712. var edge = graph.getEdgeByIndex(edgeDataIndex);
  49713. if (!node && !edge) {
  49714. return;
  49715. }
  49716. graph.eachNode(function (node) {
  49717. fadeOutItem(node, nodeOpacityPath, 0.1);
  49718. });
  49719. graph.eachEdge(function (edge) {
  49720. fadeOutItem(edge, lineOpacityPath, 0.1);
  49721. });
  49722. if (node) {
  49723. fadeInItem(node, nodeOpacityPath);
  49724. each$1(node.edges, function (adjacentEdge) {
  49725. if (adjacentEdge.dataIndex < 0) {
  49726. return;
  49727. }
  49728. fadeInItem(adjacentEdge, lineOpacityPath);
  49729. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  49730. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  49731. });
  49732. }
  49733. if (edge) {
  49734. fadeInItem(edge, lineOpacityPath);
  49735. fadeInItem(edge.node1, nodeOpacityPath);
  49736. fadeInItem(edge.node2, nodeOpacityPath);
  49737. }
  49738. },
  49739. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49740. var graph = this._model.getData().graph;
  49741. graph.eachNode(function (node) {
  49742. fadeOutItem(node, nodeOpacityPath);
  49743. });
  49744. graph.eachEdge(function (edge) {
  49745. fadeOutItem(edge, lineOpacityPath);
  49746. });
  49747. },
  49748. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  49749. var self = this;
  49750. (function step() {
  49751. forceLayout.step(function (stopped) {
  49752. self.updateLayout(self._model);
  49753. (self._layouting = !stopped) && (
  49754. layoutAnimation
  49755. ? (self._layoutTimeout = setTimeout(step, 16))
  49756. : step()
  49757. );
  49758. });
  49759. })();
  49760. },
  49761. _updateController: function (seriesModel, ecModel, api) {
  49762. var controller = this._controller;
  49763. var controllerHost = this._controllerHost;
  49764. var group = this.group;
  49765. controller.setPointerChecker(function (e, x, y) {
  49766. var rect = group.getBoundingRect();
  49767. rect.applyTransform(group.transform);
  49768. return rect.contain(x, y)
  49769. && !onIrrelevantElement(e, api, seriesModel);
  49770. });
  49771. if (seriesModel.coordinateSystem.type !== 'view') {
  49772. controller.disable();
  49773. return;
  49774. }
  49775. controller.enable(seriesModel.get('roam'));
  49776. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  49777. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  49778. controller
  49779. .off('pan')
  49780. .off('zoom')
  49781. .on('pan', function (e) {
  49782. updateViewOnPan(controllerHost, e.dx, e.dy);
  49783. api.dispatchAction({
  49784. seriesId: seriesModel.id,
  49785. type: 'graphRoam',
  49786. dx: e.dx,
  49787. dy: e.dy
  49788. });
  49789. })
  49790. .on('zoom', function (e) {
  49791. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  49792. api.dispatchAction({
  49793. seriesId: seriesModel.id,
  49794. type: 'graphRoam',
  49795. zoom: e.scale,
  49796. originX: e.originX,
  49797. originY: e.originY
  49798. });
  49799. this._updateNodeAndLinkScale();
  49800. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49801. this._lineDraw.updateLayout();
  49802. }, this);
  49803. },
  49804. _updateNodeAndLinkScale: function () {
  49805. var seriesModel = this._model;
  49806. var data = seriesModel.getData();
  49807. var nodeScale = getNodeGlobalScale(seriesModel);
  49808. var invScale = [nodeScale, nodeScale];
  49809. data.eachItemGraphicEl(function (el, idx) {
  49810. el.attr('scale', invScale);
  49811. });
  49812. },
  49813. updateLayout: function (seriesModel) {
  49814. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49815. this._symbolDraw.updateLayout();
  49816. this._lineDraw.updateLayout();
  49817. },
  49818. remove: function (ecModel, api) {
  49819. this._symbolDraw && this._symbolDraw.remove();
  49820. this._lineDraw && this._lineDraw.remove();
  49821. }
  49822. });
  49823. /*
  49824. * Licensed to the Apache Software Foundation (ASF) under one
  49825. * or more contributor license agreements. See the NOTICE file
  49826. * distributed with this work for additional information
  49827. * regarding copyright ownership. The ASF licenses this file
  49828. * to you under the Apache License, Version 2.0 (the
  49829. * "License"); you may not use this file except in compliance
  49830. * with the License. You may obtain a copy of the License at
  49831. *
  49832. * http://www.apache.org/licenses/LICENSE-2.0
  49833. *
  49834. * Unless required by applicable law or agreed to in writing,
  49835. * software distributed under the License is distributed on an
  49836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49837. * KIND, either express or implied. See the License for the
  49838. * specific language governing permissions and limitations
  49839. * under the License.
  49840. */
  49841. /**
  49842. * @payload
  49843. * @property {number} [seriesIndex]
  49844. * @property {string} [seriesId]
  49845. * @property {string} [seriesName]
  49846. * @property {number} [dataIndex]
  49847. */
  49848. registerAction({
  49849. type: 'focusNodeAdjacency',
  49850. event: 'focusNodeAdjacency',
  49851. update: 'series:focusNodeAdjacency'
  49852. }, function () {});
  49853. /**
  49854. * @payload
  49855. * @property {number} [seriesIndex]
  49856. * @property {string} [seriesId]
  49857. * @property {string} [seriesName]
  49858. */
  49859. registerAction({
  49860. type: 'unfocusNodeAdjacency',
  49861. event: 'unfocusNodeAdjacency',
  49862. update: 'series:unfocusNodeAdjacency'
  49863. }, function () {});
  49864. /*
  49865. * Licensed to the Apache Software Foundation (ASF) under one
  49866. * or more contributor license agreements. See the NOTICE file
  49867. * distributed with this work for additional information
  49868. * regarding copyright ownership. The ASF licenses this file
  49869. * to you under the Apache License, Version 2.0 (the
  49870. * "License"); you may not use this file except in compliance
  49871. * with the License. You may obtain a copy of the License at
  49872. *
  49873. * http://www.apache.org/licenses/LICENSE-2.0
  49874. *
  49875. * Unless required by applicable law or agreed to in writing,
  49876. * software distributed under the License is distributed on an
  49877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49878. * KIND, either express or implied. See the License for the
  49879. * specific language governing permissions and limitations
  49880. * under the License.
  49881. */
  49882. var actionInfo = {
  49883. type: 'graphRoam',
  49884. event: 'graphRoam',
  49885. update: 'none'
  49886. };
  49887. /**
  49888. * @payload
  49889. * @property {string} name Series name
  49890. * @property {number} [dx]
  49891. * @property {number} [dy]
  49892. * @property {number} [zoom]
  49893. * @property {number} [originX]
  49894. * @property {number} [originY]
  49895. */
  49896. registerAction(actionInfo, function (payload, ecModel) {
  49897. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  49898. var coordSys = seriesModel.coordinateSystem;
  49899. var res = updateCenterAndZoom(coordSys, payload);
  49900. seriesModel.setCenter
  49901. && seriesModel.setCenter(res.center);
  49902. seriesModel.setZoom
  49903. && seriesModel.setZoom(res.zoom);
  49904. });
  49905. });
  49906. /*
  49907. * Licensed to the Apache Software Foundation (ASF) under one
  49908. * or more contributor license agreements. See the NOTICE file
  49909. * distributed with this work for additional information
  49910. * regarding copyright ownership. The ASF licenses this file
  49911. * to you under the Apache License, Version 2.0 (the
  49912. * "License"); you may not use this file except in compliance
  49913. * with the License. You may obtain a copy of the License at
  49914. *
  49915. * http://www.apache.org/licenses/LICENSE-2.0
  49916. *
  49917. * Unless required by applicable law or agreed to in writing,
  49918. * software distributed under the License is distributed on an
  49919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49920. * KIND, either express or implied. See the License for the
  49921. * specific language governing permissions and limitations
  49922. * under the License.
  49923. */
  49924. var categoryFilter = function (ecModel) {
  49925. var legendModels = ecModel.findComponents({
  49926. mainType: 'legend'
  49927. });
  49928. if (!legendModels || !legendModels.length) {
  49929. return;
  49930. }
  49931. ecModel.eachSeriesByType('graph', function (graphSeries) {
  49932. var categoriesData = graphSeries.getCategoriesData();
  49933. var graph = graphSeries.getGraph();
  49934. var data = graph.data;
  49935. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  49936. data.filterSelf(function (idx) {
  49937. var model = data.getItemModel(idx);
  49938. var category = model.getShallow('category');
  49939. if (category != null) {
  49940. if (typeof category === 'number') {
  49941. category = categoryNames[category];
  49942. }
  49943. // If in any legend component the status is not selected.
  49944. for (var i = 0; i < legendModels.length; i++) {
  49945. if (!legendModels[i].isSelected(category)) {
  49946. return false;
  49947. }
  49948. }
  49949. }
  49950. return true;
  49951. });
  49952. }, this);
  49953. };
  49954. /*
  49955. * Licensed to the Apache Software Foundation (ASF) under one
  49956. * or more contributor license agreements. See the NOTICE file
  49957. * distributed with this work for additional information
  49958. * regarding copyright ownership. The ASF licenses this file
  49959. * to you under the Apache License, Version 2.0 (the
  49960. * "License"); you may not use this file except in compliance
  49961. * with the License. You may obtain a copy of the License at
  49962. *
  49963. * http://www.apache.org/licenses/LICENSE-2.0
  49964. *
  49965. * Unless required by applicable law or agreed to in writing,
  49966. * software distributed under the License is distributed on an
  49967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49968. * KIND, either express or implied. See the License for the
  49969. * specific language governing permissions and limitations
  49970. * under the License.
  49971. */
  49972. var categoryVisual = function (ecModel) {
  49973. var paletteScope = {};
  49974. ecModel.eachSeriesByType('graph', function (seriesModel) {
  49975. var categoriesData = seriesModel.getCategoriesData();
  49976. var data = seriesModel.getData();
  49977. var categoryNameIdxMap = {};
  49978. categoriesData.each(function (idx) {
  49979. var name = categoriesData.getName(idx);
  49980. // Add prefix to avoid conflict with Object.prototype.
  49981. categoryNameIdxMap['ec-' + name] = idx;
  49982. var itemModel = categoriesData.getItemModel(idx);
  49983. var color = itemModel.get('itemStyle.color')
  49984. || seriesModel.getColorFromPalette(name, paletteScope);
  49985. categoriesData.setItemVisual(idx, 'color', color);
  49986. var itemStyleList = ['opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  49987. for (var i = 0; i < itemStyleList.length; i++) {
  49988. var itemStyle = itemModel.getShallow(itemStyleList[i], true);
  49989. if (itemStyle != null) {
  49990. categoriesData.setItemVisual(idx, itemStyleList[i], itemStyle);
  49991. }
  49992. }
  49993. });
  49994. // Assign category color to visual
  49995. if (categoriesData.count()) {
  49996. data.each(function (idx) {
  49997. var model = data.getItemModel(idx);
  49998. var category = model.getShallow('category');
  49999. if (category != null) {
  50000. if (typeof category === 'string') {
  50001. category = categoryNameIdxMap['ec-' + category];
  50002. }
  50003. var itemStyleList = ['color', 'opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  50004. for (var i = 0; i < itemStyleList.length; i++) {
  50005. if (data.getItemVisual(idx, itemStyleList[i], true) == null) {
  50006. data.setItemVisual(
  50007. idx, itemStyleList[i],
  50008. categoriesData.getItemVisual(category, itemStyleList[i])
  50009. );
  50010. }
  50011. }
  50012. }
  50013. });
  50014. }
  50015. });
  50016. };
  50017. /*
  50018. * Licensed to the Apache Software Foundation (ASF) under one
  50019. * or more contributor license agreements. See the NOTICE file
  50020. * distributed with this work for additional information
  50021. * regarding copyright ownership. The ASF licenses this file
  50022. * to you under the Apache License, Version 2.0 (the
  50023. * "License"); you may not use this file except in compliance
  50024. * with the License. You may obtain a copy of the License at
  50025. *
  50026. * http://www.apache.org/licenses/LICENSE-2.0
  50027. *
  50028. * Unless required by applicable law or agreed to in writing,
  50029. * software distributed under the License is distributed on an
  50030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50031. * KIND, either express or implied. See the License for the
  50032. * specific language governing permissions and limitations
  50033. * under the License.
  50034. */
  50035. function normalize$1(a) {
  50036. if (!(a instanceof Array)) {
  50037. a = [a, a];
  50038. }
  50039. return a;
  50040. }
  50041. var edgeVisual = function (ecModel) {
  50042. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50043. var graph = seriesModel.getGraph();
  50044. var edgeData = seriesModel.getEdgeData();
  50045. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  50046. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  50047. var colorQuery = 'lineStyle.color'.split('.');
  50048. var opacityQuery = 'lineStyle.opacity'.split('.');
  50049. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  50050. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  50051. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  50052. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  50053. edgeData.setVisual('color', seriesModel.get(colorQuery));
  50054. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  50055. edgeData.each(function (idx) {
  50056. var itemModel = edgeData.getItemModel(idx);
  50057. var edge = graph.getEdgeByIndex(idx);
  50058. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  50059. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  50060. // Edge visual must after node visual
  50061. var color = itemModel.get(colorQuery);
  50062. var opacity = itemModel.get(opacityQuery);
  50063. switch (color) {
  50064. case 'source':
  50065. color = edge.node1.getVisual('color');
  50066. break;
  50067. case 'target':
  50068. color = edge.node2.getVisual('color');
  50069. break;
  50070. }
  50071. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  50072. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  50073. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  50074. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  50075. edge.setVisual('color', color);
  50076. edge.setVisual('opacity', opacity);
  50077. });
  50078. });
  50079. };
  50080. /*
  50081. * Licensed to the Apache Software Foundation (ASF) under one
  50082. * or more contributor license agreements. See the NOTICE file
  50083. * distributed with this work for additional information
  50084. * regarding copyright ownership. The ASF licenses this file
  50085. * to you under the Apache License, Version 2.0 (the
  50086. * "License"); you may not use this file except in compliance
  50087. * with the License. You may obtain a copy of the License at
  50088. *
  50089. * http://www.apache.org/licenses/LICENSE-2.0
  50090. *
  50091. * Unless required by applicable law or agreed to in writing,
  50092. * software distributed under the License is distributed on an
  50093. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50094. * KIND, either express or implied. See the License for the
  50095. * specific language governing permissions and limitations
  50096. * under the License.
  50097. */
  50098. function simpleLayout$1(seriesModel) {
  50099. var coordSys = seriesModel.coordinateSystem;
  50100. if (coordSys && coordSys.type !== 'view') {
  50101. return;
  50102. }
  50103. var graph = seriesModel.getGraph();
  50104. graph.eachNode(function (node) {
  50105. var model = node.getModel();
  50106. node.setLayout([+model.get('x'), +model.get('y')]);
  50107. });
  50108. simpleLayoutEdge(graph);
  50109. }
  50110. function simpleLayoutEdge(graph) {
  50111. graph.eachEdge(function (edge) {
  50112. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50113. var p1 = clone$1(edge.node1.getLayout());
  50114. var p2 = clone$1(edge.node2.getLayout());
  50115. var points = [p1, p2];
  50116. if (+curveness) {
  50117. points.push([
  50118. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  50119. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  50120. ]);
  50121. }
  50122. edge.setLayout(points);
  50123. });
  50124. }
  50125. /*
  50126. * Licensed to the Apache Software Foundation (ASF) under one
  50127. * or more contributor license agreements. See the NOTICE file
  50128. * distributed with this work for additional information
  50129. * regarding copyright ownership. The ASF licenses this file
  50130. * to you under the Apache License, Version 2.0 (the
  50131. * "License"); you may not use this file except in compliance
  50132. * with the License. You may obtain a copy of the License at
  50133. *
  50134. * http://www.apache.org/licenses/LICENSE-2.0
  50135. *
  50136. * Unless required by applicable law or agreed to in writing,
  50137. * software distributed under the License is distributed on an
  50138. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50139. * KIND, either express or implied. See the License for the
  50140. * specific language governing permissions and limitations
  50141. * under the License.
  50142. */
  50143. var simpleLayout = function (ecModel, api) {
  50144. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50145. var layout = seriesModel.get('layout');
  50146. var coordSys = seriesModel.coordinateSystem;
  50147. if (coordSys && coordSys.type !== 'view') {
  50148. var data = seriesModel.getData();
  50149. var dimensions = [];
  50150. each$1(coordSys.dimensions, function (coordDim) {
  50151. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  50152. });
  50153. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  50154. var value = [];
  50155. var hasValue = false;
  50156. for (var i = 0; i < dimensions.length; i++) {
  50157. var val = data.get(dimensions[i], dataIndex);
  50158. if (!isNaN(val)) {
  50159. hasValue = true;
  50160. }
  50161. value.push(val);
  50162. }
  50163. if (hasValue) {
  50164. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  50165. }
  50166. else {
  50167. // Also {Array.<number>}, not undefined to avoid if...else... statement
  50168. data.setItemLayout(dataIndex, [NaN, NaN]);
  50169. }
  50170. }
  50171. simpleLayoutEdge(data.graph);
  50172. }
  50173. else if (!layout || layout === 'none') {
  50174. simpleLayout$1(seriesModel);
  50175. }
  50176. });
  50177. };
  50178. /*
  50179. * Licensed to the Apache Software Foundation (ASF) under one
  50180. * or more contributor license agreements. See the NOTICE file
  50181. * distributed with this work for additional information
  50182. * regarding copyright ownership. The ASF licenses this file
  50183. * to you under the Apache License, Version 2.0 (the
  50184. * "License"); you may not use this file except in compliance
  50185. * with the License. You may obtain a copy of the License at
  50186. *
  50187. * http://www.apache.org/licenses/LICENSE-2.0
  50188. *
  50189. * Unless required by applicable law or agreed to in writing,
  50190. * software distributed under the License is distributed on an
  50191. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50192. * KIND, either express or implied. See the License for the
  50193. * specific language governing permissions and limitations
  50194. * under the License.
  50195. */
  50196. var PI$3 = Math.PI;
  50197. var _symbolRadiansHalf = [];
  50198. /**
  50199. * `basedOn` can be:
  50200. * 'value':
  50201. * This layout is not accurate and have same bad case. For example,
  50202. * if the min value is very smaller than the max value, the nodes
  50203. * with the min value probably overlap even though there is enough
  50204. * space to layout them. So we only use this approach in the as the
  50205. * init layout of the force layout.
  50206. * FIXME
  50207. * Probably we do not need this method any more but use
  50208. * `basedOn: 'symbolSize'` in force layout if
  50209. * delay its init operations to GraphView.
  50210. * 'symbolSize':
  50211. * This approach work only if all of the symbol size calculated.
  50212. * That is, the progressive rendering is not applied to graph.
  50213. * FIXME
  50214. * If progressive rendering is applied to graph some day,
  50215. * probably we have to use `basedOn: 'value'`.
  50216. *
  50217. * @param {module:echarts/src/model/Series} seriesModel
  50218. * @param {string} basedOn 'value' or 'symbolSize'
  50219. */
  50220. function circularLayout$1(seriesModel, basedOn) {
  50221. var coordSys = seriesModel.coordinateSystem;
  50222. if (coordSys && coordSys.type !== 'view') {
  50223. return;
  50224. }
  50225. var rect = coordSys.getBoundingRect();
  50226. var nodeData = seriesModel.getData();
  50227. var graph = nodeData.graph;
  50228. var cx = rect.width / 2 + rect.x;
  50229. var cy = rect.height / 2 + rect.y;
  50230. var r = Math.min(rect.width, rect.height) / 2;
  50231. var count = nodeData.count();
  50232. nodeData.setLayout({
  50233. cx: cx,
  50234. cy: cy
  50235. });
  50236. if (!count) {
  50237. return;
  50238. }
  50239. _layoutNodesBasedOn[basedOn](seriesModel, coordSys, graph, nodeData, r, cx, cy, count);
  50240. graph.eachEdge(function (edge) {
  50241. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50242. var p1 = clone$1(edge.node1.getLayout());
  50243. var p2 = clone$1(edge.node2.getLayout());
  50244. var cp1;
  50245. var x12 = (p1[0] + p2[0]) / 2;
  50246. var y12 = (p1[1] + p2[1]) / 2;
  50247. if (+curveness) {
  50248. curveness *= 3;
  50249. cp1 = [
  50250. cx * curveness + x12 * (1 - curveness),
  50251. cy * curveness + y12 * (1 - curveness)
  50252. ];
  50253. }
  50254. edge.setLayout([p1, p2, cp1]);
  50255. });
  50256. }
  50257. var _layoutNodesBasedOn = {
  50258. value: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50259. var angle = 0;
  50260. var sum = nodeData.getSum('value');
  50261. var unitAngle = Math.PI * 2 / (sum || count);
  50262. graph.eachNode(function (node) {
  50263. var value = node.getValue('value');
  50264. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  50265. angle += radianHalf;
  50266. node.setLayout([
  50267. r * Math.cos(angle) + cx,
  50268. r * Math.sin(angle) + cy
  50269. ]);
  50270. angle += radianHalf;
  50271. });
  50272. },
  50273. symbolSize: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50274. var sumRadian = 0;
  50275. _symbolRadiansHalf.length = count;
  50276. var nodeScale = getNodeGlobalScale(seriesModel);
  50277. graph.eachNode(function (node) {
  50278. var symbolSize = getSymbolSize$1(node);
  50279. // Normally this case will not happen, but we still add
  50280. // some the defensive code (2px is an arbitrary value).
  50281. isNaN(symbolSize) && (symbolSize = 2);
  50282. symbolSize < 0 && (symbolSize = 0);
  50283. symbolSize *= nodeScale;
  50284. var symbolRadianHalf = Math.asin(symbolSize / 2 / r);
  50285. // when `symbolSize / 2` is bigger than `r`.
  50286. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$3 / 2);
  50287. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  50288. sumRadian += symbolRadianHalf * 2;
  50289. });
  50290. var halfRemainRadian = (2 * PI$3 - sumRadian) / count / 2;
  50291. var angle = 0;
  50292. graph.eachNode(function (node) {
  50293. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  50294. angle += radianHalf;
  50295. node.setLayout([
  50296. r * Math.cos(angle) + cx,
  50297. r * Math.sin(angle) + cy
  50298. ]);
  50299. angle += radianHalf;
  50300. });
  50301. }
  50302. };
  50303. /*
  50304. * Licensed to the Apache Software Foundation (ASF) under one
  50305. * or more contributor license agreements. See the NOTICE file
  50306. * distributed with this work for additional information
  50307. * regarding copyright ownership. The ASF licenses this file
  50308. * to you under the Apache License, Version 2.0 (the
  50309. * "License"); you may not use this file except in compliance
  50310. * with the License. You may obtain a copy of the License at
  50311. *
  50312. * http://www.apache.org/licenses/LICENSE-2.0
  50313. *
  50314. * Unless required by applicable law or agreed to in writing,
  50315. * software distributed under the License is distributed on an
  50316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50317. * KIND, either express or implied. See the License for the
  50318. * specific language governing permissions and limitations
  50319. * under the License.
  50320. */
  50321. var circularLayout = function (ecModel) {
  50322. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50323. if (seriesModel.get('layout') === 'circular') {
  50324. circularLayout$1(seriesModel, 'symbolSize');
  50325. }
  50326. });
  50327. };
  50328. /*
  50329. * Licensed to the Apache Software Foundation (ASF) under one
  50330. * or more contributor license agreements. See the NOTICE file
  50331. * distributed with this work for additional information
  50332. * regarding copyright ownership. The ASF licenses this file
  50333. * to you under the Apache License, Version 2.0 (the
  50334. * "License"); you may not use this file except in compliance
  50335. * with the License. You may obtain a copy of the License at
  50336. *
  50337. * http://www.apache.org/licenses/LICENSE-2.0
  50338. *
  50339. * Unless required by applicable law or agreed to in writing,
  50340. * software distributed under the License is distributed on an
  50341. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50342. * KIND, either express or implied. See the License for the
  50343. * specific language governing permissions and limitations
  50344. * under the License.
  50345. */
  50346. /*
  50347. * A third-party license is embeded for some of the code in this file:
  50348. * Some formulas were originally copied from "d3.js" with some
  50349. * modifications made for this project.
  50350. * (See more details in the comment of the method "step" below.)
  50351. * The use of the source code of this file is also subject to the terms
  50352. * and consitions of the license of "d3.js" (BSD-3Clause, see
  50353. * </licenses/LICENSE-d3>).
  50354. */
  50355. var scaleAndAdd$2 = scaleAndAdd;
  50356. // function adjacentNode(n, e) {
  50357. // return e.n1 === n ? e.n2 : e.n1;
  50358. // }
  50359. function forceLayout$1(nodes, edges, opts) {
  50360. var rect = opts.rect;
  50361. var width = rect.width;
  50362. var height = rect.height;
  50363. var center = [rect.x + width / 2, rect.y + height / 2];
  50364. // var scale = opts.scale || 1;
  50365. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  50366. // for (var i = 0; i < edges.length; i++) {
  50367. // var e = edges[i];
  50368. // var n1 = e.n1;
  50369. // var n2 = e.n2;
  50370. // n1.edges = n1.edges || [];
  50371. // n2.edges = n2.edges || [];
  50372. // n1.edges.push(e);
  50373. // n2.edges.push(e);
  50374. // }
  50375. // Init position
  50376. for (var i = 0; i < nodes.length; i++) {
  50377. var n = nodes[i];
  50378. if (!n.p) {
  50379. n.p = create(
  50380. width * (Math.random() - 0.5) + center[0],
  50381. height * (Math.random() - 0.5) + center[1]
  50382. );
  50383. }
  50384. n.pp = clone$1(n.p);
  50385. n.edges = null;
  50386. }
  50387. // Formula in 'Graph Drawing by Force-directed Placement'
  50388. // var k = scale * Math.sqrt(width * height / nodes.length);
  50389. // var k2 = k * k;
  50390. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  50391. var friction = initialFriction;
  50392. return {
  50393. warmUp: function () {
  50394. friction = initialFriction * 0.8;
  50395. },
  50396. setFixed: function (idx) {
  50397. nodes[idx].fixed = true;
  50398. },
  50399. setUnfixed: function (idx) {
  50400. nodes[idx].fixed = false;
  50401. },
  50402. /**
  50403. * Some formulas were originally copied from "d3.js"
  50404. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  50405. * with some modifications made for this project.
  50406. * See the license statement at the head of this file.
  50407. */
  50408. step: function (cb) {
  50409. var v12 = [];
  50410. var nLen = nodes.length;
  50411. for (var i = 0; i < edges.length; i++) {
  50412. var e = edges[i];
  50413. if (e.ignoreForceLayout) {
  50414. continue;
  50415. }
  50416. var n1 = e.n1;
  50417. var n2 = e.n2;
  50418. sub(v12, n2.p, n1.p);
  50419. var d = len(v12) - e.d;
  50420. var w = n2.w / (n1.w + n2.w);
  50421. if (isNaN(w)) {
  50422. w = 0;
  50423. }
  50424. normalize(v12, v12);
  50425. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  50426. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  50427. }
  50428. // Gravity
  50429. for (var i = 0; i < nLen; i++) {
  50430. var n = nodes[i];
  50431. if (!n.fixed) {
  50432. sub(v12, center, n.p);
  50433. // var d = vec2.len(v12);
  50434. // vec2.scale(v12, v12, 1 / d);
  50435. // var gravityFactor = gravity;
  50436. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  50437. }
  50438. }
  50439. // Repulsive
  50440. // PENDING
  50441. for (var i = 0; i < nLen; i++) {
  50442. var n1 = nodes[i];
  50443. for (var j = i + 1; j < nLen; j++) {
  50444. var n2 = nodes[j];
  50445. sub(v12, n2.p, n1.p);
  50446. var d = len(v12);
  50447. if (d === 0) {
  50448. // Random repulse
  50449. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  50450. d = 1;
  50451. }
  50452. var repFact = (n1.rep + n2.rep) / d / d;
  50453. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  50454. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  50455. }
  50456. }
  50457. var v = [];
  50458. for (var i = 0; i < nLen; i++) {
  50459. var n = nodes[i];
  50460. if (!n.fixed) {
  50461. sub(v, n.p, n.pp);
  50462. scaleAndAdd$2(n.p, n.p, v, friction);
  50463. copy(n.pp, n.p);
  50464. }
  50465. }
  50466. friction = friction * 0.992;
  50467. cb && cb(nodes, edges, friction < 0.01);
  50468. }
  50469. };
  50470. }
  50471. /*
  50472. * Licensed to the Apache Software Foundation (ASF) under one
  50473. * or more contributor license agreements. See the NOTICE file
  50474. * distributed with this work for additional information
  50475. * regarding copyright ownership. The ASF licenses this file
  50476. * to you under the Apache License, Version 2.0 (the
  50477. * "License"); you may not use this file except in compliance
  50478. * with the License. You may obtain a copy of the License at
  50479. *
  50480. * http://www.apache.org/licenses/LICENSE-2.0
  50481. *
  50482. * Unless required by applicable law or agreed to in writing,
  50483. * software distributed under the License is distributed on an
  50484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50485. * KIND, either express or implied. See the License for the
  50486. * specific language governing permissions and limitations
  50487. * under the License.
  50488. */
  50489. var forceLayout = function (ecModel) {
  50490. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50491. var coordSys = graphSeries.coordinateSystem;
  50492. if (coordSys && coordSys.type !== 'view') {
  50493. return;
  50494. }
  50495. if (graphSeries.get('layout') === 'force') {
  50496. var preservedPoints = graphSeries.preservedPoints || {};
  50497. var graph = graphSeries.getGraph();
  50498. var nodeData = graph.data;
  50499. var edgeData = graph.edgeData;
  50500. var forceModel = graphSeries.getModel('force');
  50501. var initLayout = forceModel.get('initLayout');
  50502. if (graphSeries.preservedPoints) {
  50503. nodeData.each(function (idx) {
  50504. var id = nodeData.getId(idx);
  50505. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  50506. });
  50507. }
  50508. else if (!initLayout || initLayout === 'none') {
  50509. simpleLayout$1(graphSeries);
  50510. }
  50511. else if (initLayout === 'circular') {
  50512. circularLayout$1(graphSeries, 'value');
  50513. }
  50514. var nodeDataExtent = nodeData.getDataExtent('value');
  50515. var edgeDataExtent = edgeData.getDataExtent('value');
  50516. // var edgeDataExtent = edgeData.getDataExtent('value');
  50517. var repulsion = forceModel.get('repulsion');
  50518. var edgeLength = forceModel.get('edgeLength');
  50519. if (!isArray(repulsion)) {
  50520. repulsion = [repulsion, repulsion];
  50521. }
  50522. if (!isArray(edgeLength)) {
  50523. edgeLength = [edgeLength, edgeLength];
  50524. }
  50525. // Larger value has smaller length
  50526. edgeLength = [edgeLength[1], edgeLength[0]];
  50527. var nodes = nodeData.mapArray('value', function (value, idx) {
  50528. var point = nodeData.getItemLayout(idx);
  50529. var rep = linearMap(value, nodeDataExtent, repulsion);
  50530. if (isNaN(rep)) {
  50531. rep = (repulsion[0] + repulsion[1]) / 2;
  50532. }
  50533. return {
  50534. w: rep,
  50535. rep: rep,
  50536. fixed: nodeData.getItemModel(idx).get('fixed'),
  50537. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  50538. };
  50539. });
  50540. var edges = edgeData.mapArray('value', function (value, idx) {
  50541. var edge = graph.getEdgeByIndex(idx);
  50542. var d = linearMap(value, edgeDataExtent, edgeLength);
  50543. if (isNaN(d)) {
  50544. d = (edgeLength[0] + edgeLength[1]) / 2;
  50545. }
  50546. var edgeModel = edge.getModel();
  50547. return {
  50548. n1: nodes[edge.node1.dataIndex],
  50549. n2: nodes[edge.node2.dataIndex],
  50550. d: d,
  50551. curveness: edgeModel.get('lineStyle.curveness') || 0,
  50552. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  50553. };
  50554. });
  50555. var coordSys = graphSeries.coordinateSystem;
  50556. var rect = coordSys.getBoundingRect();
  50557. var forceInstance = forceLayout$1(nodes, edges, {
  50558. rect: rect,
  50559. gravity: forceModel.get('gravity'),
  50560. friction: forceModel.get('friction')
  50561. });
  50562. var oldStep = forceInstance.step;
  50563. forceInstance.step = function (cb) {
  50564. for (var i = 0, l = nodes.length; i < l; i++) {
  50565. if (nodes[i].fixed) {
  50566. // Write back to layout instance
  50567. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  50568. }
  50569. }
  50570. oldStep(function (nodes, edges, stopped) {
  50571. for (var i = 0, l = nodes.length; i < l; i++) {
  50572. if (!nodes[i].fixed) {
  50573. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  50574. }
  50575. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  50576. }
  50577. for (var i = 0, l = edges.length; i < l; i++) {
  50578. var e = edges[i];
  50579. var edge = graph.getEdgeByIndex(i);
  50580. var p1 = e.n1.p;
  50581. var p2 = e.n2.p;
  50582. var points = edge.getLayout();
  50583. points = points ? points.slice() : [];
  50584. points[0] = points[0] || [];
  50585. points[1] = points[1] || [];
  50586. copy(points[0], p1);
  50587. copy(points[1], p2);
  50588. if (+e.curveness) {
  50589. points[2] = [
  50590. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  50591. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  50592. ];
  50593. }
  50594. edge.setLayout(points);
  50595. }
  50596. // Update layout
  50597. cb && cb(stopped);
  50598. });
  50599. };
  50600. graphSeries.forceLayout = forceInstance;
  50601. graphSeries.preservedPoints = preservedPoints;
  50602. // Step to get the layout
  50603. forceInstance.step();
  50604. }
  50605. else {
  50606. // Remove prev injected forceLayout instance
  50607. graphSeries.forceLayout = null;
  50608. }
  50609. });
  50610. };
  50611. /*
  50612. * Licensed to the Apache Software Foundation (ASF) under one
  50613. * or more contributor license agreements. See the NOTICE file
  50614. * distributed with this work for additional information
  50615. * regarding copyright ownership. The ASF licenses this file
  50616. * to you under the Apache License, Version 2.0 (the
  50617. * "License"); you may not use this file except in compliance
  50618. * with the License. You may obtain a copy of the License at
  50619. *
  50620. * http://www.apache.org/licenses/LICENSE-2.0
  50621. *
  50622. * Unless required by applicable law or agreed to in writing,
  50623. * software distributed under the License is distributed on an
  50624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50625. * KIND, either express or implied. See the License for the
  50626. * specific language governing permissions and limitations
  50627. * under the License.
  50628. */
  50629. // FIXME Where to create the simple view coordinate system
  50630. function getViewRect$2(seriesModel, api, aspect) {
  50631. var option = seriesModel.getBoxLayoutParams();
  50632. option.aspect = aspect;
  50633. return getLayoutRect(option, {
  50634. width: api.getWidth(),
  50635. height: api.getHeight()
  50636. });
  50637. }
  50638. var createView = function (ecModel, api) {
  50639. var viewList = [];
  50640. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50641. var coordSysType = seriesModel.get('coordinateSystem');
  50642. if (!coordSysType || coordSysType === 'view') {
  50643. var data = seriesModel.getData();
  50644. var positions = data.mapArray(function (idx) {
  50645. var itemModel = data.getItemModel(idx);
  50646. return [+itemModel.get('x'), +itemModel.get('y')];
  50647. });
  50648. var min = [];
  50649. var max = [];
  50650. fromPoints(positions, min, max);
  50651. // If width or height is 0
  50652. if (max[0] - min[0] === 0) {
  50653. max[0] += 1;
  50654. min[0] -= 1;
  50655. }
  50656. if (max[1] - min[1] === 0) {
  50657. max[1] += 1;
  50658. min[1] -= 1;
  50659. }
  50660. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  50661. // FIXME If get view rect after data processed?
  50662. var viewRect = getViewRect$2(seriesModel, api, aspect);
  50663. // Position may be NaN, use view rect instead
  50664. if (isNaN(aspect)) {
  50665. min = [viewRect.x, viewRect.y];
  50666. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  50667. }
  50668. var bbWidth = max[0] - min[0];
  50669. var bbHeight = max[1] - min[1];
  50670. var viewWidth = viewRect.width;
  50671. var viewHeight = viewRect.height;
  50672. var viewCoordSys = seriesModel.coordinateSystem = new View();
  50673. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  50674. viewCoordSys.setBoundingRect(
  50675. min[0], min[1], bbWidth, bbHeight
  50676. );
  50677. viewCoordSys.setViewRect(
  50678. viewRect.x, viewRect.y, viewWidth, viewHeight
  50679. );
  50680. // Update roam info
  50681. viewCoordSys.setCenter(seriesModel.get('center'));
  50682. viewCoordSys.setZoom(seriesModel.get('zoom'));
  50683. viewList.push(viewCoordSys);
  50684. }
  50685. });
  50686. return viewList;
  50687. };
  50688. /*
  50689. * Licensed to the Apache Software Foundation (ASF) under one
  50690. * or more contributor license agreements. See the NOTICE file
  50691. * distributed with this work for additional information
  50692. * regarding copyright ownership. The ASF licenses this file
  50693. * to you under the Apache License, Version 2.0 (the
  50694. * "License"); you may not use this file except in compliance
  50695. * with the License. You may obtain a copy of the License at
  50696. *
  50697. * http://www.apache.org/licenses/LICENSE-2.0
  50698. *
  50699. * Unless required by applicable law or agreed to in writing,
  50700. * software distributed under the License is distributed on an
  50701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50702. * KIND, either express or implied. See the License for the
  50703. * specific language governing permissions and limitations
  50704. * under the License.
  50705. */
  50706. registerProcessor(categoryFilter);
  50707. registerVisual(visualSymbol('graph', 'circle', null));
  50708. registerVisual(categoryVisual);
  50709. registerVisual(edgeVisual);
  50710. registerLayout(simpleLayout);
  50711. registerLayout(PRIORITY.VISUAL.POST_CHART_LAYOUT, circularLayout);
  50712. registerLayout(forceLayout);
  50713. // Graph view coordinate system
  50714. registerCoordinateSystem('graphView', {
  50715. create: createView
  50716. });
  50717. /*
  50718. * Licensed to the Apache Software Foundation (ASF) under one
  50719. * or more contributor license agreements. See the NOTICE file
  50720. * distributed with this work for additional information
  50721. * regarding copyright ownership. The ASF licenses this file
  50722. * to you under the Apache License, Version 2.0 (the
  50723. * "License"); you may not use this file except in compliance
  50724. * with the License. You may obtain a copy of the License at
  50725. *
  50726. * http://www.apache.org/licenses/LICENSE-2.0
  50727. *
  50728. * Unless required by applicable law or agreed to in writing,
  50729. * software distributed under the License is distributed on an
  50730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50731. * KIND, either express or implied. See the License for the
  50732. * specific language governing permissions and limitations
  50733. * under the License.
  50734. */
  50735. var GaugeSeries = SeriesModel.extend({
  50736. type: 'series.gauge',
  50737. getInitialData: function (option, ecModel) {
  50738. return createListSimply(this, ['value']);
  50739. },
  50740. defaultOption: {
  50741. zlevel: 0,
  50742. z: 2,
  50743. // 默认全局居中
  50744. center: ['50%', '50%'],
  50745. legendHoverLink: true,
  50746. radius: '75%',
  50747. startAngle: 225,
  50748. endAngle: -45,
  50749. clockwise: true,
  50750. // 最小值
  50751. min: 0,
  50752. // 最大值
  50753. max: 100,
  50754. // 分割段数,默认为10
  50755. splitNumber: 10,
  50756. // 坐标轴线
  50757. axisLine: {
  50758. // 默认显示,属性show控制显示与否
  50759. show: true,
  50760. lineStyle: { // 属性lineStyle控制线条样式
  50761. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  50762. width: 30
  50763. }
  50764. },
  50765. // 分隔线
  50766. splitLine: {
  50767. // 默认显示,属性show控制显示与否
  50768. show: true,
  50769. // 属性length控制线长
  50770. length: 30,
  50771. // 属性lineStyle(详见lineStyle)控制线条样式
  50772. lineStyle: {
  50773. color: '#eee',
  50774. width: 2,
  50775. type: 'solid'
  50776. }
  50777. },
  50778. // 坐标轴小标记
  50779. axisTick: {
  50780. // 属性show控制显示与否,默认不显示
  50781. show: true,
  50782. // 每份split细分多少段
  50783. splitNumber: 5,
  50784. // 属性length控制线长
  50785. length: 8,
  50786. // 属性lineStyle控制线条样式
  50787. lineStyle: {
  50788. color: '#eee',
  50789. width: 1,
  50790. type: 'solid'
  50791. }
  50792. },
  50793. axisLabel: {
  50794. show: true,
  50795. distance: 5,
  50796. // formatter: null,
  50797. color: 'auto'
  50798. },
  50799. pointer: {
  50800. show: true,
  50801. length: '80%',
  50802. width: 8
  50803. },
  50804. itemStyle: {
  50805. color: 'auto'
  50806. },
  50807. title: {
  50808. show: true,
  50809. // x, y,单位px
  50810. offsetCenter: [0, '-40%'],
  50811. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  50812. color: '#333',
  50813. fontSize: 15
  50814. },
  50815. detail: {
  50816. show: true,
  50817. backgroundColor: 'rgba(0,0,0,0)',
  50818. borderWidth: 0,
  50819. borderColor: '#ccc',
  50820. width: 100,
  50821. height: null, // self-adaption
  50822. padding: [5, 10],
  50823. // x, y,单位px
  50824. offsetCenter: [0, '40%'],
  50825. // formatter: null,
  50826. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  50827. color: 'auto',
  50828. fontSize: 30
  50829. }
  50830. }
  50831. });
  50832. /*
  50833. * Licensed to the Apache Software Foundation (ASF) under one
  50834. * or more contributor license agreements. See the NOTICE file
  50835. * distributed with this work for additional information
  50836. * regarding copyright ownership. The ASF licenses this file
  50837. * to you under the Apache License, Version 2.0 (the
  50838. * "License"); you may not use this file except in compliance
  50839. * with the License. You may obtain a copy of the License at
  50840. *
  50841. * http://www.apache.org/licenses/LICENSE-2.0
  50842. *
  50843. * Unless required by applicable law or agreed to in writing,
  50844. * software distributed under the License is distributed on an
  50845. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50846. * KIND, either express or implied. See the License for the
  50847. * specific language governing permissions and limitations
  50848. * under the License.
  50849. */
  50850. var PointerPath = Path.extend({
  50851. type: 'echartsGaugePointer',
  50852. shape: {
  50853. angle: 0,
  50854. width: 10,
  50855. r: 10,
  50856. x: 0,
  50857. y: 0
  50858. },
  50859. buildPath: function (ctx, shape) {
  50860. var mathCos = Math.cos;
  50861. var mathSin = Math.sin;
  50862. var r = shape.r;
  50863. var width = shape.width;
  50864. var angle = shape.angle;
  50865. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  50866. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  50867. angle = shape.angle - Math.PI / 2;
  50868. ctx.moveTo(x, y);
  50869. ctx.lineTo(
  50870. shape.x + mathCos(angle) * width,
  50871. shape.y + mathSin(angle) * width
  50872. );
  50873. ctx.lineTo(
  50874. shape.x + mathCos(shape.angle) * r,
  50875. shape.y + mathSin(shape.angle) * r
  50876. );
  50877. ctx.lineTo(
  50878. shape.x - mathCos(angle) * width,
  50879. shape.y - mathSin(angle) * width
  50880. );
  50881. ctx.lineTo(x, y);
  50882. return;
  50883. }
  50884. });
  50885. /*
  50886. * Licensed to the Apache Software Foundation (ASF) under one
  50887. * or more contributor license agreements. See the NOTICE file
  50888. * distributed with this work for additional information
  50889. * regarding copyright ownership. The ASF licenses this file
  50890. * to you under the Apache License, Version 2.0 (the
  50891. * "License"); you may not use this file except in compliance
  50892. * with the License. You may obtain a copy of the License at
  50893. *
  50894. * http://www.apache.org/licenses/LICENSE-2.0
  50895. *
  50896. * Unless required by applicable law or agreed to in writing,
  50897. * software distributed under the License is distributed on an
  50898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50899. * KIND, either express or implied. See the License for the
  50900. * specific language governing permissions and limitations
  50901. * under the License.
  50902. */
  50903. function parsePosition(seriesModel, api) {
  50904. var center = seriesModel.get('center');
  50905. var width = api.getWidth();
  50906. var height = api.getHeight();
  50907. var size = Math.min(width, height);
  50908. var cx = parsePercent$1(center[0], api.getWidth());
  50909. var cy = parsePercent$1(center[1], api.getHeight());
  50910. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  50911. return {
  50912. cx: cx,
  50913. cy: cy,
  50914. r: r
  50915. };
  50916. }
  50917. function formatLabel(label, labelFormatter) {
  50918. if (labelFormatter) {
  50919. if (typeof labelFormatter === 'string') {
  50920. label = labelFormatter.replace('{value}', label != null ? label : '');
  50921. }
  50922. else if (typeof labelFormatter === 'function') {
  50923. label = labelFormatter(label);
  50924. }
  50925. }
  50926. return label;
  50927. }
  50928. var PI2$5 = Math.PI * 2;
  50929. var GaugeView = Chart.extend({
  50930. type: 'gauge',
  50931. render: function (seriesModel, ecModel, api) {
  50932. this.group.removeAll();
  50933. var colorList = seriesModel.get('axisLine.lineStyle.color');
  50934. var posInfo = parsePosition(seriesModel, api);
  50935. this._renderMain(
  50936. seriesModel, ecModel, api, colorList, posInfo
  50937. );
  50938. },
  50939. dispose: function () {},
  50940. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  50941. var group = this.group;
  50942. var axisLineModel = seriesModel.getModel('axisLine');
  50943. var lineStyleModel = axisLineModel.getModel('lineStyle');
  50944. var clockwise = seriesModel.get('clockwise');
  50945. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  50946. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  50947. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  50948. var prevEndAngle = startAngle;
  50949. var axisLineWidth = lineStyleModel.get('width');
  50950. var showAxis = axisLineModel.get('show');
  50951. for (var i = 0; showAxis && i < colorList.length; i++) {
  50952. // Clamp
  50953. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  50954. var endAngle = startAngle + angleRangeSpan * percent;
  50955. var sector = new Sector({
  50956. shape: {
  50957. startAngle: prevEndAngle,
  50958. endAngle: endAngle,
  50959. cx: posInfo.cx,
  50960. cy: posInfo.cy,
  50961. clockwise: clockwise,
  50962. r0: posInfo.r - axisLineWidth,
  50963. r: posInfo.r
  50964. },
  50965. silent: true
  50966. });
  50967. sector.setStyle({
  50968. fill: colorList[i][1]
  50969. });
  50970. sector.setStyle(lineStyleModel.getLineStyle(
  50971. // Because we use sector to simulate arc
  50972. // so the properties for stroking are useless
  50973. ['color', 'borderWidth', 'borderColor']
  50974. ));
  50975. group.add(sector);
  50976. prevEndAngle = endAngle;
  50977. }
  50978. var getColor = function (percent) {
  50979. // Less than 0
  50980. if (percent <= 0) {
  50981. return colorList[0][1];
  50982. }
  50983. for (var i = 0; i < colorList.length; i++) {
  50984. if (colorList[i][0] >= percent
  50985. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  50986. ) {
  50987. return colorList[i][1];
  50988. }
  50989. }
  50990. // More than 1
  50991. return colorList[i - 1][1];
  50992. };
  50993. if (!clockwise) {
  50994. var tmp = startAngle;
  50995. startAngle = endAngle;
  50996. endAngle = tmp;
  50997. }
  50998. this._renderTicks(
  50999. seriesModel, ecModel, api, getColor, posInfo,
  51000. startAngle, endAngle, clockwise
  51001. );
  51002. this._renderPointer(
  51003. seriesModel, ecModel, api, getColor, posInfo,
  51004. startAngle, endAngle, clockwise
  51005. );
  51006. this._renderTitle(
  51007. seriesModel, ecModel, api, getColor, posInfo
  51008. );
  51009. this._renderDetail(
  51010. seriesModel, ecModel, api, getColor, posInfo
  51011. );
  51012. },
  51013. _renderTicks: function (
  51014. seriesModel, ecModel, api, getColor, posInfo,
  51015. startAngle, endAngle, clockwise
  51016. ) {
  51017. var group = this.group;
  51018. var cx = posInfo.cx;
  51019. var cy = posInfo.cy;
  51020. var r = posInfo.r;
  51021. var minVal = +seriesModel.get('min');
  51022. var maxVal = +seriesModel.get('max');
  51023. var splitLineModel = seriesModel.getModel('splitLine');
  51024. var tickModel = seriesModel.getModel('axisTick');
  51025. var labelModel = seriesModel.getModel('axisLabel');
  51026. var splitNumber = seriesModel.get('splitNumber');
  51027. var subSplitNumber = tickModel.get('splitNumber');
  51028. var splitLineLen = parsePercent$1(
  51029. splitLineModel.get('length'), r
  51030. );
  51031. var tickLen = parsePercent$1(
  51032. tickModel.get('length'), r
  51033. );
  51034. var angle = startAngle;
  51035. var step = (endAngle - startAngle) / splitNumber;
  51036. var subStep = step / subSplitNumber;
  51037. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  51038. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  51039. for (var i = 0; i <= splitNumber; i++) {
  51040. var unitX = Math.cos(angle);
  51041. var unitY = Math.sin(angle);
  51042. // Split line
  51043. if (splitLineModel.get('show')) {
  51044. var splitLine = new Line({
  51045. shape: {
  51046. x1: unitX * r + cx,
  51047. y1: unitY * r + cy,
  51048. x2: unitX * (r - splitLineLen) + cx,
  51049. y2: unitY * (r - splitLineLen) + cy
  51050. },
  51051. style: splitLineStyle,
  51052. silent: true
  51053. });
  51054. if (splitLineStyle.stroke === 'auto') {
  51055. splitLine.setStyle({
  51056. stroke: getColor(i / splitNumber)
  51057. });
  51058. }
  51059. group.add(splitLine);
  51060. }
  51061. // Label
  51062. if (labelModel.get('show')) {
  51063. var label = formatLabel(
  51064. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  51065. labelModel.get('formatter')
  51066. );
  51067. var distance = labelModel.get('distance');
  51068. var autoColor = getColor(i / splitNumber);
  51069. group.add(new Text({
  51070. style: setTextStyle({}, labelModel, {
  51071. text: label,
  51072. x: unitX * (r - splitLineLen - distance) + cx,
  51073. y: unitY * (r - splitLineLen - distance) + cy,
  51074. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  51075. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  51076. }, {autoColor: autoColor}),
  51077. silent: true
  51078. }));
  51079. }
  51080. // Axis tick
  51081. if (tickModel.get('show') && i !== splitNumber) {
  51082. for (var j = 0; j <= subSplitNumber; j++) {
  51083. var unitX = Math.cos(angle);
  51084. var unitY = Math.sin(angle);
  51085. var tickLine = new Line({
  51086. shape: {
  51087. x1: unitX * r + cx,
  51088. y1: unitY * r + cy,
  51089. x2: unitX * (r - tickLen) + cx,
  51090. y2: unitY * (r - tickLen) + cy
  51091. },
  51092. silent: true,
  51093. style: tickLineStyle
  51094. });
  51095. if (tickLineStyle.stroke === 'auto') {
  51096. tickLine.setStyle({
  51097. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  51098. });
  51099. }
  51100. group.add(tickLine);
  51101. angle += subStep;
  51102. }
  51103. angle -= subStep;
  51104. }
  51105. else {
  51106. angle += step;
  51107. }
  51108. }
  51109. },
  51110. _renderPointer: function (
  51111. seriesModel, ecModel, api, getColor, posInfo,
  51112. startAngle, endAngle, clockwise
  51113. ) {
  51114. var group = this.group;
  51115. var oldData = this._data;
  51116. if (!seriesModel.get('pointer.show')) {
  51117. // Remove old element
  51118. oldData && oldData.eachItemGraphicEl(function (el) {
  51119. group.remove(el);
  51120. });
  51121. return;
  51122. }
  51123. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  51124. var angleExtent = [startAngle, endAngle];
  51125. var data = seriesModel.getData();
  51126. var valueDim = data.mapDimension('value');
  51127. data.diff(oldData)
  51128. .add(function (idx) {
  51129. var pointer = new PointerPath({
  51130. shape: {
  51131. angle: startAngle
  51132. }
  51133. });
  51134. initProps(pointer, {
  51135. shape: {
  51136. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  51137. }
  51138. }, seriesModel);
  51139. group.add(pointer);
  51140. data.setItemGraphicEl(idx, pointer);
  51141. })
  51142. .update(function (newIdx, oldIdx) {
  51143. var pointer = oldData.getItemGraphicEl(oldIdx);
  51144. updateProps(pointer, {
  51145. shape: {
  51146. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  51147. }
  51148. }, seriesModel);
  51149. group.add(pointer);
  51150. data.setItemGraphicEl(newIdx, pointer);
  51151. })
  51152. .remove(function (idx) {
  51153. var pointer = oldData.getItemGraphicEl(idx);
  51154. group.remove(pointer);
  51155. })
  51156. .execute();
  51157. data.eachItemGraphicEl(function (pointer, idx) {
  51158. var itemModel = data.getItemModel(idx);
  51159. var pointerModel = itemModel.getModel('pointer');
  51160. pointer.setShape({
  51161. x: posInfo.cx,
  51162. y: posInfo.cy,
  51163. width: parsePercent$1(
  51164. pointerModel.get('width'), posInfo.r
  51165. ),
  51166. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  51167. });
  51168. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  51169. if (pointer.style.fill === 'auto') {
  51170. pointer.setStyle('fill', getColor(
  51171. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  51172. ));
  51173. }
  51174. setHoverStyle(
  51175. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  51176. );
  51177. });
  51178. this._data = data;
  51179. },
  51180. _renderTitle: function (
  51181. seriesModel, ecModel, api, getColor, posInfo
  51182. ) {
  51183. var data = seriesModel.getData();
  51184. var valueDim = data.mapDimension('value');
  51185. var titleModel = seriesModel.getModel('title');
  51186. if (titleModel.get('show')) {
  51187. var offsetCenter = titleModel.get('offsetCenter');
  51188. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51189. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51190. var minVal = +seriesModel.get('min');
  51191. var maxVal = +seriesModel.get('max');
  51192. var value = seriesModel.getData().get(valueDim, 0);
  51193. var autoColor = getColor(
  51194. linearMap(value, [minVal, maxVal], [0, 1], true)
  51195. );
  51196. this.group.add(new Text({
  51197. silent: true,
  51198. style: setTextStyle({}, titleModel, {
  51199. x: x,
  51200. y: y,
  51201. // FIXME First data name ?
  51202. text: data.getName(0),
  51203. textAlign: 'center',
  51204. textVerticalAlign: 'middle'
  51205. }, {autoColor: autoColor, forceRich: true})
  51206. }));
  51207. }
  51208. },
  51209. _renderDetail: function (
  51210. seriesModel, ecModel, api, getColor, posInfo
  51211. ) {
  51212. var detailModel = seriesModel.getModel('detail');
  51213. var minVal = +seriesModel.get('min');
  51214. var maxVal = +seriesModel.get('max');
  51215. if (detailModel.get('show')) {
  51216. var offsetCenter = detailModel.get('offsetCenter');
  51217. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  51218. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  51219. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  51220. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  51221. var data = seriesModel.getData();
  51222. var value = data.get(data.mapDimension('value'), 0);
  51223. var autoColor = getColor(
  51224. linearMap(value, [minVal, maxVal], [0, 1], true)
  51225. );
  51226. this.group.add(new Text({
  51227. silent: true,
  51228. style: setTextStyle({}, detailModel, {
  51229. x: x,
  51230. y: y,
  51231. text: formatLabel(
  51232. // FIXME First data name ?
  51233. value, detailModel.get('formatter')
  51234. ),
  51235. textWidth: isNaN(width) ? null : width,
  51236. textHeight: isNaN(height) ? null : height,
  51237. textAlign: 'center',
  51238. textVerticalAlign: 'middle'
  51239. }, {autoColor: autoColor, forceRich: true})
  51240. }));
  51241. }
  51242. }
  51243. });
  51244. /*
  51245. * Licensed to the Apache Software Foundation (ASF) under one
  51246. * or more contributor license agreements. See the NOTICE file
  51247. * distributed with this work for additional information
  51248. * regarding copyright ownership. The ASF licenses this file
  51249. * to you under the Apache License, Version 2.0 (the
  51250. * "License"); you may not use this file except in compliance
  51251. * with the License. You may obtain a copy of the License at
  51252. *
  51253. * http://www.apache.org/licenses/LICENSE-2.0
  51254. *
  51255. * Unless required by applicable law or agreed to in writing,
  51256. * software distributed under the License is distributed on an
  51257. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51258. * KIND, either express or implied. See the License for the
  51259. * specific language governing permissions and limitations
  51260. * under the License.
  51261. */
  51262. /*
  51263. * Licensed to the Apache Software Foundation (ASF) under one
  51264. * or more contributor license agreements. See the NOTICE file
  51265. * distributed with this work for additional information
  51266. * regarding copyright ownership. The ASF licenses this file
  51267. * to you under the Apache License, Version 2.0 (the
  51268. * "License"); you may not use this file except in compliance
  51269. * with the License. You may obtain a copy of the License at
  51270. *
  51271. * http://www.apache.org/licenses/LICENSE-2.0
  51272. *
  51273. * Unless required by applicable law or agreed to in writing,
  51274. * software distributed under the License is distributed on an
  51275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51276. * KIND, either express or implied. See the License for the
  51277. * specific language governing permissions and limitations
  51278. * under the License.
  51279. */
  51280. var FunnelSeries = extendSeriesModel({
  51281. type: 'series.funnel',
  51282. init: function (option) {
  51283. FunnelSeries.superApply(this, 'init', arguments);
  51284. // Enable legend selection for each data item
  51285. // Use a function instead of direct access because data reference may changed
  51286. this.legendVisualProvider = new LegendVisualProvider(
  51287. bind(this.getData, this), bind(this.getRawData, this)
  51288. );
  51289. // Extend labelLine emphasis
  51290. this._defaultLabelLine(option);
  51291. },
  51292. getInitialData: function (option, ecModel) {
  51293. return createListSimply(this, {
  51294. coordDimensions: ['value'],
  51295. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  51296. });
  51297. },
  51298. _defaultLabelLine: function (option) {
  51299. // Extend labelLine emphasis
  51300. defaultEmphasis(option, 'labelLine', ['show']);
  51301. var labelLineNormalOpt = option.labelLine;
  51302. var labelLineEmphasisOpt = option.emphasis.labelLine;
  51303. // Not show label line if `label.normal.show = false`
  51304. labelLineNormalOpt.show = labelLineNormalOpt.show
  51305. && option.label.show;
  51306. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  51307. && option.emphasis.label.show;
  51308. },
  51309. // Overwrite
  51310. getDataParams: function (dataIndex) {
  51311. var data = this.getData();
  51312. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  51313. var valueDim = data.mapDimension('value');
  51314. var sum = data.getSum(valueDim);
  51315. // Percent is 0 if sum is 0
  51316. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  51317. params.$vars.push('percent');
  51318. return params;
  51319. },
  51320. defaultOption: {
  51321. zlevel: 0, // 一级层叠
  51322. z: 2, // 二级层叠
  51323. legendHoverLink: true,
  51324. left: 80,
  51325. top: 60,
  51326. right: 80,
  51327. bottom: 60,
  51328. // width: {totalWidth} - left - right,
  51329. // height: {totalHeight} - top - bottom,
  51330. // 默认取数据最小最大值
  51331. // min: 0,
  51332. // max: 100,
  51333. minSize: '0%',
  51334. maxSize: '100%',
  51335. sort: 'descending', // 'ascending', 'descending'
  51336. gap: 0,
  51337. funnelAlign: 'center',
  51338. label: {
  51339. show: true,
  51340. position: 'outer'
  51341. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  51342. },
  51343. labelLine: {
  51344. show: true,
  51345. length: 20,
  51346. lineStyle: {
  51347. // color: 各异,
  51348. width: 1,
  51349. type: 'solid'
  51350. }
  51351. },
  51352. itemStyle: {
  51353. // color: 各异,
  51354. borderColor: '#fff',
  51355. borderWidth: 1
  51356. },
  51357. emphasis: {
  51358. label: {
  51359. show: true
  51360. }
  51361. }
  51362. }
  51363. });
  51364. /*
  51365. * Licensed to the Apache Software Foundation (ASF) under one
  51366. * or more contributor license agreements. See the NOTICE file
  51367. * distributed with this work for additional information
  51368. * regarding copyright ownership. The ASF licenses this file
  51369. * to you under the Apache License, Version 2.0 (the
  51370. * "License"); you may not use this file except in compliance
  51371. * with the License. You may obtain a copy of the License at
  51372. *
  51373. * http://www.apache.org/licenses/LICENSE-2.0
  51374. *
  51375. * Unless required by applicable law or agreed to in writing,
  51376. * software distributed under the License is distributed on an
  51377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51378. * KIND, either express or implied. See the License for the
  51379. * specific language governing permissions and limitations
  51380. * under the License.
  51381. */
  51382. /**
  51383. * Piece of pie including Sector, Label, LabelLine
  51384. * @constructor
  51385. * @extends {module:zrender/graphic/Group}
  51386. */
  51387. function FunnelPiece(data, idx) {
  51388. Group.call(this);
  51389. var polygon = new Polygon();
  51390. var labelLine = new Polyline();
  51391. var text = new Text();
  51392. this.add(polygon);
  51393. this.add(labelLine);
  51394. this.add(text);
  51395. this.highDownOnUpdate = function (fromState, toState) {
  51396. if (toState === 'emphasis') {
  51397. labelLine.ignore = labelLine.hoverIgnore;
  51398. text.ignore = text.hoverIgnore;
  51399. }
  51400. else {
  51401. labelLine.ignore = labelLine.normalIgnore;
  51402. text.ignore = text.normalIgnore;
  51403. }
  51404. };
  51405. this.updateData(data, idx, true);
  51406. }
  51407. var funnelPieceProto = FunnelPiece.prototype;
  51408. var opacityAccessPath = ['itemStyle', 'opacity'];
  51409. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  51410. var polygon = this.childAt(0);
  51411. var seriesModel = data.hostModel;
  51412. var itemModel = data.getItemModel(idx);
  51413. var layout = data.getItemLayout(idx);
  51414. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  51415. opacity = opacity == null ? 1 : opacity;
  51416. // Reset style
  51417. polygon.useStyle({});
  51418. if (firstCreate) {
  51419. polygon.setShape({
  51420. points: layout.points
  51421. });
  51422. polygon.setStyle({opacity: 0});
  51423. initProps(polygon, {
  51424. style: {
  51425. opacity: opacity
  51426. }
  51427. }, seriesModel, idx);
  51428. }
  51429. else {
  51430. updateProps(polygon, {
  51431. style: {
  51432. opacity: opacity
  51433. },
  51434. shape: {
  51435. points: layout.points
  51436. }
  51437. }, seriesModel, idx);
  51438. }
  51439. // Update common style
  51440. var itemStyleModel = itemModel.getModel('itemStyle');
  51441. var visualColor = data.getItemVisual(idx, 'color');
  51442. polygon.setStyle(
  51443. defaults(
  51444. {
  51445. lineJoin: 'round',
  51446. fill: visualColor
  51447. },
  51448. itemStyleModel.getItemStyle(['opacity'])
  51449. )
  51450. );
  51451. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  51452. this._updateLabel(data, idx);
  51453. setHoverStyle(this);
  51454. };
  51455. funnelPieceProto._updateLabel = function (data, idx) {
  51456. var labelLine = this.childAt(1);
  51457. var labelText = this.childAt(2);
  51458. var seriesModel = data.hostModel;
  51459. var itemModel = data.getItemModel(idx);
  51460. var layout = data.getItemLayout(idx);
  51461. var labelLayout = layout.label;
  51462. var visualColor = data.getItemVisual(idx, 'color');
  51463. updateProps(labelLine, {
  51464. shape: {
  51465. points: labelLayout.linePoints || labelLayout.linePoints
  51466. }
  51467. }, seriesModel, idx);
  51468. updateProps(labelText, {
  51469. style: {
  51470. x: labelLayout.x,
  51471. y: labelLayout.y
  51472. }
  51473. }, seriesModel, idx);
  51474. labelText.attr({
  51475. rotation: labelLayout.rotation,
  51476. origin: [labelLayout.x, labelLayout.y],
  51477. z2: 10
  51478. });
  51479. var labelModel = itemModel.getModel('label');
  51480. var labelHoverModel = itemModel.getModel('emphasis.label');
  51481. var labelLineModel = itemModel.getModel('labelLine');
  51482. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  51483. var visualColor = data.getItemVisual(idx, 'color');
  51484. setLabelStyle(
  51485. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  51486. {
  51487. labelFetcher: data.hostModel,
  51488. labelDataIndex: idx,
  51489. defaultText: data.getName(idx),
  51490. autoColor: visualColor,
  51491. useInsideStyle: !!labelLayout.inside
  51492. },
  51493. {
  51494. textAlign: labelLayout.textAlign,
  51495. textVerticalAlign: labelLayout.verticalAlign
  51496. }
  51497. );
  51498. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  51499. labelText.hoverIgnore = !labelHoverModel.get('show');
  51500. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  51501. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  51502. // Default use item visual color
  51503. labelLine.setStyle({
  51504. stroke: visualColor
  51505. });
  51506. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  51507. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  51508. };
  51509. inherits(FunnelPiece, Group);
  51510. var FunnelView = Chart.extend({
  51511. type: 'funnel',
  51512. render: function (seriesModel, ecModel, api) {
  51513. var data = seriesModel.getData();
  51514. var oldData = this._data;
  51515. var group = this.group;
  51516. data.diff(oldData)
  51517. .add(function (idx) {
  51518. var funnelPiece = new FunnelPiece(data, idx);
  51519. data.setItemGraphicEl(idx, funnelPiece);
  51520. group.add(funnelPiece);
  51521. })
  51522. .update(function (newIdx, oldIdx) {
  51523. var piePiece = oldData.getItemGraphicEl(oldIdx);
  51524. piePiece.updateData(data, newIdx);
  51525. group.add(piePiece);
  51526. data.setItemGraphicEl(newIdx, piePiece);
  51527. })
  51528. .remove(function (idx) {
  51529. var piePiece = oldData.getItemGraphicEl(idx);
  51530. group.remove(piePiece);
  51531. })
  51532. .execute();
  51533. this._data = data;
  51534. },
  51535. remove: function () {
  51536. this.group.removeAll();
  51537. this._data = null;
  51538. },
  51539. dispose: function () {}
  51540. });
  51541. /*
  51542. * Licensed to the Apache Software Foundation (ASF) under one
  51543. * or more contributor license agreements. See the NOTICE file
  51544. * distributed with this work for additional information
  51545. * regarding copyright ownership. The ASF licenses this file
  51546. * to you under the Apache License, Version 2.0 (the
  51547. * "License"); you may not use this file except in compliance
  51548. * with the License. You may obtain a copy of the License at
  51549. *
  51550. * http://www.apache.org/licenses/LICENSE-2.0
  51551. *
  51552. * Unless required by applicable law or agreed to in writing,
  51553. * software distributed under the License is distributed on an
  51554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51555. * KIND, either express or implied. See the License for the
  51556. * specific language governing permissions and limitations
  51557. * under the License.
  51558. */
  51559. function getViewRect$3(seriesModel, api) {
  51560. return getLayoutRect(
  51561. seriesModel.getBoxLayoutParams(), {
  51562. width: api.getWidth(),
  51563. height: api.getHeight()
  51564. }
  51565. );
  51566. }
  51567. function getSortedIndices(data, sort) {
  51568. var valueDim = data.mapDimension('value');
  51569. var valueArr = data.mapArray(valueDim, function (val) {
  51570. return val;
  51571. });
  51572. var indices = [];
  51573. var isAscending = sort === 'ascending';
  51574. for (var i = 0, len = data.count(); i < len; i++) {
  51575. indices[i] = i;
  51576. }
  51577. // Add custom sortable function & none sortable opetion by "options.sort"
  51578. if (typeof sort === 'function') {
  51579. indices.sort(sort);
  51580. }
  51581. else if (sort !== 'none') {
  51582. indices.sort(function (a, b) {
  51583. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  51584. });
  51585. }
  51586. return indices;
  51587. }
  51588. function labelLayout$1(data) {
  51589. data.each(function (idx) {
  51590. var itemModel = data.getItemModel(idx);
  51591. var labelModel = itemModel.getModel('label');
  51592. var labelPosition = labelModel.get('position');
  51593. var labelLineModel = itemModel.getModel('labelLine');
  51594. var layout = data.getItemLayout(idx);
  51595. var points = layout.points;
  51596. var isLabelInside = labelPosition === 'inner'
  51597. || labelPosition === 'inside' || labelPosition === 'center'
  51598. || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  51599. var textAlign;
  51600. var textX;
  51601. var textY;
  51602. var linePoints;
  51603. if (isLabelInside) {
  51604. if (labelPosition === 'insideLeft') {
  51605. textX = (points[0][0] + points[3][0]) / 2 + 5;
  51606. textY = (points[0][1] + points[3][1]) / 2;
  51607. textAlign = 'left';
  51608. }
  51609. else if (labelPosition === 'insideRight') {
  51610. textX = (points[1][0] + points[2][0]) / 2 - 5;
  51611. textY = (points[1][1] + points[2][1]) / 2;
  51612. textAlign = 'right';
  51613. }
  51614. else {
  51615. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  51616. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  51617. textAlign = 'center';
  51618. }
  51619. linePoints = [
  51620. [textX, textY], [textX, textY]
  51621. ];
  51622. }
  51623. else {
  51624. var x1;
  51625. var y1;
  51626. var x2;
  51627. var labelLineLen = labelLineModel.get('length');
  51628. if (labelPosition === 'left') {
  51629. // Left side
  51630. x1 = (points[3][0] + points[0][0]) / 2;
  51631. y1 = (points[3][1] + points[0][1]) / 2;
  51632. x2 = x1 - labelLineLen;
  51633. textX = x2 - 5;
  51634. textAlign = 'right';
  51635. }
  51636. else if (labelPosition === 'right') {
  51637. // Right side
  51638. x1 = (points[1][0] + points[2][0]) / 2;
  51639. y1 = (points[1][1] + points[2][1]) / 2;
  51640. x2 = x1 + labelLineLen;
  51641. textX = x2 + 5;
  51642. textAlign = 'left';
  51643. }
  51644. else if (labelPosition === 'rightTop') {
  51645. // RightTop side
  51646. x1 = points[1][0];
  51647. y1 = points[1][1];
  51648. x2 = x1 + labelLineLen;
  51649. textX = x2 + 5;
  51650. textAlign = 'top';
  51651. }
  51652. else if (labelPosition === 'rightBottom') {
  51653. // RightBottom side
  51654. x1 = points[2][0];
  51655. y1 = points[2][1];
  51656. x2 = x1 + labelLineLen;
  51657. textX = x2 + 5;
  51658. textAlign = 'bottom';
  51659. }
  51660. else if (labelPosition === 'leftTop') {
  51661. // LeftTop side
  51662. x1 = points[0][0];
  51663. y1 = points[1][1];
  51664. x2 = x1 - labelLineLen;
  51665. textX = x2 - 5;
  51666. textAlign = 'right';
  51667. }
  51668. else if (labelPosition === 'leftBottom') {
  51669. // LeftBottom side
  51670. x1 = points[3][0];
  51671. y1 = points[2][1];
  51672. x2 = x1 - labelLineLen;
  51673. textX = x2 - 5;
  51674. textAlign = 'right';
  51675. }
  51676. else {
  51677. // Right side
  51678. x1 = (points[1][0] + points[2][0]) / 2;
  51679. y1 = (points[1][1] + points[2][1]) / 2;
  51680. x2 = x1 + labelLineLen;
  51681. textX = x2 + 5;
  51682. textAlign = 'left';
  51683. }
  51684. var y2 = y1;
  51685. linePoints = [[x1, y1], [x2, y2]];
  51686. textY = y2;
  51687. }
  51688. layout.label = {
  51689. linePoints: linePoints,
  51690. x: textX,
  51691. y: textY,
  51692. verticalAlign: 'middle',
  51693. textAlign: textAlign,
  51694. inside: isLabelInside
  51695. };
  51696. });
  51697. }
  51698. var funnelLayout = function (ecModel, api, payload) {
  51699. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  51700. var data = seriesModel.getData();
  51701. var valueDim = data.mapDimension('value');
  51702. var sort = seriesModel.get('sort');
  51703. var viewRect = getViewRect$3(seriesModel, api);
  51704. var indices = getSortedIndices(data, sort);
  51705. var sizeExtent = [
  51706. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  51707. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  51708. ];
  51709. var dataExtent = data.getDataExtent(valueDim);
  51710. var min = seriesModel.get('min');
  51711. var max = seriesModel.get('max');
  51712. if (min == null) {
  51713. min = Math.min(dataExtent[0], 0);
  51714. }
  51715. if (max == null) {
  51716. max = dataExtent[1];
  51717. }
  51718. var funnelAlign = seriesModel.get('funnelAlign');
  51719. var gap = seriesModel.get('gap');
  51720. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  51721. var y = viewRect.y;
  51722. var getLinePoints = function (idx, offY) {
  51723. // End point index is data.count() and we assign it 0
  51724. var val = data.get(valueDim, idx) || 0;
  51725. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  51726. var x0;
  51727. switch (funnelAlign) {
  51728. case 'left':
  51729. x0 = viewRect.x;
  51730. break;
  51731. case 'center':
  51732. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  51733. break;
  51734. case 'right':
  51735. x0 = viewRect.x + viewRect.width - itemWidth;
  51736. break;
  51737. }
  51738. return [
  51739. [x0, offY],
  51740. [x0 + itemWidth, offY]
  51741. ];
  51742. };
  51743. if (sort === 'ascending') {
  51744. // From bottom to top
  51745. itemHeight = -itemHeight;
  51746. gap = -gap;
  51747. y += viewRect.height;
  51748. indices = indices.reverse();
  51749. }
  51750. for (var i = 0; i < indices.length; i++) {
  51751. var idx = indices[i];
  51752. var nextIdx = indices[i + 1];
  51753. var itemModel = data.getItemModel(idx);
  51754. var height = itemModel.get('itemStyle.height');
  51755. if (height == null) {
  51756. height = itemHeight;
  51757. }
  51758. else {
  51759. height = parsePercent$1(height, viewRect.height);
  51760. if (sort === 'ascending') {
  51761. height = -height;
  51762. }
  51763. }
  51764. var start = getLinePoints(idx, y);
  51765. var end = getLinePoints(nextIdx, y + height);
  51766. y += height + gap;
  51767. data.setItemLayout(idx, {
  51768. points: start.concat(end.slice().reverse())
  51769. });
  51770. }
  51771. labelLayout$1(data);
  51772. });
  51773. };
  51774. /*
  51775. * Licensed to the Apache Software Foundation (ASF) under one
  51776. * or more contributor license agreements. See the NOTICE file
  51777. * distributed with this work for additional information
  51778. * regarding copyright ownership. The ASF licenses this file
  51779. * to you under the Apache License, Version 2.0 (the
  51780. * "License"); you may not use this file except in compliance
  51781. * with the License. You may obtain a copy of the License at
  51782. *
  51783. * http://www.apache.org/licenses/LICENSE-2.0
  51784. *
  51785. * Unless required by applicable law or agreed to in writing,
  51786. * software distributed under the License is distributed on an
  51787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51788. * KIND, either express or implied. See the License for the
  51789. * specific language governing permissions and limitations
  51790. * under the License.
  51791. */
  51792. registerVisual(dataColor('funnel'));
  51793. registerLayout(funnelLayout);
  51794. registerProcessor(dataFilter('funnel'));
  51795. /*
  51796. * Licensed to the Apache Software Foundation (ASF) under one
  51797. * or more contributor license agreements. See the NOTICE file
  51798. * distributed with this work for additional information
  51799. * regarding copyright ownership. The ASF licenses this file
  51800. * to you under the Apache License, Version 2.0 (the
  51801. * "License"); you may not use this file except in compliance
  51802. * with the License. You may obtain a copy of the License at
  51803. *
  51804. * http://www.apache.org/licenses/LICENSE-2.0
  51805. *
  51806. * Unless required by applicable law or agreed to in writing,
  51807. * software distributed under the License is distributed on an
  51808. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51809. * KIND, either express or implied. See the License for the
  51810. * specific language governing permissions and limitations
  51811. * under the License.
  51812. */
  51813. var parallelPreprocessor = function (option) {
  51814. createParallelIfNeeded(option);
  51815. mergeAxisOptionFromParallel(option);
  51816. };
  51817. /**
  51818. * Create a parallel coordinate if not exists.
  51819. * @inner
  51820. */
  51821. function createParallelIfNeeded(option) {
  51822. if (option.parallel) {
  51823. return;
  51824. }
  51825. var hasParallelSeries = false;
  51826. each$1(option.series, function (seriesOpt) {
  51827. if (seriesOpt && seriesOpt.type === 'parallel') {
  51828. hasParallelSeries = true;
  51829. }
  51830. });
  51831. if (hasParallelSeries) {
  51832. option.parallel = [{}];
  51833. }
  51834. }
  51835. /**
  51836. * Merge aixs definition from parallel option (if exists) to axis option.
  51837. * @inner
  51838. */
  51839. function mergeAxisOptionFromParallel(option) {
  51840. var axes = normalizeToArray(option.parallelAxis);
  51841. each$1(axes, function (axisOption) {
  51842. if (!isObject$1(axisOption)) {
  51843. return;
  51844. }
  51845. var parallelIndex = axisOption.parallelIndex || 0;
  51846. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  51847. if (parallelOption && parallelOption.parallelAxisDefault) {
  51848. merge(axisOption, parallelOption.parallelAxisDefault, false);
  51849. }
  51850. });
  51851. }
  51852. /*
  51853. * Licensed to the Apache Software Foundation (ASF) under one
  51854. * or more contributor license agreements. See the NOTICE file
  51855. * distributed with this work for additional information
  51856. * regarding copyright ownership. The ASF licenses this file
  51857. * to you under the Apache License, Version 2.0 (the
  51858. * "License"); you may not use this file except in compliance
  51859. * with the License. You may obtain a copy of the License at
  51860. *
  51861. * http://www.apache.org/licenses/LICENSE-2.0
  51862. *
  51863. * Unless required by applicable law or agreed to in writing,
  51864. * software distributed under the License is distributed on an
  51865. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51866. * KIND, either express or implied. See the License for the
  51867. * specific language governing permissions and limitations
  51868. * under the License.
  51869. */
  51870. /**
  51871. * @constructor module:echarts/coord/parallel/ParallelAxis
  51872. * @extends {module:echarts/coord/Axis}
  51873. * @param {string} dim
  51874. * @param {*} scale
  51875. * @param {Array.<number>} coordExtent
  51876. * @param {string} axisType
  51877. */
  51878. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  51879. Axis.call(this, dim, scale, coordExtent);
  51880. /**
  51881. * Axis type
  51882. * - 'category'
  51883. * - 'value'
  51884. * - 'time'
  51885. * - 'log'
  51886. * @type {string}
  51887. */
  51888. this.type = axisType || 'value';
  51889. /**
  51890. * @type {number}
  51891. * @readOnly
  51892. */
  51893. this.axisIndex = axisIndex;
  51894. };
  51895. ParallelAxis.prototype = {
  51896. constructor: ParallelAxis,
  51897. /**
  51898. * Axis model
  51899. * @param {module:echarts/coord/parallel/AxisModel}
  51900. */
  51901. model: null,
  51902. /**
  51903. * @override
  51904. */
  51905. isHorizontal: function () {
  51906. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  51907. }
  51908. };
  51909. inherits(ParallelAxis, Axis);
  51910. /*
  51911. * Licensed to the Apache Software Foundation (ASF) under one
  51912. * or more contributor license agreements. See the NOTICE file
  51913. * distributed with this work for additional information
  51914. * regarding copyright ownership. The ASF licenses this file
  51915. * to you under the Apache License, Version 2.0 (the
  51916. * "License"); you may not use this file except in compliance
  51917. * with the License. You may obtain a copy of the License at
  51918. *
  51919. * http://www.apache.org/licenses/LICENSE-2.0
  51920. *
  51921. * Unless required by applicable law or agreed to in writing,
  51922. * software distributed under the License is distributed on an
  51923. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51924. * KIND, either express or implied. See the License for the
  51925. * specific language governing permissions and limitations
  51926. * under the License.
  51927. */
  51928. /**
  51929. * Calculate slider move result.
  51930. * Usage:
  51931. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  51932. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  51933. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  51934. *
  51935. * @param {number} delta Move length.
  51936. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  51937. * handleEnds will be modified in this method.
  51938. * @param {Array.<number>} extent handleEnds is restricted by extent.
  51939. * extent[0] should less or equals than extent[1].
  51940. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  51941. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  51942. * If not set, handle0 and cross handle1. If set as a non-negative
  51943. * number (including `0`), handles will push each other when reaching
  51944. * the minSpan.
  51945. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  51946. * @return {Array.<number>} The input handleEnds.
  51947. */
  51948. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  51949. delta = delta || 0;
  51950. var extentSpan = extent[1] - extent[0];
  51951. // Notice maxSpan and minSpan can be null/undefined.
  51952. if (minSpan != null) {
  51953. minSpan = restrict$1(minSpan, [0, extentSpan]);
  51954. }
  51955. if (maxSpan != null) {
  51956. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  51957. }
  51958. if (handleIndex === 'all') {
  51959. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  51960. handleSpan = restrict$1(handleSpan, [0, extentSpan]);
  51961. minSpan = maxSpan = restrict$1(handleSpan, [minSpan, maxSpan]);
  51962. handleIndex = 0;
  51963. }
  51964. handleEnds[0] = restrict$1(handleEnds[0], extent);
  51965. handleEnds[1] = restrict$1(handleEnds[1], extent);
  51966. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  51967. handleEnds[handleIndex] += delta;
  51968. // Restrict in extent.
  51969. var extentMinSpan = minSpan || 0;
  51970. var realExtent = extent.slice();
  51971. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  51972. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  51973. // Expand span.
  51974. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51975. if (minSpan != null && (
  51976. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  51977. )) {
  51978. // If minSpan exists, 'cross' is forbidden.
  51979. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  51980. }
  51981. // Shrink span.
  51982. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51983. if (maxSpan != null && currDistSign.span > maxSpan) {
  51984. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  51985. }
  51986. return handleEnds;
  51987. };
  51988. function getSpanSign(handleEnds, handleIndex) {
  51989. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  51990. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  51991. // is at left of handleEnds[1] for non-cross case.
  51992. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  51993. }
  51994. function restrict$1(value, extend) {
  51995. return Math.min(
  51996. extend[1] != null ? extend[1] : Infinity,
  51997. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  51998. );
  51999. }
  52000. /*
  52001. * Licensed to the Apache Software Foundation (ASF) under one
  52002. * or more contributor license agreements. See the NOTICE file
  52003. * distributed with this work for additional information
  52004. * regarding copyright ownership. The ASF licenses this file
  52005. * to you under the Apache License, Version 2.0 (the
  52006. * "License"); you may not use this file except in compliance
  52007. * with the License. You may obtain a copy of the License at
  52008. *
  52009. * http://www.apache.org/licenses/LICENSE-2.0
  52010. *
  52011. * Unless required by applicable law or agreed to in writing,
  52012. * software distributed under the License is distributed on an
  52013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52014. * KIND, either express or implied. See the License for the
  52015. * specific language governing permissions and limitations
  52016. * under the License.
  52017. */
  52018. /**
  52019. * Parallel Coordinates
  52020. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  52021. */
  52022. var each$11 = each$1;
  52023. var mathMin$6 = Math.min;
  52024. var mathMax$6 = Math.max;
  52025. var mathFloor$2 = Math.floor;
  52026. var mathCeil$2 = Math.ceil;
  52027. var round$2 = round$1;
  52028. var PI$4 = Math.PI;
  52029. function Parallel(parallelModel, ecModel, api) {
  52030. /**
  52031. * key: dimension
  52032. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  52033. * @private
  52034. */
  52035. this._axesMap = createHashMap();
  52036. /**
  52037. * key: dimension
  52038. * value: {position: [], rotation, }
  52039. * @type {Object.<string, Object>}
  52040. * @private
  52041. */
  52042. this._axesLayout = {};
  52043. /**
  52044. * Always follow axis order.
  52045. * @type {Array.<string>}
  52046. * @readOnly
  52047. */
  52048. this.dimensions = parallelModel.dimensions;
  52049. /**
  52050. * @type {module:zrender/core/BoundingRect}
  52051. */
  52052. this._rect;
  52053. /**
  52054. * @type {module:echarts/coord/parallel/ParallelModel}
  52055. */
  52056. this._model = parallelModel;
  52057. this._init(parallelModel, ecModel, api);
  52058. }
  52059. Parallel.prototype = {
  52060. type: 'parallel',
  52061. constructor: Parallel,
  52062. /**
  52063. * Initialize cartesian coordinate systems
  52064. * @private
  52065. */
  52066. _init: function (parallelModel, ecModel, api) {
  52067. var dimensions = parallelModel.dimensions;
  52068. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  52069. each$11(dimensions, function (dim, idx) {
  52070. var axisIndex = parallelAxisIndex[idx];
  52071. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  52072. var axis = this._axesMap.set(dim, new ParallelAxis(
  52073. dim,
  52074. createScaleByModel(axisModel),
  52075. [0, 0],
  52076. axisModel.get('type'),
  52077. axisIndex
  52078. ));
  52079. var isCategory = axis.type === 'category';
  52080. axis.onBand = isCategory && axisModel.get('boundaryGap');
  52081. axis.inverse = axisModel.get('inverse');
  52082. // Injection
  52083. axisModel.axis = axis;
  52084. axis.model = axisModel;
  52085. axis.coordinateSystem = axisModel.coordinateSystem = this;
  52086. }, this);
  52087. },
  52088. /**
  52089. * Update axis scale after data processed
  52090. * @param {module:echarts/model/Global} ecModel
  52091. * @param {module:echarts/ExtensionAPI} api
  52092. */
  52093. update: function (ecModel, api) {
  52094. this._updateAxesFromSeries(this._model, ecModel);
  52095. },
  52096. /**
  52097. * @override
  52098. */
  52099. containPoint: function (point) {
  52100. var layoutInfo = this._makeLayoutInfo();
  52101. var axisBase = layoutInfo.axisBase;
  52102. var layoutBase = layoutInfo.layoutBase;
  52103. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52104. var pAxis = point[1 - pixelDimIndex];
  52105. var pLayout = point[pixelDimIndex];
  52106. return pAxis >= axisBase
  52107. && pAxis <= axisBase + layoutInfo.axisLength
  52108. && pLayout >= layoutBase
  52109. && pLayout <= layoutBase + layoutInfo.layoutLength;
  52110. },
  52111. getModel: function () {
  52112. return this._model;
  52113. },
  52114. /**
  52115. * Update properties from series
  52116. * @private
  52117. */
  52118. _updateAxesFromSeries: function (parallelModel, ecModel) {
  52119. ecModel.eachSeries(function (seriesModel) {
  52120. if (!parallelModel.contains(seriesModel, ecModel)) {
  52121. return;
  52122. }
  52123. var data = seriesModel.getData();
  52124. each$11(this.dimensions, function (dim) {
  52125. var axis = this._axesMap.get(dim);
  52126. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  52127. niceScaleExtent(axis.scale, axis.model);
  52128. }, this);
  52129. }, this);
  52130. },
  52131. /**
  52132. * Resize the parallel coordinate system.
  52133. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  52134. * @param {module:echarts/ExtensionAPI} api
  52135. */
  52136. resize: function (parallelModel, api) {
  52137. this._rect = getLayoutRect(
  52138. parallelModel.getBoxLayoutParams(),
  52139. {
  52140. width: api.getWidth(),
  52141. height: api.getHeight()
  52142. }
  52143. );
  52144. this._layoutAxes();
  52145. },
  52146. /**
  52147. * @return {module:zrender/core/BoundingRect}
  52148. */
  52149. getRect: function () {
  52150. return this._rect;
  52151. },
  52152. /**
  52153. * @private
  52154. */
  52155. _makeLayoutInfo: function () {
  52156. var parallelModel = this._model;
  52157. var rect = this._rect;
  52158. var xy = ['x', 'y'];
  52159. var wh = ['width', 'height'];
  52160. var layout = parallelModel.get('layout');
  52161. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  52162. var layoutLength = rect[wh[pixelDimIndex]];
  52163. var layoutExtent = [0, layoutLength];
  52164. var axisCount = this.dimensions.length;
  52165. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  52166. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  52167. var axisExpandable = parallelModel.get('axisExpandable')
  52168. && axisCount > 3
  52169. && axisCount > axisExpandCount
  52170. && axisExpandCount > 1
  52171. && axisExpandWidth > 0
  52172. && layoutLength > 0;
  52173. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  52174. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  52175. // where collapsed axes should be overlapped.
  52176. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  52177. var winSize;
  52178. if (!axisExpandWindow) {
  52179. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  52180. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  52181. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  52182. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52183. }
  52184. else {
  52185. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  52186. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52187. }
  52188. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  52189. // Avoid axisCollapseWidth is too small.
  52190. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  52191. // Find the first and last indices > ewin[0] and < ewin[1].
  52192. var winInnerIndices = [
  52193. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  52194. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  52195. ];
  52196. // Pos in ec coordinates.
  52197. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  52198. return {
  52199. layout: layout,
  52200. pixelDimIndex: pixelDimIndex,
  52201. layoutBase: rect[xy[pixelDimIndex]],
  52202. layoutLength: layoutLength,
  52203. axisBase: rect[xy[1 - pixelDimIndex]],
  52204. axisLength: rect[wh[1 - pixelDimIndex]],
  52205. axisExpandable: axisExpandable,
  52206. axisExpandWidth: axisExpandWidth,
  52207. axisCollapseWidth: axisCollapseWidth,
  52208. axisExpandWindow: axisExpandWindow,
  52209. axisCount: axisCount,
  52210. winInnerIndices: winInnerIndices,
  52211. axisExpandWindow0Pos: axisExpandWindow0Pos
  52212. };
  52213. },
  52214. /**
  52215. * @private
  52216. */
  52217. _layoutAxes: function () {
  52218. var rect = this._rect;
  52219. var axes = this._axesMap;
  52220. var dimensions = this.dimensions;
  52221. var layoutInfo = this._makeLayoutInfo();
  52222. var layout = layoutInfo.layout;
  52223. axes.each(function (axis) {
  52224. var axisExtent = [0, layoutInfo.axisLength];
  52225. var idx = axis.inverse ? 1 : 0;
  52226. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  52227. });
  52228. each$11(dimensions, function (dim, idx) {
  52229. var posInfo = (layoutInfo.axisExpandable
  52230. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  52231. )(idx, layoutInfo);
  52232. var positionTable = {
  52233. horizontal: {
  52234. x: posInfo.position,
  52235. y: layoutInfo.axisLength
  52236. },
  52237. vertical: {
  52238. x: 0,
  52239. y: posInfo.position
  52240. }
  52241. };
  52242. var rotationTable = {
  52243. horizontal: PI$4 / 2,
  52244. vertical: 0
  52245. };
  52246. var position = [
  52247. positionTable[layout].x + rect.x,
  52248. positionTable[layout].y + rect.y
  52249. ];
  52250. var rotation = rotationTable[layout];
  52251. var transform = create$1();
  52252. rotate(transform, transform, rotation);
  52253. translate(transform, transform, position);
  52254. // TODO
  52255. // tick等排布信息。
  52256. // TODO
  52257. // 根据axis order 更新 dimensions顺序。
  52258. this._axesLayout[dim] = {
  52259. position: position,
  52260. rotation: rotation,
  52261. transform: transform,
  52262. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  52263. axisLabelShow: posInfo.axisLabelShow,
  52264. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  52265. tickDirection: 1,
  52266. labelDirection: 1
  52267. };
  52268. }, this);
  52269. },
  52270. /**
  52271. * Get axis by dim.
  52272. * @param {string} dim
  52273. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  52274. */
  52275. getAxis: function (dim) {
  52276. return this._axesMap.get(dim);
  52277. },
  52278. /**
  52279. * Convert a dim value of a single item of series data to Point.
  52280. * @param {*} value
  52281. * @param {string} dim
  52282. * @return {Array}
  52283. */
  52284. dataToPoint: function (value, dim) {
  52285. return this.axisCoordToPoint(
  52286. this._axesMap.get(dim).dataToCoord(value),
  52287. dim
  52288. );
  52289. },
  52290. /**
  52291. * Travel data for one time, get activeState of each data item.
  52292. * @param {module:echarts/data/List} data
  52293. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  52294. * {number} dataIndex
  52295. * @param {number} [start=0] the start dataIndex that travel from.
  52296. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  52297. */
  52298. eachActiveState: function (data, callback, start, end) {
  52299. start == null && (start = 0);
  52300. end == null && (end = data.count());
  52301. var axesMap = this._axesMap;
  52302. var dimensions = this.dimensions;
  52303. var dataDimensions = [];
  52304. var axisModels = [];
  52305. each$1(dimensions, function (axisDim) {
  52306. dataDimensions.push(data.mapDimension(axisDim));
  52307. axisModels.push(axesMap.get(axisDim).model);
  52308. });
  52309. var hasActiveSet = this.hasAxisBrushed();
  52310. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  52311. var activeState;
  52312. if (!hasActiveSet) {
  52313. activeState = 'normal';
  52314. }
  52315. else {
  52316. activeState = 'active';
  52317. var values = data.getValues(dataDimensions, dataIndex);
  52318. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52319. var state = axisModels[j].getActiveState(values[j]);
  52320. if (state === 'inactive') {
  52321. activeState = 'inactive';
  52322. break;
  52323. }
  52324. }
  52325. }
  52326. callback(activeState, dataIndex);
  52327. }
  52328. },
  52329. /**
  52330. * Whether has any activeSet.
  52331. * @return {boolean}
  52332. */
  52333. hasAxisBrushed: function () {
  52334. var dimensions = this.dimensions;
  52335. var axesMap = this._axesMap;
  52336. var hasActiveSet = false;
  52337. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52338. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  52339. hasActiveSet = true;
  52340. }
  52341. }
  52342. return hasActiveSet;
  52343. },
  52344. /**
  52345. * Convert coords of each axis to Point.
  52346. * Return point. For example: [10, 20]
  52347. * @param {Array.<number>} coords
  52348. * @param {string} dim
  52349. * @return {Array.<number>}
  52350. */
  52351. axisCoordToPoint: function (coord, dim) {
  52352. var axisLayout = this._axesLayout[dim];
  52353. return applyTransform$1([coord, 0], axisLayout.transform);
  52354. },
  52355. /**
  52356. * Get axis layout.
  52357. */
  52358. getAxisLayout: function (dim) {
  52359. return clone(this._axesLayout[dim]);
  52360. },
  52361. /**
  52362. * @param {Array.<number>} point
  52363. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  52364. */
  52365. getSlidedAxisExpandWindow: function (point) {
  52366. var layoutInfo = this._makeLayoutInfo();
  52367. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52368. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  52369. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  52370. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  52371. // Out of the area of coordinate system.
  52372. if (!this.containPoint(point)) {
  52373. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  52374. }
  52375. // Conver the point from global to expand coordinates.
  52376. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  52377. // For dragging operation convenience, the window should not be
  52378. // slided when mouse is the center area of the window.
  52379. var delta;
  52380. var behavior = 'slide';
  52381. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  52382. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  52383. // But consider touch device, jump is necessary.
  52384. var useJump = triggerArea[0] != null;
  52385. if (axisCollapseWidth) {
  52386. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  52387. behavior = 'jump';
  52388. delta = pointCoord - winSize * triggerArea[2];
  52389. }
  52390. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  52391. behavior = 'jump';
  52392. delta = pointCoord - winSize * (1 - triggerArea[2]);
  52393. }
  52394. else {
  52395. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  52396. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  52397. && (delta = 0);
  52398. }
  52399. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  52400. delta
  52401. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  52402. // Avoid nonsense triger on mousemove.
  52403. : (behavior = 'none');
  52404. }
  52405. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  52406. else {
  52407. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  52408. var pos = extent[1] * pointCoord / winSize;
  52409. axisExpandWindow = [mathMax$6(0, pos - winSize / 2)];
  52410. axisExpandWindow[1] = mathMin$6(extent[1], axisExpandWindow[0] + winSize);
  52411. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  52412. }
  52413. return {
  52414. axisExpandWindow: axisExpandWindow,
  52415. behavior: behavior
  52416. };
  52417. }
  52418. };
  52419. function restrict(len, extent) {
  52420. return mathMin$6(mathMax$6(len, extent[0]), extent[1]);
  52421. }
  52422. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  52423. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  52424. return {
  52425. position: step * axisIndex,
  52426. axisNameAvailableWidth: step,
  52427. axisLabelShow: true
  52428. };
  52429. }
  52430. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  52431. var layoutLength = layoutInfo.layoutLength;
  52432. var axisExpandWidth = layoutInfo.axisExpandWidth;
  52433. var axisCount = layoutInfo.axisCount;
  52434. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  52435. var winInnerIndices = layoutInfo.winInnerIndices;
  52436. var position;
  52437. var axisNameAvailableWidth = axisCollapseWidth;
  52438. var axisLabelShow = false;
  52439. var nameTruncateMaxWidth;
  52440. if (axisIndex < winInnerIndices[0]) {
  52441. position = axisIndex * axisCollapseWidth;
  52442. nameTruncateMaxWidth = axisCollapseWidth;
  52443. }
  52444. else if (axisIndex <= winInnerIndices[1]) {
  52445. position = layoutInfo.axisExpandWindow0Pos
  52446. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  52447. axisNameAvailableWidth = axisExpandWidth;
  52448. axisLabelShow = true;
  52449. }
  52450. else {
  52451. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  52452. nameTruncateMaxWidth = axisCollapseWidth;
  52453. }
  52454. return {
  52455. position: position,
  52456. axisNameAvailableWidth: axisNameAvailableWidth,
  52457. axisLabelShow: axisLabelShow,
  52458. nameTruncateMaxWidth: nameTruncateMaxWidth
  52459. };
  52460. }
  52461. /*
  52462. * Licensed to the Apache Software Foundation (ASF) under one
  52463. * or more contributor license agreements. See the NOTICE file
  52464. * distributed with this work for additional information
  52465. * regarding copyright ownership. The ASF licenses this file
  52466. * to you under the Apache License, Version 2.0 (the
  52467. * "License"); you may not use this file except in compliance
  52468. * with the License. You may obtain a copy of the License at
  52469. *
  52470. * http://www.apache.org/licenses/LICENSE-2.0
  52471. *
  52472. * Unless required by applicable law or agreed to in writing,
  52473. * software distributed under the License is distributed on an
  52474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52475. * KIND, either express or implied. See the License for the
  52476. * specific language governing permissions and limitations
  52477. * under the License.
  52478. */
  52479. /**
  52480. * Parallel coordinate system creater.
  52481. */
  52482. function create$2(ecModel, api) {
  52483. var coordSysList = [];
  52484. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  52485. var coordSys = new Parallel(parallelModel, ecModel, api);
  52486. coordSys.name = 'parallel_' + idx;
  52487. coordSys.resize(parallelModel, api);
  52488. parallelModel.coordinateSystem = coordSys;
  52489. coordSys.model = parallelModel;
  52490. coordSysList.push(coordSys);
  52491. });
  52492. // Inject the coordinateSystems into seriesModel
  52493. ecModel.eachSeries(function (seriesModel) {
  52494. if (seriesModel.get('coordinateSystem') === 'parallel') {
  52495. var parallelModel = ecModel.queryComponents({
  52496. mainType: 'parallel',
  52497. index: seriesModel.get('parallelIndex'),
  52498. id: seriesModel.get('parallelId')
  52499. })[0];
  52500. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  52501. }
  52502. });
  52503. return coordSysList;
  52504. }
  52505. CoordinateSystemManager.register('parallel', {create: create$2});
  52506. /*
  52507. * Licensed to the Apache Software Foundation (ASF) under one
  52508. * or more contributor license agreements. See the NOTICE file
  52509. * distributed with this work for additional information
  52510. * regarding copyright ownership. The ASF licenses this file
  52511. * to you under the Apache License, Version 2.0 (the
  52512. * "License"); you may not use this file except in compliance
  52513. * with the License. You may obtain a copy of the License at
  52514. *
  52515. * http://www.apache.org/licenses/LICENSE-2.0
  52516. *
  52517. * Unless required by applicable law or agreed to in writing,
  52518. * software distributed under the License is distributed on an
  52519. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52520. * KIND, either express or implied. See the License for the
  52521. * specific language governing permissions and limitations
  52522. * under the License.
  52523. */
  52524. var AxisModel$2 = ComponentModel.extend({
  52525. type: 'baseParallelAxis',
  52526. /**
  52527. * @type {module:echarts/coord/parallel/Axis}
  52528. */
  52529. axis: null,
  52530. /**
  52531. * @type {Array.<Array.<number>}
  52532. * @readOnly
  52533. */
  52534. activeIntervals: [],
  52535. /**
  52536. * @return {Object}
  52537. */
  52538. getAreaSelectStyle: function () {
  52539. return makeStyleMapper(
  52540. [
  52541. ['fill', 'color'],
  52542. ['lineWidth', 'borderWidth'],
  52543. ['stroke', 'borderColor'],
  52544. ['width', 'width'],
  52545. ['opacity', 'opacity']
  52546. ]
  52547. )(this.getModel('areaSelectStyle'));
  52548. },
  52549. /**
  52550. * The code of this feature is put on AxisModel but not ParallelAxis,
  52551. * because axisModel can be alive after echarts updating but instance of
  52552. * ParallelAxis having been disposed. this._activeInterval should be kept
  52553. * when action dispatched (i.e. legend click).
  52554. *
  52555. * @param {Array.<Array<number>>} intervals interval.length === 0
  52556. * means set all active.
  52557. * @public
  52558. */
  52559. setActiveIntervals: function (intervals) {
  52560. var activeIntervals = this.activeIntervals = clone(intervals);
  52561. // Normalize
  52562. if (activeIntervals) {
  52563. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  52564. asc(activeIntervals[i]);
  52565. }
  52566. }
  52567. },
  52568. /**
  52569. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  52570. * value can not be input.
  52571. * @return {string} 'normal': no activeIntervals set,
  52572. * 'active',
  52573. * 'inactive'.
  52574. * @public
  52575. */
  52576. getActiveState: function (value) {
  52577. var activeIntervals = this.activeIntervals;
  52578. if (!activeIntervals.length) {
  52579. return 'normal';
  52580. }
  52581. if (value == null || isNaN(value)) {
  52582. return 'inactive';
  52583. }
  52584. // Simple optimization
  52585. if (activeIntervals.length === 1) {
  52586. var interval = activeIntervals[0];
  52587. if (interval[0] <= value && value <= interval[1]) {
  52588. return 'active';
  52589. }
  52590. }
  52591. else {
  52592. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  52593. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  52594. return 'active';
  52595. }
  52596. }
  52597. }
  52598. return 'inactive';
  52599. }
  52600. });
  52601. var defaultOption$1 = {
  52602. type: 'value',
  52603. /**
  52604. * @type {Array.<number>}
  52605. */
  52606. dim: null, // 0, 1, 2, ...
  52607. // parallelIndex: null,
  52608. areaSelectStyle: {
  52609. width: 20,
  52610. borderWidth: 1,
  52611. borderColor: 'rgba(160,197,232)',
  52612. color: 'rgba(160,197,232)',
  52613. opacity: 0.3
  52614. },
  52615. realtime: true, // Whether realtime update view when select.
  52616. z: 10
  52617. };
  52618. merge(AxisModel$2.prototype, axisModelCommonMixin);
  52619. function getAxisType$1(axisName, option) {
  52620. return option.type || (option.data ? 'category' : 'value');
  52621. }
  52622. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  52623. /*
  52624. * Licensed to the Apache Software Foundation (ASF) under one
  52625. * or more contributor license agreements. See the NOTICE file
  52626. * distributed with this work for additional information
  52627. * regarding copyright ownership. The ASF licenses this file
  52628. * to you under the Apache License, Version 2.0 (the
  52629. * "License"); you may not use this file except in compliance
  52630. * with the License. You may obtain a copy of the License at
  52631. *
  52632. * http://www.apache.org/licenses/LICENSE-2.0
  52633. *
  52634. * Unless required by applicable law or agreed to in writing,
  52635. * software distributed under the License is distributed on an
  52636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52637. * KIND, either express or implied. See the License for the
  52638. * specific language governing permissions and limitations
  52639. * under the License.
  52640. */
  52641. ComponentModel.extend({
  52642. type: 'parallel',
  52643. dependencies: ['parallelAxis'],
  52644. /**
  52645. * @type {module:echarts/coord/parallel/Parallel}
  52646. */
  52647. coordinateSystem: null,
  52648. /**
  52649. * Each item like: 'dim0', 'dim1', 'dim2', ...
  52650. * @type {Array.<string>}
  52651. * @readOnly
  52652. */
  52653. dimensions: null,
  52654. /**
  52655. * Coresponding to dimensions.
  52656. * @type {Array.<number>}
  52657. * @readOnly
  52658. */
  52659. parallelAxisIndex: null,
  52660. layoutMode: 'box',
  52661. defaultOption: {
  52662. zlevel: 0,
  52663. z: 0,
  52664. left: 80,
  52665. top: 60,
  52666. right: 80,
  52667. bottom: 60,
  52668. // width: {totalWidth} - left - right,
  52669. // height: {totalHeight} - top - bottom,
  52670. layout: 'horizontal', // 'horizontal' or 'vertical'
  52671. // FIXME
  52672. // naming?
  52673. axisExpandable: false,
  52674. axisExpandCenter: null,
  52675. axisExpandCount: 0,
  52676. axisExpandWidth: 50, // FIXME '10%' ?
  52677. axisExpandRate: 17,
  52678. axisExpandDebounce: 50,
  52679. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  52680. // Do not doc to user until necessary.
  52681. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  52682. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  52683. parallelAxisDefault: null
  52684. },
  52685. /**
  52686. * @override
  52687. */
  52688. init: function () {
  52689. ComponentModel.prototype.init.apply(this, arguments);
  52690. this.mergeOption({});
  52691. },
  52692. /**
  52693. * @override
  52694. */
  52695. mergeOption: function (newOption) {
  52696. var thisOption = this.option;
  52697. newOption && merge(thisOption, newOption, true);
  52698. this._initDimensions();
  52699. },
  52700. /**
  52701. * Whether series or axis is in this coordinate system.
  52702. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  52703. * @param {module:echarts/model/Global} ecModel
  52704. */
  52705. contains: function (model, ecModel) {
  52706. var parallelIndex = model.get('parallelIndex');
  52707. return parallelIndex != null
  52708. && ecModel.getComponent('parallel', parallelIndex) === this;
  52709. },
  52710. setAxisExpand: function (opt) {
  52711. each$1(
  52712. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  52713. function (name) {
  52714. if (opt.hasOwnProperty(name)) {
  52715. this.option[name] = opt[name];
  52716. }
  52717. },
  52718. this
  52719. );
  52720. },
  52721. /**
  52722. * @private
  52723. */
  52724. _initDimensions: function () {
  52725. var dimensions = this.dimensions = [];
  52726. var parallelAxisIndex = this.parallelAxisIndex = [];
  52727. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  52728. // Can not use this.contains here, because
  52729. // initialization has not been completed yet.
  52730. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  52731. }, this);
  52732. each$1(axisModels, function (axisModel) {
  52733. dimensions.push('dim' + axisModel.get('dim'));
  52734. parallelAxisIndex.push(axisModel.componentIndex);
  52735. });
  52736. }
  52737. });
  52738. /*
  52739. * Licensed to the Apache Software Foundation (ASF) under one
  52740. * or more contributor license agreements. See the NOTICE file
  52741. * distributed with this work for additional information
  52742. * regarding copyright ownership. The ASF licenses this file
  52743. * to you under the Apache License, Version 2.0 (the
  52744. * "License"); you may not use this file except in compliance
  52745. * with the License. You may obtain a copy of the License at
  52746. *
  52747. * http://www.apache.org/licenses/LICENSE-2.0
  52748. *
  52749. * Unless required by applicable law or agreed to in writing,
  52750. * software distributed under the License is distributed on an
  52751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52752. * KIND, either express or implied. See the License for the
  52753. * specific language governing permissions and limitations
  52754. * under the License.
  52755. */
  52756. /**
  52757. * @payload
  52758. * @property {string} parallelAxisId
  52759. * @property {Array.<Array.<number>>} intervals
  52760. */
  52761. var actionInfo$1 = {
  52762. type: 'axisAreaSelect',
  52763. event: 'axisAreaSelected'
  52764. // update: 'updateVisual'
  52765. };
  52766. registerAction(actionInfo$1, function (payload, ecModel) {
  52767. ecModel.eachComponent(
  52768. {mainType: 'parallelAxis', query: payload},
  52769. function (parallelAxisModel) {
  52770. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  52771. }
  52772. );
  52773. });
  52774. /**
  52775. * @payload
  52776. */
  52777. registerAction('parallelAxisExpand', function (payload, ecModel) {
  52778. ecModel.eachComponent(
  52779. {mainType: 'parallel', query: payload},
  52780. function (parallelModel) {
  52781. parallelModel.setAxisExpand(payload);
  52782. }
  52783. );
  52784. });
  52785. /*
  52786. * Licensed to the Apache Software Foundation (ASF) under one
  52787. * or more contributor license agreements. See the NOTICE file
  52788. * distributed with this work for additional information
  52789. * regarding copyright ownership. The ASF licenses this file
  52790. * to you under the Apache License, Version 2.0 (the
  52791. * "License"); you may not use this file except in compliance
  52792. * with the License. You may obtain a copy of the License at
  52793. *
  52794. * http://www.apache.org/licenses/LICENSE-2.0
  52795. *
  52796. * Unless required by applicable law or agreed to in writing,
  52797. * software distributed under the License is distributed on an
  52798. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52799. * KIND, either express or implied. See the License for the
  52800. * specific language governing permissions and limitations
  52801. * under the License.
  52802. */
  52803. var curry$2 = curry;
  52804. var each$12 = each$1;
  52805. var map$2 = map;
  52806. var mathMin$7 = Math.min;
  52807. var mathMax$7 = Math.max;
  52808. var mathPow$2 = Math.pow;
  52809. var COVER_Z = 10000;
  52810. var UNSELECT_THRESHOLD = 6;
  52811. var MIN_RESIZE_LINE_WIDTH = 6;
  52812. var MUTEX_RESOURCE_KEY = 'globalPan';
  52813. var DIRECTION_MAP = {
  52814. w: [0, 0],
  52815. e: [0, 1],
  52816. n: [1, 0],
  52817. s: [1, 1]
  52818. };
  52819. var CURSOR_MAP = {
  52820. w: 'ew',
  52821. e: 'ew',
  52822. n: 'ns',
  52823. s: 'ns',
  52824. ne: 'nesw',
  52825. sw: 'nesw',
  52826. nw: 'nwse',
  52827. se: 'nwse'
  52828. };
  52829. var DEFAULT_BRUSH_OPT = {
  52830. brushStyle: {
  52831. lineWidth: 2,
  52832. stroke: 'rgba(0,0,0,0.3)',
  52833. fill: 'rgba(0,0,0,0.1)'
  52834. },
  52835. transformable: true,
  52836. brushMode: 'single',
  52837. removeOnClick: false
  52838. };
  52839. var baseUID = 0;
  52840. /**
  52841. * @alias module:echarts/component/helper/BrushController
  52842. * @constructor
  52843. * @mixin {module:zrender/mixin/Eventful}
  52844. * @event module:echarts/component/helper/BrushController#brush
  52845. * params:
  52846. * areas: Array.<Array>, coord relates to container group,
  52847. * If no container specified, to global.
  52848. * opt {
  52849. * isEnd: boolean,
  52850. * removeOnClick: boolean
  52851. * }
  52852. *
  52853. * @param {module:zrender/zrender~ZRender} zr
  52854. */
  52855. function BrushController(zr) {
  52856. if (__DEV__) {
  52857. assert$1(zr);
  52858. }
  52859. Eventful.call(this);
  52860. /**
  52861. * @type {module:zrender/zrender~ZRender}
  52862. * @private
  52863. */
  52864. this._zr = zr;
  52865. /**
  52866. * @type {module:zrender/container/Group}
  52867. * @readOnly
  52868. */
  52869. this.group = new Group();
  52870. /**
  52871. * Only for drawing (after enabledBrush).
  52872. * 'line', 'rect', 'polygon' or false
  52873. * If passing false/null/undefined, disable brush.
  52874. * If passing 'auto', determined by panel.defaultBrushType
  52875. * @private
  52876. * @type {string}
  52877. */
  52878. this._brushType;
  52879. /**
  52880. * Only for drawing (after enabledBrush).
  52881. *
  52882. * @private
  52883. * @type {Object}
  52884. */
  52885. this._brushOption;
  52886. /**
  52887. * @private
  52888. * @type {Object}
  52889. */
  52890. this._panels;
  52891. /**
  52892. * @private
  52893. * @type {Array.<nubmer>}
  52894. */
  52895. this._track = [];
  52896. /**
  52897. * @private
  52898. * @type {boolean}
  52899. */
  52900. this._dragging;
  52901. /**
  52902. * @private
  52903. * @type {Array}
  52904. */
  52905. this._covers = [];
  52906. /**
  52907. * @private
  52908. * @type {moudule:zrender/container/Group}
  52909. */
  52910. this._creatingCover;
  52911. /**
  52912. * `true` means global panel
  52913. * @private
  52914. * @type {module:zrender/container/Group|boolean}
  52915. */
  52916. this._creatingPanel;
  52917. /**
  52918. * @private
  52919. * @type {boolean}
  52920. */
  52921. this._enableGlobalPan;
  52922. /**
  52923. * @private
  52924. * @type {boolean}
  52925. */
  52926. if (__DEV__) {
  52927. this._mounted;
  52928. }
  52929. /**
  52930. * @private
  52931. * @type {string}
  52932. */
  52933. this._uid = 'brushController_' + baseUID++;
  52934. /**
  52935. * @private
  52936. * @type {Object}
  52937. */
  52938. this._handlers = {};
  52939. each$12(pointerHandlers, function (handler, eventName) {
  52940. this._handlers[eventName] = bind(handler, this);
  52941. }, this);
  52942. }
  52943. BrushController.prototype = {
  52944. constructor: BrushController,
  52945. /**
  52946. * If set to null/undefined/false, select disabled.
  52947. * @param {Object} brushOption
  52948. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  52949. * If passing false/null/undefined, disable brush.
  52950. * If passing 'auto', determined by panel.defaultBrushType.
  52951. * ('auto' can not be used in global panel)
  52952. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  52953. * @param {boolean} [brushOption.transformable=true]
  52954. * @param {boolean} [brushOption.removeOnClick=false]
  52955. * @param {Object} [brushOption.brushStyle]
  52956. * @param {number} [brushOption.brushStyle.width]
  52957. * @param {number} [brushOption.brushStyle.lineWidth]
  52958. * @param {string} [brushOption.brushStyle.stroke]
  52959. * @param {string} [brushOption.brushStyle.fill]
  52960. * @param {number} [brushOption.z]
  52961. */
  52962. enableBrush: function (brushOption) {
  52963. if (__DEV__) {
  52964. assert$1(this._mounted);
  52965. }
  52966. this._brushType && doDisableBrush(this);
  52967. brushOption.brushType && doEnableBrush(this, brushOption);
  52968. return this;
  52969. },
  52970. /**
  52971. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  52972. * Each items: {
  52973. * panelId, // mandatory.
  52974. * clipPath, // mandatory. function.
  52975. * isTargetByCursor, // mandatory. function.
  52976. * defaultBrushType, // optional, only used when brushType is 'auto'.
  52977. * getLinearBrushOtherExtent, // optional. function.
  52978. * }
  52979. */
  52980. setPanels: function (panelOpts) {
  52981. if (panelOpts && panelOpts.length) {
  52982. var panels = this._panels = {};
  52983. each$1(panelOpts, function (panelOpts) {
  52984. panels[panelOpts.panelId] = clone(panelOpts);
  52985. });
  52986. }
  52987. else {
  52988. this._panels = null;
  52989. }
  52990. return this;
  52991. },
  52992. /**
  52993. * @param {Object} [opt]
  52994. * @return {boolean} [opt.enableGlobalPan=false]
  52995. */
  52996. mount: function (opt) {
  52997. opt = opt || {};
  52998. if (__DEV__) {
  52999. this._mounted = true; // should be at first.
  53000. }
  53001. this._enableGlobalPan = opt.enableGlobalPan;
  53002. var thisGroup = this.group;
  53003. this._zr.add(thisGroup);
  53004. thisGroup.attr({
  53005. position: opt.position || [0, 0],
  53006. rotation: opt.rotation || 0,
  53007. scale: opt.scale || [1, 1]
  53008. });
  53009. this._transform = thisGroup.getLocalTransform();
  53010. return this;
  53011. },
  53012. eachCover: function (cb, context) {
  53013. each$12(this._covers, cb, context);
  53014. },
  53015. /**
  53016. * Update covers.
  53017. * @param {Array.<Object>} brushOptionList Like:
  53018. * [
  53019. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  53020. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  53021. * ...
  53022. * ]
  53023. * `brushType` is required in each cover info. (can not be 'auto')
  53024. * `id` is not mandatory.
  53025. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  53026. * If brushOptionList is null/undefined, all covers removed.
  53027. */
  53028. updateCovers: function (brushOptionList) {
  53029. if (__DEV__) {
  53030. assert$1(this._mounted);
  53031. }
  53032. brushOptionList = map(brushOptionList, function (brushOption) {
  53033. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53034. });
  53035. var tmpIdPrefix = '\0-brush-index-';
  53036. var oldCovers = this._covers;
  53037. var newCovers = this._covers = [];
  53038. var controller = this;
  53039. var creatingCover = this._creatingCover;
  53040. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  53041. .add(addOrUpdate)
  53042. .update(addOrUpdate)
  53043. .remove(remove)
  53044. .execute();
  53045. return this;
  53046. function getKey(brushOption, index) {
  53047. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  53048. + '-' + brushOption.brushType;
  53049. }
  53050. function oldGetKey(cover, index) {
  53051. return getKey(cover.__brushOption, index);
  53052. }
  53053. function addOrUpdate(newIndex, oldIndex) {
  53054. var newBrushOption = brushOptionList[newIndex];
  53055. // Consider setOption in event listener of brushSelect,
  53056. // where updating cover when creating should be forbiden.
  53057. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  53058. newCovers[newIndex] = oldCovers[oldIndex];
  53059. }
  53060. else {
  53061. var cover = newCovers[newIndex] = oldIndex != null
  53062. ? (
  53063. oldCovers[oldIndex].__brushOption = newBrushOption,
  53064. oldCovers[oldIndex]
  53065. )
  53066. : endCreating(controller, createCover(controller, newBrushOption));
  53067. updateCoverAfterCreation(controller, cover);
  53068. }
  53069. }
  53070. function remove(oldIndex) {
  53071. if (oldCovers[oldIndex] !== creatingCover) {
  53072. controller.group.remove(oldCovers[oldIndex]);
  53073. }
  53074. }
  53075. },
  53076. unmount: function () {
  53077. if (__DEV__) {
  53078. if (!this._mounted) {
  53079. return;
  53080. }
  53081. }
  53082. this.enableBrush(false);
  53083. // container may 'removeAll' outside.
  53084. clearCovers(this);
  53085. this._zr.remove(this.group);
  53086. if (__DEV__) {
  53087. this._mounted = false; // should be at last.
  53088. }
  53089. return this;
  53090. },
  53091. dispose: function () {
  53092. this.unmount();
  53093. this.off();
  53094. }
  53095. };
  53096. mixin(BrushController, Eventful);
  53097. function doEnableBrush(controller, brushOption) {
  53098. var zr = controller._zr;
  53099. // Consider roam, which takes globalPan too.
  53100. if (!controller._enableGlobalPan) {
  53101. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53102. }
  53103. mountHandlers(zr, controller._handlers);
  53104. controller._brushType = brushOption.brushType;
  53105. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53106. }
  53107. function doDisableBrush(controller) {
  53108. var zr = controller._zr;
  53109. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  53110. unmountHandlers(zr, controller._handlers);
  53111. controller._brushType = controller._brushOption = null;
  53112. }
  53113. function mountHandlers(zr, handlers) {
  53114. each$12(handlers, function (handler, eventName) {
  53115. zr.on(eventName, handler);
  53116. });
  53117. }
  53118. function unmountHandlers(zr, handlers) {
  53119. each$12(handlers, function (handler, eventName) {
  53120. zr.off(eventName, handler);
  53121. });
  53122. }
  53123. function createCover(controller, brushOption) {
  53124. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  53125. cover.__brushOption = brushOption;
  53126. updateZ$1(cover, brushOption);
  53127. controller.group.add(cover);
  53128. return cover;
  53129. }
  53130. function endCreating(controller, creatingCover) {
  53131. var coverRenderer = getCoverRenderer(creatingCover);
  53132. if (coverRenderer.endCreating) {
  53133. coverRenderer.endCreating(controller, creatingCover);
  53134. updateZ$1(creatingCover, creatingCover.__brushOption);
  53135. }
  53136. return creatingCover;
  53137. }
  53138. function updateCoverShape(controller, cover) {
  53139. var brushOption = cover.__brushOption;
  53140. getCoverRenderer(cover).updateCoverShape(
  53141. controller, cover, brushOption.range, brushOption
  53142. );
  53143. }
  53144. function updateZ$1(cover, brushOption) {
  53145. var z = brushOption.z;
  53146. z == null && (z = COVER_Z);
  53147. cover.traverse(function (el) {
  53148. el.z = z;
  53149. el.z2 = z; // Consider in given container.
  53150. });
  53151. }
  53152. function updateCoverAfterCreation(controller, cover) {
  53153. getCoverRenderer(cover).updateCommon(controller, cover);
  53154. updateCoverShape(controller, cover);
  53155. }
  53156. function getCoverRenderer(cover) {
  53157. return coverRenderers[cover.__brushOption.brushType];
  53158. }
  53159. // return target panel or `true` (means global panel)
  53160. function getPanelByPoint(controller, e, localCursorPoint) {
  53161. var panels = controller._panels;
  53162. if (!panels) {
  53163. return true; // Global panel
  53164. }
  53165. var panel;
  53166. var transform = controller._transform;
  53167. each$12(panels, function (pn) {
  53168. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  53169. });
  53170. return panel;
  53171. }
  53172. // Return a panel or true
  53173. function getPanelByCover(controller, cover) {
  53174. var panels = controller._panels;
  53175. if (!panels) {
  53176. return true; // Global panel
  53177. }
  53178. var panelId = cover.__brushOption.panelId;
  53179. // User may give cover without coord sys info,
  53180. // which is then treated as global panel.
  53181. return panelId != null ? panels[panelId] : true;
  53182. }
  53183. function clearCovers(controller) {
  53184. var covers = controller._covers;
  53185. var originalLength = covers.length;
  53186. each$12(covers, function (cover) {
  53187. controller.group.remove(cover);
  53188. }, controller);
  53189. covers.length = 0;
  53190. return !!originalLength;
  53191. }
  53192. function trigger$1(controller, opt) {
  53193. var areas = map$2(controller._covers, function (cover) {
  53194. var brushOption = cover.__brushOption;
  53195. var range = clone(brushOption.range);
  53196. return {
  53197. brushType: brushOption.brushType,
  53198. panelId: brushOption.panelId,
  53199. range: range
  53200. };
  53201. });
  53202. controller.trigger('brush', areas, {
  53203. isEnd: !!opt.isEnd,
  53204. removeOnClick: !!opt.removeOnClick
  53205. });
  53206. }
  53207. function shouldShowCover(controller) {
  53208. var track = controller._track;
  53209. if (!track.length) {
  53210. return false;
  53211. }
  53212. var p2 = track[track.length - 1];
  53213. var p1 = track[0];
  53214. var dx = p2[0] - p1[0];
  53215. var dy = p2[1] - p1[1];
  53216. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  53217. return dist > UNSELECT_THRESHOLD;
  53218. }
  53219. function getTrackEnds(track) {
  53220. var tail = track.length - 1;
  53221. tail < 0 && (tail = 0);
  53222. return [track[0], track[tail]];
  53223. }
  53224. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  53225. var cover = new Group();
  53226. cover.add(new Rect({
  53227. name: 'main',
  53228. style: makeStyle(brushOption),
  53229. silent: true,
  53230. draggable: true,
  53231. cursor: 'move',
  53232. drift: curry$2(doDrift, controller, cover, 'nswe'),
  53233. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53234. }));
  53235. each$12(
  53236. edgeNames,
  53237. function (name) {
  53238. cover.add(new Rect({
  53239. name: name,
  53240. style: {opacity: 0},
  53241. draggable: true,
  53242. silent: true,
  53243. invisible: true,
  53244. drift: curry$2(doDrift, controller, cover, name),
  53245. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53246. }));
  53247. }
  53248. );
  53249. return cover;
  53250. }
  53251. function updateBaseRect(controller, cover, localRange, brushOption) {
  53252. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  53253. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  53254. var x = localRange[0][0];
  53255. var y = localRange[1][0];
  53256. var xa = x - lineWidth / 2;
  53257. var ya = y - lineWidth / 2;
  53258. var x2 = localRange[0][1];
  53259. var y2 = localRange[1][1];
  53260. var x2a = x2 - handleSize + lineWidth / 2;
  53261. var y2a = y2 - handleSize + lineWidth / 2;
  53262. var width = x2 - x;
  53263. var height = y2 - y;
  53264. var widtha = width + lineWidth;
  53265. var heighta = height + lineWidth;
  53266. updateRectShape(controller, cover, 'main', x, y, width, height);
  53267. if (brushOption.transformable) {
  53268. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  53269. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  53270. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  53271. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  53272. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  53273. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  53274. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  53275. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  53276. }
  53277. }
  53278. function updateCommon(controller, cover) {
  53279. var brushOption = cover.__brushOption;
  53280. var transformable = brushOption.transformable;
  53281. var mainEl = cover.childAt(0);
  53282. mainEl.useStyle(makeStyle(brushOption));
  53283. mainEl.attr({
  53284. silent: !transformable,
  53285. cursor: transformable ? 'move' : 'default'
  53286. });
  53287. each$12(
  53288. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  53289. function (name) {
  53290. var el = cover.childOfName(name);
  53291. var globalDir = getGlobalDirection(controller, name);
  53292. el && el.attr({
  53293. silent: !transformable,
  53294. invisible: !transformable,
  53295. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  53296. });
  53297. }
  53298. );
  53299. }
  53300. function updateRectShape(controller, cover, name, x, y, w, h) {
  53301. var el = cover.childOfName(name);
  53302. el && el.setShape(pointsToRect(
  53303. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  53304. ));
  53305. }
  53306. function makeStyle(brushOption) {
  53307. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  53308. }
  53309. function formatRectRange(x, y, x2, y2) {
  53310. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  53311. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  53312. return [
  53313. [min[0], max[0]], // x range
  53314. [min[1], max[1]] // y range
  53315. ];
  53316. }
  53317. function getTransform$1(controller) {
  53318. return getTransform(controller.group);
  53319. }
  53320. function getGlobalDirection(controller, localDirection) {
  53321. if (localDirection.length > 1) {
  53322. localDirection = localDirection.split('');
  53323. var globalDir = [
  53324. getGlobalDirection(controller, localDirection[0]),
  53325. getGlobalDirection(controller, localDirection[1])
  53326. ];
  53327. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  53328. return globalDir.join('');
  53329. }
  53330. else {
  53331. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  53332. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  53333. var globalDir = transformDirection(
  53334. map$$1[localDirection], getTransform$1(controller)
  53335. );
  53336. return inverseMap[globalDir];
  53337. }
  53338. }
  53339. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  53340. var brushOption = cover.__brushOption;
  53341. var rectRange = toRectRange(brushOption.range);
  53342. var localDelta = toLocalDelta(controller, dx, dy);
  53343. each$12(name.split(''), function (namePart) {
  53344. var ind = DIRECTION_MAP[namePart];
  53345. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  53346. });
  53347. brushOption.range = fromRectRange(formatRectRange(
  53348. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  53349. ));
  53350. updateCoverAfterCreation(controller, cover);
  53351. trigger$1(controller, {isEnd: false});
  53352. }
  53353. function driftPolygon(controller, cover, dx, dy, e) {
  53354. var range = cover.__brushOption.range;
  53355. var localDelta = toLocalDelta(controller, dx, dy);
  53356. each$12(range, function (point) {
  53357. point[0] += localDelta[0];
  53358. point[1] += localDelta[1];
  53359. });
  53360. updateCoverAfterCreation(controller, cover);
  53361. trigger$1(controller, {isEnd: false});
  53362. }
  53363. function toLocalDelta(controller, dx, dy) {
  53364. var thisGroup = controller.group;
  53365. var localD = thisGroup.transformCoordToLocal(dx, dy);
  53366. var localZero = thisGroup.transformCoordToLocal(0, 0);
  53367. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  53368. }
  53369. function clipByPanel(controller, cover, data) {
  53370. var panel = getPanelByCover(controller, cover);
  53371. return (panel && panel !== true)
  53372. ? panel.clipPath(data, controller._transform)
  53373. : clone(data);
  53374. }
  53375. function pointsToRect(points) {
  53376. var xmin = mathMin$7(points[0][0], points[1][0]);
  53377. var ymin = mathMin$7(points[0][1], points[1][1]);
  53378. var xmax = mathMax$7(points[0][0], points[1][0]);
  53379. var ymax = mathMax$7(points[0][1], points[1][1]);
  53380. return {
  53381. x: xmin,
  53382. y: ymin,
  53383. width: xmax - xmin,
  53384. height: ymax - ymin
  53385. };
  53386. }
  53387. function resetCursor(controller, e, localCursorPoint) {
  53388. if (
  53389. // Check active
  53390. !controller._brushType
  53391. // resetCursor should be always called when mouse is in zr area,
  53392. // but not called when mouse is out of zr area to avoid bad influence
  53393. // if `mousemove`, `mouseup` are triggered from `document` event.
  53394. || isOutsideZrArea(controller, e)
  53395. ) {
  53396. return;
  53397. }
  53398. var zr = controller._zr;
  53399. var covers = controller._covers;
  53400. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  53401. // Check whether in covers.
  53402. if (!controller._dragging) {
  53403. for (var i = 0; i < covers.length; i++) {
  53404. var brushOption = covers[i].__brushOption;
  53405. if (currPanel
  53406. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  53407. && coverRenderers[brushOption.brushType].contain(
  53408. covers[i], localCursorPoint[0], localCursorPoint[1]
  53409. )
  53410. ) {
  53411. // Use cursor style set on cover.
  53412. return;
  53413. }
  53414. }
  53415. }
  53416. currPanel && zr.setCursorStyle('crosshair');
  53417. }
  53418. function preventDefault(e) {
  53419. var rawE = e.event;
  53420. rawE.preventDefault && rawE.preventDefault();
  53421. }
  53422. function mainShapeContain(cover, x, y) {
  53423. return cover.childOfName('main').contain(x, y);
  53424. }
  53425. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  53426. var creatingCover = controller._creatingCover;
  53427. var panel = controller._creatingPanel;
  53428. var thisBrushOption = controller._brushOption;
  53429. var eventParams;
  53430. controller._track.push(localCursorPoint.slice());
  53431. if (shouldShowCover(controller) || creatingCover) {
  53432. if (panel && !creatingCover) {
  53433. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  53434. var brushOption = clone(thisBrushOption);
  53435. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  53436. brushOption.panelId = panel === true ? null : panel.panelId;
  53437. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  53438. controller._covers.push(creatingCover);
  53439. }
  53440. if (creatingCover) {
  53441. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  53442. var coverBrushOption = creatingCover.__brushOption;
  53443. coverBrushOption.range = coverRenderer.getCreatingRange(
  53444. clipByPanel(controller, creatingCover, controller._track)
  53445. );
  53446. if (isEnd) {
  53447. endCreating(controller, creatingCover);
  53448. coverRenderer.updateCommon(controller, creatingCover);
  53449. }
  53450. updateCoverShape(controller, creatingCover);
  53451. eventParams = {isEnd: isEnd};
  53452. }
  53453. }
  53454. else if (
  53455. isEnd
  53456. && thisBrushOption.brushMode === 'single'
  53457. && thisBrushOption.removeOnClick
  53458. ) {
  53459. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  53460. // But a single click do not clear covers, because user may have casual
  53461. // clicks (for example, click on other component and do not expect covers
  53462. // disappear).
  53463. // Only some cover removed, trigger action, but not every click trigger action.
  53464. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  53465. eventParams = {isEnd: isEnd, removeOnClick: true};
  53466. }
  53467. }
  53468. return eventParams;
  53469. }
  53470. function determineBrushType(brushType, panel) {
  53471. if (brushType === 'auto') {
  53472. if (__DEV__) {
  53473. assert$1(
  53474. panel && panel.defaultBrushType,
  53475. 'MUST have defaultBrushType when brushType is "atuo"'
  53476. );
  53477. }
  53478. return panel.defaultBrushType;
  53479. }
  53480. return brushType;
  53481. }
  53482. var pointerHandlers = {
  53483. mousedown: function (e) {
  53484. if (this._dragging) {
  53485. // In case some browser do not support globalOut,
  53486. // and release mose out side the browser.
  53487. handleDragEnd(this, e);
  53488. }
  53489. else if (!e.target || !e.target.draggable) {
  53490. preventDefault(e);
  53491. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  53492. this._creatingCover = null;
  53493. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  53494. if (panel) {
  53495. this._dragging = true;
  53496. this._track = [localCursorPoint.slice()];
  53497. }
  53498. }
  53499. },
  53500. mousemove: function (e) {
  53501. var x = e.offsetX;
  53502. var y = e.offsetY;
  53503. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  53504. resetCursor(this, e, localCursorPoint);
  53505. if (this._dragging) {
  53506. preventDefault(e);
  53507. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  53508. eventParams && trigger$1(this, eventParams);
  53509. }
  53510. },
  53511. mouseup: function (e) {
  53512. handleDragEnd(this, e);
  53513. }
  53514. };
  53515. function handleDragEnd(controller, e) {
  53516. if (controller._dragging) {
  53517. preventDefault(e);
  53518. var x = e.offsetX;
  53519. var y = e.offsetY;
  53520. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  53521. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  53522. controller._dragging = false;
  53523. controller._track = [];
  53524. controller._creatingCover = null;
  53525. // trigger event shoule be at final, after procedure will be nested.
  53526. eventParams && trigger$1(controller, eventParams);
  53527. }
  53528. }
  53529. function isOutsideZrArea(controller, x, y) {
  53530. var zr = controller._zr;
  53531. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  53532. }
  53533. /**
  53534. * key: brushType
  53535. * @type {Object}
  53536. */
  53537. var coverRenderers = {
  53538. lineX: getLineRenderer(0),
  53539. lineY: getLineRenderer(1),
  53540. rect: {
  53541. createCover: function (controller, brushOption) {
  53542. return createBaseRectCover(
  53543. curry$2(
  53544. driftRect,
  53545. function (range) {
  53546. return range;
  53547. },
  53548. function (range) {
  53549. return range;
  53550. }
  53551. ),
  53552. controller,
  53553. brushOption,
  53554. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  53555. );
  53556. },
  53557. getCreatingRange: function (localTrack) {
  53558. var ends = getTrackEnds(localTrack);
  53559. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  53560. },
  53561. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53562. updateBaseRect(controller, cover, localRange, brushOption);
  53563. },
  53564. updateCommon: updateCommon,
  53565. contain: mainShapeContain
  53566. },
  53567. polygon: {
  53568. createCover: function (controller, brushOption) {
  53569. var cover = new Group();
  53570. // Do not use graphic.Polygon because graphic.Polyline do not close the
  53571. // border of the shape when drawing, which is a better experience for user.
  53572. cover.add(new Polyline({
  53573. name: 'main',
  53574. style: makeStyle(brushOption),
  53575. silent: true
  53576. }));
  53577. return cover;
  53578. },
  53579. getCreatingRange: function (localTrack) {
  53580. return localTrack;
  53581. },
  53582. endCreating: function (controller, cover) {
  53583. cover.remove(cover.childAt(0));
  53584. // Use graphic.Polygon close the shape.
  53585. cover.add(new Polygon({
  53586. name: 'main',
  53587. draggable: true,
  53588. drift: curry$2(driftPolygon, controller, cover),
  53589. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  53590. }));
  53591. },
  53592. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53593. cover.childAt(0).setShape({
  53594. points: clipByPanel(controller, cover, localRange)
  53595. });
  53596. },
  53597. updateCommon: updateCommon,
  53598. contain: mainShapeContain
  53599. }
  53600. };
  53601. function getLineRenderer(xyIndex) {
  53602. return {
  53603. createCover: function (controller, brushOption) {
  53604. return createBaseRectCover(
  53605. curry$2(
  53606. driftRect,
  53607. function (range) {
  53608. var rectRange = [range, [0, 100]];
  53609. xyIndex && rectRange.reverse();
  53610. return rectRange;
  53611. },
  53612. function (rectRange) {
  53613. return rectRange[xyIndex];
  53614. }
  53615. ),
  53616. controller,
  53617. brushOption,
  53618. [['w', 'e'], ['n', 's']][xyIndex]
  53619. );
  53620. },
  53621. getCreatingRange: function (localTrack) {
  53622. var ends = getTrackEnds(localTrack);
  53623. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  53624. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  53625. return [min, max];
  53626. },
  53627. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53628. var otherExtent;
  53629. // If brushWidth not specified, fit the panel.
  53630. var panel = getPanelByCover(controller, cover);
  53631. if (panel !== true && panel.getLinearBrushOtherExtent) {
  53632. otherExtent = panel.getLinearBrushOtherExtent(
  53633. xyIndex, controller._transform
  53634. );
  53635. }
  53636. else {
  53637. var zr = controller._zr;
  53638. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  53639. }
  53640. var rectRange = [localRange, otherExtent];
  53641. xyIndex && rectRange.reverse();
  53642. updateBaseRect(controller, cover, rectRange, brushOption);
  53643. },
  53644. updateCommon: updateCommon,
  53645. contain: mainShapeContain
  53646. };
  53647. }
  53648. /*
  53649. * Licensed to the Apache Software Foundation (ASF) under one
  53650. * or more contributor license agreements. See the NOTICE file
  53651. * distributed with this work for additional information
  53652. * regarding copyright ownership. The ASF licenses this file
  53653. * to you under the Apache License, Version 2.0 (the
  53654. * "License"); you may not use this file except in compliance
  53655. * with the License. You may obtain a copy of the License at
  53656. *
  53657. * http://www.apache.org/licenses/LICENSE-2.0
  53658. *
  53659. * Unless required by applicable law or agreed to in writing,
  53660. * software distributed under the License is distributed on an
  53661. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53662. * KIND, either express or implied. See the License for the
  53663. * specific language governing permissions and limitations
  53664. * under the License.
  53665. */
  53666. function makeRectPanelClipPath(rect) {
  53667. rect = normalizeRect(rect);
  53668. return function (localPoints, transform) {
  53669. return clipPointsByRect(localPoints, rect);
  53670. };
  53671. }
  53672. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  53673. rect = normalizeRect(rect);
  53674. return function (xyIndex) {
  53675. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  53676. var brushWidth = idx ? rect.width : rect.height;
  53677. var base = idx ? rect.x : rect.y;
  53678. return [base, base + (brushWidth || 0)];
  53679. };
  53680. }
  53681. function makeRectIsTargetByCursor(rect, api, targetModel) {
  53682. rect = normalizeRect(rect);
  53683. return function (e, localCursorPoint, transform) {
  53684. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  53685. && !onIrrelevantElement(e, api, targetModel);
  53686. };
  53687. }
  53688. // Consider width/height is negative.
  53689. function normalizeRect(rect) {
  53690. return BoundingRect.create(rect);
  53691. }
  53692. /*
  53693. * Licensed to the Apache Software Foundation (ASF) under one
  53694. * or more contributor license agreements. See the NOTICE file
  53695. * distributed with this work for additional information
  53696. * regarding copyright ownership. The ASF licenses this file
  53697. * to you under the Apache License, Version 2.0 (the
  53698. * "License"); you may not use this file except in compliance
  53699. * with the License. You may obtain a copy of the License at
  53700. *
  53701. * http://www.apache.org/licenses/LICENSE-2.0
  53702. *
  53703. * Unless required by applicable law or agreed to in writing,
  53704. * software distributed under the License is distributed on an
  53705. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53706. * KIND, either express or implied. See the License for the
  53707. * specific language governing permissions and limitations
  53708. * under the License.
  53709. */
  53710. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  53711. var AxisView$2 = extendComponentView({
  53712. type: 'parallelAxis',
  53713. /**
  53714. * @override
  53715. */
  53716. init: function (ecModel, api) {
  53717. AxisView$2.superApply(this, 'init', arguments);
  53718. /**
  53719. * @type {module:echarts/component/helper/BrushController}
  53720. */
  53721. (this._brushController = new BrushController(api.getZr()))
  53722. .on('brush', bind(this._onBrush, this));
  53723. },
  53724. /**
  53725. * @override
  53726. */
  53727. render: function (axisModel, ecModel, api, payload) {
  53728. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  53729. return;
  53730. }
  53731. this.axisModel = axisModel;
  53732. this.api = api;
  53733. this.group.removeAll();
  53734. var oldAxisGroup = this._axisGroup;
  53735. this._axisGroup = new Group();
  53736. this.group.add(this._axisGroup);
  53737. if (!axisModel.get('show')) {
  53738. return;
  53739. }
  53740. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  53741. var coordSys = coordSysModel.coordinateSystem;
  53742. var areaSelectStyle = axisModel.getAreaSelectStyle();
  53743. var areaWidth = areaSelectStyle.width;
  53744. var dim = axisModel.axis.dim;
  53745. var axisLayout = coordSys.getAxisLayout(dim);
  53746. var builderOpt = extend(
  53747. {strokeContainThreshold: areaWidth},
  53748. axisLayout
  53749. );
  53750. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  53751. each$1(elementList, axisBuilder.add, axisBuilder);
  53752. this._axisGroup.add(axisBuilder.getGroup());
  53753. this._refreshBrushController(
  53754. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  53755. );
  53756. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  53757. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  53758. },
  53759. // /**
  53760. // * @override
  53761. // */
  53762. // updateVisual: function (axisModel, ecModel, api, payload) {
  53763. // this._brushController && this._brushController
  53764. // .updateCovers(getCoverInfoList(axisModel));
  53765. // },
  53766. _refreshBrushController: function (
  53767. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  53768. ) {
  53769. // After filtering, axis may change, select area needs to be update.
  53770. var extent = axisModel.axis.getExtent();
  53771. var extentLen = extent[1] - extent[0];
  53772. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  53773. // width/height might be negative, which will be
  53774. // normalized in BoundingRect.
  53775. var rect = BoundingRect.create({
  53776. x: extent[0],
  53777. y: -areaWidth / 2,
  53778. width: extentLen,
  53779. height: areaWidth
  53780. });
  53781. rect.x -= extra;
  53782. rect.width += 2 * extra;
  53783. this._brushController
  53784. .mount({
  53785. enableGlobalPan: true,
  53786. rotation: builderOpt.rotation,
  53787. position: builderOpt.position
  53788. })
  53789. .setPanels([{
  53790. panelId: 'pl',
  53791. clipPath: makeRectPanelClipPath(rect),
  53792. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  53793. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  53794. }])
  53795. .enableBrush({
  53796. brushType: 'lineX',
  53797. brushStyle: areaSelectStyle,
  53798. removeOnClick: true
  53799. })
  53800. .updateCovers(getCoverInfoList(axisModel));
  53801. },
  53802. _onBrush: function (coverInfoList, opt) {
  53803. // Do not cache these object, because the mey be changed.
  53804. var axisModel = this.axisModel;
  53805. var axis = axisModel.axis;
  53806. var intervals = map(coverInfoList, function (coverInfo) {
  53807. return [
  53808. axis.coordToData(coverInfo.range[0], true),
  53809. axis.coordToData(coverInfo.range[1], true)
  53810. ];
  53811. });
  53812. // If realtime is true, action is not dispatched on drag end, because
  53813. // the drag end emits the same params with the last drag move event,
  53814. // and may have some delay when using touch pad.
  53815. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  53816. this.api.dispatchAction({
  53817. type: 'axisAreaSelect',
  53818. parallelAxisId: axisModel.id,
  53819. intervals: intervals
  53820. });
  53821. }
  53822. },
  53823. /**
  53824. * @override
  53825. */
  53826. dispose: function () {
  53827. this._brushController.dispose();
  53828. }
  53829. });
  53830. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  53831. return payload
  53832. && payload.type === 'axisAreaSelect'
  53833. && ecModel.findComponents(
  53834. {mainType: 'parallelAxis', query: payload}
  53835. )[0] === axisModel;
  53836. }
  53837. function getCoverInfoList(axisModel) {
  53838. var axis = axisModel.axis;
  53839. return map(axisModel.activeIntervals, function (interval) {
  53840. return {
  53841. brushType: 'lineX',
  53842. panelId: 'pl',
  53843. range: [
  53844. axis.dataToCoord(interval[0], true),
  53845. axis.dataToCoord(interval[1], true)
  53846. ]
  53847. };
  53848. });
  53849. }
  53850. function getCoordSysModel(axisModel, ecModel) {
  53851. return ecModel.getComponent(
  53852. 'parallel', axisModel.get('parallelIndex')
  53853. );
  53854. }
  53855. /*
  53856. * Licensed to the Apache Software Foundation (ASF) under one
  53857. * or more contributor license agreements. See the NOTICE file
  53858. * distributed with this work for additional information
  53859. * regarding copyright ownership. The ASF licenses this file
  53860. * to you under the Apache License, Version 2.0 (the
  53861. * "License"); you may not use this file except in compliance
  53862. * with the License. You may obtain a copy of the License at
  53863. *
  53864. * http://www.apache.org/licenses/LICENSE-2.0
  53865. *
  53866. * Unless required by applicable law or agreed to in writing,
  53867. * software distributed under the License is distributed on an
  53868. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53869. * KIND, either express or implied. See the License for the
  53870. * specific language governing permissions and limitations
  53871. * under the License.
  53872. */
  53873. /*
  53874. * Licensed to the Apache Software Foundation (ASF) under one
  53875. * or more contributor license agreements. See the NOTICE file
  53876. * distributed with this work for additional information
  53877. * regarding copyright ownership. The ASF licenses this file
  53878. * to you under the Apache License, Version 2.0 (the
  53879. * "License"); you may not use this file except in compliance
  53880. * with the License. You may obtain a copy of the License at
  53881. *
  53882. * http://www.apache.org/licenses/LICENSE-2.0
  53883. *
  53884. * Unless required by applicable law or agreed to in writing,
  53885. * software distributed under the License is distributed on an
  53886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53887. * KIND, either express or implied. See the License for the
  53888. * specific language governing permissions and limitations
  53889. * under the License.
  53890. */
  53891. var CLICK_THRESHOLD = 5; // > 4
  53892. // Parallel view
  53893. extendComponentView({
  53894. type: 'parallel',
  53895. render: function (parallelModel, ecModel, api) {
  53896. this._model = parallelModel;
  53897. this._api = api;
  53898. if (!this._handlers) {
  53899. this._handlers = {};
  53900. each$1(handlers, function (handler, eventName) {
  53901. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  53902. }, this);
  53903. }
  53904. createOrUpdate(
  53905. this,
  53906. '_throttledDispatchExpand',
  53907. parallelModel.get('axisExpandRate'),
  53908. 'fixRate'
  53909. );
  53910. },
  53911. dispose: function (ecModel, api) {
  53912. each$1(this._handlers, function (handler, eventName) {
  53913. api.getZr().off(eventName, handler);
  53914. });
  53915. this._handlers = null;
  53916. },
  53917. /**
  53918. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  53919. */
  53920. _throttledDispatchExpand: function (opt) {
  53921. this._dispatchExpand(opt);
  53922. },
  53923. _dispatchExpand: function (opt) {
  53924. opt && this._api.dispatchAction(
  53925. extend({type: 'parallelAxisExpand'}, opt)
  53926. );
  53927. }
  53928. });
  53929. var handlers = {
  53930. mousedown: function (e) {
  53931. if (checkTrigger(this, 'click')) {
  53932. this._mouseDownPoint = [e.offsetX, e.offsetY];
  53933. }
  53934. },
  53935. mouseup: function (e) {
  53936. var mouseDownPoint = this._mouseDownPoint;
  53937. if (checkTrigger(this, 'click') && mouseDownPoint) {
  53938. var point = [e.offsetX, e.offsetY];
  53939. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  53940. + Math.pow(mouseDownPoint[1] - point[1], 2);
  53941. if (dist > CLICK_THRESHOLD) {
  53942. return;
  53943. }
  53944. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  53945. [e.offsetX, e.offsetY]
  53946. );
  53947. result.behavior !== 'none' && this._dispatchExpand({
  53948. axisExpandWindow: result.axisExpandWindow
  53949. });
  53950. }
  53951. this._mouseDownPoint = null;
  53952. },
  53953. mousemove: function (e) {
  53954. // Should do nothing when brushing.
  53955. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  53956. return;
  53957. }
  53958. var model = this._model;
  53959. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  53960. [e.offsetX, e.offsetY]
  53961. );
  53962. var behavior = result.behavior;
  53963. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  53964. this._throttledDispatchExpand(
  53965. behavior === 'none'
  53966. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  53967. : {
  53968. axisExpandWindow: result.axisExpandWindow,
  53969. // Jumping uses animation, and sliding suppresses animation.
  53970. animation: behavior === 'jump' ? null : false
  53971. }
  53972. );
  53973. }
  53974. };
  53975. function checkTrigger(view, triggerOn) {
  53976. var model = view._model;
  53977. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  53978. }
  53979. registerPreprocessor(parallelPreprocessor);
  53980. /*
  53981. * Licensed to the Apache Software Foundation (ASF) under one
  53982. * or more contributor license agreements. See the NOTICE file
  53983. * distributed with this work for additional information
  53984. * regarding copyright ownership. The ASF licenses this file
  53985. * to you under the Apache License, Version 2.0 (the
  53986. * "License"); you may not use this file except in compliance
  53987. * with the License. You may obtain a copy of the License at
  53988. *
  53989. * http://www.apache.org/licenses/LICENSE-2.0
  53990. *
  53991. * Unless required by applicable law or agreed to in writing,
  53992. * software distributed under the License is distributed on an
  53993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53994. * KIND, either express or implied. See the License for the
  53995. * specific language governing permissions and limitations
  53996. * under the License.
  53997. */
  53998. SeriesModel.extend({
  53999. type: 'series.parallel',
  54000. dependencies: ['parallel'],
  54001. visualColorAccessPath: 'lineStyle.color',
  54002. getInitialData: function (option, ecModel) {
  54003. var source = this.getSource();
  54004. setEncodeAndDimensions(source, this);
  54005. return createListFromArray(source, this);
  54006. },
  54007. /**
  54008. * User can get data raw indices on 'axisAreaSelected' event received.
  54009. *
  54010. * @public
  54011. * @param {string} activeState 'active' or 'inactive' or 'normal'
  54012. * @return {Array.<number>} Raw indices
  54013. */
  54014. getRawIndicesByActiveState: function (activeState) {
  54015. var coordSys = this.coordinateSystem;
  54016. var data = this.getData();
  54017. var indices = [];
  54018. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  54019. if (activeState === theActiveState) {
  54020. indices.push(data.getRawIndex(dataIndex));
  54021. }
  54022. });
  54023. return indices;
  54024. },
  54025. defaultOption: {
  54026. zlevel: 0, // 一级层叠
  54027. z: 2, // 二级层叠
  54028. coordinateSystem: 'parallel',
  54029. parallelIndex: 0,
  54030. label: {
  54031. show: false
  54032. },
  54033. inactiveOpacity: 0.05,
  54034. activeOpacity: 1,
  54035. lineStyle: {
  54036. width: 1,
  54037. opacity: 0.45,
  54038. type: 'solid'
  54039. },
  54040. emphasis: {
  54041. label: {
  54042. show: false
  54043. }
  54044. },
  54045. progressive: 500,
  54046. smooth: false, // true | false | number
  54047. animationEasing: 'linear'
  54048. }
  54049. });
  54050. function setEncodeAndDimensions(source, seriesModel) {
  54051. // The mapping of parallelAxis dimension to data dimension can
  54052. // be specified in parallelAxis.option.dim. For example, if
  54053. // parallelAxis.option.dim is 'dim3', it mapping to the third
  54054. // dimension of data. But `data.encode` has higher priority.
  54055. // Moreover, parallelModel.dimension should not be regarded as data
  54056. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  54057. if (source.encodeDefine) {
  54058. return;
  54059. }
  54060. var parallelModel = seriesModel.ecModel.getComponent(
  54061. 'parallel', seriesModel.get('parallelIndex')
  54062. );
  54063. if (!parallelModel) {
  54064. return;
  54065. }
  54066. var encodeDefine = source.encodeDefine = createHashMap();
  54067. each$1(parallelModel.dimensions, function (axisDim) {
  54068. var dataDimIndex = convertDimNameToNumber(axisDim);
  54069. encodeDefine.set(axisDim, dataDimIndex);
  54070. });
  54071. }
  54072. function convertDimNameToNumber(dimName) {
  54073. return +dimName.replace('dim', '');
  54074. }
  54075. /*
  54076. * Licensed to the Apache Software Foundation (ASF) under one
  54077. * or more contributor license agreements. See the NOTICE file
  54078. * distributed with this work for additional information
  54079. * regarding copyright ownership. The ASF licenses this file
  54080. * to you under the Apache License, Version 2.0 (the
  54081. * "License"); you may not use this file except in compliance
  54082. * with the License. You may obtain a copy of the License at
  54083. *
  54084. * http://www.apache.org/licenses/LICENSE-2.0
  54085. *
  54086. * Unless required by applicable law or agreed to in writing,
  54087. * software distributed under the License is distributed on an
  54088. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54089. * KIND, either express or implied. See the License for the
  54090. * specific language governing permissions and limitations
  54091. * under the License.
  54092. */
  54093. var DEFAULT_SMOOTH = 0.3;
  54094. var ParallelView = Chart.extend({
  54095. type: 'parallel',
  54096. init: function () {
  54097. /**
  54098. * @type {module:zrender/container/Group}
  54099. * @private
  54100. */
  54101. this._dataGroup = new Group();
  54102. this.group.add(this._dataGroup);
  54103. /**
  54104. * @type {module:echarts/data/List}
  54105. */
  54106. this._data;
  54107. /**
  54108. * @type {boolean}
  54109. */
  54110. this._initialized;
  54111. },
  54112. /**
  54113. * @override
  54114. */
  54115. render: function (seriesModel, ecModel, api, payload) {
  54116. var dataGroup = this._dataGroup;
  54117. var data = seriesModel.getData();
  54118. var oldData = this._data;
  54119. var coordSys = seriesModel.coordinateSystem;
  54120. var dimensions = coordSys.dimensions;
  54121. var seriesScope = makeSeriesScope$2(seriesModel);
  54122. data.diff(oldData)
  54123. .add(add)
  54124. .update(update)
  54125. .remove(remove)
  54126. .execute();
  54127. function add(newDataIndex) {
  54128. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  54129. updateElCommon(line, data, newDataIndex, seriesScope);
  54130. }
  54131. function update(newDataIndex, oldDataIndex) {
  54132. var line = oldData.getItemGraphicEl(oldDataIndex);
  54133. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  54134. data.setItemGraphicEl(newDataIndex, line);
  54135. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  54136. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  54137. updateElCommon(line, data, newDataIndex, seriesScope);
  54138. }
  54139. function remove(oldDataIndex) {
  54140. var line = oldData.getItemGraphicEl(oldDataIndex);
  54141. dataGroup.remove(line);
  54142. }
  54143. // First create
  54144. if (!this._initialized) {
  54145. this._initialized = true;
  54146. var clipPath = createGridClipShape(
  54147. coordSys, seriesModel, function () {
  54148. // Callback will be invoked immediately if there is no animation
  54149. setTimeout(function () {
  54150. dataGroup.removeClipPath();
  54151. });
  54152. }
  54153. );
  54154. dataGroup.setClipPath(clipPath);
  54155. }
  54156. this._data = data;
  54157. },
  54158. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  54159. this._initialized = true;
  54160. this._data = null;
  54161. this._dataGroup.removeAll();
  54162. },
  54163. incrementalRender: function (taskParams, seriesModel, ecModel) {
  54164. var data = seriesModel.getData();
  54165. var coordSys = seriesModel.coordinateSystem;
  54166. var dimensions = coordSys.dimensions;
  54167. var seriesScope = makeSeriesScope$2(seriesModel);
  54168. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  54169. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  54170. line.incremental = true;
  54171. updateElCommon(line, data, dataIndex, seriesScope);
  54172. }
  54173. },
  54174. dispose: function () {},
  54175. // _renderForProgressive: function (seriesModel) {
  54176. // var dataGroup = this._dataGroup;
  54177. // var data = seriesModel.getData();
  54178. // var oldData = this._data;
  54179. // var coordSys = seriesModel.coordinateSystem;
  54180. // var dimensions = coordSys.dimensions;
  54181. // var option = seriesModel.option;
  54182. // var progressive = option.progressive;
  54183. // var smooth = option.smooth ? SMOOTH : null;
  54184. // // In progressive animation is disabled, so use simple data diff,
  54185. // // which effects performance less.
  54186. // // (Typically performance for data with length 7000+ like:
  54187. // // simpleDiff: 60ms, addEl: 184ms,
  54188. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  54189. // if (simpleDiff(oldData, data, dimensions)) {
  54190. // dataGroup.removeAll();
  54191. // data.each(function (dataIndex) {
  54192. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  54193. // });
  54194. // }
  54195. // updateElCommon(data, progressive, smooth);
  54196. // // Consider switch between progressive and not.
  54197. // data.__plProgressive = true;
  54198. // this._data = data;
  54199. // },
  54200. /**
  54201. * @override
  54202. */
  54203. remove: function () {
  54204. this._dataGroup && this._dataGroup.removeAll();
  54205. this._data = null;
  54206. }
  54207. });
  54208. function createGridClipShape(coordSys, seriesModel, cb) {
  54209. var parallelModel = coordSys.model;
  54210. var rect = coordSys.getRect();
  54211. var rectEl = new Rect({
  54212. shape: {
  54213. x: rect.x,
  54214. y: rect.y,
  54215. width: rect.width,
  54216. height: rect.height
  54217. }
  54218. });
  54219. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  54220. rectEl.setShape(dim, 0);
  54221. initProps(rectEl, {
  54222. shape: {
  54223. width: rect.width,
  54224. height: rect.height
  54225. }
  54226. }, seriesModel, cb);
  54227. return rectEl;
  54228. }
  54229. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  54230. var points = [];
  54231. for (var i = 0; i < dimensions.length; i++) {
  54232. var dimName = dimensions[i];
  54233. var value = data.get(data.mapDimension(dimName), dataIndex);
  54234. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  54235. points.push(coordSys.dataToPoint(value, dimName));
  54236. }
  54237. }
  54238. return points;
  54239. }
  54240. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  54241. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  54242. var line = new Polyline({
  54243. shape: {points: points},
  54244. silent: true,
  54245. z2: 10
  54246. });
  54247. dataGroup.add(line);
  54248. data.setItemGraphicEl(dataIndex, line);
  54249. return line;
  54250. }
  54251. function makeSeriesScope$2(seriesModel) {
  54252. var smooth = seriesModel.get('smooth', true);
  54253. smooth === true && (smooth = DEFAULT_SMOOTH);
  54254. return {
  54255. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  54256. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  54257. };
  54258. }
  54259. function updateElCommon(el, data, dataIndex, seriesScope) {
  54260. var lineStyle = seriesScope.lineStyle;
  54261. if (data.hasItemOption) {
  54262. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  54263. lineStyle = lineStyleModel.getLineStyle();
  54264. }
  54265. el.useStyle(lineStyle);
  54266. var elStyle = el.style;
  54267. elStyle.fill = null;
  54268. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  54269. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  54270. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  54271. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  54272. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  54273. }
  54274. // function simpleDiff(oldData, newData, dimensions) {
  54275. // var oldLen;
  54276. // if (!oldData
  54277. // || !oldData.__plProgressive
  54278. // || (oldLen = oldData.count()) !== newData.count()
  54279. // ) {
  54280. // return true;
  54281. // }
  54282. // var dimLen = dimensions.length;
  54283. // for (var i = 0; i < oldLen; i++) {
  54284. // for (var j = 0; j < dimLen; j++) {
  54285. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  54286. // return true;
  54287. // }
  54288. // }
  54289. // }
  54290. // return false;
  54291. // }
  54292. // FIXME
  54293. // 公用方法?
  54294. function isEmptyValue(val, axisType) {
  54295. return axisType === 'category'
  54296. ? val == null
  54297. : (val == null || isNaN(val)); // axisType === 'value'
  54298. }
  54299. /*
  54300. * Licensed to the Apache Software Foundation (ASF) under one
  54301. * or more contributor license agreements. See the NOTICE file
  54302. * distributed with this work for additional information
  54303. * regarding copyright ownership. The ASF licenses this file
  54304. * to you under the Apache License, Version 2.0 (the
  54305. * "License"); you may not use this file except in compliance
  54306. * with the License. You may obtain a copy of the License at
  54307. *
  54308. * http://www.apache.org/licenses/LICENSE-2.0
  54309. *
  54310. * Unless required by applicable law or agreed to in writing,
  54311. * software distributed under the License is distributed on an
  54312. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54313. * KIND, either express or implied. See the License for the
  54314. * specific language governing permissions and limitations
  54315. * under the License.
  54316. */
  54317. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  54318. var parallelVisual = {
  54319. seriesType: 'parallel',
  54320. reset: function (seriesModel, ecModel, api) {
  54321. var itemStyleModel = seriesModel.getModel('itemStyle');
  54322. var lineStyleModel = seriesModel.getModel('lineStyle');
  54323. var globalColors = ecModel.get('color');
  54324. var color = lineStyleModel.get('color')
  54325. || itemStyleModel.get('color')
  54326. || globalColors[seriesModel.seriesIndex % globalColors.length];
  54327. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  54328. var activeOpacity = seriesModel.get('activeOpacity');
  54329. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  54330. var coordSys = seriesModel.coordinateSystem;
  54331. var data = seriesModel.getData();
  54332. var opacityMap = {
  54333. normal: lineStyle.opacity,
  54334. active: activeOpacity,
  54335. inactive: inactiveOpacity
  54336. };
  54337. data.setVisual('color', color);
  54338. function progress(params, data) {
  54339. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  54340. var opacity = opacityMap[activeState];
  54341. if (activeState === 'normal' && data.hasItemOption) {
  54342. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  54343. itemOpacity != null && (opacity = itemOpacity);
  54344. }
  54345. data.setItemVisual(dataIndex, 'opacity', opacity);
  54346. }, params.start, params.end);
  54347. }
  54348. return {progress: progress};
  54349. }
  54350. };
  54351. /*
  54352. * Licensed to the Apache Software Foundation (ASF) under one
  54353. * or more contributor license agreements. See the NOTICE file
  54354. * distributed with this work for additional information
  54355. * regarding copyright ownership. The ASF licenses this file
  54356. * to you under the Apache License, Version 2.0 (the
  54357. * "License"); you may not use this file except in compliance
  54358. * with the License. You may obtain a copy of the License at
  54359. *
  54360. * http://www.apache.org/licenses/LICENSE-2.0
  54361. *
  54362. * Unless required by applicable law or agreed to in writing,
  54363. * software distributed under the License is distributed on an
  54364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54365. * KIND, either express or implied. See the License for the
  54366. * specific language governing permissions and limitations
  54367. * under the License.
  54368. */
  54369. registerVisual(parallelVisual);
  54370. /*
  54371. * Licensed to the Apache Software Foundation (ASF) under one
  54372. * or more contributor license agreements. See the NOTICE file
  54373. * distributed with this work for additional information
  54374. * regarding copyright ownership. The ASF licenses this file
  54375. * to you under the Apache License, Version 2.0 (the
  54376. * "License"); you may not use this file except in compliance
  54377. * with the License. You may obtain a copy of the License at
  54378. *
  54379. * http://www.apache.org/licenses/LICENSE-2.0
  54380. *
  54381. * Unless required by applicable law or agreed to in writing,
  54382. * software distributed under the License is distributed on an
  54383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54384. * KIND, either express or implied. See the License for the
  54385. * specific language governing permissions and limitations
  54386. * under the License.
  54387. */
  54388. var SankeySeries = SeriesModel.extend({
  54389. type: 'series.sankey',
  54390. layoutInfo: null,
  54391. levelModels: null,
  54392. /**
  54393. * Init a graph data structure from data in option series
  54394. *
  54395. * @param {Object} option the object used to config echarts view
  54396. * @return {module:echarts/data/List} storage initial data
  54397. */
  54398. getInitialData: function (option, ecModel) {
  54399. var links = option.edges || option.links;
  54400. var nodes = option.data || option.nodes;
  54401. var levels = option.levels;
  54402. var levelModels = this.levelModels = {};
  54403. for (var i = 0; i < levels.length; i++) {
  54404. if (levels[i].depth != null && levels[i].depth >= 0) {
  54405. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  54406. }
  54407. else {
  54408. if (__DEV__) {
  54409. throw new Error('levels[i].depth is mandatory and should be natural number');
  54410. }
  54411. }
  54412. }
  54413. if (nodes && links) {
  54414. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  54415. return graph.data;
  54416. }
  54417. function beforeLink(nodeData, edgeData) {
  54418. nodeData.wrapMethod('getItemModel', function (model, idx) {
  54419. model.customizeGetParent(function (path) {
  54420. var parentModel = this.parentModel;
  54421. var nodeDepth = parentModel.getData().getItemLayout(idx).depth;
  54422. var levelModel = parentModel.levelModels[nodeDepth];
  54423. return levelModel || this.parentModel;
  54424. });
  54425. return model;
  54426. });
  54427. edgeData.wrapMethod('getItemModel', function (model, idx) {
  54428. model.customizeGetParent(function (path) {
  54429. var parentModel = this.parentModel;
  54430. var edge = parentModel.getGraph().getEdgeByIndex(idx);
  54431. var depth = edge.node1.getLayout().depth;
  54432. var levelModel = parentModel.levelModels[depth];
  54433. return levelModel || this.parentModel;
  54434. });
  54435. return model;
  54436. });
  54437. }
  54438. },
  54439. setNodePosition: function (dataIndex, localPosition) {
  54440. var dataItem = this.option.data[dataIndex];
  54441. dataItem.localX = localPosition[0];
  54442. dataItem.localY = localPosition[1];
  54443. },
  54444. /**
  54445. * Return the graphic data structure
  54446. *
  54447. * @return {module:echarts/data/Graph} graphic data structure
  54448. */
  54449. getGraph: function () {
  54450. return this.getData().graph;
  54451. },
  54452. /**
  54453. * Get edge data of graphic data structure
  54454. *
  54455. * @return {module:echarts/data/List} data structure of list
  54456. */
  54457. getEdgeData: function () {
  54458. return this.getGraph().edgeData;
  54459. },
  54460. /**
  54461. * @override
  54462. */
  54463. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  54464. // dataType === 'node' or empty do not show tooltip by default
  54465. if (dataType === 'edge') {
  54466. var params = this.getDataParams(dataIndex, dataType);
  54467. var rawDataOpt = params.data;
  54468. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  54469. if (params.value) {
  54470. html += ' : ' + params.value;
  54471. }
  54472. return encodeHTML(html);
  54473. }
  54474. else if (dataType === 'node') {
  54475. var node = this.getGraph().getNodeByIndex(dataIndex);
  54476. var value = node.getLayout().value;
  54477. var name = this.getDataParams(dataIndex, dataType).data.name;
  54478. if (value) {
  54479. var html = name + ' : ' + value;
  54480. }
  54481. return encodeHTML(html);
  54482. }
  54483. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  54484. },
  54485. optionUpdated: function () {
  54486. var option = this.option;
  54487. if (option.focusNodeAdjacency === true) {
  54488. option.focusNodeAdjacency = 'allEdges';
  54489. }
  54490. },
  54491. defaultOption: {
  54492. zlevel: 0,
  54493. z: 2,
  54494. coordinateSystem: 'view',
  54495. layout: null,
  54496. // The position of the whole view
  54497. left: '5%',
  54498. top: '5%',
  54499. right: '20%',
  54500. bottom: '5%',
  54501. // Value can be 'vertical'
  54502. orient: 'horizontal',
  54503. // The dx of the node
  54504. nodeWidth: 20,
  54505. // The vertical distance between two nodes
  54506. nodeGap: 8,
  54507. // Control if the node can move or not
  54508. draggable: true,
  54509. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  54510. focusNodeAdjacency: false,
  54511. // The number of iterations to change the position of the node
  54512. layoutIterations: 32,
  54513. label: {
  54514. show: true,
  54515. position: 'right',
  54516. color: '#000',
  54517. fontSize: 12
  54518. },
  54519. levels: [],
  54520. // Value can be 'left' or 'right'
  54521. nodeAlign: 'justify',
  54522. itemStyle: {
  54523. borderWidth: 1,
  54524. borderColor: '#333'
  54525. },
  54526. lineStyle: {
  54527. color: '#314656',
  54528. opacity: 0.2,
  54529. curveness: 0.5
  54530. },
  54531. emphasis: {
  54532. label: {
  54533. show: true
  54534. },
  54535. lineStyle: {
  54536. opacity: 0.6
  54537. }
  54538. },
  54539. animationEasing: 'linear',
  54540. animationDuration: 1000
  54541. }
  54542. });
  54543. /*
  54544. * Licensed to the Apache Software Foundation (ASF) under one
  54545. * or more contributor license agreements. See the NOTICE file
  54546. * distributed with this work for additional information
  54547. * regarding copyright ownership. The ASF licenses this file
  54548. * to you under the Apache License, Version 2.0 (the
  54549. * "License"); you may not use this file except in compliance
  54550. * with the License. You may obtain a copy of the License at
  54551. *
  54552. * http://www.apache.org/licenses/LICENSE-2.0
  54553. *
  54554. * Unless required by applicable law or agreed to in writing,
  54555. * software distributed under the License is distributed on an
  54556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54557. * KIND, either express or implied. See the License for the
  54558. * specific language governing permissions and limitations
  54559. * under the License.
  54560. */
  54561. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  54562. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  54563. function getItemOpacity$1(item, opacityPath) {
  54564. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  54565. }
  54566. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  54567. var el = item.getGraphicEl();
  54568. var opacity = getItemOpacity$1(item, opacityPath);
  54569. if (opacityRatio != null) {
  54570. opacity == null && (opacity = 1);
  54571. opacity *= opacityRatio;
  54572. }
  54573. el.downplay && el.downplay();
  54574. el.traverse(function (child) {
  54575. if (child.type !== 'group') {
  54576. child.setStyle('opacity', opacity);
  54577. }
  54578. });
  54579. }
  54580. function fadeInItem$1(item, opacityPath) {
  54581. var opacity = getItemOpacity$1(item, opacityPath);
  54582. var el = item.getGraphicEl();
  54583. el.highlight && el.highlight();
  54584. el.traverse(function (child) {
  54585. if (child.type !== 'group') {
  54586. child.setStyle('opacity', opacity);
  54587. }
  54588. });
  54589. }
  54590. var SankeyShape = extendShape({
  54591. shape: {
  54592. x1: 0, y1: 0,
  54593. x2: 0, y2: 0,
  54594. cpx1: 0, cpy1: 0,
  54595. cpx2: 0, cpy2: 0,
  54596. extent: 0,
  54597. orient: ''
  54598. },
  54599. buildPath: function (ctx, shape) {
  54600. var extent = shape.extent;
  54601. ctx.moveTo(shape.x1, shape.y1);
  54602. ctx.bezierCurveTo(
  54603. shape.cpx1, shape.cpy1,
  54604. shape.cpx2, shape.cpy2,
  54605. shape.x2, shape.y2
  54606. );
  54607. if (shape.orient === 'vertical') {
  54608. ctx.lineTo(shape.x2 + extent, shape.y2);
  54609. ctx.bezierCurveTo(
  54610. shape.cpx2 + extent, shape.cpy2,
  54611. shape.cpx1 + extent, shape.cpy1,
  54612. shape.x1 + extent, shape.y1
  54613. );
  54614. }
  54615. else {
  54616. ctx.lineTo(shape.x2, shape.y2 + extent);
  54617. ctx.bezierCurveTo(
  54618. shape.cpx2, shape.cpy2 + extent,
  54619. shape.cpx1, shape.cpy1 + extent,
  54620. shape.x1, shape.y1 + extent
  54621. );
  54622. }
  54623. ctx.closePath();
  54624. }
  54625. });
  54626. extendChartView({
  54627. type: 'sankey',
  54628. /**
  54629. * @private
  54630. * @type {module:echarts/chart/sankey/SankeySeries}
  54631. */
  54632. _model: null,
  54633. /**
  54634. * @private
  54635. * @type {boolean}
  54636. */
  54637. _focusAdjacencyDisabled: false,
  54638. render: function (seriesModel, ecModel, api) {
  54639. var sankeyView = this;
  54640. var graph = seriesModel.getGraph();
  54641. var group = this.group;
  54642. var layoutInfo = seriesModel.layoutInfo;
  54643. // view width
  54644. var width = layoutInfo.width;
  54645. // view height
  54646. var height = layoutInfo.height;
  54647. var nodeData = seriesModel.getData();
  54648. var edgeData = seriesModel.getData('edge');
  54649. var orient = seriesModel.get('orient');
  54650. this._model = seriesModel;
  54651. group.removeAll();
  54652. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  54653. // generate a bezire Curve for each edge
  54654. graph.eachEdge(function (edge) {
  54655. var curve = new SankeyShape();
  54656. curve.dataIndex = edge.dataIndex;
  54657. curve.seriesIndex = seriesModel.seriesIndex;
  54658. curve.dataType = 'edge';
  54659. var lineStyleModel = edge.getModel('lineStyle');
  54660. var curvature = lineStyleModel.get('curveness');
  54661. var n1Layout = edge.node1.getLayout();
  54662. var node1Model = edge.node1.getModel();
  54663. var dragX1 = node1Model.get('localX');
  54664. var dragY1 = node1Model.get('localY');
  54665. var n2Layout = edge.node2.getLayout();
  54666. var node2Model = edge.node2.getModel();
  54667. var dragX2 = node2Model.get('localX');
  54668. var dragY2 = node2Model.get('localY');
  54669. var edgeLayout = edge.getLayout();
  54670. var x1;
  54671. var y1;
  54672. var x2;
  54673. var y2;
  54674. var cpx1;
  54675. var cpy1;
  54676. var cpx2;
  54677. var cpy2;
  54678. curve.shape.extent = Math.max(1, edgeLayout.dy);
  54679. curve.shape.orient = orient;
  54680. if (orient === 'vertical') {
  54681. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  54682. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  54683. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  54684. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  54685. cpx1 = x1;
  54686. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  54687. cpx2 = x2;
  54688. cpy2 = y1 * curvature + y2 * (1 - curvature);
  54689. }
  54690. else {
  54691. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  54692. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  54693. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  54694. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  54695. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  54696. cpy1 = y1;
  54697. cpx2 = x1 * curvature + x2 * (1 - curvature);
  54698. cpy2 = y2;
  54699. }
  54700. curve.setShape({
  54701. x1: x1,
  54702. y1: y1,
  54703. x2: x2,
  54704. y2: y2,
  54705. cpx1: cpx1,
  54706. cpy1: cpy1,
  54707. cpx2: cpx2,
  54708. cpy2: cpy2
  54709. });
  54710. curve.setStyle(lineStyleModel.getItemStyle());
  54711. // Special color, use source node color or target node color
  54712. switch (curve.style.fill) {
  54713. case 'source':
  54714. curve.style.fill = edge.node1.getVisual('color');
  54715. break;
  54716. case 'target':
  54717. curve.style.fill = edge.node2.getVisual('color');
  54718. break;
  54719. }
  54720. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  54721. group.add(curve);
  54722. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  54723. });
  54724. // Generate a rect for each node
  54725. graph.eachNode(function (node) {
  54726. var layout = node.getLayout();
  54727. var itemModel = node.getModel();
  54728. var dragX = itemModel.get('localX');
  54729. var dragY = itemModel.get('localY');
  54730. var labelModel = itemModel.getModel('label');
  54731. var labelHoverModel = itemModel.getModel('emphasis.label');
  54732. var rect = new Rect({
  54733. shape: {
  54734. x: dragX != null ? dragX * width : layout.x,
  54735. y: dragY != null ? dragY * height : layout.y,
  54736. width: layout.dx,
  54737. height: layout.dy
  54738. },
  54739. style: itemModel.getModel('itemStyle').getItemStyle()
  54740. });
  54741. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  54742. setLabelStyle(
  54743. rect.style, hoverStyle, labelModel, labelHoverModel,
  54744. {
  54745. labelFetcher: seriesModel,
  54746. labelDataIndex: node.dataIndex,
  54747. defaultText: node.id,
  54748. isRectText: true
  54749. }
  54750. );
  54751. rect.setStyle('fill', node.getVisual('color'));
  54752. setHoverStyle(rect, hoverStyle);
  54753. group.add(rect);
  54754. nodeData.setItemGraphicEl(node.dataIndex, rect);
  54755. rect.dataType = 'node';
  54756. });
  54757. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  54758. var itemModel = nodeData.getItemModel(dataIndex);
  54759. if (itemModel.get('draggable')) {
  54760. el.drift = function (dx, dy) {
  54761. sankeyView._focusAdjacencyDisabled = true;
  54762. this.shape.x += dx;
  54763. this.shape.y += dy;
  54764. this.dirty();
  54765. api.dispatchAction({
  54766. type: 'dragNode',
  54767. seriesId: seriesModel.id,
  54768. dataIndex: nodeData.getRawIndex(dataIndex),
  54769. localX: this.shape.x / width,
  54770. localY: this.shape.y / height
  54771. });
  54772. };
  54773. el.ondragend = function () {
  54774. sankeyView._focusAdjacencyDisabled = false;
  54775. };
  54776. el.draggable = true;
  54777. el.cursor = 'move';
  54778. }
  54779. if (itemModel.get('focusNodeAdjacency')) {
  54780. el.off('mouseover').on('mouseover', function () {
  54781. if (!sankeyView._focusAdjacencyDisabled) {
  54782. sankeyView._clearTimer();
  54783. api.dispatchAction({
  54784. type: 'focusNodeAdjacency',
  54785. seriesId: seriesModel.id,
  54786. dataIndex: el.dataIndex
  54787. });
  54788. }
  54789. });
  54790. el.off('mouseout').on('mouseout', function () {
  54791. if (!sankeyView._focusAdjacencyDisabled) {
  54792. sankeyView._dispatchUnfocus(api);
  54793. }
  54794. });
  54795. }
  54796. });
  54797. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  54798. var edgeModel = edgeData.getItemModel(dataIndex);
  54799. if (edgeModel.get('focusNodeAdjacency')) {
  54800. el.off('mouseover').on('mouseover', function () {
  54801. if (!sankeyView._focusAdjacencyDisabled) {
  54802. sankeyView._clearTimer();
  54803. api.dispatchAction({
  54804. type: 'focusNodeAdjacency',
  54805. seriesId: seriesModel.id,
  54806. edgeDataIndex: el.dataIndex
  54807. });
  54808. }
  54809. });
  54810. el.off('mouseout').on('mouseout', function () {
  54811. if (!sankeyView._focusAdjacencyDisabled) {
  54812. sankeyView._dispatchUnfocus(api);
  54813. }
  54814. });
  54815. }
  54816. });
  54817. if (!this._data && seriesModel.get('animation')) {
  54818. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  54819. group.removeClipPath();
  54820. }));
  54821. }
  54822. this._data = seriesModel.getData();
  54823. },
  54824. dispose: function () {
  54825. this._clearTimer();
  54826. },
  54827. _dispatchUnfocus: function (api) {
  54828. var self = this;
  54829. this._clearTimer();
  54830. this._unfocusDelayTimer = setTimeout(function () {
  54831. self._unfocusDelayTimer = null;
  54832. api.dispatchAction({
  54833. type: 'unfocusNodeAdjacency',
  54834. seriesId: self._model.id
  54835. });
  54836. }, 500);
  54837. },
  54838. _clearTimer: function () {
  54839. if (this._unfocusDelayTimer) {
  54840. clearTimeout(this._unfocusDelayTimer);
  54841. this._unfocusDelayTimer = null;
  54842. }
  54843. },
  54844. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  54845. var data = this._model.getData();
  54846. var graph = data.graph;
  54847. var dataIndex = payload.dataIndex;
  54848. var itemModel = data.getItemModel(dataIndex);
  54849. var edgeDataIndex = payload.edgeDataIndex;
  54850. if (dataIndex == null && edgeDataIndex == null) {
  54851. return;
  54852. }
  54853. var node = graph.getNodeByIndex(dataIndex);
  54854. var edge = graph.getEdgeByIndex(edgeDataIndex);
  54855. graph.eachNode(function (node) {
  54856. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  54857. });
  54858. graph.eachEdge(function (edge) {
  54859. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  54860. });
  54861. if (node) {
  54862. fadeInItem$1(node, nodeOpacityPath$1);
  54863. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  54864. if (focusNodeAdj === 'outEdges') {
  54865. each$1(node.outEdges, function (edge) {
  54866. if (edge.dataIndex < 0) {
  54867. return;
  54868. }
  54869. fadeInItem$1(edge, lineOpacityPath$1);
  54870. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54871. });
  54872. }
  54873. else if (focusNodeAdj === 'inEdges') {
  54874. each$1(node.inEdges, function (edge) {
  54875. if (edge.dataIndex < 0) {
  54876. return;
  54877. }
  54878. fadeInItem$1(edge, lineOpacityPath$1);
  54879. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54880. });
  54881. }
  54882. else if (focusNodeAdj === 'allEdges') {
  54883. each$1(node.edges, function (edge) {
  54884. if (edge.dataIndex < 0) {
  54885. return;
  54886. }
  54887. fadeInItem$1(edge, lineOpacityPath$1);
  54888. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54889. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54890. });
  54891. }
  54892. }
  54893. if (edge) {
  54894. fadeInItem$1(edge, lineOpacityPath$1);
  54895. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  54896. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  54897. }
  54898. },
  54899. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  54900. var graph = this._model.getGraph();
  54901. graph.eachNode(function (node) {
  54902. fadeOutItem$1(node, nodeOpacityPath$1);
  54903. });
  54904. graph.eachEdge(function (edge) {
  54905. fadeOutItem$1(edge, lineOpacityPath$1);
  54906. });
  54907. }
  54908. });
  54909. // Add animation to the view
  54910. function createGridClipShape$1(rect, seriesModel, cb) {
  54911. var rectEl = new Rect({
  54912. shape: {
  54913. x: rect.x - 10,
  54914. y: rect.y - 10,
  54915. width: 0,
  54916. height: rect.height + 20
  54917. }
  54918. });
  54919. initProps(rectEl, {
  54920. shape: {
  54921. width: rect.width + 20,
  54922. height: rect.height + 20
  54923. }
  54924. }, seriesModel, cb);
  54925. return rectEl;
  54926. }
  54927. /*
  54928. * Licensed to the Apache Software Foundation (ASF) under one
  54929. * or more contributor license agreements. See the NOTICE file
  54930. * distributed with this work for additional information
  54931. * regarding copyright ownership. The ASF licenses this file
  54932. * to you under the Apache License, Version 2.0 (the
  54933. * "License"); you may not use this file except in compliance
  54934. * with the License. You may obtain a copy of the License at
  54935. *
  54936. * http://www.apache.org/licenses/LICENSE-2.0
  54937. *
  54938. * Unless required by applicable law or agreed to in writing,
  54939. * software distributed under the License is distributed on an
  54940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54941. * KIND, either express or implied. See the License for the
  54942. * specific language governing permissions and limitations
  54943. * under the License.
  54944. */
  54945. registerAction({
  54946. type: 'dragNode',
  54947. event: 'dragnode',
  54948. // here can only use 'update' now, other value is not support in echarts.
  54949. update: 'update'
  54950. }, function (payload, ecModel) {
  54951. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  54952. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  54953. });
  54954. });
  54955. /*
  54956. * Licensed to the Apache Software Foundation (ASF) under one
  54957. * or more contributor license agreements. See the NOTICE file
  54958. * distributed with this work for additional information
  54959. * regarding copyright ownership. The ASF licenses this file
  54960. * to you under the Apache License, Version 2.0 (the
  54961. * "License"); you may not use this file except in compliance
  54962. * with the License. You may obtain a copy of the License at
  54963. *
  54964. * http://www.apache.org/licenses/LICENSE-2.0
  54965. *
  54966. * Unless required by applicable law or agreed to in writing,
  54967. * software distributed under the License is distributed on an
  54968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54969. * KIND, either express or implied. See the License for the
  54970. * specific language governing permissions and limitations
  54971. * under the License.
  54972. */
  54973. var sankeyLayout = function (ecModel, api, payload) {
  54974. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  54975. var nodeWidth = seriesModel.get('nodeWidth');
  54976. var nodeGap = seriesModel.get('nodeGap');
  54977. var layoutInfo = getViewRect$4(seriesModel, api);
  54978. seriesModel.layoutInfo = layoutInfo;
  54979. var width = layoutInfo.width;
  54980. var height = layoutInfo.height;
  54981. var graph = seriesModel.getGraph();
  54982. var nodes = graph.nodes;
  54983. var edges = graph.edges;
  54984. computeNodeValues(nodes);
  54985. var filteredNodes = filter(nodes, function (node) {
  54986. return node.getLayout().value === 0;
  54987. });
  54988. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  54989. var orient = seriesModel.get('orient');
  54990. var nodeAlign = seriesModel.get('nodeAlign');
  54991. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  54992. });
  54993. };
  54994. /**
  54995. * Get the layout position of the whole view
  54996. *
  54997. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  54998. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  54999. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  55000. */
  55001. function getViewRect$4(seriesModel, api) {
  55002. return getLayoutRect(
  55003. seriesModel.getBoxLayoutParams(), {
  55004. width: api.getWidth(),
  55005. height: api.getHeight()
  55006. }
  55007. );
  55008. }
  55009. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  55010. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  55011. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  55012. computeEdgeDepths(nodes, orient);
  55013. }
  55014. /**
  55015. * Compute the value of each node by summing the associated edge's value
  55016. *
  55017. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55018. */
  55019. function computeNodeValues(nodes) {
  55020. each$1(nodes, function (node) {
  55021. var value1 = sum(node.outEdges, getEdgeValue);
  55022. var value2 = sum(node.inEdges, getEdgeValue);
  55023. var value = Math.max(value1, value2);
  55024. node.setLayout({value: value}, true);
  55025. });
  55026. }
  55027. /**
  55028. * Compute the x-position for each node.
  55029. *
  55030. * Here we use Kahn algorithm to detect cycle when we traverse
  55031. * the node to computer the initial x position.
  55032. *
  55033. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55034. * @param {number} nodeWidth the dx of the node
  55035. * @param {number} width the whole width of the area to draw the view
  55036. */
  55037. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  55038. // Used to mark whether the edge is deleted. if it is deleted,
  55039. // the value is 0, otherwise it is 1.
  55040. var remainEdges = [];
  55041. // Storage each node's indegree.
  55042. var indegreeArr = [];
  55043. //Used to storage the node with indegree is equal to 0.
  55044. var zeroIndegrees = [];
  55045. var nextTargetNode = [];
  55046. var x = 0;
  55047. var kx = 0;
  55048. for (var i = 0; i < edges.length; i++) {
  55049. remainEdges[i] = 1;
  55050. }
  55051. for (i = 0; i < nodes.length; i++) {
  55052. indegreeArr[i] = nodes[i].inEdges.length;
  55053. if (indegreeArr[i] === 0) {
  55054. zeroIndegrees.push(nodes[i]);
  55055. }
  55056. }
  55057. var maxNodeDepth = -1;
  55058. // Traversing nodes using topological sorting to calculate the
  55059. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  55060. // position of the nodes.
  55061. while (zeroIndegrees.length) {
  55062. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  55063. var node = zeroIndegrees[idx];
  55064. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55065. var isItemDepth = item.depth != null && item.depth >= 0;
  55066. if (isItemDepth && item.depth > maxNodeDepth) {
  55067. maxNodeDepth = item.depth;
  55068. }
  55069. node.setLayout({depth: isItemDepth ? item.depth : x}, true);
  55070. orient === 'vertical'
  55071. ? node.setLayout({dy: nodeWidth}, true)
  55072. : node.setLayout({dx: nodeWidth}, true);
  55073. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  55074. var edge = node.outEdges[edgeIdx];
  55075. var indexEdge = edges.indexOf(edge);
  55076. remainEdges[indexEdge] = 0;
  55077. var targetNode = edge.node2;
  55078. var nodeIndex = nodes.indexOf(targetNode);
  55079. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  55080. nextTargetNode.push(targetNode);
  55081. }
  55082. }
  55083. }
  55084. ++x;
  55085. zeroIndegrees = nextTargetNode;
  55086. nextTargetNode = [];
  55087. }
  55088. for (i = 0; i < remainEdges.length; i++) {
  55089. if (remainEdges[i] === 1) {
  55090. throw new Error('Sankey is a DAG, the original data has cycle!');
  55091. }
  55092. }
  55093. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  55094. if (nodeAlign && nodeAlign !== 'left') {
  55095. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  55096. }
  55097. var kx = orient === 'vertical'
  55098. ? (height - nodeWidth) / maxDepth
  55099. : (width - nodeWidth) / maxDepth;
  55100. scaleNodeBreadths(nodes, kx, orient);
  55101. }
  55102. function isNodeDepth(node) {
  55103. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55104. return item.depth != null && item.depth >= 0;
  55105. }
  55106. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  55107. if (nodeAlign === 'right') {
  55108. var nextSourceNode = [];
  55109. var remainNodes = nodes;
  55110. var nodeHeight = 0;
  55111. while (remainNodes.length) {
  55112. for (var i = 0; i < remainNodes.length; i++) {
  55113. var node = remainNodes[i];
  55114. node.setLayout({skNodeHeight: nodeHeight}, true);
  55115. for (var j = 0; j < node.inEdges.length; j++) {
  55116. var edge = node.inEdges[j];
  55117. if (nextSourceNode.indexOf(edge.node1) < 0) {
  55118. nextSourceNode.push(edge.node1);
  55119. }
  55120. }
  55121. }
  55122. remainNodes = nextSourceNode;
  55123. nextSourceNode = [];
  55124. ++nodeHeight;
  55125. }
  55126. each$1(nodes, function (node) {
  55127. if (!isNodeDepth(node)) {
  55128. node.setLayout({depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)}, true);
  55129. }
  55130. });
  55131. }
  55132. else if (nodeAlign === 'justify') {
  55133. moveSinksRight(nodes, maxDepth);
  55134. }
  55135. }
  55136. /**
  55137. * All the node without outEgdes are assigned maximum x-position and
  55138. * be aligned in the last column.
  55139. *
  55140. * @param {module:echarts/data/Graph~Node} nodes. node of sankey view.
  55141. * @param {number} maxDepth. use to assign to node without outEdges as x-position.
  55142. */
  55143. function moveSinksRight(nodes, maxDepth) {
  55144. each$1(nodes, function (node) {
  55145. if (!isNodeDepth(node) && !node.outEdges.length) {
  55146. node.setLayout({depth: maxDepth}, true);
  55147. }
  55148. });
  55149. }
  55150. /**
  55151. * Scale node x-position to the width
  55152. *
  55153. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55154. * @param {number} kx multiple used to scale nodes
  55155. */
  55156. function scaleNodeBreadths(nodes, kx, orient) {
  55157. each$1(nodes, function (node) {
  55158. var nodeDepth = node.getLayout().depth * kx;
  55159. orient === 'vertical'
  55160. ? node.setLayout({y: nodeDepth}, true)
  55161. : node.setLayout({x: nodeDepth}, true);
  55162. });
  55163. }
  55164. /**
  55165. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  55166. *
  55167. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55168. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55169. * @param {number} height the whole height of the area to draw the view
  55170. * @param {number} nodeGap the vertical distance between two nodes
  55171. * in the same column.
  55172. * @param {number} iterations the number of iterations for the algorithm
  55173. */
  55174. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  55175. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  55176. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  55177. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55178. for (var alpha = 1; iterations > 0; iterations--) {
  55179. // 0.99 is a experience parameter, ensure that each iterations of
  55180. // changes as small as possible.
  55181. alpha *= 0.99;
  55182. relaxRightToLeft(nodesByBreadth, alpha, orient);
  55183. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55184. relaxLeftToRight(nodesByBreadth, alpha, orient);
  55185. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55186. }
  55187. }
  55188. function prepareNodesByBreadth(nodes, orient) {
  55189. var nodesByBreadth = [];
  55190. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  55191. var groupResult = groupData(nodes, function (node) {
  55192. return node.getLayout()[keyAttr];
  55193. });
  55194. groupResult.keys.sort(function (a, b) {
  55195. return a - b;
  55196. });
  55197. each$1(groupResult.keys, function (key) {
  55198. nodesByBreadth.push(groupResult.buckets.get(key));
  55199. });
  55200. return nodesByBreadth;
  55201. }
  55202. /**
  55203. * Compute the original y-position for each node
  55204. *
  55205. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55206. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55207. * group by the array of all sankey nodes based on the nodes x-position.
  55208. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55209. * @param {number} height the whole height of the area to draw the view
  55210. * @param {number} nodeGap the vertical distance between two nodes
  55211. */
  55212. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  55213. var minKy = Infinity;
  55214. each$1(nodesByBreadth, function (nodes) {
  55215. var n = nodes.length;
  55216. var sum = 0;
  55217. each$1(nodes, function (node) {
  55218. sum += node.getLayout().value;
  55219. });
  55220. var ky = orient === 'vertical'
  55221. ? (width - (n - 1) * nodeGap) / sum
  55222. : (height - (n - 1) * nodeGap) / sum;
  55223. if (ky < minKy) {
  55224. minKy = ky;
  55225. }
  55226. });
  55227. each$1(nodesByBreadth, function (nodes) {
  55228. each$1(nodes, function (node, i) {
  55229. var nodeDy = node.getLayout().value * minKy;
  55230. if (orient === 'vertical') {
  55231. node.setLayout({x: i}, true);
  55232. node.setLayout({dx: nodeDy}, true);
  55233. }
  55234. else {
  55235. node.setLayout({y: i}, true);
  55236. node.setLayout({dy: nodeDy}, true);
  55237. }
  55238. });
  55239. });
  55240. each$1(edges, function (edge) {
  55241. var edgeDy = +edge.getValue() * minKy;
  55242. edge.setLayout({dy: edgeDy}, true);
  55243. });
  55244. }
  55245. /**
  55246. * Resolve the collision of initialized depth (y-position)
  55247. *
  55248. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55249. * group by the array of all sankey nodes based on the nodes x-position.
  55250. * @param {number} nodeGap the vertical distance between two nodes
  55251. * @param {number} height the whole height of the area to draw the view
  55252. */
  55253. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  55254. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55255. each$1(nodesByBreadth, function (nodes) {
  55256. nodes.sort(function (a, b) {
  55257. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  55258. });
  55259. var nodeX;
  55260. var node;
  55261. var dy;
  55262. var y0 = 0;
  55263. var n = nodes.length;
  55264. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  55265. for (var i = 0; i < n; i++) {
  55266. node = nodes[i];
  55267. dy = y0 - node.getLayout()[keyAttr];
  55268. if (dy > 0) {
  55269. nodeX = node.getLayout()[keyAttr] + dy;
  55270. orient === 'vertical'
  55271. ? node.setLayout({x: nodeX}, true)
  55272. : node.setLayout({y: nodeX}, true);
  55273. }
  55274. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  55275. }
  55276. var viewWidth = orient === 'vertical' ? width : height;
  55277. // If the bottommost node goes outside the bounds, push it back up
  55278. dy = y0 - nodeGap - viewWidth;
  55279. if (dy > 0) {
  55280. nodeX = node.getLayout()[keyAttr] - dy;
  55281. orient === 'vertical'
  55282. ? node.setLayout({x: nodeX}, true)
  55283. : node.setLayout({y: nodeX}, true);
  55284. y0 = nodeX;
  55285. for (i = n - 2; i >= 0; --i) {
  55286. node = nodes[i];
  55287. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  55288. if (dy > 0) {
  55289. nodeX = node.getLayout()[keyAttr] - dy;
  55290. orient === 'vertical'
  55291. ? node.setLayout({x: nodeX}, true)
  55292. : node.setLayout({y: nodeX}, true);
  55293. }
  55294. y0 = node.getLayout()[keyAttr];
  55295. }
  55296. }
  55297. });
  55298. }
  55299. /**
  55300. * Change the y-position of the nodes, except most the right side nodes
  55301. *
  55302. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55303. * group by the array of all sankey nodes based on the node x-position.
  55304. * @param {number} alpha parameter used to adjust the nodes y-position
  55305. */
  55306. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  55307. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  55308. each$1(nodes, function (node) {
  55309. if (node.outEdges.length) {
  55310. var y = sum(node.outEdges, weightedTarget, orient)
  55311. / sum(node.outEdges, getEdgeValue, orient);
  55312. if (orient === 'vertical') {
  55313. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55314. node.setLayout({x: nodeX}, true);
  55315. }
  55316. else {
  55317. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55318. node.setLayout({y: nodeY}, true);
  55319. }
  55320. }
  55321. });
  55322. });
  55323. }
  55324. function weightedTarget(edge, orient) {
  55325. return center$1(edge.node2, orient) * edge.getValue();
  55326. }
  55327. function weightedSource(edge, orient) {
  55328. return center$1(edge.node1, orient) * edge.getValue();
  55329. }
  55330. function center$1(node, orient) {
  55331. return orient === 'vertical'
  55332. ? node.getLayout().x + node.getLayout().dx / 2
  55333. : node.getLayout().y + node.getLayout().dy / 2;
  55334. }
  55335. function getEdgeValue(edge) {
  55336. return edge.getValue();
  55337. }
  55338. function sum(array, f, orient) {
  55339. var sum = 0;
  55340. var len = array.length;
  55341. var i = -1;
  55342. while (++i < len) {
  55343. var value = +f.call(array, array[i], orient);
  55344. if (!isNaN(value)) {
  55345. sum += value;
  55346. }
  55347. }
  55348. return sum;
  55349. }
  55350. /**
  55351. * Change the y-position of the nodes, except most the left side nodes
  55352. *
  55353. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55354. * group by the array of all sankey nodes based on the node x-position.
  55355. * @param {number} alpha parameter used to adjust the nodes y-position
  55356. */
  55357. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  55358. each$1(nodesByBreadth, function (nodes) {
  55359. each$1(nodes, function (node) {
  55360. if (node.inEdges.length) {
  55361. var y = sum(node.inEdges, weightedSource, orient)
  55362. / sum(node.inEdges, getEdgeValue, orient);
  55363. if (orient === 'vertical') {
  55364. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55365. node.setLayout({x: nodeX}, true);
  55366. }
  55367. else {
  55368. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55369. node.setLayout({y: nodeY}, true);
  55370. }
  55371. }
  55372. });
  55373. });
  55374. }
  55375. /**
  55376. * Compute the depth(y-position) of each edge
  55377. *
  55378. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55379. */
  55380. function computeEdgeDepths(nodes, orient) {
  55381. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55382. each$1(nodes, function (node) {
  55383. node.outEdges.sort(function (a, b) {
  55384. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  55385. });
  55386. node.inEdges.sort(function (a, b) {
  55387. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  55388. });
  55389. });
  55390. each$1(nodes, function (node) {
  55391. var sy = 0;
  55392. var ty = 0;
  55393. each$1(node.outEdges, function (edge) {
  55394. edge.setLayout({sy: sy}, true);
  55395. sy += edge.getLayout().dy;
  55396. });
  55397. each$1(node.inEdges, function (edge) {
  55398. edge.setLayout({ty: ty}, true);
  55399. ty += edge.getLayout().dy;
  55400. });
  55401. });
  55402. }
  55403. /*
  55404. * Licensed to the Apache Software Foundation (ASF) under one
  55405. * or more contributor license agreements. See the NOTICE file
  55406. * distributed with this work for additional information
  55407. * regarding copyright ownership. The ASF licenses this file
  55408. * to you under the Apache License, Version 2.0 (the
  55409. * "License"); you may not use this file except in compliance
  55410. * with the License. You may obtain a copy of the License at
  55411. *
  55412. * http://www.apache.org/licenses/LICENSE-2.0
  55413. *
  55414. * Unless required by applicable law or agreed to in writing,
  55415. * software distributed under the License is distributed on an
  55416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55417. * KIND, either express or implied. See the License for the
  55418. * specific language governing permissions and limitations
  55419. * under the License.
  55420. */
  55421. var sankeyVisual = function (ecModel, payload) {
  55422. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  55423. var graph = seriesModel.getGraph();
  55424. var nodes = graph.nodes;
  55425. if (nodes.length) {
  55426. var minValue = Infinity;
  55427. var maxValue = -Infinity;
  55428. each$1(nodes, function (node) {
  55429. var nodeValue = node.getLayout().value;
  55430. if (nodeValue < minValue) {
  55431. minValue = nodeValue;
  55432. }
  55433. if (nodeValue > maxValue) {
  55434. maxValue = nodeValue;
  55435. }
  55436. });
  55437. each$1(nodes, function (node) {
  55438. var mapping = new VisualMapping({
  55439. type: 'color',
  55440. mappingMethod: 'linear',
  55441. dataExtent: [minValue, maxValue],
  55442. visual: seriesModel.get('color')
  55443. });
  55444. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  55445. var customColor = node.getModel().get('itemStyle.color');
  55446. customColor != null
  55447. ? node.setVisual('color', customColor)
  55448. : node.setVisual('color', mapValueToColor);
  55449. });
  55450. }
  55451. });
  55452. };
  55453. /*
  55454. * Licensed to the Apache Software Foundation (ASF) under one
  55455. * or more contributor license agreements. See the NOTICE file
  55456. * distributed with this work for additional information
  55457. * regarding copyright ownership. The ASF licenses this file
  55458. * to you under the Apache License, Version 2.0 (the
  55459. * "License"); you may not use this file except in compliance
  55460. * with the License. You may obtain a copy of the License at
  55461. *
  55462. * http://www.apache.org/licenses/LICENSE-2.0
  55463. *
  55464. * Unless required by applicable law or agreed to in writing,
  55465. * software distributed under the License is distributed on an
  55466. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55467. * KIND, either express or implied. See the License for the
  55468. * specific language governing permissions and limitations
  55469. * under the License.
  55470. */
  55471. registerLayout(sankeyLayout);
  55472. registerVisual(sankeyVisual);
  55473. /*
  55474. * Licensed to the Apache Software Foundation (ASF) under one
  55475. * or more contributor license agreements. See the NOTICE file
  55476. * distributed with this work for additional information
  55477. * regarding copyright ownership. The ASF licenses this file
  55478. * to you under the Apache License, Version 2.0 (the
  55479. * "License"); you may not use this file except in compliance
  55480. * with the License. You may obtain a copy of the License at
  55481. *
  55482. * http://www.apache.org/licenses/LICENSE-2.0
  55483. *
  55484. * Unless required by applicable law or agreed to in writing,
  55485. * software distributed under the License is distributed on an
  55486. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55487. * KIND, either express or implied. See the License for the
  55488. * specific language governing permissions and limitations
  55489. * under the License.
  55490. */
  55491. var seriesModelMixin = {
  55492. /**
  55493. * @private
  55494. * @type {string}
  55495. */
  55496. _baseAxisDim: null,
  55497. /**
  55498. * @override
  55499. */
  55500. getInitialData: function (option, ecModel) {
  55501. // When both types of xAxis and yAxis are 'value', layout is
  55502. // needed to be specified by user. Otherwise, layout can be
  55503. // judged by which axis is category.
  55504. var ordinalMeta;
  55505. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  55506. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  55507. var xAxisType = xAxisModel.get('type');
  55508. var yAxisType = yAxisModel.get('type');
  55509. var addOrdinal;
  55510. // FIXME
  55511. // Consider time axis.
  55512. if (xAxisType === 'category') {
  55513. option.layout = 'horizontal';
  55514. ordinalMeta = xAxisModel.getOrdinalMeta();
  55515. addOrdinal = true;
  55516. }
  55517. else if (yAxisType === 'category') {
  55518. option.layout = 'vertical';
  55519. ordinalMeta = yAxisModel.getOrdinalMeta();
  55520. addOrdinal = true;
  55521. }
  55522. else {
  55523. option.layout = option.layout || 'horizontal';
  55524. }
  55525. var coordDims = ['x', 'y'];
  55526. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  55527. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  55528. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  55529. var axisModels = [xAxisModel, yAxisModel];
  55530. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  55531. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  55532. var data = option.data;
  55533. // ??? FIXME make a stage to perform data transfrom.
  55534. // MUST create a new data, consider setOption({}) again.
  55535. if (data && addOrdinal) {
  55536. var newOptionData = [];
  55537. each$1(data, function (item, index) {
  55538. var newItem;
  55539. if (item.value && isArray(item.value)) {
  55540. newItem = item.value.slice();
  55541. item.value.unshift(index);
  55542. }
  55543. else if (isArray(item)) {
  55544. newItem = item.slice();
  55545. item.unshift(index);
  55546. }
  55547. else {
  55548. newItem = item;
  55549. }
  55550. newOptionData.push(newItem);
  55551. });
  55552. option.data = newOptionData;
  55553. }
  55554. var defaultValueDimensions = this.defaultValueDimensions;
  55555. var coordDimensions = [{
  55556. name: baseAxisDim,
  55557. type: getDimensionTypeByAxis(baseAxisType),
  55558. ordinalMeta: ordinalMeta,
  55559. otherDims: {
  55560. tooltip: false,
  55561. itemName: 0
  55562. },
  55563. dimsDef: ['base']
  55564. }, {
  55565. name: otherAxisDim,
  55566. type: getDimensionTypeByAxis(otherAxisType),
  55567. dimsDef: defaultValueDimensions.slice()
  55568. }];
  55569. return createListSimply(
  55570. this,
  55571. {
  55572. coordDimensions: coordDimensions,
  55573. dimensionsCount: defaultValueDimensions.length + 1,
  55574. encodeDefaulter: curry(
  55575. makeSeriesEncodeForAxisCoordSys, coordDimensions, this
  55576. )
  55577. }
  55578. );
  55579. },
  55580. /**
  55581. * If horizontal, base axis is x, otherwise y.
  55582. * @override
  55583. */
  55584. getBaseAxis: function () {
  55585. var dim = this._baseAxisDim;
  55586. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  55587. }
  55588. };
  55589. /*
  55590. * Licensed to the Apache Software Foundation (ASF) under one
  55591. * or more contributor license agreements. See the NOTICE file
  55592. * distributed with this work for additional information
  55593. * regarding copyright ownership. The ASF licenses this file
  55594. * to you under the Apache License, Version 2.0 (the
  55595. * "License"); you may not use this file except in compliance
  55596. * with the License. You may obtain a copy of the License at
  55597. *
  55598. * http://www.apache.org/licenses/LICENSE-2.0
  55599. *
  55600. * Unless required by applicable law or agreed to in writing,
  55601. * software distributed under the License is distributed on an
  55602. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55603. * KIND, either express or implied. See the License for the
  55604. * specific language governing permissions and limitations
  55605. * under the License.
  55606. */
  55607. var BoxplotSeries = SeriesModel.extend({
  55608. type: 'series.boxplot',
  55609. dependencies: ['xAxis', 'yAxis', 'grid'],
  55610. // TODO
  55611. // box width represents group size, so dimension should have 'size'.
  55612. /**
  55613. * @see <https://en.wikipedia.org/wiki/Box_plot>
  55614. * The meanings of 'min' and 'max' depend on user,
  55615. * and echarts do not need to know it.
  55616. * @readOnly
  55617. */
  55618. defaultValueDimensions: [
  55619. {name: 'min', defaultTooltip: true},
  55620. {name: 'Q1', defaultTooltip: true},
  55621. {name: 'median', defaultTooltip: true},
  55622. {name: 'Q3', defaultTooltip: true},
  55623. {name: 'max', defaultTooltip: true}
  55624. ],
  55625. /**
  55626. * @type {Array.<string>}
  55627. * @readOnly
  55628. */
  55629. dimensions: null,
  55630. /**
  55631. * @override
  55632. */
  55633. defaultOption: {
  55634. zlevel: 0, // 一级层叠
  55635. z: 2, // 二级层叠
  55636. coordinateSystem: 'cartesian2d',
  55637. legendHoverLink: true,
  55638. hoverAnimation: true,
  55639. // xAxisIndex: 0,
  55640. // yAxisIndex: 0,
  55641. layout: null, // 'horizontal' or 'vertical'
  55642. boxWidth: [7, 50], // [min, max] can be percent of band width.
  55643. itemStyle: {
  55644. color: '#fff',
  55645. borderWidth: 1
  55646. },
  55647. emphasis: {
  55648. itemStyle: {
  55649. borderWidth: 2,
  55650. shadowBlur: 5,
  55651. shadowOffsetX: 2,
  55652. shadowOffsetY: 2,
  55653. shadowColor: 'rgba(0,0,0,0.4)'
  55654. }
  55655. },
  55656. animationEasing: 'elasticOut',
  55657. animationDuration: 800
  55658. }
  55659. });
  55660. mixin(BoxplotSeries, seriesModelMixin, true);
  55661. /*
  55662. * Licensed to the Apache Software Foundation (ASF) under one
  55663. * or more contributor license agreements. See the NOTICE file
  55664. * distributed with this work for additional information
  55665. * regarding copyright ownership. The ASF licenses this file
  55666. * to you under the Apache License, Version 2.0 (the
  55667. * "License"); you may not use this file except in compliance
  55668. * with the License. You may obtain a copy of the License at
  55669. *
  55670. * http://www.apache.org/licenses/LICENSE-2.0
  55671. *
  55672. * Unless required by applicable law or agreed to in writing,
  55673. * software distributed under the License is distributed on an
  55674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55675. * KIND, either express or implied. See the License for the
  55676. * specific language governing permissions and limitations
  55677. * under the License.
  55678. */
  55679. // Update common properties
  55680. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  55681. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  55682. var BoxplotView = Chart.extend({
  55683. type: 'boxplot',
  55684. render: function (seriesModel, ecModel, api) {
  55685. var data = seriesModel.getData();
  55686. var group = this.group;
  55687. var oldData = this._data;
  55688. // There is no old data only when first rendering or switching from
  55689. // stream mode to normal mode, where previous elements should be removed.
  55690. if (!this._data) {
  55691. group.removeAll();
  55692. }
  55693. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  55694. data.diff(oldData)
  55695. .add(function (newIdx) {
  55696. if (data.hasValue(newIdx)) {
  55697. var itemLayout = data.getItemLayout(newIdx);
  55698. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  55699. data.setItemGraphicEl(newIdx, symbolEl);
  55700. group.add(symbolEl);
  55701. }
  55702. })
  55703. .update(function (newIdx, oldIdx) {
  55704. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  55705. // Empty data
  55706. if (!data.hasValue(newIdx)) {
  55707. group.remove(symbolEl);
  55708. return;
  55709. }
  55710. var itemLayout = data.getItemLayout(newIdx);
  55711. if (!symbolEl) {
  55712. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  55713. }
  55714. else {
  55715. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  55716. }
  55717. group.add(symbolEl);
  55718. data.setItemGraphicEl(newIdx, symbolEl);
  55719. })
  55720. .remove(function (oldIdx) {
  55721. var el = oldData.getItemGraphicEl(oldIdx);
  55722. el && group.remove(el);
  55723. })
  55724. .execute();
  55725. this._data = data;
  55726. },
  55727. remove: function (ecModel) {
  55728. var group = this.group;
  55729. var data = this._data;
  55730. this._data = null;
  55731. data && data.eachItemGraphicEl(function (el) {
  55732. el && group.remove(el);
  55733. });
  55734. },
  55735. dispose: noop
  55736. });
  55737. var BoxPath = Path.extend({
  55738. type: 'boxplotBoxPath',
  55739. shape: {},
  55740. buildPath: function (ctx, shape) {
  55741. var ends = shape.points;
  55742. var i = 0;
  55743. ctx.moveTo(ends[i][0], ends[i][1]);
  55744. i++;
  55745. for (; i < 4; i++) {
  55746. ctx.lineTo(ends[i][0], ends[i][1]);
  55747. }
  55748. ctx.closePath();
  55749. for (; i < ends.length; i++) {
  55750. ctx.moveTo(ends[i][0], ends[i][1]);
  55751. i++;
  55752. ctx.lineTo(ends[i][0], ends[i][1]);
  55753. }
  55754. }
  55755. });
  55756. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  55757. var ends = itemLayout.ends;
  55758. var el = new BoxPath({
  55759. shape: {
  55760. points: isInit
  55761. ? transInit(ends, constDim, itemLayout)
  55762. : ends
  55763. }
  55764. });
  55765. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  55766. return el;
  55767. }
  55768. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  55769. var seriesModel = data.hostModel;
  55770. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  55771. updateMethod(
  55772. el,
  55773. {shape: {points: itemLayout.ends}},
  55774. seriesModel,
  55775. dataIndex
  55776. );
  55777. var itemModel = data.getItemModel(dataIndex);
  55778. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  55779. var borderColor = data.getItemVisual(dataIndex, 'color');
  55780. // Exclude borderColor.
  55781. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  55782. itemStyle.stroke = borderColor;
  55783. itemStyle.strokeNoScale = true;
  55784. el.useStyle(itemStyle);
  55785. el.z2 = 100;
  55786. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  55787. setHoverStyle(el, hoverStyle);
  55788. }
  55789. function transInit(points, dim, itemLayout) {
  55790. return map(points, function (point) {
  55791. point = point.slice();
  55792. point[dim] = itemLayout.initBaseline;
  55793. return point;
  55794. });
  55795. }
  55796. /*
  55797. * Licensed to the Apache Software Foundation (ASF) under one
  55798. * or more contributor license agreements. See the NOTICE file
  55799. * distributed with this work for additional information
  55800. * regarding copyright ownership. The ASF licenses this file
  55801. * to you under the Apache License, Version 2.0 (the
  55802. * "License"); you may not use this file except in compliance
  55803. * with the License. You may obtain a copy of the License at
  55804. *
  55805. * http://www.apache.org/licenses/LICENSE-2.0
  55806. *
  55807. * Unless required by applicable law or agreed to in writing,
  55808. * software distributed under the License is distributed on an
  55809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55810. * KIND, either express or implied. See the License for the
  55811. * specific language governing permissions and limitations
  55812. * under the License.
  55813. */
  55814. var borderColorQuery = ['itemStyle', 'borderColor'];
  55815. var boxplotVisual = function (ecModel, api) {
  55816. var globalColors = ecModel.get('color');
  55817. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  55818. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  55819. var data = seriesModel.getData();
  55820. data.setVisual({
  55821. legendSymbol: 'roundRect',
  55822. // Use name 'color' but not 'borderColor' for legend usage and
  55823. // visual coding from other component like dataRange.
  55824. color: seriesModel.get(borderColorQuery) || defaulColor
  55825. });
  55826. // Only visible series has each data be visual encoded
  55827. if (!ecModel.isSeriesFiltered(seriesModel)) {
  55828. data.each(function (idx) {
  55829. var itemModel = data.getItemModel(idx);
  55830. data.setItemVisual(
  55831. idx,
  55832. {color: itemModel.get(borderColorQuery, true)}
  55833. );
  55834. });
  55835. }
  55836. });
  55837. };
  55838. /*
  55839. * Licensed to the Apache Software Foundation (ASF) under one
  55840. * or more contributor license agreements. See the NOTICE file
  55841. * distributed with this work for additional information
  55842. * regarding copyright ownership. The ASF licenses this file
  55843. * to you under the Apache License, Version 2.0 (the
  55844. * "License"); you may not use this file except in compliance
  55845. * with the License. You may obtain a copy of the License at
  55846. *
  55847. * http://www.apache.org/licenses/LICENSE-2.0
  55848. *
  55849. * Unless required by applicable law or agreed to in writing,
  55850. * software distributed under the License is distributed on an
  55851. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55852. * KIND, either express or implied. See the License for the
  55853. * specific language governing permissions and limitations
  55854. * under the License.
  55855. */
  55856. var each$13 = each$1;
  55857. var boxplotLayout = function (ecModel) {
  55858. var groupResult = groupSeriesByAxis(ecModel);
  55859. each$13(groupResult, function (groupItem) {
  55860. var seriesModels = groupItem.seriesModels;
  55861. if (!seriesModels.length) {
  55862. return;
  55863. }
  55864. calculateBase(groupItem);
  55865. each$13(seriesModels, function (seriesModel, idx) {
  55866. layoutSingleSeries(
  55867. seriesModel,
  55868. groupItem.boxOffsetList[idx],
  55869. groupItem.boxWidthList[idx]
  55870. );
  55871. });
  55872. });
  55873. };
  55874. /**
  55875. * Group series by axis.
  55876. */
  55877. function groupSeriesByAxis(ecModel) {
  55878. var result = [];
  55879. var axisList = [];
  55880. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  55881. var baseAxis = seriesModel.getBaseAxis();
  55882. var idx = indexOf(axisList, baseAxis);
  55883. if (idx < 0) {
  55884. idx = axisList.length;
  55885. axisList[idx] = baseAxis;
  55886. result[idx] = {axis: baseAxis, seriesModels: []};
  55887. }
  55888. result[idx].seriesModels.push(seriesModel);
  55889. });
  55890. return result;
  55891. }
  55892. /**
  55893. * Calculate offset and box width for each series.
  55894. */
  55895. function calculateBase(groupItem) {
  55896. var extent;
  55897. var baseAxis = groupItem.axis;
  55898. var seriesModels = groupItem.seriesModels;
  55899. var seriesCount = seriesModels.length;
  55900. var boxWidthList = groupItem.boxWidthList = [];
  55901. var boxOffsetList = groupItem.boxOffsetList = [];
  55902. var boundList = [];
  55903. var bandWidth;
  55904. if (baseAxis.type === 'category') {
  55905. bandWidth = baseAxis.getBandWidth();
  55906. }
  55907. else {
  55908. var maxDataCount = 0;
  55909. each$13(seriesModels, function (seriesModel) {
  55910. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  55911. });
  55912. extent = baseAxis.getExtent(),
  55913. Math.abs(extent[1] - extent[0]) / maxDataCount;
  55914. }
  55915. each$13(seriesModels, function (seriesModel) {
  55916. var boxWidthBound = seriesModel.get('boxWidth');
  55917. if (!isArray(boxWidthBound)) {
  55918. boxWidthBound = [boxWidthBound, boxWidthBound];
  55919. }
  55920. boundList.push([
  55921. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  55922. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  55923. ]);
  55924. });
  55925. var availableWidth = bandWidth * 0.8 - 2;
  55926. var boxGap = availableWidth / seriesCount * 0.3;
  55927. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  55928. var base = boxWidth / 2 - availableWidth / 2;
  55929. each$13(seriesModels, function (seriesModel, idx) {
  55930. boxOffsetList.push(base);
  55931. base += boxGap + boxWidth;
  55932. boxWidthList.push(
  55933. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  55934. );
  55935. });
  55936. }
  55937. /**
  55938. * Calculate points location for each series.
  55939. */
  55940. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  55941. var coordSys = seriesModel.coordinateSystem;
  55942. var data = seriesModel.getData();
  55943. var halfWidth = boxWidth / 2;
  55944. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  55945. var vDimIdx = 1 - cDimIdx;
  55946. var coordDims = ['x', 'y'];
  55947. var cDim = data.mapDimension(coordDims[cDimIdx]);
  55948. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  55949. if (cDim == null || vDims.length < 5) {
  55950. return;
  55951. }
  55952. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  55953. var axisDimVal = data.get(cDim, dataIndex);
  55954. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  55955. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  55956. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  55957. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  55958. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  55959. var ends = [];
  55960. addBodyEnd(ends, end2, 0);
  55961. addBodyEnd(ends, end4, 1);
  55962. ends.push(end1, end2, end5, end4);
  55963. layEndLine(ends, end1);
  55964. layEndLine(ends, end5);
  55965. layEndLine(ends, median);
  55966. data.setItemLayout(dataIndex, {
  55967. initBaseline: median[vDimIdx],
  55968. ends: ends
  55969. });
  55970. }
  55971. function getPoint(axisDimVal, dimIdx, dataIndex) {
  55972. var val = data.get(dimIdx, dataIndex);
  55973. var p = [];
  55974. p[cDimIdx] = axisDimVal;
  55975. p[vDimIdx] = val;
  55976. var point;
  55977. if (isNaN(axisDimVal) || isNaN(val)) {
  55978. point = [NaN, NaN];
  55979. }
  55980. else {
  55981. point = coordSys.dataToPoint(p);
  55982. point[cDimIdx] += offset;
  55983. }
  55984. return point;
  55985. }
  55986. function addBodyEnd(ends, point, start) {
  55987. var point1 = point.slice();
  55988. var point2 = point.slice();
  55989. point1[cDimIdx] += halfWidth;
  55990. point2[cDimIdx] -= halfWidth;
  55991. start
  55992. ? ends.push(point1, point2)
  55993. : ends.push(point2, point1);
  55994. }
  55995. function layEndLine(ends, endCenter) {
  55996. var from = endCenter.slice();
  55997. var to = endCenter.slice();
  55998. from[cDimIdx] -= halfWidth;
  55999. to[cDimIdx] += halfWidth;
  56000. ends.push(from, to);
  56001. }
  56002. }
  56003. /*
  56004. * Licensed to the Apache Software Foundation (ASF) under one
  56005. * or more contributor license agreements. See the NOTICE file
  56006. * distributed with this work for additional information
  56007. * regarding copyright ownership. The ASF licenses this file
  56008. * to you under the Apache License, Version 2.0 (the
  56009. * "License"); you may not use this file except in compliance
  56010. * with the License. You may obtain a copy of the License at
  56011. *
  56012. * http://www.apache.org/licenses/LICENSE-2.0
  56013. *
  56014. * Unless required by applicable law or agreed to in writing,
  56015. * software distributed under the License is distributed on an
  56016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56017. * KIND, either express or implied. See the License for the
  56018. * specific language governing permissions and limitations
  56019. * under the License.
  56020. */
  56021. registerVisual(boxplotVisual);
  56022. registerLayout(boxplotLayout);
  56023. /*
  56024. * Licensed to the Apache Software Foundation (ASF) under one
  56025. * or more contributor license agreements. See the NOTICE file
  56026. * distributed with this work for additional information
  56027. * regarding copyright ownership. The ASF licenses this file
  56028. * to you under the Apache License, Version 2.0 (the
  56029. * "License"); you may not use this file except in compliance
  56030. * with the License. You may obtain a copy of the License at
  56031. *
  56032. * http://www.apache.org/licenses/LICENSE-2.0
  56033. *
  56034. * Unless required by applicable law or agreed to in writing,
  56035. * software distributed under the License is distributed on an
  56036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56037. * KIND, either express or implied. See the License for the
  56038. * specific language governing permissions and limitations
  56039. * under the License.
  56040. */
  56041. var CandlestickSeries = SeriesModel.extend({
  56042. type: 'series.candlestick',
  56043. dependencies: ['xAxis', 'yAxis', 'grid'],
  56044. /**
  56045. * @readOnly
  56046. */
  56047. defaultValueDimensions: [
  56048. {name: 'open', defaultTooltip: true},
  56049. {name: 'close', defaultTooltip: true},
  56050. {name: 'lowest', defaultTooltip: true},
  56051. {name: 'highest', defaultTooltip: true}
  56052. ],
  56053. /**
  56054. * @type {Array.<string>}
  56055. * @readOnly
  56056. */
  56057. dimensions: null,
  56058. /**
  56059. * @override
  56060. */
  56061. defaultOption: {
  56062. zlevel: 0,
  56063. z: 2,
  56064. coordinateSystem: 'cartesian2d',
  56065. legendHoverLink: true,
  56066. hoverAnimation: true,
  56067. // xAxisIndex: 0,
  56068. // yAxisIndex: 0,
  56069. layout: null, // 'horizontal' or 'vertical'
  56070. clip: true,
  56071. itemStyle: {
  56072. color: '#c23531', // 阳线 positive
  56073. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  56074. borderWidth: 1,
  56075. // FIXME
  56076. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  56077. borderColor: '#c23531',
  56078. borderColor0: '#314656'
  56079. },
  56080. emphasis: {
  56081. itemStyle: {
  56082. borderWidth: 2
  56083. }
  56084. },
  56085. barMaxWidth: null,
  56086. barMinWidth: null,
  56087. barWidth: null,
  56088. large: true,
  56089. largeThreshold: 600,
  56090. progressive: 3e3,
  56091. progressiveThreshold: 1e4,
  56092. progressiveChunkMode: 'mod',
  56093. animationUpdate: false,
  56094. animationEasing: 'linear',
  56095. animationDuration: 300
  56096. },
  56097. /**
  56098. * Get dimension for shadow in dataZoom
  56099. * @return {string} dimension name
  56100. */
  56101. getShadowDim: function () {
  56102. return 'open';
  56103. },
  56104. brushSelector: function (dataIndex, data, selectors) {
  56105. var itemLayout = data.getItemLayout(dataIndex);
  56106. return itemLayout && selectors.rect(itemLayout.brushRect);
  56107. }
  56108. });
  56109. mixin(CandlestickSeries, seriesModelMixin, true);
  56110. /*
  56111. * Licensed to the Apache Software Foundation (ASF) under one
  56112. * or more contributor license agreements. See the NOTICE file
  56113. * distributed with this work for additional information
  56114. * regarding copyright ownership. The ASF licenses this file
  56115. * to you under the Apache License, Version 2.0 (the
  56116. * "License"); you may not use this file except in compliance
  56117. * with the License. You may obtain a copy of the License at
  56118. *
  56119. * http://www.apache.org/licenses/LICENSE-2.0
  56120. *
  56121. * Unless required by applicable law or agreed to in writing,
  56122. * software distributed under the License is distributed on an
  56123. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56124. * KIND, either express or implied. See the License for the
  56125. * specific language governing permissions and limitations
  56126. * under the License.
  56127. */
  56128. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  56129. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  56130. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  56131. var CandlestickView = Chart.extend({
  56132. type: 'candlestick',
  56133. render: function (seriesModel, ecModel, api) {
  56134. // If there is clipPath created in large mode. Remove it.
  56135. this.group.removeClipPath();
  56136. this._updateDrawMode(seriesModel);
  56137. this._isLargeDraw
  56138. ? this._renderLarge(seriesModel)
  56139. : this._renderNormal(seriesModel);
  56140. },
  56141. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  56142. this._clear();
  56143. this._updateDrawMode(seriesModel);
  56144. },
  56145. incrementalRender: function (params, seriesModel, ecModel, api) {
  56146. this._isLargeDraw
  56147. ? this._incrementalRenderLarge(params, seriesModel)
  56148. : this._incrementalRenderNormal(params, seriesModel);
  56149. },
  56150. _updateDrawMode: function (seriesModel) {
  56151. var isLargeDraw = seriesModel.pipelineContext.large;
  56152. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  56153. this._isLargeDraw = isLargeDraw;
  56154. this._clear();
  56155. }
  56156. },
  56157. _renderNormal: function (seriesModel) {
  56158. var data = seriesModel.getData();
  56159. var oldData = this._data;
  56160. var group = this.group;
  56161. var isSimpleBox = data.getLayout('isSimpleBox');
  56162. var needsClip = seriesModel.get('clip', true);
  56163. var coord = seriesModel.coordinateSystem;
  56164. var clipArea = coord.getArea && coord.getArea();
  56165. // There is no old data only when first rendering or switching from
  56166. // stream mode to normal mode, where previous elements should be removed.
  56167. if (!this._data) {
  56168. group.removeAll();
  56169. }
  56170. data.diff(oldData)
  56171. .add(function (newIdx) {
  56172. if (data.hasValue(newIdx)) {
  56173. var el;
  56174. var itemLayout = data.getItemLayout(newIdx);
  56175. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56176. return;
  56177. }
  56178. el = createNormalBox$1(itemLayout, newIdx, true);
  56179. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56180. setBoxCommon(el, data, newIdx, isSimpleBox);
  56181. group.add(el);
  56182. data.setItemGraphicEl(newIdx, el);
  56183. }
  56184. })
  56185. .update(function (newIdx, oldIdx) {
  56186. var el = oldData.getItemGraphicEl(oldIdx);
  56187. // Empty data
  56188. if (!data.hasValue(newIdx)) {
  56189. group.remove(el);
  56190. return;
  56191. }
  56192. var itemLayout = data.getItemLayout(newIdx);
  56193. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  56194. group.remove(el);
  56195. return;
  56196. }
  56197. if (!el) {
  56198. el = createNormalBox$1(itemLayout, newIdx);
  56199. }
  56200. else {
  56201. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  56202. }
  56203. setBoxCommon(el, data, newIdx, isSimpleBox);
  56204. group.add(el);
  56205. data.setItemGraphicEl(newIdx, el);
  56206. })
  56207. .remove(function (oldIdx) {
  56208. var el = oldData.getItemGraphicEl(oldIdx);
  56209. el && group.remove(el);
  56210. })
  56211. .execute();
  56212. this._data = data;
  56213. },
  56214. _renderLarge: function (seriesModel) {
  56215. this._clear();
  56216. createLarge$1(seriesModel, this.group);
  56217. var clipPath = seriesModel.get('clip', true)
  56218. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  56219. : null;
  56220. if (clipPath) {
  56221. this.group.setClipPath(clipPath);
  56222. }
  56223. else {
  56224. this.group.removeClipPath();
  56225. }
  56226. },
  56227. _incrementalRenderNormal: function (params, seriesModel) {
  56228. var data = seriesModel.getData();
  56229. var isSimpleBox = data.getLayout('isSimpleBox');
  56230. var dataIndex;
  56231. while ((dataIndex = params.next()) != null) {
  56232. var el;
  56233. var itemLayout = data.getItemLayout(dataIndex);
  56234. el = createNormalBox$1(itemLayout, dataIndex);
  56235. setBoxCommon(el, data, dataIndex, isSimpleBox);
  56236. el.incremental = true;
  56237. this.group.add(el);
  56238. }
  56239. },
  56240. _incrementalRenderLarge: function (params, seriesModel) {
  56241. createLarge$1(seriesModel, this.group, true);
  56242. },
  56243. remove: function (ecModel) {
  56244. this._clear();
  56245. },
  56246. _clear: function () {
  56247. this.group.removeAll();
  56248. this._data = null;
  56249. },
  56250. dispose: noop
  56251. });
  56252. var NormalBoxPath = Path.extend({
  56253. type: 'normalCandlestickBox',
  56254. shape: {},
  56255. buildPath: function (ctx, shape) {
  56256. var ends = shape.points;
  56257. if (this.__simpleBox) {
  56258. ctx.moveTo(ends[4][0], ends[4][1]);
  56259. ctx.lineTo(ends[6][0], ends[6][1]);
  56260. }
  56261. else {
  56262. ctx.moveTo(ends[0][0], ends[0][1]);
  56263. ctx.lineTo(ends[1][0], ends[1][1]);
  56264. ctx.lineTo(ends[2][0], ends[2][1]);
  56265. ctx.lineTo(ends[3][0], ends[3][1]);
  56266. ctx.closePath();
  56267. ctx.moveTo(ends[4][0], ends[4][1]);
  56268. ctx.lineTo(ends[5][0], ends[5][1]);
  56269. ctx.moveTo(ends[6][0], ends[6][1]);
  56270. ctx.lineTo(ends[7][0], ends[7][1]);
  56271. }
  56272. }
  56273. });
  56274. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  56275. var ends = itemLayout.ends;
  56276. return new NormalBoxPath({
  56277. shape: {
  56278. points: isInit
  56279. ? transInit$1(ends, itemLayout)
  56280. : ends
  56281. },
  56282. z2: 100
  56283. });
  56284. }
  56285. function isNormalBoxClipped(clipArea, itemLayout) {
  56286. var clipped = true;
  56287. for (var i = 0; i < itemLayout.ends.length; i++) {
  56288. // If any point are in the region.
  56289. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  56290. clipped = false;
  56291. break;
  56292. }
  56293. }
  56294. return clipped;
  56295. }
  56296. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  56297. var itemModel = data.getItemModel(dataIndex);
  56298. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  56299. var color = data.getItemVisual(dataIndex, 'color');
  56300. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  56301. // Color must be excluded.
  56302. // Because symbol provide setColor individually to set fill and stroke
  56303. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  56304. el.useStyle(itemStyle);
  56305. el.style.strokeNoScale = true;
  56306. el.style.fill = color;
  56307. el.style.stroke = borderColor;
  56308. el.__simpleBox = isSimpleBox;
  56309. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  56310. setHoverStyle(el, hoverStyle);
  56311. }
  56312. function transInit$1(points, itemLayout) {
  56313. return map(points, function (point) {
  56314. point = point.slice();
  56315. point[1] = itemLayout.initBaseline;
  56316. return point;
  56317. });
  56318. }
  56319. var LargeBoxPath = Path.extend({
  56320. type: 'largeCandlestickBox',
  56321. shape: {},
  56322. buildPath: function (ctx, shape) {
  56323. // Drawing lines is more efficient than drawing
  56324. // a whole line or drawing rects.
  56325. var points = shape.points;
  56326. for (var i = 0; i < points.length;) {
  56327. if (this.__sign === points[i++]) {
  56328. var x = points[i++];
  56329. ctx.moveTo(x, points[i++]);
  56330. ctx.lineTo(x, points[i++]);
  56331. }
  56332. else {
  56333. i += 3;
  56334. }
  56335. }
  56336. }
  56337. });
  56338. function createLarge$1(seriesModel, group, incremental) {
  56339. var data = seriesModel.getData();
  56340. var largePoints = data.getLayout('largePoints');
  56341. var elP = new LargeBoxPath({
  56342. shape: {points: largePoints},
  56343. __sign: 1
  56344. });
  56345. group.add(elP);
  56346. var elN = new LargeBoxPath({
  56347. shape: {points: largePoints},
  56348. __sign: -1
  56349. });
  56350. group.add(elN);
  56351. setLargeStyle$1(1, elP, seriesModel, data);
  56352. setLargeStyle$1(-1, elN, seriesModel, data);
  56353. if (incremental) {
  56354. elP.incremental = true;
  56355. elN.incremental = true;
  56356. }
  56357. }
  56358. function setLargeStyle$1(sign, el, seriesModel, data) {
  56359. var suffix = sign > 0 ? 'P' : 'N';
  56360. var borderColor = data.getVisual('borderColor' + suffix)
  56361. || data.getVisual('color' + suffix);
  56362. // Color must be excluded.
  56363. // Because symbol provide setColor individually to set fill and stroke
  56364. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  56365. el.useStyle(itemStyle);
  56366. el.style.fill = null;
  56367. el.style.stroke = borderColor;
  56368. // No different
  56369. // el.style.lineWidth = .5;
  56370. }
  56371. /*
  56372. * Licensed to the Apache Software Foundation (ASF) under one
  56373. * or more contributor license agreements. See the NOTICE file
  56374. * distributed with this work for additional information
  56375. * regarding copyright ownership. The ASF licenses this file
  56376. * to you under the Apache License, Version 2.0 (the
  56377. * "License"); you may not use this file except in compliance
  56378. * with the License. You may obtain a copy of the License at
  56379. *
  56380. * http://www.apache.org/licenses/LICENSE-2.0
  56381. *
  56382. * Unless required by applicable law or agreed to in writing,
  56383. * software distributed under the License is distributed on an
  56384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56385. * KIND, either express or implied. See the License for the
  56386. * specific language governing permissions and limitations
  56387. * under the License.
  56388. */
  56389. var preprocessor = function (option) {
  56390. if (!option || !isArray(option.series)) {
  56391. return;
  56392. }
  56393. // Translate 'k' to 'candlestick'.
  56394. each$1(option.series, function (seriesItem) {
  56395. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  56396. seriesItem.type = 'candlestick';
  56397. }
  56398. });
  56399. };
  56400. /*
  56401. * Licensed to the Apache Software Foundation (ASF) under one
  56402. * or more contributor license agreements. See the NOTICE file
  56403. * distributed with this work for additional information
  56404. * regarding copyright ownership. The ASF licenses this file
  56405. * to you under the Apache License, Version 2.0 (the
  56406. * "License"); you may not use this file except in compliance
  56407. * with the License. You may obtain a copy of the License at
  56408. *
  56409. * http://www.apache.org/licenses/LICENSE-2.0
  56410. *
  56411. * Unless required by applicable law or agreed to in writing,
  56412. * software distributed under the License is distributed on an
  56413. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56414. * KIND, either express or implied. See the License for the
  56415. * specific language governing permissions and limitations
  56416. * under the License.
  56417. */
  56418. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  56419. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  56420. var positiveColorQuery = ['itemStyle', 'color'];
  56421. var negativeColorQuery = ['itemStyle', 'color0'];
  56422. var candlestickVisual = {
  56423. seriesType: 'candlestick',
  56424. plan: createRenderPlanner(),
  56425. // For legend.
  56426. performRawSeries: true,
  56427. reset: function (seriesModel, ecModel) {
  56428. var data = seriesModel.getData();
  56429. var isLargeRender = seriesModel.pipelineContext.large;
  56430. data.setVisual({
  56431. legendSymbol: 'roundRect',
  56432. colorP: getColor(1, seriesModel),
  56433. colorN: getColor(-1, seriesModel),
  56434. borderColorP: getBorderColor(1, seriesModel),
  56435. borderColorN: getBorderColor(-1, seriesModel)
  56436. });
  56437. // Only visible series has each data be visual encoded
  56438. if (ecModel.isSeriesFiltered(seriesModel)) {
  56439. return;
  56440. }
  56441. return !isLargeRender && {progress: progress};
  56442. function progress(params, data) {
  56443. var dataIndex;
  56444. while ((dataIndex = params.next()) != null) {
  56445. var itemModel = data.getItemModel(dataIndex);
  56446. var sign = data.getItemLayout(dataIndex).sign;
  56447. data.setItemVisual(
  56448. dataIndex,
  56449. {
  56450. color: getColor(sign, itemModel),
  56451. borderColor: getBorderColor(sign, itemModel)
  56452. }
  56453. );
  56454. }
  56455. }
  56456. function getColor(sign, model) {
  56457. return model.get(
  56458. sign > 0 ? positiveColorQuery : negativeColorQuery
  56459. );
  56460. }
  56461. function getBorderColor(sign, model) {
  56462. return model.get(
  56463. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  56464. );
  56465. }
  56466. }
  56467. };
  56468. /*
  56469. * Licensed to the Apache Software Foundation (ASF) under one
  56470. * or more contributor license agreements. See the NOTICE file
  56471. * distributed with this work for additional information
  56472. * regarding copyright ownership. The ASF licenses this file
  56473. * to you under the Apache License, Version 2.0 (the
  56474. * "License"); you may not use this file except in compliance
  56475. * with the License. You may obtain a copy of the License at
  56476. *
  56477. * http://www.apache.org/licenses/LICENSE-2.0
  56478. *
  56479. * Unless required by applicable law or agreed to in writing,
  56480. * software distributed under the License is distributed on an
  56481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56482. * KIND, either express or implied. See the License for the
  56483. * specific language governing permissions and limitations
  56484. * under the License.
  56485. */
  56486. /* global Float32Array */
  56487. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  56488. var candlestickLayout = {
  56489. seriesType: 'candlestick',
  56490. plan: createRenderPlanner(),
  56491. reset: function (seriesModel) {
  56492. var coordSys = seriesModel.coordinateSystem;
  56493. var data = seriesModel.getData();
  56494. var candleWidth = calculateCandleWidth(seriesModel, data);
  56495. var cDimIdx = 0;
  56496. var vDimIdx = 1;
  56497. var coordDims = ['x', 'y'];
  56498. var cDim = data.mapDimension(coordDims[cDimIdx]);
  56499. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  56500. var openDim = vDims[0];
  56501. var closeDim = vDims[1];
  56502. var lowestDim = vDims[2];
  56503. var highestDim = vDims[3];
  56504. data.setLayout({
  56505. candleWidth: candleWidth,
  56506. // The value is experimented visually.
  56507. isSimpleBox: candleWidth <= 1.3
  56508. });
  56509. if (cDim == null || vDims.length < 4) {
  56510. return;
  56511. }
  56512. return {
  56513. progress: seriesModel.pipelineContext.large
  56514. ? largeProgress : normalProgress
  56515. };
  56516. function normalProgress(params, data) {
  56517. var dataIndex;
  56518. while ((dataIndex = params.next()) != null) {
  56519. var axisDimVal = data.get(cDim, dataIndex);
  56520. var openVal = data.get(openDim, dataIndex);
  56521. var closeVal = data.get(closeDim, dataIndex);
  56522. var lowestVal = data.get(lowestDim, dataIndex);
  56523. var highestVal = data.get(highestDim, dataIndex);
  56524. var ocLow = Math.min(openVal, closeVal);
  56525. var ocHigh = Math.max(openVal, closeVal);
  56526. var ocLowPoint = getPoint(ocLow, axisDimVal);
  56527. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  56528. var lowestPoint = getPoint(lowestVal, axisDimVal);
  56529. var highestPoint = getPoint(highestVal, axisDimVal);
  56530. var ends = [];
  56531. addBodyEnd(ends, ocHighPoint, 0);
  56532. addBodyEnd(ends, ocLowPoint, 1);
  56533. ends.push(
  56534. subPixelOptimizePoint(highestPoint),
  56535. subPixelOptimizePoint(ocHighPoint),
  56536. subPixelOptimizePoint(lowestPoint),
  56537. subPixelOptimizePoint(ocLowPoint)
  56538. );
  56539. data.setItemLayout(dataIndex, {
  56540. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  56541. initBaseline: openVal > closeVal
  56542. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  56543. ends: ends,
  56544. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  56545. });
  56546. }
  56547. function getPoint(val, axisDimVal) {
  56548. var p = [];
  56549. p[cDimIdx] = axisDimVal;
  56550. p[vDimIdx] = val;
  56551. return (isNaN(axisDimVal) || isNaN(val))
  56552. ? [NaN, NaN]
  56553. : coordSys.dataToPoint(p);
  56554. }
  56555. function addBodyEnd(ends, point, start) {
  56556. var point1 = point.slice();
  56557. var point2 = point.slice();
  56558. point1[cDimIdx] = subPixelOptimize(
  56559. point1[cDimIdx] + candleWidth / 2, 1, false
  56560. );
  56561. point2[cDimIdx] = subPixelOptimize(
  56562. point2[cDimIdx] - candleWidth / 2, 1, true
  56563. );
  56564. start
  56565. ? ends.push(point1, point2)
  56566. : ends.push(point2, point1);
  56567. }
  56568. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  56569. var pmin = getPoint(lowestVal, axisDimVal);
  56570. var pmax = getPoint(highestVal, axisDimVal);
  56571. pmin[cDimIdx] -= candleWidth / 2;
  56572. pmax[cDimIdx] -= candleWidth / 2;
  56573. return {
  56574. x: pmin[0],
  56575. y: pmin[1],
  56576. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  56577. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  56578. };
  56579. }
  56580. function subPixelOptimizePoint(point) {
  56581. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  56582. return point;
  56583. }
  56584. }
  56585. function largeProgress(params, data) {
  56586. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  56587. var points = new LargeArr$1(params.count * 4);
  56588. var offset = 0;
  56589. var point;
  56590. var tmpIn = [];
  56591. var tmpOut = [];
  56592. var dataIndex;
  56593. while ((dataIndex = params.next()) != null) {
  56594. var axisDimVal = data.get(cDim, dataIndex);
  56595. var openVal = data.get(openDim, dataIndex);
  56596. var closeVal = data.get(closeDim, dataIndex);
  56597. var lowestVal = data.get(lowestDim, dataIndex);
  56598. var highestVal = data.get(highestDim, dataIndex);
  56599. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  56600. points[offset++] = NaN;
  56601. offset += 3;
  56602. continue;
  56603. }
  56604. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  56605. tmpIn[cDimIdx] = axisDimVal;
  56606. tmpIn[vDimIdx] = lowestVal;
  56607. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  56608. points[offset++] = point ? point[0] : NaN;
  56609. points[offset++] = point ? point[1] : NaN;
  56610. tmpIn[vDimIdx] = highestVal;
  56611. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  56612. points[offset++] = point ? point[1] : NaN;
  56613. }
  56614. data.setLayout('largePoints', points);
  56615. }
  56616. }
  56617. };
  56618. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  56619. var sign;
  56620. if (openVal > closeVal) {
  56621. sign = -1;
  56622. }
  56623. else if (openVal < closeVal) {
  56624. sign = 1;
  56625. }
  56626. else {
  56627. sign = dataIndex > 0
  56628. // If close === open, compare with close of last record
  56629. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  56630. // No record of previous, set to be positive
  56631. : 1;
  56632. }
  56633. return sign;
  56634. }
  56635. function calculateCandleWidth(seriesModel, data) {
  56636. var baseAxis = seriesModel.getBaseAxis();
  56637. var extent;
  56638. var bandWidth = baseAxis.type === 'category'
  56639. ? baseAxis.getBandWidth()
  56640. : (
  56641. extent = baseAxis.getExtent(),
  56642. Math.abs(extent[1] - extent[0]) / data.count()
  56643. );
  56644. var barMaxWidth = parsePercent$1(
  56645. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  56646. bandWidth
  56647. );
  56648. var barMinWidth = parsePercent$1(
  56649. retrieve2(seriesModel.get('barMinWidth'), 1),
  56650. bandWidth
  56651. );
  56652. var barWidth = seriesModel.get('barWidth');
  56653. return barWidth != null
  56654. ? parsePercent$1(barWidth, bandWidth)
  56655. // Put max outer to ensure bar visible in spite of overlap.
  56656. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  56657. }
  56658. /*
  56659. * Licensed to the Apache Software Foundation (ASF) under one
  56660. * or more contributor license agreements. See the NOTICE file
  56661. * distributed with this work for additional information
  56662. * regarding copyright ownership. The ASF licenses this file
  56663. * to you under the Apache License, Version 2.0 (the
  56664. * "License"); you may not use this file except in compliance
  56665. * with the License. You may obtain a copy of the License at
  56666. *
  56667. * http://www.apache.org/licenses/LICENSE-2.0
  56668. *
  56669. * Unless required by applicable law or agreed to in writing,
  56670. * software distributed under the License is distributed on an
  56671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56672. * KIND, either express or implied. See the License for the
  56673. * specific language governing permissions and limitations
  56674. * under the License.
  56675. */
  56676. registerPreprocessor(preprocessor);
  56677. registerVisual(candlestickVisual);
  56678. registerLayout(candlestickLayout);
  56679. /*
  56680. * Licensed to the Apache Software Foundation (ASF) under one
  56681. * or more contributor license agreements. See the NOTICE file
  56682. * distributed with this work for additional information
  56683. * regarding copyright ownership. The ASF licenses this file
  56684. * to you under the Apache License, Version 2.0 (the
  56685. * "License"); you may not use this file except in compliance
  56686. * with the License. You may obtain a copy of the License at
  56687. *
  56688. * http://www.apache.org/licenses/LICENSE-2.0
  56689. *
  56690. * Unless required by applicable law or agreed to in writing,
  56691. * software distributed under the License is distributed on an
  56692. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56693. * KIND, either express or implied. See the License for the
  56694. * specific language governing permissions and limitations
  56695. * under the License.
  56696. */
  56697. SeriesModel.extend({
  56698. type: 'series.effectScatter',
  56699. dependencies: ['grid', 'polar'],
  56700. getInitialData: function (option, ecModel) {
  56701. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  56702. },
  56703. brushSelector: 'point',
  56704. defaultOption: {
  56705. coordinateSystem: 'cartesian2d',
  56706. zlevel: 0,
  56707. z: 2,
  56708. legendHoverLink: true,
  56709. effectType: 'ripple',
  56710. progressive: 0,
  56711. // When to show the effect, option: 'render'|'emphasis'
  56712. showEffectOn: 'render',
  56713. // Ripple effect config
  56714. rippleEffect: {
  56715. period: 4,
  56716. // Scale of ripple
  56717. scale: 2.5,
  56718. // Brush type can be fill or stroke
  56719. brushType: 'fill'
  56720. },
  56721. // Cartesian coordinate system
  56722. // xAxisIndex: 0,
  56723. // yAxisIndex: 0,
  56724. // Polar coordinate system
  56725. // polarIndex: 0,
  56726. // Geo coordinate system
  56727. // geoIndex: 0,
  56728. // symbol: null, // 图形类型
  56729. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  56730. // symbolRotate: null, // 图形旋转控制
  56731. // large: false,
  56732. // Available when large is true
  56733. // largeThreshold: 2000,
  56734. // itemStyle: {
  56735. // opacity: 1
  56736. // }
  56737. }
  56738. });
  56739. /*
  56740. * Licensed to the Apache Software Foundation (ASF) under one
  56741. * or more contributor license agreements. See the NOTICE file
  56742. * distributed with this work for additional information
  56743. * regarding copyright ownership. The ASF licenses this file
  56744. * to you under the Apache License, Version 2.0 (the
  56745. * "License"); you may not use this file except in compliance
  56746. * with the License. You may obtain a copy of the License at
  56747. *
  56748. * http://www.apache.org/licenses/LICENSE-2.0
  56749. *
  56750. * Unless required by applicable law or agreed to in writing,
  56751. * software distributed under the License is distributed on an
  56752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56753. * KIND, either express or implied. See the License for the
  56754. * specific language governing permissions and limitations
  56755. * under the License.
  56756. */
  56757. /**
  56758. * Symbol with ripple effect
  56759. * @module echarts/chart/helper/EffectSymbol
  56760. */
  56761. var EFFECT_RIPPLE_NUMBER = 3;
  56762. function normalizeSymbolSize$1(symbolSize) {
  56763. if (!isArray(symbolSize)) {
  56764. symbolSize = [+symbolSize, +symbolSize];
  56765. }
  56766. return symbolSize;
  56767. }
  56768. function updateRipplePath(rippleGroup, effectCfg) {
  56769. var color = effectCfg.rippleEffectColor || effectCfg.color;
  56770. rippleGroup.eachChild(function (ripplePath) {
  56771. ripplePath.attr({
  56772. z: effectCfg.z,
  56773. zlevel: effectCfg.zlevel,
  56774. style: {
  56775. stroke: effectCfg.brushType === 'stroke' ? color : null,
  56776. fill: effectCfg.brushType === 'fill' ? color : null
  56777. }
  56778. });
  56779. });
  56780. }
  56781. /**
  56782. * @constructor
  56783. * @param {module:echarts/data/List} data
  56784. * @param {number} idx
  56785. * @extends {module:zrender/graphic/Group}
  56786. */
  56787. function EffectSymbol(data, idx) {
  56788. Group.call(this);
  56789. var symbol = new SymbolClz$1(data, idx);
  56790. var rippleGroup = new Group();
  56791. this.add(symbol);
  56792. this.add(rippleGroup);
  56793. rippleGroup.beforeUpdate = function () {
  56794. this.attr(symbol.getScale());
  56795. };
  56796. this.updateData(data, idx);
  56797. }
  56798. var effectSymbolProto = EffectSymbol.prototype;
  56799. effectSymbolProto.stopEffectAnimation = function () {
  56800. this.childAt(1).removeAll();
  56801. };
  56802. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  56803. var symbolType = effectCfg.symbolType;
  56804. var color = effectCfg.color;
  56805. var rippleGroup = this.childAt(1);
  56806. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  56807. // If width/height are set too small (e.g., set to 1) on ios10
  56808. // and macOS Sierra, a circle stroke become a rect, no matter what
  56809. // the scale is set. So we set width/height as 2. See #4136.
  56810. var ripplePath = createSymbol(
  56811. symbolType, -1, -1, 2, 2, color
  56812. );
  56813. ripplePath.attr({
  56814. style: {
  56815. strokeNoScale: true
  56816. },
  56817. z2: 99,
  56818. silent: true,
  56819. scale: [0.5, 0.5]
  56820. });
  56821. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  56822. // TODO Configurable effectCfg.period
  56823. ripplePath.animate('', true)
  56824. .when(effectCfg.period, {
  56825. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  56826. })
  56827. .delay(delay)
  56828. .start();
  56829. ripplePath.animateStyle(true)
  56830. .when(effectCfg.period, {
  56831. opacity: 0
  56832. })
  56833. .delay(delay)
  56834. .start();
  56835. rippleGroup.add(ripplePath);
  56836. }
  56837. updateRipplePath(rippleGroup, effectCfg);
  56838. };
  56839. /**
  56840. * Update effect symbol
  56841. */
  56842. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  56843. var oldEffectCfg = this._effectCfg;
  56844. var rippleGroup = this.childAt(1);
  56845. // Must reinitialize effect if following configuration changed
  56846. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  56847. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  56848. var propName = DIFFICULT_PROPS[i];
  56849. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  56850. this.stopEffectAnimation();
  56851. this.startEffectAnimation(effectCfg);
  56852. return;
  56853. }
  56854. }
  56855. updateRipplePath(rippleGroup, effectCfg);
  56856. };
  56857. /**
  56858. * Highlight symbol
  56859. */
  56860. effectSymbolProto.highlight = function () {
  56861. this.trigger('emphasis');
  56862. };
  56863. /**
  56864. * Downplay symbol
  56865. */
  56866. effectSymbolProto.downplay = function () {
  56867. this.trigger('normal');
  56868. };
  56869. /**
  56870. * Update symbol properties
  56871. * @param {module:echarts/data/List} data
  56872. * @param {number} idx
  56873. */
  56874. effectSymbolProto.updateData = function (data, idx) {
  56875. var seriesModel = data.hostModel;
  56876. this.childAt(0).updateData(data, idx);
  56877. var rippleGroup = this.childAt(1);
  56878. var itemModel = data.getItemModel(idx);
  56879. var symbolType = data.getItemVisual(idx, 'symbol');
  56880. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  56881. var color = data.getItemVisual(idx, 'color');
  56882. rippleGroup.attr('scale', symbolSize);
  56883. rippleGroup.traverse(function (ripplePath) {
  56884. ripplePath.attr({
  56885. fill: color
  56886. });
  56887. });
  56888. var symbolOffset = itemModel.getShallow('symbolOffset');
  56889. if (symbolOffset) {
  56890. var pos = rippleGroup.position;
  56891. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  56892. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  56893. }
  56894. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  56895. var effectCfg = {};
  56896. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  56897. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  56898. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  56899. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  56900. effectCfg.effectOffset = idx / data.count();
  56901. effectCfg.z = itemModel.getShallow('z') || 0;
  56902. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  56903. effectCfg.symbolType = symbolType;
  56904. effectCfg.color = color;
  56905. effectCfg.rippleEffectColor = itemModel.get('rippleEffect.color');
  56906. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  56907. if (effectCfg.showEffectOn === 'render') {
  56908. this._effectCfg
  56909. ? this.updateEffectAnimation(effectCfg)
  56910. : this.startEffectAnimation(effectCfg);
  56911. this._effectCfg = effectCfg;
  56912. }
  56913. else {
  56914. // Not keep old effect config
  56915. this._effectCfg = null;
  56916. this.stopEffectAnimation();
  56917. var symbol = this.childAt(0);
  56918. var onEmphasis = function () {
  56919. symbol.highlight();
  56920. if (effectCfg.showEffectOn !== 'render') {
  56921. this.startEffectAnimation(effectCfg);
  56922. }
  56923. };
  56924. var onNormal = function () {
  56925. symbol.downplay();
  56926. if (effectCfg.showEffectOn !== 'render') {
  56927. this.stopEffectAnimation();
  56928. }
  56929. };
  56930. this.on('mouseover', onEmphasis, this)
  56931. .on('mouseout', onNormal, this)
  56932. .on('emphasis', onEmphasis, this)
  56933. .on('normal', onNormal, this);
  56934. }
  56935. this._effectCfg = effectCfg;
  56936. };
  56937. effectSymbolProto.fadeOut = function (cb) {
  56938. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  56939. cb && cb();
  56940. };
  56941. inherits(EffectSymbol, Group);
  56942. /*
  56943. * Licensed to the Apache Software Foundation (ASF) under one
  56944. * or more contributor license agreements. See the NOTICE file
  56945. * distributed with this work for additional information
  56946. * regarding copyright ownership. The ASF licenses this file
  56947. * to you under the Apache License, Version 2.0 (the
  56948. * "License"); you may not use this file except in compliance
  56949. * with the License. You may obtain a copy of the License at
  56950. *
  56951. * http://www.apache.org/licenses/LICENSE-2.0
  56952. *
  56953. * Unless required by applicable law or agreed to in writing,
  56954. * software distributed under the License is distributed on an
  56955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56956. * KIND, either express or implied. See the License for the
  56957. * specific language governing permissions and limitations
  56958. * under the License.
  56959. */
  56960. extendChartView({
  56961. type: 'effectScatter',
  56962. init: function () {
  56963. this._symbolDraw = new SymbolDraw(EffectSymbol);
  56964. },
  56965. render: function (seriesModel, ecModel, api) {
  56966. var data = seriesModel.getData();
  56967. var effectSymbolDraw = this._symbolDraw;
  56968. effectSymbolDraw.updateData(data);
  56969. this.group.add(effectSymbolDraw.group);
  56970. },
  56971. updateTransform: function (seriesModel, ecModel, api) {
  56972. var data = seriesModel.getData();
  56973. this.group.dirty();
  56974. var res = pointsLayout().reset(seriesModel);
  56975. if (res.progress) {
  56976. res.progress({ start: 0, end: data.count() }, data);
  56977. }
  56978. this._symbolDraw.updateLayout(data);
  56979. },
  56980. _updateGroupTransform: function (seriesModel) {
  56981. var coordSys = seriesModel.coordinateSystem;
  56982. if (coordSys && coordSys.getRoamTransform) {
  56983. this.group.transform = clone$2(coordSys.getRoamTransform());
  56984. this.group.decomposeTransform();
  56985. }
  56986. },
  56987. remove: function (ecModel, api) {
  56988. this._symbolDraw && this._symbolDraw.remove(api);
  56989. },
  56990. dispose: function () {}
  56991. });
  56992. /*
  56993. * Licensed to the Apache Software Foundation (ASF) under one
  56994. * or more contributor license agreements. See the NOTICE file
  56995. * distributed with this work for additional information
  56996. * regarding copyright ownership. The ASF licenses this file
  56997. * to you under the Apache License, Version 2.0 (the
  56998. * "License"); you may not use this file except in compliance
  56999. * with the License. You may obtain a copy of the License at
  57000. *
  57001. * http://www.apache.org/licenses/LICENSE-2.0
  57002. *
  57003. * Unless required by applicable law or agreed to in writing,
  57004. * software distributed under the License is distributed on an
  57005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57006. * KIND, either express or implied. See the License for the
  57007. * specific language governing permissions and limitations
  57008. * under the License.
  57009. */
  57010. registerVisual(visualSymbol('effectScatter', 'circle'));
  57011. registerLayout(pointsLayout('effectScatter'));
  57012. /*
  57013. * Licensed to the Apache Software Foundation (ASF) under one
  57014. * or more contributor license agreements. See the NOTICE file
  57015. * distributed with this work for additional information
  57016. * regarding copyright ownership. The ASF licenses this file
  57017. * to you under the Apache License, Version 2.0 (the
  57018. * "License"); you may not use this file except in compliance
  57019. * with the License. You may obtain a copy of the License at
  57020. *
  57021. * http://www.apache.org/licenses/LICENSE-2.0
  57022. *
  57023. * Unless required by applicable law or agreed to in writing,
  57024. * software distributed under the License is distributed on an
  57025. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57026. * KIND, either express or implied. See the License for the
  57027. * specific language governing permissions and limitations
  57028. * under the License.
  57029. */
  57030. /* global Uint32Array, Float64Array, Float32Array */
  57031. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  57032. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  57033. function compatEc2(seriesOpt) {
  57034. var data = seriesOpt.data;
  57035. if (data && data[0] && data[0][0] && data[0][0].coord) {
  57036. if (__DEV__) {
  57037. console.warn('Lines data configuration has been changed to'
  57038. + ' { coords:[[1,2],[2,3]] }');
  57039. }
  57040. seriesOpt.data = map(data, function (itemOpt) {
  57041. var coords = [
  57042. itemOpt[0].coord, itemOpt[1].coord
  57043. ];
  57044. var target = {
  57045. coords: coords
  57046. };
  57047. if (itemOpt[0].name) {
  57048. target.fromName = itemOpt[0].name;
  57049. }
  57050. if (itemOpt[1].name) {
  57051. target.toName = itemOpt[1].name;
  57052. }
  57053. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  57054. });
  57055. }
  57056. }
  57057. var LinesSeries = SeriesModel.extend({
  57058. type: 'series.lines',
  57059. dependencies: ['grid', 'polar'],
  57060. visualColorAccessPath: 'lineStyle.color',
  57061. init: function (option) {
  57062. // The input data may be null/undefined.
  57063. option.data = option.data || [];
  57064. // Not using preprocessor because mergeOption may not have series.type
  57065. compatEc2(option);
  57066. var result = this._processFlatCoordsArray(option.data);
  57067. this._flatCoords = result.flatCoords;
  57068. this._flatCoordsOffset = result.flatCoordsOffset;
  57069. if (result.flatCoords) {
  57070. option.data = new Float32Array(result.count);
  57071. }
  57072. LinesSeries.superApply(this, 'init', arguments);
  57073. },
  57074. mergeOption: function (option) {
  57075. // The input data may be null/undefined.
  57076. option.data = option.data || [];
  57077. compatEc2(option);
  57078. if (option.data) {
  57079. // Only update when have option data to merge.
  57080. var result = this._processFlatCoordsArray(option.data);
  57081. this._flatCoords = result.flatCoords;
  57082. this._flatCoordsOffset = result.flatCoordsOffset;
  57083. if (result.flatCoords) {
  57084. option.data = new Float32Array(result.count);
  57085. }
  57086. }
  57087. LinesSeries.superApply(this, 'mergeOption', arguments);
  57088. },
  57089. appendData: function (params) {
  57090. var result = this._processFlatCoordsArray(params.data);
  57091. if (result.flatCoords) {
  57092. if (!this._flatCoords) {
  57093. this._flatCoords = result.flatCoords;
  57094. this._flatCoordsOffset = result.flatCoordsOffset;
  57095. }
  57096. else {
  57097. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  57098. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  57099. }
  57100. params.data = new Float32Array(result.count);
  57101. }
  57102. this.getRawData().appendData(params.data);
  57103. },
  57104. _getCoordsFromItemModel: function (idx) {
  57105. var itemModel = this.getData().getItemModel(idx);
  57106. var coords = (itemModel.option instanceof Array)
  57107. ? itemModel.option : itemModel.getShallow('coords');
  57108. if (__DEV__) {
  57109. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  57110. throw new Error(
  57111. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  57112. );
  57113. }
  57114. }
  57115. return coords;
  57116. },
  57117. getLineCoordsCount: function (idx) {
  57118. if (this._flatCoordsOffset) {
  57119. return this._flatCoordsOffset[idx * 2 + 1];
  57120. }
  57121. else {
  57122. return this._getCoordsFromItemModel(idx).length;
  57123. }
  57124. },
  57125. getLineCoords: function (idx, out) {
  57126. if (this._flatCoordsOffset) {
  57127. var offset = this._flatCoordsOffset[idx * 2];
  57128. var len = this._flatCoordsOffset[idx * 2 + 1];
  57129. for (var i = 0; i < len; i++) {
  57130. out[i] = out[i] || [];
  57131. out[i][0] = this._flatCoords[offset + i * 2];
  57132. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  57133. }
  57134. return len;
  57135. }
  57136. else {
  57137. var coords = this._getCoordsFromItemModel(idx);
  57138. for (var i = 0; i < coords.length; i++) {
  57139. out[i] = out[i] || [];
  57140. out[i][0] = coords[i][0];
  57141. out[i][1] = coords[i][1];
  57142. }
  57143. return coords.length;
  57144. }
  57145. },
  57146. _processFlatCoordsArray: function (data) {
  57147. var startOffset = 0;
  57148. if (this._flatCoords) {
  57149. startOffset = this._flatCoords.length;
  57150. }
  57151. // Stored as a typed array. In format
  57152. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  57153. if (typeof data[0] === 'number') {
  57154. var len = data.length;
  57155. // Store offset and len of each segment
  57156. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  57157. var coordsStorage = new Float64Arr(len);
  57158. var coordsCursor = 0;
  57159. var offsetCursor = 0;
  57160. var dataCount = 0;
  57161. for (var i = 0; i < len;) {
  57162. dataCount++;
  57163. var count = data[i++];
  57164. // Offset
  57165. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  57166. // Len
  57167. coordsOffsetAndLenStorage[offsetCursor++] = count;
  57168. for (var k = 0; k < count; k++) {
  57169. var x = data[i++];
  57170. var y = data[i++];
  57171. coordsStorage[coordsCursor++] = x;
  57172. coordsStorage[coordsCursor++] = y;
  57173. if (i > len) {
  57174. if (__DEV__) {
  57175. throw new Error('Invalid data format.');
  57176. }
  57177. }
  57178. }
  57179. }
  57180. return {
  57181. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  57182. flatCoords: coordsStorage,
  57183. count: dataCount
  57184. };
  57185. }
  57186. return {
  57187. flatCoordsOffset: null,
  57188. flatCoords: null,
  57189. count: data.length
  57190. };
  57191. },
  57192. getInitialData: function (option, ecModel) {
  57193. if (__DEV__) {
  57194. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  57195. if (!CoordSys) {
  57196. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  57197. }
  57198. }
  57199. var lineData = new List(['value'], this);
  57200. lineData.hasItemOption = false;
  57201. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  57202. // dataItem is simply coords
  57203. if (dataItem instanceof Array) {
  57204. return NaN;
  57205. }
  57206. else {
  57207. lineData.hasItemOption = true;
  57208. var value = dataItem.value;
  57209. if (value != null) {
  57210. return value instanceof Array ? value[dimIndex] : value;
  57211. }
  57212. }
  57213. });
  57214. return lineData;
  57215. },
  57216. formatTooltip: function (dataIndex) {
  57217. var data = this.getData();
  57218. var itemModel = data.getItemModel(dataIndex);
  57219. var name = itemModel.get('name');
  57220. if (name) {
  57221. return name;
  57222. }
  57223. var fromName = itemModel.get('fromName');
  57224. var toName = itemModel.get('toName');
  57225. var html = [];
  57226. fromName != null && html.push(fromName);
  57227. toName != null && html.push(toName);
  57228. return encodeHTML(html.join(' > '));
  57229. },
  57230. preventIncremental: function () {
  57231. return !!this.get('effect.show');
  57232. },
  57233. getProgressive: function () {
  57234. var progressive = this.option.progressive;
  57235. if (progressive == null) {
  57236. return this.option.large ? 1e4 : this.get('progressive');
  57237. }
  57238. return progressive;
  57239. },
  57240. getProgressiveThreshold: function () {
  57241. var progressiveThreshold = this.option.progressiveThreshold;
  57242. if (progressiveThreshold == null) {
  57243. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  57244. }
  57245. return progressiveThreshold;
  57246. },
  57247. defaultOption: {
  57248. coordinateSystem: 'geo',
  57249. zlevel: 0,
  57250. z: 2,
  57251. legendHoverLink: true,
  57252. hoverAnimation: true,
  57253. // Cartesian coordinate system
  57254. xAxisIndex: 0,
  57255. yAxisIndex: 0,
  57256. symbol: ['none', 'none'],
  57257. symbolSize: [10, 10],
  57258. // Geo coordinate system
  57259. geoIndex: 0,
  57260. effect: {
  57261. show: false,
  57262. period: 4,
  57263. // Animation delay. support callback
  57264. // delay: 0,
  57265. // If move with constant speed px/sec
  57266. // period will be ignored if this property is > 0,
  57267. constantSpeed: 0,
  57268. symbol: 'circle',
  57269. symbolSize: 3,
  57270. loop: true,
  57271. // Length of trail, 0 - 1
  57272. trailLength: 0.2
  57273. // Same with lineStyle.color
  57274. // color
  57275. },
  57276. large: false,
  57277. // Available when large is true
  57278. largeThreshold: 2000,
  57279. // If lines are polyline
  57280. // polyline not support curveness, label, animation
  57281. polyline: false,
  57282. // If clip the overflow.
  57283. // Available when coordinateSystem is cartesian or polar.
  57284. clip: true,
  57285. label: {
  57286. show: false,
  57287. position: 'end'
  57288. // distance: 5,
  57289. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  57290. },
  57291. lineStyle: {
  57292. opacity: 0.5
  57293. }
  57294. }
  57295. });
  57296. /*
  57297. * Licensed to the Apache Software Foundation (ASF) under one
  57298. * or more contributor license agreements. See the NOTICE file
  57299. * distributed with this work for additional information
  57300. * regarding copyright ownership. The ASF licenses this file
  57301. * to you under the Apache License, Version 2.0 (the
  57302. * "License"); you may not use this file except in compliance
  57303. * with the License. You may obtain a copy of the License at
  57304. *
  57305. * http://www.apache.org/licenses/LICENSE-2.0
  57306. *
  57307. * Unless required by applicable law or agreed to in writing,
  57308. * software distributed under the License is distributed on an
  57309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57310. * KIND, either express or implied. See the License for the
  57311. * specific language governing permissions and limitations
  57312. * under the License.
  57313. */
  57314. /**
  57315. * Provide effect for line
  57316. * @module echarts/chart/helper/EffectLine
  57317. */
  57318. /**
  57319. * @constructor
  57320. * @extends {module:zrender/graphic/Group}
  57321. * @alias {module:echarts/chart/helper/Line}
  57322. */
  57323. function EffectLine(lineData, idx, seriesScope) {
  57324. Group.call(this);
  57325. this.add(this.createLine(lineData, idx, seriesScope));
  57326. this._updateEffectSymbol(lineData, idx);
  57327. }
  57328. var effectLineProto = EffectLine.prototype;
  57329. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  57330. return new Line$1(lineData, idx, seriesScope);
  57331. };
  57332. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  57333. var itemModel = lineData.getItemModel(idx);
  57334. var effectModel = itemModel.getModel('effect');
  57335. var size = effectModel.get('symbolSize');
  57336. var symbolType = effectModel.get('symbol');
  57337. if (!isArray(size)) {
  57338. size = [size, size];
  57339. }
  57340. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  57341. var symbol = this.childAt(1);
  57342. if (this._symbolType !== symbolType) {
  57343. // Remove previous
  57344. this.remove(symbol);
  57345. symbol = createSymbol(
  57346. symbolType, -0.5, -0.5, 1, 1, color
  57347. );
  57348. symbol.z2 = 100;
  57349. symbol.culling = true;
  57350. this.add(symbol);
  57351. }
  57352. // Symbol may be removed if loop is false
  57353. if (!symbol) {
  57354. return;
  57355. }
  57356. // Shadow color is same with color in default
  57357. symbol.setStyle('shadowColor', color);
  57358. symbol.setStyle(effectModel.getItemStyle(['color']));
  57359. symbol.attr('scale', size);
  57360. symbol.setColor(color);
  57361. symbol.attr('scale', size);
  57362. this._symbolType = symbolType;
  57363. this._updateEffectAnimation(lineData, effectModel, idx);
  57364. };
  57365. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  57366. var symbol = this.childAt(1);
  57367. if (!symbol) {
  57368. return;
  57369. }
  57370. var self = this;
  57371. var points = lineData.getItemLayout(idx);
  57372. var period = effectModel.get('period') * 1000;
  57373. var loop = effectModel.get('loop');
  57374. var constantSpeed = effectModel.get('constantSpeed');
  57375. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  57376. return idx / lineData.count() * period / 3;
  57377. });
  57378. var isDelayFunc = typeof delayExpr === 'function';
  57379. // Ignore when updating
  57380. symbol.ignore = true;
  57381. this.updateAnimationPoints(symbol, points);
  57382. if (constantSpeed > 0) {
  57383. period = this.getLineLength(symbol) / constantSpeed * 1000;
  57384. }
  57385. if (period !== this._period || loop !== this._loop) {
  57386. symbol.stopAnimation();
  57387. var delay = delayExpr;
  57388. if (isDelayFunc) {
  57389. delay = delayExpr(idx);
  57390. }
  57391. if (symbol.__t > 0) {
  57392. delay = -period * symbol.__t;
  57393. }
  57394. symbol.__t = 0;
  57395. var animator = symbol.animate('', loop)
  57396. .when(period, {
  57397. __t: 1
  57398. })
  57399. .delay(delay)
  57400. .during(function () {
  57401. self.updateSymbolPosition(symbol);
  57402. });
  57403. if (!loop) {
  57404. animator.done(function () {
  57405. self.remove(symbol);
  57406. });
  57407. }
  57408. animator.start();
  57409. }
  57410. this._period = period;
  57411. this._loop = loop;
  57412. };
  57413. effectLineProto.getLineLength = function (symbol) {
  57414. // Not so accurate
  57415. return (dist(symbol.__p1, symbol.__cp1)
  57416. + dist(symbol.__cp1, symbol.__p2));
  57417. };
  57418. effectLineProto.updateAnimationPoints = function (symbol, points) {
  57419. symbol.__p1 = points[0];
  57420. symbol.__p2 = points[1];
  57421. symbol.__cp1 = points[2] || [
  57422. (points[0][0] + points[1][0]) / 2,
  57423. (points[0][1] + points[1][1]) / 2
  57424. ];
  57425. };
  57426. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  57427. this.childAt(0).updateData(lineData, idx, seriesScope);
  57428. this._updateEffectSymbol(lineData, idx);
  57429. };
  57430. effectLineProto.updateSymbolPosition = function (symbol) {
  57431. var p1 = symbol.__p1;
  57432. var p2 = symbol.__p2;
  57433. var cp1 = symbol.__cp1;
  57434. var t = symbol.__t;
  57435. var pos = symbol.position;
  57436. var quadraticAt$$1 = quadraticAt;
  57437. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  57438. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  57439. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  57440. // Tangent
  57441. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  57442. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  57443. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  57444. symbol.ignore = false;
  57445. };
  57446. effectLineProto.updateLayout = function (lineData, idx) {
  57447. this.childAt(0).updateLayout(lineData, idx);
  57448. var effectModel = lineData.getItemModel(idx).getModel('effect');
  57449. this._updateEffectAnimation(lineData, effectModel, idx);
  57450. };
  57451. inherits(EffectLine, Group);
  57452. /*
  57453. * Licensed to the Apache Software Foundation (ASF) under one
  57454. * or more contributor license agreements. See the NOTICE file
  57455. * distributed with this work for additional information
  57456. * regarding copyright ownership. The ASF licenses this file
  57457. * to you under the Apache License, Version 2.0 (the
  57458. * "License"); you may not use this file except in compliance
  57459. * with the License. You may obtain a copy of the License at
  57460. *
  57461. * http://www.apache.org/licenses/LICENSE-2.0
  57462. *
  57463. * Unless required by applicable law or agreed to in writing,
  57464. * software distributed under the License is distributed on an
  57465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57466. * KIND, either express or implied. See the License for the
  57467. * specific language governing permissions and limitations
  57468. * under the License.
  57469. */
  57470. /**
  57471. * @module echarts/chart/helper/Line
  57472. */
  57473. /**
  57474. * @constructor
  57475. * @extends {module:zrender/graphic/Group}
  57476. * @alias {module:echarts/chart/helper/Polyline}
  57477. */
  57478. function Polyline$2(lineData, idx, seriesScope) {
  57479. Group.call(this);
  57480. this._createPolyline(lineData, idx, seriesScope);
  57481. }
  57482. var polylineProto = Polyline$2.prototype;
  57483. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  57484. // var seriesModel = lineData.hostModel;
  57485. var points = lineData.getItemLayout(idx);
  57486. var line = new Polyline({
  57487. shape: {
  57488. points: points
  57489. }
  57490. });
  57491. this.add(line);
  57492. this._updateCommonStl(lineData, idx, seriesScope);
  57493. };
  57494. polylineProto.updateData = function (lineData, idx, seriesScope) {
  57495. var seriesModel = lineData.hostModel;
  57496. var line = this.childAt(0);
  57497. var target = {
  57498. shape: {
  57499. points: lineData.getItemLayout(idx)
  57500. }
  57501. };
  57502. updateProps(line, target, seriesModel, idx);
  57503. this._updateCommonStl(lineData, idx, seriesScope);
  57504. };
  57505. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  57506. var line = this.childAt(0);
  57507. var itemModel = lineData.getItemModel(idx);
  57508. var visualColor = lineData.getItemVisual(idx, 'color');
  57509. var lineStyle = seriesScope && seriesScope.lineStyle;
  57510. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  57511. if (!seriesScope || lineData.hasItemOption) {
  57512. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  57513. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  57514. }
  57515. line.useStyle(defaults(
  57516. {
  57517. strokeNoScale: true,
  57518. fill: 'none',
  57519. stroke: visualColor
  57520. },
  57521. lineStyle
  57522. ));
  57523. line.hoverStyle = hoverLineStyle;
  57524. setHoverStyle(this);
  57525. };
  57526. polylineProto.updateLayout = function (lineData, idx) {
  57527. var polyline = this.childAt(0);
  57528. polyline.setShape('points', lineData.getItemLayout(idx));
  57529. };
  57530. inherits(Polyline$2, Group);
  57531. /*
  57532. * Licensed to the Apache Software Foundation (ASF) under one
  57533. * or more contributor license agreements. See the NOTICE file
  57534. * distributed with this work for additional information
  57535. * regarding copyright ownership. The ASF licenses this file
  57536. * to you under the Apache License, Version 2.0 (the
  57537. * "License"); you may not use this file except in compliance
  57538. * with the License. You may obtain a copy of the License at
  57539. *
  57540. * http://www.apache.org/licenses/LICENSE-2.0
  57541. *
  57542. * Unless required by applicable law or agreed to in writing,
  57543. * software distributed under the License is distributed on an
  57544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57545. * KIND, either express or implied. See the License for the
  57546. * specific language governing permissions and limitations
  57547. * under the License.
  57548. */
  57549. /**
  57550. * Provide effect for line
  57551. * @module echarts/chart/helper/EffectLine
  57552. */
  57553. /**
  57554. * @constructor
  57555. * @extends {module:echarts/chart/helper/EffectLine}
  57556. * @alias {module:echarts/chart/helper/Polyline}
  57557. */
  57558. function EffectPolyline(lineData, idx, seriesScope) {
  57559. EffectLine.call(this, lineData, idx, seriesScope);
  57560. this._lastFrame = 0;
  57561. this._lastFramePercent = 0;
  57562. }
  57563. var effectPolylineProto = EffectPolyline.prototype;
  57564. // Overwrite
  57565. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  57566. return new Polyline$2(lineData, idx, seriesScope);
  57567. };
  57568. // Overwrite
  57569. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  57570. this._points = points;
  57571. var accLenArr = [0];
  57572. var len$$1 = 0;
  57573. for (var i = 1; i < points.length; i++) {
  57574. var p1 = points[i - 1];
  57575. var p2 = points[i];
  57576. len$$1 += dist(p1, p2);
  57577. accLenArr.push(len$$1);
  57578. }
  57579. if (len$$1 === 0) {
  57580. return;
  57581. }
  57582. for (var i = 0; i < accLenArr.length; i++) {
  57583. accLenArr[i] /= len$$1;
  57584. }
  57585. this._offsets = accLenArr;
  57586. this._length = len$$1;
  57587. };
  57588. // Overwrite
  57589. effectPolylineProto.getLineLength = function (symbol) {
  57590. return this._length;
  57591. };
  57592. // Overwrite
  57593. effectPolylineProto.updateSymbolPosition = function (symbol) {
  57594. var t = symbol.__t;
  57595. var points = this._points;
  57596. var offsets = this._offsets;
  57597. var len$$1 = points.length;
  57598. if (!offsets) {
  57599. // Has length 0
  57600. return;
  57601. }
  57602. var lastFrame = this._lastFrame;
  57603. var frame;
  57604. if (t < this._lastFramePercent) {
  57605. // Start from the next frame
  57606. // PENDING start from lastFrame ?
  57607. var start = Math.min(lastFrame + 1, len$$1 - 1);
  57608. for (frame = start; frame >= 0; frame--) {
  57609. if (offsets[frame] <= t) {
  57610. break;
  57611. }
  57612. }
  57613. // PENDING really need to do this ?
  57614. frame = Math.min(frame, len$$1 - 2);
  57615. }
  57616. else {
  57617. for (var frame = lastFrame; frame < len$$1; frame++) {
  57618. if (offsets[frame] > t) {
  57619. break;
  57620. }
  57621. }
  57622. frame = Math.min(frame - 1, len$$1 - 2);
  57623. }
  57624. lerp(
  57625. symbol.position, points[frame], points[frame + 1],
  57626. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  57627. );
  57628. var tx = points[frame + 1][0] - points[frame][0];
  57629. var ty = points[frame + 1][1] - points[frame][1];
  57630. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  57631. this._lastFrame = frame;
  57632. this._lastFramePercent = t;
  57633. symbol.ignore = false;
  57634. };
  57635. inherits(EffectPolyline, EffectLine);
  57636. /*
  57637. * Licensed to the Apache Software Foundation (ASF) under one
  57638. * or more contributor license agreements. See the NOTICE file
  57639. * distributed with this work for additional information
  57640. * regarding copyright ownership. The ASF licenses this file
  57641. * to you under the Apache License, Version 2.0 (the
  57642. * "License"); you may not use this file except in compliance
  57643. * with the License. You may obtain a copy of the License at
  57644. *
  57645. * http://www.apache.org/licenses/LICENSE-2.0
  57646. *
  57647. * Unless required by applicable law or agreed to in writing,
  57648. * software distributed under the License is distributed on an
  57649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57650. * KIND, either express or implied. See the License for the
  57651. * specific language governing permissions and limitations
  57652. * under the License.
  57653. */
  57654. // TODO Batch by color
  57655. var LargeLineShape = extendShape({
  57656. shape: {
  57657. polyline: false,
  57658. curveness: 0,
  57659. segs: []
  57660. },
  57661. buildPath: function (path, shape) {
  57662. var segs = shape.segs;
  57663. var curveness = shape.curveness;
  57664. if (shape.polyline) {
  57665. for (var i = 0; i < segs.length;) {
  57666. var count = segs[i++];
  57667. if (count > 0) {
  57668. path.moveTo(segs[i++], segs[i++]);
  57669. for (var k = 1; k < count; k++) {
  57670. path.lineTo(segs[i++], segs[i++]);
  57671. }
  57672. }
  57673. }
  57674. }
  57675. else {
  57676. for (var i = 0; i < segs.length;) {
  57677. var x0 = segs[i++];
  57678. var y0 = segs[i++];
  57679. var x1 = segs[i++];
  57680. var y1 = segs[i++];
  57681. path.moveTo(x0, y0);
  57682. if (curveness > 0) {
  57683. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  57684. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  57685. path.quadraticCurveTo(x2, y2, x1, y1);
  57686. }
  57687. else {
  57688. path.lineTo(x1, y1);
  57689. }
  57690. }
  57691. }
  57692. },
  57693. findDataIndex: function (x, y) {
  57694. var shape = this.shape;
  57695. var segs = shape.segs;
  57696. var curveness = shape.curveness;
  57697. if (shape.polyline) {
  57698. var dataIndex = 0;
  57699. for (var i = 0; i < segs.length;) {
  57700. var count = segs[i++];
  57701. if (count > 0) {
  57702. var x0 = segs[i++];
  57703. var y0 = segs[i++];
  57704. for (var k = 1; k < count; k++) {
  57705. var x1 = segs[i++];
  57706. var y1 = segs[i++];
  57707. if (containStroke$1(x0, y0, x1, y1)) {
  57708. return dataIndex;
  57709. }
  57710. }
  57711. }
  57712. dataIndex++;
  57713. }
  57714. }
  57715. else {
  57716. var dataIndex = 0;
  57717. for (var i = 0; i < segs.length;) {
  57718. var x0 = segs[i++];
  57719. var y0 = segs[i++];
  57720. var x1 = segs[i++];
  57721. var y1 = segs[i++];
  57722. if (curveness > 0) {
  57723. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  57724. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  57725. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  57726. return dataIndex;
  57727. }
  57728. }
  57729. else {
  57730. if (containStroke$1(x0, y0, x1, y1)) {
  57731. return dataIndex;
  57732. }
  57733. }
  57734. dataIndex++;
  57735. }
  57736. }
  57737. return -1;
  57738. }
  57739. });
  57740. function LargeLineDraw() {
  57741. this.group = new Group();
  57742. }
  57743. var largeLineProto = LargeLineDraw.prototype;
  57744. largeLineProto.isPersistent = function () {
  57745. return !this._incremental;
  57746. };
  57747. /**
  57748. * Update symbols draw by new data
  57749. * @param {module:echarts/data/List} data
  57750. */
  57751. largeLineProto.updateData = function (data) {
  57752. this.group.removeAll();
  57753. var lineEl = new LargeLineShape({
  57754. rectHover: true,
  57755. cursor: 'default'
  57756. });
  57757. lineEl.setShape({
  57758. segs: data.getLayout('linesPoints')
  57759. });
  57760. this._setCommon(lineEl, data);
  57761. // Add back
  57762. this.group.add(lineEl);
  57763. this._incremental = null;
  57764. };
  57765. /**
  57766. * @override
  57767. */
  57768. largeLineProto.incrementalPrepareUpdate = function (data) {
  57769. this.group.removeAll();
  57770. this._clearIncremental();
  57771. if (data.count() > 5e5) {
  57772. if (!this._incremental) {
  57773. this._incremental = new IncrementalDisplayble({
  57774. silent: true
  57775. });
  57776. }
  57777. this.group.add(this._incremental);
  57778. }
  57779. else {
  57780. this._incremental = null;
  57781. }
  57782. };
  57783. /**
  57784. * @override
  57785. */
  57786. largeLineProto.incrementalUpdate = function (taskParams, data) {
  57787. var lineEl = new LargeLineShape();
  57788. lineEl.setShape({
  57789. segs: data.getLayout('linesPoints')
  57790. });
  57791. this._setCommon(lineEl, data, !!this._incremental);
  57792. if (!this._incremental) {
  57793. lineEl.rectHover = true;
  57794. lineEl.cursor = 'default';
  57795. lineEl.__startIndex = taskParams.start;
  57796. this.group.add(lineEl);
  57797. }
  57798. else {
  57799. this._incremental.addDisplayable(lineEl, true);
  57800. }
  57801. };
  57802. /**
  57803. * @override
  57804. */
  57805. largeLineProto.remove = function () {
  57806. this._clearIncremental();
  57807. this._incremental = null;
  57808. this.group.removeAll();
  57809. };
  57810. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  57811. var hostModel = data.hostModel;
  57812. lineEl.setShape({
  57813. polyline: hostModel.get('polyline'),
  57814. curveness: hostModel.get('lineStyle.curveness')
  57815. });
  57816. lineEl.useStyle(
  57817. hostModel.getModel('lineStyle').getLineStyle()
  57818. );
  57819. lineEl.style.strokeNoScale = true;
  57820. var visualColor = data.getVisual('color');
  57821. if (visualColor) {
  57822. lineEl.setStyle('stroke', visualColor);
  57823. }
  57824. lineEl.setStyle('fill');
  57825. if (!isIncremental) {
  57826. // Enable tooltip
  57827. // PENDING May have performance issue when path is extremely large
  57828. lineEl.seriesIndex = hostModel.seriesIndex;
  57829. lineEl.on('mousemove', function (e) {
  57830. lineEl.dataIndex = null;
  57831. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  57832. if (dataIndex > 0) {
  57833. // Provide dataIndex for tooltip
  57834. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  57835. }
  57836. });
  57837. }
  57838. };
  57839. largeLineProto._clearIncremental = function () {
  57840. var incremental = this._incremental;
  57841. if (incremental) {
  57842. incremental.clearDisplaybles();
  57843. }
  57844. };
  57845. /*
  57846. * Licensed to the Apache Software Foundation (ASF) under one
  57847. * or more contributor license agreements. See the NOTICE file
  57848. * distributed with this work for additional information
  57849. * regarding copyright ownership. The ASF licenses this file
  57850. * to you under the Apache License, Version 2.0 (the
  57851. * "License"); you may not use this file except in compliance
  57852. * with the License. You may obtain a copy of the License at
  57853. *
  57854. * http://www.apache.org/licenses/LICENSE-2.0
  57855. *
  57856. * Unless required by applicable law or agreed to in writing,
  57857. * software distributed under the License is distributed on an
  57858. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57859. * KIND, either express or implied. See the License for the
  57860. * specific language governing permissions and limitations
  57861. * under the License.
  57862. */
  57863. /* global Float32Array */
  57864. var linesLayout = {
  57865. seriesType: 'lines',
  57866. plan: createRenderPlanner(),
  57867. reset: function (seriesModel) {
  57868. var coordSys = seriesModel.coordinateSystem;
  57869. var isPolyline = seriesModel.get('polyline');
  57870. var isLarge = seriesModel.pipelineContext.large;
  57871. function progress(params, lineData) {
  57872. var lineCoords = [];
  57873. if (isLarge) {
  57874. var points;
  57875. var segCount = params.end - params.start;
  57876. if (isPolyline) {
  57877. var totalCoordsCount = 0;
  57878. for (var i = params.start; i < params.end; i++) {
  57879. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  57880. }
  57881. points = new Float32Array(segCount + totalCoordsCount * 2);
  57882. }
  57883. else {
  57884. points = new Float32Array(segCount * 4);
  57885. }
  57886. var offset = 0;
  57887. var pt = [];
  57888. for (var i = params.start; i < params.end; i++) {
  57889. var len = seriesModel.getLineCoords(i, lineCoords);
  57890. if (isPolyline) {
  57891. points[offset++] = len;
  57892. }
  57893. for (var k = 0; k < len; k++) {
  57894. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  57895. points[offset++] = pt[0];
  57896. points[offset++] = pt[1];
  57897. }
  57898. }
  57899. lineData.setLayout('linesPoints', points);
  57900. }
  57901. else {
  57902. for (var i = params.start; i < params.end; i++) {
  57903. var itemModel = lineData.getItemModel(i);
  57904. var len = seriesModel.getLineCoords(i, lineCoords);
  57905. var pts = [];
  57906. if (isPolyline) {
  57907. for (var j = 0; j < len; j++) {
  57908. pts.push(coordSys.dataToPoint(lineCoords[j]));
  57909. }
  57910. }
  57911. else {
  57912. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  57913. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  57914. var curveness = itemModel.get('lineStyle.curveness');
  57915. if (+curveness) {
  57916. pts[2] = [
  57917. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  57918. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  57919. ];
  57920. }
  57921. }
  57922. lineData.setItemLayout(i, pts);
  57923. }
  57924. }
  57925. }
  57926. return { progress: progress };
  57927. }
  57928. };
  57929. /*
  57930. * Licensed to the Apache Software Foundation (ASF) under one
  57931. * or more contributor license agreements. See the NOTICE file
  57932. * distributed with this work for additional information
  57933. * regarding copyright ownership. The ASF licenses this file
  57934. * to you under the Apache License, Version 2.0 (the
  57935. * "License"); you may not use this file except in compliance
  57936. * with the License. You may obtain a copy of the License at
  57937. *
  57938. * http://www.apache.org/licenses/LICENSE-2.0
  57939. *
  57940. * Unless required by applicable law or agreed to in writing,
  57941. * software distributed under the License is distributed on an
  57942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57943. * KIND, either express or implied. See the License for the
  57944. * specific language governing permissions and limitations
  57945. * under the License.
  57946. */
  57947. extendChartView({
  57948. type: 'lines',
  57949. init: function () {},
  57950. render: function (seriesModel, ecModel, api) {
  57951. var data = seriesModel.getData();
  57952. var lineDraw = this._updateLineDraw(data, seriesModel);
  57953. var zlevel = seriesModel.get('zlevel');
  57954. var trailLength = seriesModel.get('effect.trailLength');
  57955. var zr = api.getZr();
  57956. // Avoid the drag cause ghost shadow
  57957. // FIXME Better way ?
  57958. // SVG doesn't support
  57959. var isSvg = zr.painter.getType() === 'svg';
  57960. if (!isSvg) {
  57961. zr.painter.getLayer(zlevel).clear(true);
  57962. }
  57963. // Config layer with motion blur
  57964. if (this._lastZlevel != null && !isSvg) {
  57965. zr.configLayer(this._lastZlevel, {
  57966. motionBlur: false
  57967. });
  57968. }
  57969. if (this._showEffect(seriesModel) && trailLength) {
  57970. if (__DEV__) {
  57971. var notInIndividual = false;
  57972. ecModel.eachSeries(function (otherSeriesModel) {
  57973. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  57974. notInIndividual = true;
  57975. }
  57976. });
  57977. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  57978. }
  57979. if (!isSvg) {
  57980. zr.configLayer(zlevel, {
  57981. motionBlur: true,
  57982. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  57983. });
  57984. }
  57985. }
  57986. lineDraw.updateData(data);
  57987. var clipPath = seriesModel.get('clip', true) && createClipPath(
  57988. seriesModel.coordinateSystem, false, seriesModel
  57989. );
  57990. if (clipPath) {
  57991. this.group.setClipPath(clipPath);
  57992. }
  57993. else {
  57994. this.group.removeClipPath();
  57995. }
  57996. this._lastZlevel = zlevel;
  57997. this._finished = true;
  57998. },
  57999. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  58000. var data = seriesModel.getData();
  58001. var lineDraw = this._updateLineDraw(data, seriesModel);
  58002. lineDraw.incrementalPrepareUpdate(data);
  58003. this._clearLayer(api);
  58004. this._finished = false;
  58005. },
  58006. incrementalRender: function (taskParams, seriesModel, ecModel) {
  58007. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  58008. this._finished = taskParams.end === seriesModel.getData().count();
  58009. },
  58010. updateTransform: function (seriesModel, ecModel, api) {
  58011. var data = seriesModel.getData();
  58012. var pipelineContext = seriesModel.pipelineContext;
  58013. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  58014. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  58015. return {
  58016. update: true
  58017. };
  58018. }
  58019. else {
  58020. // TODO Use same logic with ScatterView.
  58021. // Manually update layout
  58022. var res = linesLayout.reset(seriesModel);
  58023. if (res.progress) {
  58024. res.progress({ start: 0, end: data.count() }, data);
  58025. }
  58026. this._lineDraw.updateLayout();
  58027. this._clearLayer(api);
  58028. }
  58029. },
  58030. _updateLineDraw: function (data, seriesModel) {
  58031. var lineDraw = this._lineDraw;
  58032. var hasEffect = this._showEffect(seriesModel);
  58033. var isPolyline = !!seriesModel.get('polyline');
  58034. var pipelineContext = seriesModel.pipelineContext;
  58035. var isLargeDraw = pipelineContext.large;
  58036. if (__DEV__) {
  58037. if (hasEffect && isLargeDraw) {
  58038. console.warn('Large lines not support effect');
  58039. }
  58040. }
  58041. if (!lineDraw
  58042. || hasEffect !== this._hasEffet
  58043. || isPolyline !== this._isPolyline
  58044. || isLargeDraw !== this._isLargeDraw
  58045. ) {
  58046. if (lineDraw) {
  58047. lineDraw.remove();
  58048. }
  58049. lineDraw = this._lineDraw = isLargeDraw
  58050. ? new LargeLineDraw()
  58051. : new LineDraw(
  58052. isPolyline
  58053. ? (hasEffect ? EffectPolyline : Polyline$2)
  58054. : (hasEffect ? EffectLine : Line$1)
  58055. );
  58056. this._hasEffet = hasEffect;
  58057. this._isPolyline = isPolyline;
  58058. this._isLargeDraw = isLargeDraw;
  58059. this.group.removeAll();
  58060. }
  58061. this.group.add(lineDraw.group);
  58062. return lineDraw;
  58063. },
  58064. _showEffect: function (seriesModel) {
  58065. return !!seriesModel.get('effect.show');
  58066. },
  58067. _clearLayer: function (api) {
  58068. // Not use motion when dragging or zooming
  58069. var zr = api.getZr();
  58070. var isSvg = zr.painter.getType() === 'svg';
  58071. if (!isSvg && this._lastZlevel != null) {
  58072. zr.painter.getLayer(this._lastZlevel).clear(true);
  58073. }
  58074. },
  58075. remove: function (ecModel, api) {
  58076. this._lineDraw && this._lineDraw.remove();
  58077. this._lineDraw = null;
  58078. // Clear motion when lineDraw is removed
  58079. this._clearLayer(api);
  58080. },
  58081. dispose: function () {}
  58082. });
  58083. /*
  58084. * Licensed to the Apache Software Foundation (ASF) under one
  58085. * or more contributor license agreements. See the NOTICE file
  58086. * distributed with this work for additional information
  58087. * regarding copyright ownership. The ASF licenses this file
  58088. * to you under the Apache License, Version 2.0 (the
  58089. * "License"); you may not use this file except in compliance
  58090. * with the License. You may obtain a copy of the License at
  58091. *
  58092. * http://www.apache.org/licenses/LICENSE-2.0
  58093. *
  58094. * Unless required by applicable law or agreed to in writing,
  58095. * software distributed under the License is distributed on an
  58096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58097. * KIND, either express or implied. See the License for the
  58098. * specific language governing permissions and limitations
  58099. * under the License.
  58100. */
  58101. function normalize$2(a) {
  58102. if (!(a instanceof Array)) {
  58103. a = [a, a];
  58104. }
  58105. return a;
  58106. }
  58107. var opacityQuery = 'lineStyle.opacity'.split('.');
  58108. var linesVisual = {
  58109. seriesType: 'lines',
  58110. reset: function (seriesModel, ecModel, api) {
  58111. var symbolType = normalize$2(seriesModel.get('symbol'));
  58112. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  58113. var data = seriesModel.getData();
  58114. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  58115. data.setVisual('toSymbol', symbolType && symbolType[1]);
  58116. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  58117. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  58118. data.setVisual('opacity', seriesModel.get(opacityQuery));
  58119. function dataEach(data, idx) {
  58120. var itemModel = data.getItemModel(idx);
  58121. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  58122. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  58123. var opacity = itemModel.get(opacityQuery);
  58124. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  58125. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  58126. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  58127. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  58128. data.setItemVisual(idx, 'opacity', opacity);
  58129. }
  58130. return {dataEach: data.hasItemOption ? dataEach : null};
  58131. }
  58132. };
  58133. /*
  58134. * Licensed to the Apache Software Foundation (ASF) under one
  58135. * or more contributor license agreements. See the NOTICE file
  58136. * distributed with this work for additional information
  58137. * regarding copyright ownership. The ASF licenses this file
  58138. * to you under the Apache License, Version 2.0 (the
  58139. * "License"); you may not use this file except in compliance
  58140. * with the License. You may obtain a copy of the License at
  58141. *
  58142. * http://www.apache.org/licenses/LICENSE-2.0
  58143. *
  58144. * Unless required by applicable law or agreed to in writing,
  58145. * software distributed under the License is distributed on an
  58146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58147. * KIND, either express or implied. See the License for the
  58148. * specific language governing permissions and limitations
  58149. * under the License.
  58150. */
  58151. registerLayout(linesLayout);
  58152. registerVisual(linesVisual);
  58153. /*
  58154. * Licensed to the Apache Software Foundation (ASF) under one
  58155. * or more contributor license agreements. See the NOTICE file
  58156. * distributed with this work for additional information
  58157. * regarding copyright ownership. The ASF licenses this file
  58158. * to you under the Apache License, Version 2.0 (the
  58159. * "License"); you may not use this file except in compliance
  58160. * with the License. You may obtain a copy of the License at
  58161. *
  58162. * http://www.apache.org/licenses/LICENSE-2.0
  58163. *
  58164. * Unless required by applicable law or agreed to in writing,
  58165. * software distributed under the License is distributed on an
  58166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58167. * KIND, either express or implied. See the License for the
  58168. * specific language governing permissions and limitations
  58169. * under the License.
  58170. */
  58171. SeriesModel.extend({
  58172. type: 'series.heatmap',
  58173. getInitialData: function (option, ecModel) {
  58174. return createListFromArray(this.getSource(), this, {
  58175. generateCoord: 'value'
  58176. });
  58177. },
  58178. preventIncremental: function () {
  58179. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  58180. if (coordSysCreator && coordSysCreator.dimensions) {
  58181. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  58182. }
  58183. },
  58184. defaultOption: {
  58185. // Cartesian2D or geo
  58186. coordinateSystem: 'cartesian2d',
  58187. zlevel: 0,
  58188. z: 2,
  58189. // Cartesian coordinate system
  58190. // xAxisIndex: 0,
  58191. // yAxisIndex: 0,
  58192. // Geo coordinate system
  58193. geoIndex: 0,
  58194. blurSize: 30,
  58195. pointSize: 20,
  58196. maxOpacity: 1,
  58197. minOpacity: 0
  58198. }
  58199. });
  58200. /*
  58201. * Licensed to the Apache Software Foundation (ASF) under one
  58202. * or more contributor license agreements. See the NOTICE file
  58203. * distributed with this work for additional information
  58204. * regarding copyright ownership. The ASF licenses this file
  58205. * to you under the Apache License, Version 2.0 (the
  58206. * "License"); you may not use this file except in compliance
  58207. * with the License. You may obtain a copy of the License at
  58208. *
  58209. * http://www.apache.org/licenses/LICENSE-2.0
  58210. *
  58211. * Unless required by applicable law or agreed to in writing,
  58212. * software distributed under the License is distributed on an
  58213. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58214. * KIND, either express or implied. See the License for the
  58215. * specific language governing permissions and limitations
  58216. * under the License.
  58217. */
  58218. /* global Uint8ClampedArray */
  58219. var GRADIENT_LEVELS = 256;
  58220. /**
  58221. * Heatmap Chart
  58222. *
  58223. * @class
  58224. */
  58225. function Heatmap() {
  58226. var canvas = createCanvas();
  58227. this.canvas = canvas;
  58228. this.blurSize = 30;
  58229. this.pointSize = 20;
  58230. this.maxOpacity = 1;
  58231. this.minOpacity = 0;
  58232. this._gradientPixels = {};
  58233. }
  58234. Heatmap.prototype = {
  58235. /**
  58236. * Renders Heatmap and returns the rendered canvas
  58237. * @param {Array} data array of data, each has x, y, value
  58238. * @param {number} width canvas width
  58239. * @param {number} height canvas height
  58240. */
  58241. update: function (data, width, height, normalize, colorFunc, isInRange) {
  58242. var brush = this._getBrush();
  58243. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  58244. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  58245. var r = this.pointSize + this.blurSize;
  58246. var canvas = this.canvas;
  58247. var ctx = canvas.getContext('2d');
  58248. var len = data.length;
  58249. canvas.width = width;
  58250. canvas.height = height;
  58251. for (var i = 0; i < len; ++i) {
  58252. var p = data[i];
  58253. var x = p[0];
  58254. var y = p[1];
  58255. var value = p[2];
  58256. // calculate alpha using value
  58257. var alpha = normalize(value);
  58258. // draw with the circle brush with alpha
  58259. ctx.globalAlpha = alpha;
  58260. ctx.drawImage(brush, x - r, y - r);
  58261. }
  58262. if (!canvas.width || !canvas.height) {
  58263. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  58264. // 'CanvasRenderingContext2D': The source height is 0."
  58265. return canvas;
  58266. }
  58267. // colorize the canvas using alpha value and set with gradient
  58268. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  58269. var pixels = imageData.data;
  58270. var offset = 0;
  58271. var pixelLen = pixels.length;
  58272. var minOpacity = this.minOpacity;
  58273. var maxOpacity = this.maxOpacity;
  58274. var diffOpacity = maxOpacity - minOpacity;
  58275. while (offset < pixelLen) {
  58276. var alpha = pixels[offset + 3] / 256;
  58277. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  58278. // Simple optimize to ignore the empty data
  58279. if (alpha > 0) {
  58280. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  58281. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  58282. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  58283. pixels[offset++] = gradient[gradientOffset];
  58284. pixels[offset++] = gradient[gradientOffset + 1];
  58285. pixels[offset++] = gradient[gradientOffset + 2];
  58286. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  58287. }
  58288. else {
  58289. offset += 4;
  58290. }
  58291. }
  58292. ctx.putImageData(imageData, 0, 0);
  58293. return canvas;
  58294. },
  58295. /**
  58296. * get canvas of a black circle brush used for canvas to draw later
  58297. * @private
  58298. * @returns {Object} circle brush canvas
  58299. */
  58300. _getBrush: function () {
  58301. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  58302. // set brush size
  58303. var r = this.pointSize + this.blurSize;
  58304. var d = r * 2;
  58305. brushCanvas.width = d;
  58306. brushCanvas.height = d;
  58307. var ctx = brushCanvas.getContext('2d');
  58308. ctx.clearRect(0, 0, d, d);
  58309. // in order to render shadow without the distinct circle,
  58310. // draw the distinct circle in an invisible place,
  58311. // and use shadowOffset to draw shadow in the center of the canvas
  58312. ctx.shadowOffsetX = d;
  58313. ctx.shadowBlur = this.blurSize;
  58314. // draw the shadow in black, and use alpha and shadow blur to generate
  58315. // color in color map
  58316. ctx.shadowColor = '#000';
  58317. // draw circle in the left to the canvas
  58318. ctx.beginPath();
  58319. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  58320. ctx.closePath();
  58321. ctx.fill();
  58322. return brushCanvas;
  58323. },
  58324. /**
  58325. * get gradient color map
  58326. * @private
  58327. */
  58328. _getGradient: function (data, colorFunc, state) {
  58329. var gradientPixels = this._gradientPixels;
  58330. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  58331. var color = [0, 0, 0, 0];
  58332. var off = 0;
  58333. for (var i = 0; i < 256; i++) {
  58334. colorFunc[state](i / 255, true, color);
  58335. pixelsSingleState[off++] = color[0];
  58336. pixelsSingleState[off++] = color[1];
  58337. pixelsSingleState[off++] = color[2];
  58338. pixelsSingleState[off++] = color[3];
  58339. }
  58340. return pixelsSingleState;
  58341. }
  58342. };
  58343. /*
  58344. * Licensed to the Apache Software Foundation (ASF) under one
  58345. * or more contributor license agreements. See the NOTICE file
  58346. * distributed with this work for additional information
  58347. * regarding copyright ownership. The ASF licenses this file
  58348. * to you under the Apache License, Version 2.0 (the
  58349. * "License"); you may not use this file except in compliance
  58350. * with the License. You may obtain a copy of the License at
  58351. *
  58352. * http://www.apache.org/licenses/LICENSE-2.0
  58353. *
  58354. * Unless required by applicable law or agreed to in writing,
  58355. * software distributed under the License is distributed on an
  58356. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58357. * KIND, either express or implied. See the License for the
  58358. * specific language governing permissions and limitations
  58359. * under the License.
  58360. */
  58361. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  58362. var dataSpan = dataExtent[1] - dataExtent[0];
  58363. pieceList = map(pieceList, function (piece) {
  58364. return {
  58365. interval: [
  58366. (piece.interval[0] - dataExtent[0]) / dataSpan,
  58367. (piece.interval[1] - dataExtent[0]) / dataSpan
  58368. ]
  58369. };
  58370. });
  58371. var len = pieceList.length;
  58372. var lastIndex = 0;
  58373. return function (val) {
  58374. // Try to find in the location of the last found
  58375. for (var i = lastIndex; i < len; i++) {
  58376. var interval = pieceList[i].interval;
  58377. if (interval[0] <= val && val <= interval[1]) {
  58378. lastIndex = i;
  58379. break;
  58380. }
  58381. }
  58382. if (i === len) { // Not found, back interation
  58383. for (var i = lastIndex - 1; i >= 0; i--) {
  58384. var interval = pieceList[i].interval;
  58385. if (interval[0] <= val && val <= interval[1]) {
  58386. lastIndex = i;
  58387. break;
  58388. }
  58389. }
  58390. }
  58391. return i >= 0 && i < len && selected[i];
  58392. };
  58393. }
  58394. function getIsInContinuousRange(dataExtent, range) {
  58395. var dataSpan = dataExtent[1] - dataExtent[0];
  58396. range = [
  58397. (range[0] - dataExtent[0]) / dataSpan,
  58398. (range[1] - dataExtent[0]) / dataSpan
  58399. ];
  58400. return function (val) {
  58401. return val >= range[0] && val <= range[1];
  58402. };
  58403. }
  58404. function isGeoCoordSys(coordSys) {
  58405. var dimensions = coordSys.dimensions;
  58406. // Not use coorSys.type === 'geo' because coordSys maybe extended
  58407. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  58408. }
  58409. extendChartView({
  58410. type: 'heatmap',
  58411. render: function (seriesModel, ecModel, api) {
  58412. var visualMapOfThisSeries;
  58413. ecModel.eachComponent('visualMap', function (visualMap) {
  58414. visualMap.eachTargetSeries(function (targetSeries) {
  58415. if (targetSeries === seriesModel) {
  58416. visualMapOfThisSeries = visualMap;
  58417. }
  58418. });
  58419. });
  58420. if (__DEV__) {
  58421. if (!visualMapOfThisSeries) {
  58422. throw new Error('Heatmap must use with visualMap');
  58423. }
  58424. }
  58425. this.group.removeAll();
  58426. this._incrementalDisplayable = null;
  58427. var coordSys = seriesModel.coordinateSystem;
  58428. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  58429. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  58430. }
  58431. else if (isGeoCoordSys(coordSys)) {
  58432. this._renderOnGeo(
  58433. coordSys, seriesModel, visualMapOfThisSeries, api
  58434. );
  58435. }
  58436. },
  58437. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  58438. this.group.removeAll();
  58439. },
  58440. incrementalRender: function (params, seriesModel, ecModel, api) {
  58441. var coordSys = seriesModel.coordinateSystem;
  58442. if (coordSys) {
  58443. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  58444. }
  58445. },
  58446. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  58447. var coordSys = seriesModel.coordinateSystem;
  58448. var width;
  58449. var height;
  58450. if (coordSys.type === 'cartesian2d') {
  58451. var xAxis = coordSys.getAxis('x');
  58452. var yAxis = coordSys.getAxis('y');
  58453. if (__DEV__) {
  58454. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  58455. throw new Error('Heatmap on cartesian must have two category axes');
  58456. }
  58457. if (!(xAxis.onBand && yAxis.onBand)) {
  58458. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  58459. }
  58460. }
  58461. width = xAxis.getBandWidth();
  58462. height = yAxis.getBandWidth();
  58463. }
  58464. var group = this.group;
  58465. var data = seriesModel.getData();
  58466. var itemStyleQuery = 'itemStyle';
  58467. var hoverItemStyleQuery = 'emphasis.itemStyle';
  58468. var labelQuery = 'label';
  58469. var hoverLabelQuery = 'emphasis.label';
  58470. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  58471. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  58472. var labelModel = seriesModel.getModel(labelQuery);
  58473. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  58474. var coordSysType = coordSys.type;
  58475. var dataDims = coordSysType === 'cartesian2d'
  58476. ? [
  58477. data.mapDimension('x'),
  58478. data.mapDimension('y'),
  58479. data.mapDimension('value')
  58480. ]
  58481. : [
  58482. data.mapDimension('time'),
  58483. data.mapDimension('value')
  58484. ];
  58485. for (var idx = start; idx < end; idx++) {
  58486. var rect;
  58487. if (coordSysType === 'cartesian2d') {
  58488. // Ignore empty data
  58489. if (isNaN(data.get(dataDims[2], idx))) {
  58490. continue;
  58491. }
  58492. var point = coordSys.dataToPoint([
  58493. data.get(dataDims[0], idx),
  58494. data.get(dataDims[1], idx)
  58495. ]);
  58496. rect = new Rect({
  58497. shape: {
  58498. x: Math.floor(point[0] - width / 2),
  58499. y: Math.floor(point[1] - height / 2),
  58500. width: Math.ceil(width),
  58501. height: Math.ceil(height)
  58502. },
  58503. style: {
  58504. fill: data.getItemVisual(idx, 'color'),
  58505. opacity: data.getItemVisual(idx, 'opacity')
  58506. }
  58507. });
  58508. }
  58509. else {
  58510. // Ignore empty data
  58511. if (isNaN(data.get(dataDims[1], idx))) {
  58512. continue;
  58513. }
  58514. rect = new Rect({
  58515. z2: 1,
  58516. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  58517. style: {
  58518. fill: data.getItemVisual(idx, 'color'),
  58519. opacity: data.getItemVisual(idx, 'opacity')
  58520. }
  58521. });
  58522. }
  58523. var itemModel = data.getItemModel(idx);
  58524. // Optimization for large datset
  58525. if (data.hasItemOption) {
  58526. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  58527. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  58528. labelModel = itemModel.getModel(labelQuery);
  58529. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  58530. }
  58531. var rawValue = seriesModel.getRawValue(idx);
  58532. var defaultText = '-';
  58533. if (rawValue && rawValue[2] != null) {
  58534. defaultText = rawValue[2];
  58535. }
  58536. setLabelStyle(
  58537. style, hoverStl, labelModel, hoverLabelModel,
  58538. {
  58539. labelFetcher: seriesModel,
  58540. labelDataIndex: idx,
  58541. defaultText: defaultText,
  58542. isRectText: true
  58543. }
  58544. );
  58545. rect.setStyle(style);
  58546. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  58547. rect.incremental = incremental;
  58548. // PENDING
  58549. if (incremental) {
  58550. // Rect must use hover layer if it's incremental.
  58551. rect.useHoverLayer = true;
  58552. }
  58553. group.add(rect);
  58554. data.setItemGraphicEl(idx, rect);
  58555. }
  58556. },
  58557. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  58558. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  58559. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  58560. // if (!visualMapping) {
  58561. // throw new Error('Data range must have color visuals');
  58562. // }
  58563. var data = seriesModel.getData();
  58564. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  58565. hmLayer.blurSize = seriesModel.get('blurSize');
  58566. hmLayer.pointSize = seriesModel.get('pointSize');
  58567. hmLayer.minOpacity = seriesModel.get('minOpacity');
  58568. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  58569. var rect = geo.getViewRect().clone();
  58570. var roamTransform = geo.getRoamTransform();
  58571. rect.applyTransform(roamTransform);
  58572. // Clamp on viewport
  58573. var x = Math.max(rect.x, 0);
  58574. var y = Math.max(rect.y, 0);
  58575. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  58576. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  58577. var width = x2 - x;
  58578. var height = y2 - y;
  58579. var dims = [
  58580. data.mapDimension('lng'),
  58581. data.mapDimension('lat'),
  58582. data.mapDimension('value')
  58583. ];
  58584. var points = data.mapArray(dims, function (lng, lat, value) {
  58585. var pt = geo.dataToPoint([lng, lat]);
  58586. pt[0] -= x;
  58587. pt[1] -= y;
  58588. pt.push(value);
  58589. return pt;
  58590. });
  58591. var dataExtent = visualMapModel.getExtent();
  58592. var isInRange = visualMapModel.type === 'visualMap.continuous'
  58593. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  58594. : getIsInPiecewiseRange(
  58595. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  58596. );
  58597. hmLayer.update(
  58598. points, width, height,
  58599. inRangeVisuals.color.getNormalizer(),
  58600. {
  58601. inRange: inRangeVisuals.color.getColorMapper(),
  58602. outOfRange: outOfRangeVisuals.color.getColorMapper()
  58603. },
  58604. isInRange
  58605. );
  58606. var img = new ZImage({
  58607. style: {
  58608. width: width,
  58609. height: height,
  58610. x: x,
  58611. y: y,
  58612. image: hmLayer.canvas
  58613. },
  58614. silent: true
  58615. });
  58616. this.group.add(img);
  58617. },
  58618. dispose: function () {}
  58619. });
  58620. /*
  58621. * Licensed to the Apache Software Foundation (ASF) under one
  58622. * or more contributor license agreements. See the NOTICE file
  58623. * distributed with this work for additional information
  58624. * regarding copyright ownership. The ASF licenses this file
  58625. * to you under the Apache License, Version 2.0 (the
  58626. * "License"); you may not use this file except in compliance
  58627. * with the License. You may obtain a copy of the License at
  58628. *
  58629. * http://www.apache.org/licenses/LICENSE-2.0
  58630. *
  58631. * Unless required by applicable law or agreed to in writing,
  58632. * software distributed under the License is distributed on an
  58633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58634. * KIND, either express or implied. See the License for the
  58635. * specific language governing permissions and limitations
  58636. * under the License.
  58637. */
  58638. /*
  58639. * Licensed to the Apache Software Foundation (ASF) under one
  58640. * or more contributor license agreements. See the NOTICE file
  58641. * distributed with this work for additional information
  58642. * regarding copyright ownership. The ASF licenses this file
  58643. * to you under the Apache License, Version 2.0 (the
  58644. * "License"); you may not use this file except in compliance
  58645. * with the License. You may obtain a copy of the License at
  58646. *
  58647. * http://www.apache.org/licenses/LICENSE-2.0
  58648. *
  58649. * Unless required by applicable law or agreed to in writing,
  58650. * software distributed under the License is distributed on an
  58651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58652. * KIND, either express or implied. See the License for the
  58653. * specific language governing permissions and limitations
  58654. * under the License.
  58655. */
  58656. var PictorialBarSeries = BaseBarSeries.extend({
  58657. type: 'series.pictorialBar',
  58658. dependencies: ['grid'],
  58659. defaultOption: {
  58660. symbol: 'circle', // Customized bar shape
  58661. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  58662. symbolRotate: null,
  58663. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  58664. symbolOffset: null,
  58665. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  58666. // Auto margin by defualt.
  58667. symbolRepeat: false, // false/null/undefined, means no repeat.
  58668. // Can be true, means auto calculate repeat times and cut by data.
  58669. // Can be a number, specifies repeat times, and do not cut by data.
  58670. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  58671. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  58672. symbolClip: false,
  58673. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  58674. symbolPatternSize: 400, // 400 * 400 px
  58675. barGap: '-100%', // In most case, overlap is needed.
  58676. // z can be set in data item, which is z2 actually.
  58677. // Disable progressive
  58678. progressive: 0,
  58679. hoverAnimation: false // Open only when needed.
  58680. },
  58681. getInitialData: function (option) {
  58682. // Disable stack.
  58683. option.stack = null;
  58684. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  58685. }
  58686. });
  58687. /*
  58688. * Licensed to the Apache Software Foundation (ASF) under one
  58689. * or more contributor license agreements. See the NOTICE file
  58690. * distributed with this work for additional information
  58691. * regarding copyright ownership. The ASF licenses this file
  58692. * to you under the Apache License, Version 2.0 (the
  58693. * "License"); you may not use this file except in compliance
  58694. * with the License. You may obtain a copy of the License at
  58695. *
  58696. * http://www.apache.org/licenses/LICENSE-2.0
  58697. *
  58698. * Unless required by applicable law or agreed to in writing,
  58699. * software distributed under the License is distributed on an
  58700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58701. * KIND, either express or implied. See the License for the
  58702. * specific language governing permissions and limitations
  58703. * under the License.
  58704. */
  58705. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  58706. // index: +isHorizontal
  58707. var LAYOUT_ATTRS = [
  58708. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  58709. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  58710. ];
  58711. var pathForLineWidth = new Circle();
  58712. var BarView$1 = extendChartView({
  58713. type: 'pictorialBar',
  58714. render: function (seriesModel, ecModel, api) {
  58715. var group = this.group;
  58716. var data = seriesModel.getData();
  58717. var oldData = this._data;
  58718. var cartesian = seriesModel.coordinateSystem;
  58719. var baseAxis = cartesian.getBaseAxis();
  58720. var isHorizontal = !!baseAxis.isHorizontal();
  58721. var coordSysRect = cartesian.grid.getRect();
  58722. var opt = {
  58723. ecSize: {width: api.getWidth(), height: api.getHeight()},
  58724. seriesModel: seriesModel,
  58725. coordSys: cartesian,
  58726. coordSysExtent: [
  58727. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  58728. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  58729. ],
  58730. isHorizontal: isHorizontal,
  58731. valueDim: LAYOUT_ATTRS[+isHorizontal],
  58732. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  58733. };
  58734. data.diff(oldData)
  58735. .add(function (dataIndex) {
  58736. if (!data.hasValue(dataIndex)) {
  58737. return;
  58738. }
  58739. var itemModel = getItemModel(data, dataIndex);
  58740. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  58741. var bar = createBar(data, opt, symbolMeta);
  58742. data.setItemGraphicEl(dataIndex, bar);
  58743. group.add(bar);
  58744. updateCommon$1(bar, opt, symbolMeta);
  58745. })
  58746. .update(function (newIndex, oldIndex) {
  58747. var bar = oldData.getItemGraphicEl(oldIndex);
  58748. if (!data.hasValue(newIndex)) {
  58749. group.remove(bar);
  58750. return;
  58751. }
  58752. var itemModel = getItemModel(data, newIndex);
  58753. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  58754. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  58755. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  58756. group.remove(bar);
  58757. data.setItemGraphicEl(newIndex, null);
  58758. bar = null;
  58759. }
  58760. if (bar) {
  58761. updateBar(bar, opt, symbolMeta);
  58762. }
  58763. else {
  58764. bar = createBar(data, opt, symbolMeta, true);
  58765. }
  58766. data.setItemGraphicEl(newIndex, bar);
  58767. bar.__pictorialSymbolMeta = symbolMeta;
  58768. // Add back
  58769. group.add(bar);
  58770. updateCommon$1(bar, opt, symbolMeta);
  58771. })
  58772. .remove(function (dataIndex) {
  58773. var bar = oldData.getItemGraphicEl(dataIndex);
  58774. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  58775. })
  58776. .execute();
  58777. this._data = data;
  58778. return this.group;
  58779. },
  58780. dispose: noop,
  58781. remove: function (ecModel, api) {
  58782. var group = this.group;
  58783. var data = this._data;
  58784. if (ecModel.get('animation')) {
  58785. if (data) {
  58786. data.eachItemGraphicEl(function (bar) {
  58787. removeBar(data, bar.dataIndex, ecModel, bar);
  58788. });
  58789. }
  58790. }
  58791. else {
  58792. group.removeAll();
  58793. }
  58794. }
  58795. });
  58796. // Set or calculate default value about symbol, and calculate layout info.
  58797. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  58798. var layout = data.getItemLayout(dataIndex);
  58799. var symbolRepeat = itemModel.get('symbolRepeat');
  58800. var symbolClip = itemModel.get('symbolClip');
  58801. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  58802. var symbolRotate = itemModel.get('symbolRotate');
  58803. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  58804. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  58805. var isAnimationEnabled = itemModel.isAnimationEnabled();
  58806. var symbolMeta = {
  58807. dataIndex: dataIndex,
  58808. layout: layout,
  58809. itemModel: itemModel,
  58810. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  58811. color: data.getItemVisual(dataIndex, 'color'),
  58812. symbolClip: symbolClip,
  58813. symbolRepeat: symbolRepeat,
  58814. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  58815. symbolPatternSize: symbolPatternSize,
  58816. rotation: rotation,
  58817. animationModel: isAnimationEnabled ? itemModel : null,
  58818. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  58819. z2: itemModel.getShallow('z', true) || 0
  58820. };
  58821. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  58822. prepareSymbolSize(
  58823. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  58824. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  58825. );
  58826. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  58827. var symbolSize = symbolMeta.symbolSize;
  58828. var symbolOffset = itemModel.get('symbolOffset');
  58829. if (isArray(symbolOffset)) {
  58830. symbolOffset = [
  58831. parsePercent$1(symbolOffset[0], symbolSize[0]),
  58832. parsePercent$1(symbolOffset[1], symbolSize[1])
  58833. ];
  58834. }
  58835. prepareLayoutInfo(
  58836. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  58837. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  58838. opt, symbolMeta
  58839. );
  58840. return symbolMeta;
  58841. }
  58842. // bar length can be negative.
  58843. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  58844. var valueDim = opt.valueDim;
  58845. var symbolBoundingData = itemModel.get('symbolBoundingData');
  58846. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  58847. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  58848. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  58849. var boundingLength;
  58850. if (isArray(symbolBoundingData)) {
  58851. var symbolBoundingExtent = [
  58852. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  58853. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  58854. ];
  58855. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  58856. boundingLength = symbolBoundingExtent[pxSignIdx];
  58857. }
  58858. else if (symbolBoundingData != null) {
  58859. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  58860. }
  58861. else if (symbolRepeat) {
  58862. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  58863. }
  58864. else {
  58865. boundingLength = layout[valueDim.wh];
  58866. }
  58867. output.boundingLength = boundingLength;
  58868. if (symbolRepeat) {
  58869. output.repeatCutLength = layout[valueDim.wh];
  58870. }
  58871. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  58872. }
  58873. function convertToCoordOnAxis(axis, value) {
  58874. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  58875. }
  58876. // Support ['100%', '100%']
  58877. function prepareSymbolSize(
  58878. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  58879. pxSign, symbolPatternSize, opt, output
  58880. ) {
  58881. var valueDim = opt.valueDim;
  58882. var categoryDim = opt.categoryDim;
  58883. var categorySize = Math.abs(layout[categoryDim.wh]);
  58884. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  58885. if (isArray(symbolSize)) {
  58886. symbolSize = symbolSize.slice();
  58887. }
  58888. else {
  58889. if (symbolSize == null) {
  58890. symbolSize = '100%';
  58891. }
  58892. symbolSize = [symbolSize, symbolSize];
  58893. }
  58894. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  58895. // to complicated to calculate real percent value if considering scaled lineWidth.
  58896. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  58897. // which can be tolerated in pictorial chart.
  58898. symbolSize[categoryDim.index] = parsePercent$1(
  58899. symbolSize[categoryDim.index],
  58900. categorySize
  58901. );
  58902. symbolSize[valueDim.index] = parsePercent$1(
  58903. symbolSize[valueDim.index],
  58904. symbolRepeat ? categorySize : Math.abs(boundingLength)
  58905. );
  58906. output.symbolSize = symbolSize;
  58907. // If x or y is less than zero, show reversed shape.
  58908. var symbolScale = output.symbolScale = [
  58909. symbolSize[0] / symbolPatternSize,
  58910. symbolSize[1] / symbolPatternSize
  58911. ];
  58912. // Follow convention, 'right' and 'top' is the normal scale.
  58913. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  58914. }
  58915. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  58916. // In symbols are drawn with scale, so do not need to care about the case that width
  58917. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  58918. // be calculated.
  58919. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  58920. if (valueLineWidth) {
  58921. pathForLineWidth.attr({
  58922. scale: symbolScale.slice(),
  58923. rotation: rotation
  58924. });
  58925. pathForLineWidth.updateTransform();
  58926. valueLineWidth /= pathForLineWidth.getLineScale();
  58927. valueLineWidth *= symbolScale[opt.valueDim.index];
  58928. }
  58929. output.valueLineWidth = valueLineWidth;
  58930. }
  58931. function prepareLayoutInfo(
  58932. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  58933. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  58934. ) {
  58935. var categoryDim = opt.categoryDim;
  58936. var valueDim = opt.valueDim;
  58937. var pxSign = output.pxSign;
  58938. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  58939. var pathLen = unitLength;
  58940. // Note: rotation will not effect the layout of symbols, because user may
  58941. // want symbols to rotate on its center, which should not be translated
  58942. // when rotating.
  58943. if (symbolRepeat) {
  58944. var absBoundingLength = Math.abs(boundingLength);
  58945. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  58946. var hasEndGap = false;
  58947. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  58948. hasEndGap = true;
  58949. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  58950. }
  58951. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  58952. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  58953. // When symbol margin is less than 0, margin at both ends will be subtracted
  58954. // to ensure that all of the symbols will not be overflow the given area.
  58955. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  58956. // Both final repeatTimes and final symbolMargin area calculated based on
  58957. // boundingLength.
  58958. var repeatSpecified = isNumeric(symbolRepeat);
  58959. var repeatTimes = repeatSpecified
  58960. ? symbolRepeat
  58961. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  58962. // Adjust calculate margin, to ensure each symbol is displayed
  58963. // entirely in the given layout area.
  58964. var mDiff = absBoundingLength - repeatTimes * unitLength;
  58965. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  58966. uLenWithMargin = unitLength + symbolMargin * 2;
  58967. endFix = hasEndGap ? 0 : symbolMargin * 2;
  58968. // Update repeatTimes when not all symbol will be shown.
  58969. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  58970. repeatTimes = repeatCutLength
  58971. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  58972. : 0;
  58973. }
  58974. pathLen = repeatTimes * uLenWithMargin - endFix;
  58975. output.repeatTimes = repeatTimes;
  58976. output.symbolMargin = symbolMargin;
  58977. }
  58978. var sizeFix = pxSign * (pathLen / 2);
  58979. var pathPosition = output.pathPosition = [];
  58980. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  58981. pathPosition[valueDim.index] = symbolPosition === 'start'
  58982. ? sizeFix
  58983. : symbolPosition === 'end'
  58984. ? boundingLength - sizeFix
  58985. : boundingLength / 2; // 'center'
  58986. if (symbolOffset) {
  58987. pathPosition[0] += symbolOffset[0];
  58988. pathPosition[1] += symbolOffset[1];
  58989. }
  58990. var bundlePosition = output.bundlePosition = [];
  58991. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  58992. bundlePosition[valueDim.index] = layout[valueDim.xy];
  58993. var barRectShape = output.barRectShape = extend({}, layout);
  58994. barRectShape[valueDim.wh] = pxSign * Math.max(
  58995. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  58996. );
  58997. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  58998. var clipShape = output.clipShape = {};
  58999. // Consider that symbol may be overflow layout rect.
  59000. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  59001. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  59002. clipShape[valueDim.xy] = 0;
  59003. clipShape[valueDim.wh] = layout[valueDim.wh];
  59004. }
  59005. function createPath(symbolMeta) {
  59006. var symbolPatternSize = symbolMeta.symbolPatternSize;
  59007. var path = createSymbol(
  59008. // Consider texture img, make a big size.
  59009. symbolMeta.symbolType,
  59010. -symbolPatternSize / 2,
  59011. -symbolPatternSize / 2,
  59012. symbolPatternSize,
  59013. symbolPatternSize,
  59014. symbolMeta.color
  59015. );
  59016. path.attr({
  59017. culling: true
  59018. });
  59019. path.type !== 'image' && path.setStyle({
  59020. strokeNoScale: true
  59021. });
  59022. return path;
  59023. }
  59024. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  59025. var bundle = bar.__pictorialBundle;
  59026. var symbolSize = symbolMeta.symbolSize;
  59027. var valueLineWidth = symbolMeta.valueLineWidth;
  59028. var pathPosition = symbolMeta.pathPosition;
  59029. var valueDim = opt.valueDim;
  59030. var repeatTimes = symbolMeta.repeatTimes || 0;
  59031. var index = 0;
  59032. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  59033. eachPath(bar, function (path) {
  59034. path.__pictorialAnimationIndex = index;
  59035. path.__pictorialRepeatTimes = repeatTimes;
  59036. if (index < repeatTimes) {
  59037. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  59038. }
  59039. else {
  59040. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  59041. bundle.remove(path);
  59042. });
  59043. }
  59044. updateHoverAnimation(path, symbolMeta);
  59045. index++;
  59046. });
  59047. for (; index < repeatTimes; index++) {
  59048. var path = createPath(symbolMeta);
  59049. path.__pictorialAnimationIndex = index;
  59050. path.__pictorialRepeatTimes = repeatTimes;
  59051. bundle.add(path);
  59052. var target = makeTarget(index);
  59053. updateAttr(
  59054. path,
  59055. {
  59056. position: target.position,
  59057. scale: [0, 0]
  59058. },
  59059. {
  59060. scale: target.scale,
  59061. rotation: target.rotation
  59062. },
  59063. symbolMeta,
  59064. isUpdate
  59065. );
  59066. // FIXME
  59067. // If all emphasis/normal through action.
  59068. path
  59069. .on('mouseover', onMouseOver)
  59070. .on('mouseout', onMouseOut);
  59071. updateHoverAnimation(path, symbolMeta);
  59072. }
  59073. function makeTarget(index) {
  59074. var position = pathPosition.slice();
  59075. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  59076. // Otherwise: i = index;
  59077. var pxSign = symbolMeta.pxSign;
  59078. var i = index;
  59079. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  59080. i = repeatTimes - 1 - index;
  59081. }
  59082. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  59083. return {
  59084. position: position,
  59085. scale: symbolMeta.symbolScale.slice(),
  59086. rotation: symbolMeta.rotation
  59087. };
  59088. }
  59089. function onMouseOver() {
  59090. eachPath(bar, function (path) {
  59091. path.trigger('emphasis');
  59092. });
  59093. }
  59094. function onMouseOut() {
  59095. eachPath(bar, function (path) {
  59096. path.trigger('normal');
  59097. });
  59098. }
  59099. }
  59100. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  59101. var bundle = bar.__pictorialBundle;
  59102. var mainPath = bar.__pictorialMainPath;
  59103. if (!mainPath) {
  59104. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  59105. bundle.add(mainPath);
  59106. updateAttr(
  59107. mainPath,
  59108. {
  59109. position: symbolMeta.pathPosition.slice(),
  59110. scale: [0, 0],
  59111. rotation: symbolMeta.rotation
  59112. },
  59113. {
  59114. scale: symbolMeta.symbolScale.slice()
  59115. },
  59116. symbolMeta,
  59117. isUpdate
  59118. );
  59119. mainPath
  59120. .on('mouseover', onMouseOver)
  59121. .on('mouseout', onMouseOut);
  59122. }
  59123. else {
  59124. updateAttr(
  59125. mainPath,
  59126. null,
  59127. {
  59128. position: symbolMeta.pathPosition.slice(),
  59129. scale: symbolMeta.symbolScale.slice(),
  59130. rotation: symbolMeta.rotation
  59131. },
  59132. symbolMeta,
  59133. isUpdate
  59134. );
  59135. }
  59136. updateHoverAnimation(mainPath, symbolMeta);
  59137. function onMouseOver() {
  59138. this.trigger('emphasis');
  59139. }
  59140. function onMouseOut() {
  59141. this.trigger('normal');
  59142. }
  59143. }
  59144. // bar rect is used for label.
  59145. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  59146. var rectShape = extend({}, symbolMeta.barRectShape);
  59147. var barRect = bar.__pictorialBarRect;
  59148. if (!barRect) {
  59149. barRect = bar.__pictorialBarRect = new Rect({
  59150. z2: 2,
  59151. shape: rectShape,
  59152. silent: true,
  59153. style: {
  59154. stroke: 'transparent',
  59155. fill: 'transparent',
  59156. lineWidth: 0
  59157. }
  59158. });
  59159. bar.add(barRect);
  59160. }
  59161. else {
  59162. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  59163. }
  59164. }
  59165. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  59166. // If not clip, symbol will be remove and rebuilt.
  59167. if (symbolMeta.symbolClip) {
  59168. var clipPath = bar.__pictorialClipPath;
  59169. var clipShape = extend({}, symbolMeta.clipShape);
  59170. var valueDim = opt.valueDim;
  59171. var animationModel = symbolMeta.animationModel;
  59172. var dataIndex = symbolMeta.dataIndex;
  59173. if (clipPath) {
  59174. updateProps(
  59175. clipPath, {shape: clipShape}, animationModel, dataIndex
  59176. );
  59177. }
  59178. else {
  59179. clipShape[valueDim.wh] = 0;
  59180. clipPath = new Rect({shape: clipShape});
  59181. bar.__pictorialBundle.setClipPath(clipPath);
  59182. bar.__pictorialClipPath = clipPath;
  59183. var target = {};
  59184. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  59185. graphic[isUpdate ? 'updateProps' : 'initProps'](
  59186. clipPath, {shape: target}, animationModel, dataIndex
  59187. );
  59188. }
  59189. }
  59190. }
  59191. function getItemModel(data, dataIndex) {
  59192. var itemModel = data.getItemModel(dataIndex);
  59193. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  59194. itemModel.isAnimationEnabled = isAnimationEnabled;
  59195. return itemModel;
  59196. }
  59197. function getAnimationDelayParams(path) {
  59198. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  59199. return {
  59200. index: path.__pictorialAnimationIndex,
  59201. count: path.__pictorialRepeatTimes
  59202. };
  59203. }
  59204. function isAnimationEnabled() {
  59205. // `animation` prop can be set on itemModel in pictorial bar chart.
  59206. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  59207. }
  59208. function updateHoverAnimation(path, symbolMeta) {
  59209. path.off('emphasis').off('normal');
  59210. var scale = symbolMeta.symbolScale.slice();
  59211. symbolMeta.hoverAnimation && path
  59212. .on('emphasis', function () {
  59213. this.animateTo({
  59214. scale: [scale[0] * 1.1, scale[1] * 1.1]
  59215. }, 400, 'elasticOut');
  59216. })
  59217. .on('normal', function () {
  59218. this.animateTo({
  59219. scale: scale.slice()
  59220. }, 400, 'elasticOut');
  59221. });
  59222. }
  59223. function createBar(data, opt, symbolMeta, isUpdate) {
  59224. // bar is the main element for each data.
  59225. var bar = new Group();
  59226. // bundle is used for location and clip.
  59227. var bundle = new Group();
  59228. bar.add(bundle);
  59229. bar.__pictorialBundle = bundle;
  59230. bundle.attr('position', symbolMeta.bundlePosition.slice());
  59231. if (symbolMeta.symbolRepeat) {
  59232. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  59233. }
  59234. else {
  59235. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  59236. }
  59237. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  59238. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  59239. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  59240. bar.__pictorialSymbolMeta = symbolMeta;
  59241. return bar;
  59242. }
  59243. function updateBar(bar, opt, symbolMeta) {
  59244. var animationModel = symbolMeta.animationModel;
  59245. var dataIndex = symbolMeta.dataIndex;
  59246. var bundle = bar.__pictorialBundle;
  59247. updateProps(
  59248. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  59249. );
  59250. if (symbolMeta.symbolRepeat) {
  59251. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  59252. }
  59253. else {
  59254. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  59255. }
  59256. createOrUpdateBarRect(bar, symbolMeta, true);
  59257. createOrUpdateClip(bar, opt, symbolMeta, true);
  59258. }
  59259. function removeBar(data, dataIndex, animationModel, bar) {
  59260. // Not show text when animating
  59261. var labelRect = bar.__pictorialBarRect;
  59262. labelRect && (labelRect.style.text = null);
  59263. var pathes = [];
  59264. eachPath(bar, function (path) {
  59265. pathes.push(path);
  59266. });
  59267. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  59268. // I do not find proper remove animation for clip yet.
  59269. bar.__pictorialClipPath && (animationModel = null);
  59270. each$1(pathes, function (path) {
  59271. updateProps(
  59272. path, {scale: [0, 0]}, animationModel, dataIndex,
  59273. function () {
  59274. bar.parent && bar.parent.remove(bar);
  59275. }
  59276. );
  59277. });
  59278. data.setItemGraphicEl(dataIndex, null);
  59279. }
  59280. function getShapeStr(data, symbolMeta) {
  59281. return [
  59282. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  59283. !!symbolMeta.symbolRepeat,
  59284. !!symbolMeta.symbolClip
  59285. ].join(':');
  59286. }
  59287. function eachPath(bar, cb, context) {
  59288. // Do not use Group#eachChild, because it do not support remove.
  59289. each$1(bar.__pictorialBundle.children(), function (el) {
  59290. el !== bar.__pictorialBarRect && cb.call(context, el);
  59291. });
  59292. }
  59293. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  59294. immediateAttrs && el.attr(immediateAttrs);
  59295. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  59296. if (symbolMeta.symbolClip && !isUpdate) {
  59297. animationAttrs && el.attr(animationAttrs);
  59298. }
  59299. else {
  59300. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  59301. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  59302. );
  59303. }
  59304. }
  59305. function updateCommon$1(bar, opt, symbolMeta) {
  59306. var color = symbolMeta.color;
  59307. var dataIndex = symbolMeta.dataIndex;
  59308. var itemModel = symbolMeta.itemModel;
  59309. // Color must be excluded.
  59310. // Because symbol provide setColor individually to set fill and stroke
  59311. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  59312. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  59313. var cursorStyle = itemModel.getShallow('cursor');
  59314. eachPath(bar, function (path) {
  59315. // PENDING setColor should be before setStyle!!!
  59316. path.setColor(color);
  59317. path.setStyle(defaults(
  59318. {
  59319. fill: color,
  59320. opacity: symbolMeta.opacity
  59321. },
  59322. normalStyle
  59323. ));
  59324. setHoverStyle(path, hoverStyle);
  59325. cursorStyle && (path.cursor = cursorStyle);
  59326. path.z2 = symbolMeta.z2;
  59327. });
  59328. var barRectHoverStyle = {};
  59329. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  59330. var barRect = bar.__pictorialBarRect;
  59331. setLabel(
  59332. barRect.style, barRectHoverStyle, itemModel,
  59333. color, opt.seriesModel, dataIndex, barPositionOutside
  59334. );
  59335. setHoverStyle(barRect, barRectHoverStyle);
  59336. }
  59337. function toIntTimes(times) {
  59338. var roundedTimes = Math.round(times);
  59339. // Escapse accurate error
  59340. return Math.abs(times - roundedTimes) < 1e-4
  59341. ? roundedTimes
  59342. : Math.ceil(times);
  59343. }
  59344. /*
  59345. * Licensed to the Apache Software Foundation (ASF) under one
  59346. * or more contributor license agreements. See the NOTICE file
  59347. * distributed with this work for additional information
  59348. * regarding copyright ownership. The ASF licenses this file
  59349. * to you under the Apache License, Version 2.0 (the
  59350. * "License"); you may not use this file except in compliance
  59351. * with the License. You may obtain a copy of the License at
  59352. *
  59353. * http://www.apache.org/licenses/LICENSE-2.0
  59354. *
  59355. * Unless required by applicable law or agreed to in writing,
  59356. * software distributed under the License is distributed on an
  59357. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59358. * KIND, either express or implied. See the License for the
  59359. * specific language governing permissions and limitations
  59360. * under the License.
  59361. */
  59362. // In case developer forget to include grid component
  59363. registerLayout(curry(
  59364. layout, 'pictorialBar'
  59365. ));
  59366. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  59367. /*
  59368. * Licensed to the Apache Software Foundation (ASF) under one
  59369. * or more contributor license agreements. See the NOTICE file
  59370. * distributed with this work for additional information
  59371. * regarding copyright ownership. The ASF licenses this file
  59372. * to you under the Apache License, Version 2.0 (the
  59373. * "License"); you may not use this file except in compliance
  59374. * with the License. You may obtain a copy of the License at
  59375. *
  59376. * http://www.apache.org/licenses/LICENSE-2.0
  59377. *
  59378. * Unless required by applicable law or agreed to in writing,
  59379. * software distributed under the License is distributed on an
  59380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59381. * KIND, either express or implied. See the License for the
  59382. * specific language governing permissions and limitations
  59383. * under the License.
  59384. */
  59385. /**
  59386. * @constructor module:echarts/coord/single/SingleAxis
  59387. * @extends {module:echarts/coord/Axis}
  59388. * @param {string} dim
  59389. * @param {*} scale
  59390. * @param {Array.<number>} coordExtent
  59391. * @param {string} axisType
  59392. * @param {string} position
  59393. */
  59394. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  59395. Axis.call(this, dim, scale, coordExtent);
  59396. /**
  59397. * Axis type
  59398. * - 'category'
  59399. * - 'value'
  59400. * - 'time'
  59401. * - 'log'
  59402. * @type {string}
  59403. */
  59404. this.type = axisType || 'value';
  59405. /**
  59406. * Axis position
  59407. * - 'top'
  59408. * - 'bottom'
  59409. * - 'left'
  59410. * - 'right'
  59411. * @type {string}
  59412. */
  59413. this.position = position || 'bottom';
  59414. /**
  59415. * Axis orient
  59416. * - 'horizontal'
  59417. * - 'vertical'
  59418. * @type {[type]}
  59419. */
  59420. this.orient = null;
  59421. };
  59422. SingleAxis.prototype = {
  59423. constructor: SingleAxis,
  59424. /**
  59425. * Axis model
  59426. * @type {module:echarts/coord/single/AxisModel}
  59427. */
  59428. model: null,
  59429. /**
  59430. * Judge the orient of the axis.
  59431. * @return {boolean}
  59432. */
  59433. isHorizontal: function () {
  59434. var position = this.position;
  59435. return position === 'top' || position === 'bottom';
  59436. },
  59437. /**
  59438. * @override
  59439. */
  59440. pointToData: function (point, clamp) {
  59441. return this.coordinateSystem.pointToData(point, clamp)[0];
  59442. },
  59443. /**
  59444. * Convert the local coord(processed by dataToCoord())
  59445. * to global coord(concrete pixel coord).
  59446. * designated by module:echarts/coord/single/Single.
  59447. * @type {Function}
  59448. */
  59449. toGlobalCoord: null,
  59450. /**
  59451. * Convert the global coord to local coord.
  59452. * designated by module:echarts/coord/single/Single.
  59453. * @type {Function}
  59454. */
  59455. toLocalCoord: null
  59456. };
  59457. inherits(SingleAxis, Axis);
  59458. /*
  59459. * Licensed to the Apache Software Foundation (ASF) under one
  59460. * or more contributor license agreements. See the NOTICE file
  59461. * distributed with this work for additional information
  59462. * regarding copyright ownership. The ASF licenses this file
  59463. * to you under the Apache License, Version 2.0 (the
  59464. * "License"); you may not use this file except in compliance
  59465. * with the License. You may obtain a copy of the License at
  59466. *
  59467. * http://www.apache.org/licenses/LICENSE-2.0
  59468. *
  59469. * Unless required by applicable law or agreed to in writing,
  59470. * software distributed under the License is distributed on an
  59471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59472. * KIND, either express or implied. See the License for the
  59473. * specific language governing permissions and limitations
  59474. * under the License.
  59475. */
  59476. /**
  59477. * Single coordinates system.
  59478. */
  59479. /**
  59480. * Create a single coordinates system.
  59481. *
  59482. * @param {module:echarts/coord/single/AxisModel} axisModel
  59483. * @param {module:echarts/model/Global} ecModel
  59484. * @param {module:echarts/ExtensionAPI} api
  59485. */
  59486. function Single(axisModel, ecModel, api) {
  59487. /**
  59488. * @type {string}
  59489. * @readOnly
  59490. */
  59491. this.dimension = 'single';
  59492. /**
  59493. * Add it just for draw tooltip.
  59494. *
  59495. * @type {Array.<string>}
  59496. * @readOnly
  59497. */
  59498. this.dimensions = ['single'];
  59499. /**
  59500. * @private
  59501. * @type {module:echarts/coord/single/SingleAxis}.
  59502. */
  59503. this._axis = null;
  59504. /**
  59505. * @private
  59506. * @type {module:zrender/core/BoundingRect}
  59507. */
  59508. this._rect;
  59509. this._init(axisModel, ecModel, api);
  59510. /**
  59511. * @type {module:echarts/coord/single/AxisModel}
  59512. */
  59513. this.model = axisModel;
  59514. }
  59515. Single.prototype = {
  59516. type: 'singleAxis',
  59517. axisPointerEnabled: true,
  59518. constructor: Single,
  59519. /**
  59520. * Initialize single coordinate system.
  59521. *
  59522. * @param {module:echarts/coord/single/AxisModel} axisModel
  59523. * @param {module:echarts/model/Global} ecModel
  59524. * @param {module:echarts/ExtensionAPI} api
  59525. * @private
  59526. */
  59527. _init: function (axisModel, ecModel, api) {
  59528. var dim = this.dimension;
  59529. var axis = new SingleAxis(
  59530. dim,
  59531. createScaleByModel(axisModel),
  59532. [0, 0],
  59533. axisModel.get('type'),
  59534. axisModel.get('position')
  59535. );
  59536. var isCategory = axis.type === 'category';
  59537. axis.onBand = isCategory && axisModel.get('boundaryGap');
  59538. axis.inverse = axisModel.get('inverse');
  59539. axis.orient = axisModel.get('orient');
  59540. axisModel.axis = axis;
  59541. axis.model = axisModel;
  59542. axis.coordinateSystem = this;
  59543. this._axis = axis;
  59544. },
  59545. /**
  59546. * Update axis scale after data processed
  59547. * @param {module:echarts/model/Global} ecModel
  59548. * @param {module:echarts/ExtensionAPI} api
  59549. */
  59550. update: function (ecModel, api) {
  59551. ecModel.eachSeries(function (seriesModel) {
  59552. if (seriesModel.coordinateSystem === this) {
  59553. var data = seriesModel.getData();
  59554. each$1(data.mapDimension(this.dimension, true), function (dim) {
  59555. this._axis.scale.unionExtentFromData(data, dim);
  59556. }, this);
  59557. niceScaleExtent(this._axis.scale, this._axis.model);
  59558. }
  59559. }, this);
  59560. },
  59561. /**
  59562. * Resize the single coordinate system.
  59563. *
  59564. * @param {module:echarts/coord/single/AxisModel} axisModel
  59565. * @param {module:echarts/ExtensionAPI} api
  59566. */
  59567. resize: function (axisModel, api) {
  59568. this._rect = getLayoutRect(
  59569. {
  59570. left: axisModel.get('left'),
  59571. top: axisModel.get('top'),
  59572. right: axisModel.get('right'),
  59573. bottom: axisModel.get('bottom'),
  59574. width: axisModel.get('width'),
  59575. height: axisModel.get('height')
  59576. },
  59577. {
  59578. width: api.getWidth(),
  59579. height: api.getHeight()
  59580. }
  59581. );
  59582. this._adjustAxis();
  59583. },
  59584. /**
  59585. * @return {module:zrender/core/BoundingRect}
  59586. */
  59587. getRect: function () {
  59588. return this._rect;
  59589. },
  59590. /**
  59591. * @private
  59592. */
  59593. _adjustAxis: function () {
  59594. var rect = this._rect;
  59595. var axis = this._axis;
  59596. var isHorizontal = axis.isHorizontal();
  59597. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  59598. var idx = axis.reverse ? 1 : 0;
  59599. axis.setExtent(extent[idx], extent[1 - idx]);
  59600. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  59601. },
  59602. /**
  59603. * @param {module:echarts/coord/single/SingleAxis} axis
  59604. * @param {number} coordBase
  59605. */
  59606. _updateAxisTransform: function (axis, coordBase) {
  59607. var axisExtent = axis.getExtent();
  59608. var extentSum = axisExtent[0] + axisExtent[1];
  59609. var isHorizontal = axis.isHorizontal();
  59610. axis.toGlobalCoord = isHorizontal
  59611. ? function (coord) {
  59612. return coord + coordBase;
  59613. }
  59614. : function (coord) {
  59615. return extentSum - coord + coordBase;
  59616. };
  59617. axis.toLocalCoord = isHorizontal
  59618. ? function (coord) {
  59619. return coord - coordBase;
  59620. }
  59621. : function (coord) {
  59622. return extentSum - coord + coordBase;
  59623. };
  59624. },
  59625. /**
  59626. * Get axis.
  59627. *
  59628. * @return {module:echarts/coord/single/SingleAxis}
  59629. */
  59630. getAxis: function () {
  59631. return this._axis;
  59632. },
  59633. /**
  59634. * Get axis, add it just for draw tooltip.
  59635. *
  59636. * @return {[type]} [description]
  59637. */
  59638. getBaseAxis: function () {
  59639. return this._axis;
  59640. },
  59641. /**
  59642. * @return {Array.<module:echarts/coord/Axis>}
  59643. */
  59644. getAxes: function () {
  59645. return [this._axis];
  59646. },
  59647. /**
  59648. * @return {Object} {baseAxes: [], otherAxes: []}
  59649. */
  59650. getTooltipAxes: function () {
  59651. return {baseAxes: [this.getAxis()]};
  59652. },
  59653. /**
  59654. * If contain point.
  59655. *
  59656. * @param {Array.<number>} point
  59657. * @return {boolean}
  59658. */
  59659. containPoint: function (point) {
  59660. var rect = this.getRect();
  59661. var axis = this.getAxis();
  59662. var orient = axis.orient;
  59663. if (orient === 'horizontal') {
  59664. return axis.contain(axis.toLocalCoord(point[0]))
  59665. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  59666. }
  59667. else {
  59668. return axis.contain(axis.toLocalCoord(point[1]))
  59669. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  59670. }
  59671. },
  59672. /**
  59673. * @param {Array.<number>} point
  59674. * @return {Array.<number>}
  59675. */
  59676. pointToData: function (point) {
  59677. var axis = this.getAxis();
  59678. return [axis.coordToData(axis.toLocalCoord(
  59679. point[axis.orient === 'horizontal' ? 0 : 1]
  59680. ))];
  59681. },
  59682. /**
  59683. * Convert the series data to concrete point.
  59684. *
  59685. * @param {number|Array.<number>} val
  59686. * @return {Array.<number>}
  59687. */
  59688. dataToPoint: function (val) {
  59689. var axis = this.getAxis();
  59690. var rect = this.getRect();
  59691. var pt = [];
  59692. var idx = axis.orient === 'horizontal' ? 0 : 1;
  59693. if (val instanceof Array) {
  59694. val = val[0];
  59695. }
  59696. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  59697. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  59698. return pt;
  59699. }
  59700. };
  59701. /*
  59702. * Licensed to the Apache Software Foundation (ASF) under one
  59703. * or more contributor license agreements. See the NOTICE file
  59704. * distributed with this work for additional information
  59705. * regarding copyright ownership. The ASF licenses this file
  59706. * to you under the Apache License, Version 2.0 (the
  59707. * "License"); you may not use this file except in compliance
  59708. * with the License. You may obtain a copy of the License at
  59709. *
  59710. * http://www.apache.org/licenses/LICENSE-2.0
  59711. *
  59712. * Unless required by applicable law or agreed to in writing,
  59713. * software distributed under the License is distributed on an
  59714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59715. * KIND, either express or implied. See the License for the
  59716. * specific language governing permissions and limitations
  59717. * under the License.
  59718. */
  59719. /**
  59720. * Single coordinate system creator.
  59721. */
  59722. /**
  59723. * Create single coordinate system and inject it into seriesModel.
  59724. *
  59725. * @param {module:echarts/model/Global} ecModel
  59726. * @param {module:echarts/ExtensionAPI} api
  59727. * @return {Array.<module:echarts/coord/single/Single>}
  59728. */
  59729. function create$3(ecModel, api) {
  59730. var singles = [];
  59731. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  59732. var single = new Single(axisModel, ecModel, api);
  59733. single.name = 'single_' + idx;
  59734. single.resize(axisModel, api);
  59735. axisModel.coordinateSystem = single;
  59736. singles.push(single);
  59737. });
  59738. ecModel.eachSeries(function (seriesModel) {
  59739. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  59740. var singleAxisModel = ecModel.queryComponents({
  59741. mainType: 'singleAxis',
  59742. index: seriesModel.get('singleAxisIndex'),
  59743. id: seriesModel.get('singleAxisId')
  59744. })[0];
  59745. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  59746. }
  59747. });
  59748. return singles;
  59749. }
  59750. CoordinateSystemManager.register('single', {
  59751. create: create$3,
  59752. dimensions: Single.prototype.dimensions
  59753. });
  59754. /*
  59755. * Licensed to the Apache Software Foundation (ASF) under one
  59756. * or more contributor license agreements. See the NOTICE file
  59757. * distributed with this work for additional information
  59758. * regarding copyright ownership. The ASF licenses this file
  59759. * to you under the Apache License, Version 2.0 (the
  59760. * "License"); you may not use this file except in compliance
  59761. * with the License. You may obtain a copy of the License at
  59762. *
  59763. * http://www.apache.org/licenses/LICENSE-2.0
  59764. *
  59765. * Unless required by applicable law or agreed to in writing,
  59766. * software distributed under the License is distributed on an
  59767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59768. * KIND, either express or implied. See the License for the
  59769. * specific language governing permissions and limitations
  59770. * under the License.
  59771. */
  59772. /**
  59773. * @param {Object} opt {labelInside}
  59774. * @return {Object} {
  59775. * position, rotation, labelDirection, labelOffset,
  59776. * tickDirection, labelRotate, z2
  59777. * }
  59778. */
  59779. function layout$2(axisModel, opt) {
  59780. opt = opt || {};
  59781. var single = axisModel.coordinateSystem;
  59782. var axis = axisModel.axis;
  59783. var layout = {};
  59784. var axisPosition = axis.position;
  59785. var orient = axis.orient;
  59786. var rect = single.getRect();
  59787. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  59788. var positionMap = {
  59789. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  59790. vertical: {left: rectBound[0], right: rectBound[1]}
  59791. };
  59792. layout.position = [
  59793. orient === 'vertical'
  59794. ? positionMap.vertical[axisPosition]
  59795. : rectBound[0],
  59796. orient === 'horizontal'
  59797. ? positionMap.horizontal[axisPosition]
  59798. : rectBound[3]
  59799. ];
  59800. var r = {horizontal: 0, vertical: 1};
  59801. layout.rotation = Math.PI / 2 * r[orient];
  59802. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  59803. layout.labelDirection = layout.tickDirection =
  59804. layout.nameDirection = directionMap[axisPosition];
  59805. if (axisModel.get('axisTick.inside')) {
  59806. layout.tickDirection = -layout.tickDirection;
  59807. }
  59808. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  59809. layout.labelDirection = -layout.labelDirection;
  59810. }
  59811. var labelRotation = opt.rotate;
  59812. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  59813. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  59814. layout.z2 = 1;
  59815. return layout;
  59816. }
  59817. /*
  59818. * Licensed to the Apache Software Foundation (ASF) under one
  59819. * or more contributor license agreements. See the NOTICE file
  59820. * distributed with this work for additional information
  59821. * regarding copyright ownership. The ASF licenses this file
  59822. * to you under the Apache License, Version 2.0 (the
  59823. * "License"); you may not use this file except in compliance
  59824. * with the License. You may obtain a copy of the License at
  59825. *
  59826. * http://www.apache.org/licenses/LICENSE-2.0
  59827. *
  59828. * Unless required by applicable law or agreed to in writing,
  59829. * software distributed under the License is distributed on an
  59830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59831. * KIND, either express or implied. See the License for the
  59832. * specific language governing permissions and limitations
  59833. * under the License.
  59834. */
  59835. var axisBuilderAttrs$2 = [
  59836. 'axisLine', 'axisTickLabel', 'axisName'
  59837. ];
  59838. var selfBuilderAttr = 'splitLine';
  59839. var SingleAxisView = AxisView.extend({
  59840. type: 'singleAxis',
  59841. axisPointerClass: 'SingleAxisPointer',
  59842. render: function (axisModel, ecModel, api, payload) {
  59843. var group = this.group;
  59844. group.removeAll();
  59845. var layout = layout$2(axisModel);
  59846. var axisBuilder = new AxisBuilder(axisModel, layout);
  59847. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  59848. group.add(axisBuilder.getGroup());
  59849. if (axisModel.get(selfBuilderAttr + '.show')) {
  59850. this['_' + selfBuilderAttr](axisModel);
  59851. }
  59852. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  59853. },
  59854. _splitLine: function (axisModel) {
  59855. var axis = axisModel.axis;
  59856. if (axis.scale.isBlank()) {
  59857. return;
  59858. }
  59859. var splitLineModel = axisModel.getModel('splitLine');
  59860. var lineStyleModel = splitLineModel.getModel('lineStyle');
  59861. var lineWidth = lineStyleModel.get('width');
  59862. var lineColors = lineStyleModel.get('color');
  59863. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  59864. var gridRect = axisModel.coordinateSystem.getRect();
  59865. var isHorizontal = axis.isHorizontal();
  59866. var splitLines = [];
  59867. var lineCount = 0;
  59868. var ticksCoords = axis.getTicksCoords({
  59869. tickModel: splitLineModel
  59870. });
  59871. var p1 = [];
  59872. var p2 = [];
  59873. for (var i = 0; i < ticksCoords.length; ++i) {
  59874. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  59875. if (isHorizontal) {
  59876. p1[0] = tickCoord;
  59877. p1[1] = gridRect.y;
  59878. p2[0] = tickCoord;
  59879. p2[1] = gridRect.y + gridRect.height;
  59880. }
  59881. else {
  59882. p1[0] = gridRect.x;
  59883. p1[1] = tickCoord;
  59884. p2[0] = gridRect.x + gridRect.width;
  59885. p2[1] = tickCoord;
  59886. }
  59887. var colorIndex = (lineCount++) % lineColors.length;
  59888. splitLines[colorIndex] = splitLines[colorIndex] || [];
  59889. splitLines[colorIndex].push(new Line({
  59890. subPixelOptimize: true,
  59891. shape: {
  59892. x1: p1[0],
  59893. y1: p1[1],
  59894. x2: p2[0],
  59895. y2: p2[1]
  59896. },
  59897. style: {
  59898. lineWidth: lineWidth
  59899. },
  59900. silent: true
  59901. }));
  59902. }
  59903. for (var i = 0; i < splitLines.length; ++i) {
  59904. this.group.add(mergePath(splitLines[i], {
  59905. style: {
  59906. stroke: lineColors[i % lineColors.length],
  59907. lineDash: lineStyleModel.getLineDash(lineWidth),
  59908. lineWidth: lineWidth
  59909. },
  59910. silent: true
  59911. }));
  59912. }
  59913. }
  59914. });
  59915. /*
  59916. * Licensed to the Apache Software Foundation (ASF) under one
  59917. * or more contributor license agreements. See the NOTICE file
  59918. * distributed with this work for additional information
  59919. * regarding copyright ownership. The ASF licenses this file
  59920. * to you under the Apache License, Version 2.0 (the
  59921. * "License"); you may not use this file except in compliance
  59922. * with the License. You may obtain a copy of the License at
  59923. *
  59924. * http://www.apache.org/licenses/LICENSE-2.0
  59925. *
  59926. * Unless required by applicable law or agreed to in writing,
  59927. * software distributed under the License is distributed on an
  59928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59929. * KIND, either express or implied. See the License for the
  59930. * specific language governing permissions and limitations
  59931. * under the License.
  59932. */
  59933. var AxisModel$4 = ComponentModel.extend({
  59934. type: 'singleAxis',
  59935. layoutMode: 'box',
  59936. /**
  59937. * @type {module:echarts/coord/single/SingleAxis}
  59938. */
  59939. axis: null,
  59940. /**
  59941. * @type {module:echarts/coord/single/Single}
  59942. */
  59943. coordinateSystem: null,
  59944. /**
  59945. * @override
  59946. */
  59947. getCoordSysModel: function () {
  59948. return this;
  59949. }
  59950. });
  59951. var defaultOption$2 = {
  59952. left: '5%',
  59953. top: '5%',
  59954. right: '5%',
  59955. bottom: '5%',
  59956. type: 'value',
  59957. position: 'bottom',
  59958. orient: 'horizontal',
  59959. axisLine: {
  59960. show: true,
  59961. lineStyle: {
  59962. width: 1,
  59963. type: 'solid'
  59964. }
  59965. },
  59966. // Single coordinate system and single axis is the,
  59967. // which is used as the parent tooltip model.
  59968. // same model, so we set default tooltip show as true.
  59969. tooltip: {
  59970. show: true
  59971. },
  59972. axisTick: {
  59973. show: true,
  59974. length: 6,
  59975. lineStyle: {
  59976. width: 1
  59977. }
  59978. },
  59979. axisLabel: {
  59980. show: true,
  59981. interval: 'auto'
  59982. },
  59983. splitLine: {
  59984. show: true,
  59985. lineStyle: {
  59986. type: 'dashed',
  59987. opacity: 0.2
  59988. }
  59989. }
  59990. };
  59991. function getAxisType$2(axisName, option) {
  59992. return option.type || (option.data ? 'category' : 'value');
  59993. }
  59994. merge(AxisModel$4.prototype, axisModelCommonMixin);
  59995. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  59996. /*
  59997. * Licensed to the Apache Software Foundation (ASF) under one
  59998. * or more contributor license agreements. See the NOTICE file
  59999. * distributed with this work for additional information
  60000. * regarding copyright ownership. The ASF licenses this file
  60001. * to you under the Apache License, Version 2.0 (the
  60002. * "License"); you may not use this file except in compliance
  60003. * with the License. You may obtain a copy of the License at
  60004. *
  60005. * http://www.apache.org/licenses/LICENSE-2.0
  60006. *
  60007. * Unless required by applicable law or agreed to in writing,
  60008. * software distributed under the License is distributed on an
  60009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60010. * KIND, either express or implied. See the License for the
  60011. * specific language governing permissions and limitations
  60012. * under the License.
  60013. */
  60014. /**
  60015. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  60016. * @param {module:echarts/model/Global} ecModel
  60017. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  60018. */
  60019. var findPointFromSeries = function (finder, ecModel) {
  60020. var point = [];
  60021. var seriesIndex = finder.seriesIndex;
  60022. var seriesModel;
  60023. if (seriesIndex == null || !(
  60024. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  60025. )) {
  60026. return {point: []};
  60027. }
  60028. var data = seriesModel.getData();
  60029. var dataIndex = queryDataIndex(data, finder);
  60030. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  60031. return {point: []};
  60032. }
  60033. var el = data.getItemGraphicEl(dataIndex);
  60034. var coordSys = seriesModel.coordinateSystem;
  60035. if (seriesModel.getTooltipPosition) {
  60036. point = seriesModel.getTooltipPosition(dataIndex) || [];
  60037. }
  60038. else if (coordSys && coordSys.dataToPoint) {
  60039. point = coordSys.dataToPoint(
  60040. data.getValues(
  60041. map(coordSys.dimensions, function (dim) {
  60042. return data.mapDimension(dim);
  60043. }), dataIndex, true
  60044. )
  60045. ) || [];
  60046. }
  60047. else if (el) {
  60048. // Use graphic bounding rect
  60049. var rect = el.getBoundingRect().clone();
  60050. rect.applyTransform(el.transform);
  60051. point = [
  60052. rect.x + rect.width / 2,
  60053. rect.y + rect.height / 2
  60054. ];
  60055. }
  60056. return {point: point, el: el};
  60057. };
  60058. /*
  60059. * Licensed to the Apache Software Foundation (ASF) under one
  60060. * or more contributor license agreements. See the NOTICE file
  60061. * distributed with this work for additional information
  60062. * regarding copyright ownership. The ASF licenses this file
  60063. * to you under the Apache License, Version 2.0 (the
  60064. * "License"); you may not use this file except in compliance
  60065. * with the License. You may obtain a copy of the License at
  60066. *
  60067. * http://www.apache.org/licenses/LICENSE-2.0
  60068. *
  60069. * Unless required by applicable law or agreed to in writing,
  60070. * software distributed under the License is distributed on an
  60071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60072. * KIND, either express or implied. See the License for the
  60073. * specific language governing permissions and limitations
  60074. * under the License.
  60075. */
  60076. var each$14 = each$1;
  60077. var curry$3 = curry;
  60078. var inner$9 = makeInner();
  60079. /**
  60080. * Basic logic: check all axis, if they do not demand show/highlight,
  60081. * then hide/downplay them.
  60082. *
  60083. * @param {Object} coordSysAxesInfo
  60084. * @param {Object} payload
  60085. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  60086. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  60087. * trigger axisPointer and tooltip.
  60088. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  60089. * trigger axisPointer and tooltip.
  60090. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  60091. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  60092. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  60093. * [{
  60094. * axisDim: 'x'|'y'|'angle'|...,
  60095. * axisIndex: ...,
  60096. * value: ...
  60097. * }, ...]
  60098. * @param {Function} [payload.dispatchAction]
  60099. * @param {Object} [payload.tooltipOption]
  60100. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  60101. * which can be specified in dispatchAction
  60102. * @param {module:echarts/model/Global} ecModel
  60103. * @param {module:echarts/ExtensionAPI} api
  60104. * @return {Object} content of event obj for echarts.connect.
  60105. */
  60106. var axisTrigger = function (payload, ecModel, api) {
  60107. var currTrigger = payload.currTrigger;
  60108. var point = [payload.x, payload.y];
  60109. var finder = payload;
  60110. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  60111. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  60112. // Pending
  60113. // See #6121. But we are not able to reproduce it yet.
  60114. if (!coordSysAxesInfo) {
  60115. return;
  60116. }
  60117. if (illegalPoint(point)) {
  60118. // Used in the default behavior of `connection`: use the sample seriesIndex
  60119. // and dataIndex. And also used in the tooltipView trigger.
  60120. point = findPointFromSeries({
  60121. seriesIndex: finder.seriesIndex,
  60122. // Do not use dataIndexInside from other ec instance.
  60123. // FIXME: auto detect it?
  60124. dataIndex: finder.dataIndex
  60125. }, ecModel).point;
  60126. }
  60127. var isIllegalPoint = illegalPoint(point);
  60128. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  60129. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  60130. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  60131. // and dataIndex.
  60132. var inputAxesInfo = finder.axesInfo;
  60133. var axesInfo = coordSysAxesInfo.axesInfo;
  60134. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  60135. var outputFinder = {};
  60136. var showValueMap = {};
  60137. var dataByCoordSys = {list: [], map: {}};
  60138. var updaters = {
  60139. showPointer: curry$3(showPointer, showValueMap),
  60140. showTooltip: curry$3(showTooltip, dataByCoordSys)
  60141. };
  60142. // Process for triggered axes.
  60143. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  60144. // If a point given, it must be contained by the coordinate system.
  60145. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  60146. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  60147. var axis = axisInfo.axis;
  60148. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  60149. // If no inputAxesInfo, no axis is restricted.
  60150. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  60151. var val = inputAxisInfo && inputAxisInfo.value;
  60152. if (val == null && !isIllegalPoint) {
  60153. val = axis.pointToData(point);
  60154. }
  60155. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  60156. }
  60157. });
  60158. });
  60159. // Process for linked axes.
  60160. var linkTriggers = {};
  60161. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  60162. var linkGroup = tarAxisInfo.linkGroup;
  60163. // If axis has been triggered in the previous stage, it should not be triggered by link.
  60164. if (linkGroup && !showValueMap[tarKey]) {
  60165. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  60166. var srcValItem = showValueMap[srcKey];
  60167. // If srcValItem exist, source axis is triggered, so link to target axis.
  60168. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  60169. var val = srcValItem.value;
  60170. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  60171. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  60172. )));
  60173. linkTriggers[tarAxisInfo.key] = val;
  60174. }
  60175. });
  60176. }
  60177. });
  60178. each$14(linkTriggers, function (val, tarKey) {
  60179. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  60180. });
  60181. updateModelActually(showValueMap, axesInfo, outputFinder);
  60182. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  60183. dispatchHighDownActually(axesInfo, dispatchAction, api);
  60184. return outputFinder;
  60185. };
  60186. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  60187. var axis = axisInfo.axis;
  60188. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  60189. return;
  60190. }
  60191. if (!axisInfo.involveSeries) {
  60192. updaters.showPointer(axisInfo, newValue);
  60193. return;
  60194. }
  60195. // Heavy calculation. So put it after axis.containData checking.
  60196. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  60197. var payloadBatch = payloadInfo.payloadBatch;
  60198. var snapToValue = payloadInfo.snapToValue;
  60199. // Fill content of event obj for echarts.connect.
  60200. // By defualt use the first involved series data as a sample to connect.
  60201. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  60202. extend(outputFinder, payloadBatch[0]);
  60203. }
  60204. // If no linkSource input, this process is for collecting link
  60205. // target, where snap should not be accepted.
  60206. if (!dontSnap && axisInfo.snap) {
  60207. if (axis.containData(snapToValue) && snapToValue != null) {
  60208. newValue = snapToValue;
  60209. }
  60210. }
  60211. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  60212. // Tooltip should always be snapToValue, otherwise there will be
  60213. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  60214. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  60215. }
  60216. function buildPayloadsBySeries(value, axisInfo) {
  60217. var axis = axisInfo.axis;
  60218. var dim = axis.dim;
  60219. var snapToValue = value;
  60220. var payloadBatch = [];
  60221. var minDist = Number.MAX_VALUE;
  60222. var minDiff = -1;
  60223. each$14(axisInfo.seriesModels, function (series, idx) {
  60224. var dataDim = series.getData().mapDimension(dim, true);
  60225. var seriesNestestValue;
  60226. var dataIndices;
  60227. if (series.getAxisTooltipData) {
  60228. var result = series.getAxisTooltipData(dataDim, value, axis);
  60229. dataIndices = result.dataIndices;
  60230. seriesNestestValue = result.nestestValue;
  60231. }
  60232. else {
  60233. dataIndices = series.getData().indicesOfNearest(
  60234. dataDim[0],
  60235. value,
  60236. // Add a threshold to avoid find the wrong dataIndex
  60237. // when data length is not same.
  60238. // false,
  60239. axis.type === 'category' ? 0.5 : null
  60240. );
  60241. if (!dataIndices.length) {
  60242. return;
  60243. }
  60244. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  60245. }
  60246. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  60247. return;
  60248. }
  60249. var diff = value - seriesNestestValue;
  60250. var dist = Math.abs(diff);
  60251. // Consider category case
  60252. if (dist <= minDist) {
  60253. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  60254. minDist = dist;
  60255. minDiff = diff;
  60256. snapToValue = seriesNestestValue;
  60257. payloadBatch.length = 0;
  60258. }
  60259. each$14(dataIndices, function (dataIndex) {
  60260. payloadBatch.push({
  60261. seriesIndex: series.seriesIndex,
  60262. dataIndexInside: dataIndex,
  60263. dataIndex: series.getData().getRawIndex(dataIndex)
  60264. });
  60265. });
  60266. }
  60267. });
  60268. return {
  60269. payloadBatch: payloadBatch,
  60270. snapToValue: snapToValue
  60271. };
  60272. }
  60273. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  60274. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  60275. }
  60276. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  60277. var payloadBatch = payloadInfo.payloadBatch;
  60278. var axis = axisInfo.axis;
  60279. var axisModel = axis.model;
  60280. var axisPointerModel = axisInfo.axisPointerModel;
  60281. // If no data, do not create anything in dataByCoordSys,
  60282. // whose length will be used to judge whether dispatch action.
  60283. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  60284. return;
  60285. }
  60286. var coordSysModel = axisInfo.coordSys.model;
  60287. var coordSysKey = makeKey(coordSysModel);
  60288. var coordSysItem = dataByCoordSys.map[coordSysKey];
  60289. if (!coordSysItem) {
  60290. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  60291. coordSysId: coordSysModel.id,
  60292. coordSysIndex: coordSysModel.componentIndex,
  60293. coordSysType: coordSysModel.type,
  60294. coordSysMainType: coordSysModel.mainType,
  60295. dataByAxis: []
  60296. };
  60297. dataByCoordSys.list.push(coordSysItem);
  60298. }
  60299. coordSysItem.dataByAxis.push({
  60300. axisDim: axis.dim,
  60301. axisIndex: axisModel.componentIndex,
  60302. axisType: axisModel.type,
  60303. axisId: axisModel.id,
  60304. value: value,
  60305. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  60306. // depends that all models have been updated. So it should not be performed
  60307. // here. Considering axisPointerModel used here is volatile, which is hard
  60308. // to be retrieve in TooltipView, we prepare parameters here.
  60309. valueLabelOpt: {
  60310. precision: axisPointerModel.get('label.precision'),
  60311. formatter: axisPointerModel.get('label.formatter')
  60312. },
  60313. seriesDataIndices: payloadBatch.slice()
  60314. });
  60315. }
  60316. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  60317. var outputAxesInfo = outputFinder.axesInfo = [];
  60318. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  60319. each$14(axesInfo, function (axisInfo, key) {
  60320. var option = axisInfo.axisPointerModel.option;
  60321. var valItem = showValueMap[key];
  60322. if (valItem) {
  60323. !axisInfo.useHandle && (option.status = 'show');
  60324. option.value = valItem.value;
  60325. // For label formatter param and highlight.
  60326. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  60327. }
  60328. // When always show (e.g., handle used), remain
  60329. // original value and status.
  60330. else {
  60331. // If hide, value still need to be set, consider
  60332. // click legend to toggle axis blank.
  60333. !axisInfo.useHandle && (option.status = 'hide');
  60334. }
  60335. // If status is 'hide', should be no info in payload.
  60336. option.status === 'show' && outputAxesInfo.push({
  60337. axisDim: axisInfo.axis.dim,
  60338. axisIndex: axisInfo.axis.model.componentIndex,
  60339. value: option.value
  60340. });
  60341. });
  60342. }
  60343. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  60344. // Basic logic: If no showTip required, hideTip will be dispatched.
  60345. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  60346. dispatchAction({type: 'hideTip'});
  60347. return;
  60348. }
  60349. // In most case only one axis (or event one series is used). It is
  60350. // convinient to fetch payload.seriesIndex and payload.dataIndex
  60351. // dirtectly. So put the first seriesIndex and dataIndex of the first
  60352. // axis on the payload.
  60353. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  60354. dispatchAction({
  60355. type: 'showTip',
  60356. escapeConnect: true,
  60357. x: point[0],
  60358. y: point[1],
  60359. tooltipOption: payload.tooltipOption,
  60360. position: payload.position,
  60361. dataIndexInside: sampleItem.dataIndexInside,
  60362. dataIndex: sampleItem.dataIndex,
  60363. seriesIndex: sampleItem.seriesIndex,
  60364. dataByCoordSys: dataByCoordSys.list
  60365. });
  60366. }
  60367. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  60368. // FIXME
  60369. // highlight status modification shoule be a stage of main process?
  60370. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  60371. var zr = api.getZr();
  60372. var highDownKey = 'axisPointerLastHighlights';
  60373. var lastHighlights = inner$9(zr)[highDownKey] || {};
  60374. var newHighlights = inner$9(zr)[highDownKey] = {};
  60375. // Update highlight/downplay status according to axisPointer model.
  60376. // Build hash map and remove duplicate incidentally.
  60377. each$14(axesInfo, function (axisInfo, key) {
  60378. var option = axisInfo.axisPointerModel.option;
  60379. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  60380. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  60381. newHighlights[key] = batchItem;
  60382. });
  60383. });
  60384. // Diff.
  60385. var toHighlight = [];
  60386. var toDownplay = [];
  60387. each$1(lastHighlights, function (batchItem, key) {
  60388. !newHighlights[key] && toDownplay.push(batchItem);
  60389. });
  60390. each$1(newHighlights, function (batchItem, key) {
  60391. !lastHighlights[key] && toHighlight.push(batchItem);
  60392. });
  60393. toDownplay.length && api.dispatchAction({
  60394. type: 'downplay', escapeConnect: true, batch: toDownplay
  60395. });
  60396. toHighlight.length && api.dispatchAction({
  60397. type: 'highlight', escapeConnect: true, batch: toHighlight
  60398. });
  60399. }
  60400. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  60401. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  60402. var inputAxisInfo = inputAxesInfo[i];
  60403. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  60404. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  60405. ) {
  60406. return inputAxisInfo;
  60407. }
  60408. }
  60409. }
  60410. function makeMapperParam(axisInfo) {
  60411. var axisModel = axisInfo.axis.model;
  60412. var item = {};
  60413. var dim = item.axisDim = axisInfo.axis.dim;
  60414. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  60415. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  60416. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  60417. return item;
  60418. }
  60419. function illegalPoint(point) {
  60420. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  60421. }
  60422. /*
  60423. * Licensed to the Apache Software Foundation (ASF) under one
  60424. * or more contributor license agreements. See the NOTICE file
  60425. * distributed with this work for additional information
  60426. * regarding copyright ownership. The ASF licenses this file
  60427. * to you under the Apache License, Version 2.0 (the
  60428. * "License"); you may not use this file except in compliance
  60429. * with the License. You may obtain a copy of the License at
  60430. *
  60431. * http://www.apache.org/licenses/LICENSE-2.0
  60432. *
  60433. * Unless required by applicable law or agreed to in writing,
  60434. * software distributed under the License is distributed on an
  60435. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60436. * KIND, either express or implied. See the License for the
  60437. * specific language governing permissions and limitations
  60438. * under the License.
  60439. */
  60440. var AxisPointerModel = extendComponentModel({
  60441. type: 'axisPointer',
  60442. coordSysAxesInfo: null,
  60443. defaultOption: {
  60444. // 'auto' means that show when triggered by tooltip or handle.
  60445. show: 'auto',
  60446. // 'click' | 'mousemove' | 'none'
  60447. triggerOn: null, // set default in AxisPonterView.js
  60448. zlevel: 0,
  60449. z: 50,
  60450. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  60451. // axispointer triggered by tootip determine snap automatically,
  60452. // see `modelHelper`.
  60453. snap: false,
  60454. triggerTooltip: true,
  60455. value: null,
  60456. status: null, // Init value depends on whether handle is used.
  60457. // [group0, group1, ...]
  60458. // Each group can be: {
  60459. // mapper: function () {},
  60460. // singleTooltip: 'multiple', // 'multiple' or 'single'
  60461. // xAxisId: ...,
  60462. // yAxisName: ...,
  60463. // angleAxisIndex: ...
  60464. // }
  60465. // mapper: can be ignored.
  60466. // input: {axisInfo, value}
  60467. // output: {axisInfo, value}
  60468. link: [],
  60469. // Do not set 'auto' here, otherwise global animation: false
  60470. // will not effect at this axispointer.
  60471. animation: null,
  60472. animationDurationUpdate: 200,
  60473. lineStyle: {
  60474. color: '#aaa',
  60475. width: 1,
  60476. type: 'solid'
  60477. },
  60478. shadowStyle: {
  60479. color: 'rgba(150,150,150,0.3)'
  60480. },
  60481. label: {
  60482. show: true,
  60483. formatter: null, // string | Function
  60484. precision: 'auto', // Or a number like 0, 1, 2 ...
  60485. margin: 3,
  60486. color: '#fff',
  60487. padding: [5, 7, 5, 7],
  60488. backgroundColor: 'auto', // default: axis line color
  60489. borderColor: null,
  60490. borderWidth: 0,
  60491. shadowBlur: 3,
  60492. shadowColor: '#aaa'
  60493. // Considering applicability, common style should
  60494. // better not have shadowOffset.
  60495. // shadowOffsetX: 0,
  60496. // shadowOffsetY: 2
  60497. },
  60498. handle: {
  60499. show: false,
  60500. /* eslint-disable */
  60501. 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
  60502. /* eslint-enable */
  60503. size: 45,
  60504. // handle margin is from symbol center to axis, which is stable when circular move.
  60505. margin: 50,
  60506. // color: '#1b8bbd'
  60507. // color: '#2f4554'
  60508. color: '#333',
  60509. shadowBlur: 3,
  60510. shadowColor: '#aaa',
  60511. shadowOffsetX: 0,
  60512. shadowOffsetY: 2,
  60513. // For mobile performance
  60514. throttle: 40
  60515. }
  60516. }
  60517. });
  60518. /*
  60519. * Licensed to the Apache Software Foundation (ASF) under one
  60520. * or more contributor license agreements. See the NOTICE file
  60521. * distributed with this work for additional information
  60522. * regarding copyright ownership. The ASF licenses this file
  60523. * to you under the Apache License, Version 2.0 (the
  60524. * "License"); you may not use this file except in compliance
  60525. * with the License. You may obtain a copy of the License at
  60526. *
  60527. * http://www.apache.org/licenses/LICENSE-2.0
  60528. *
  60529. * Unless required by applicable law or agreed to in writing,
  60530. * software distributed under the License is distributed on an
  60531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60532. * KIND, either express or implied. See the License for the
  60533. * specific language governing permissions and limitations
  60534. * under the License.
  60535. */
  60536. var inner$10 = makeInner();
  60537. var each$15 = each$1;
  60538. /**
  60539. * @param {string} key
  60540. * @param {module:echarts/ExtensionAPI} api
  60541. * @param {Function} handler
  60542. * param: {string} currTrigger
  60543. * param: {Array.<number>} point
  60544. */
  60545. function register(key, api, handler) {
  60546. if (env$1.node) {
  60547. return;
  60548. }
  60549. var zr = api.getZr();
  60550. inner$10(zr).records || (inner$10(zr).records = {});
  60551. initGlobalListeners(zr, api);
  60552. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  60553. record.handler = handler;
  60554. }
  60555. function initGlobalListeners(zr, api) {
  60556. if (inner$10(zr).initialized) {
  60557. return;
  60558. }
  60559. inner$10(zr).initialized = true;
  60560. useHandler('click', curry(doEnter, 'click'));
  60561. useHandler('mousemove', curry(doEnter, 'mousemove'));
  60562. // useHandler('mouseout', onLeave);
  60563. useHandler('globalout', onLeave);
  60564. function useHandler(eventType, cb) {
  60565. zr.on(eventType, function (e) {
  60566. var dis = makeDispatchAction(api);
  60567. each$15(inner$10(zr).records, function (record) {
  60568. record && cb(record, e, dis.dispatchAction);
  60569. });
  60570. dispatchTooltipFinally(dis.pendings, api);
  60571. });
  60572. }
  60573. }
  60574. function dispatchTooltipFinally(pendings, api) {
  60575. var showLen = pendings.showTip.length;
  60576. var hideLen = pendings.hideTip.length;
  60577. var actuallyPayload;
  60578. if (showLen) {
  60579. actuallyPayload = pendings.showTip[showLen - 1];
  60580. }
  60581. else if (hideLen) {
  60582. actuallyPayload = pendings.hideTip[hideLen - 1];
  60583. }
  60584. if (actuallyPayload) {
  60585. actuallyPayload.dispatchAction = null;
  60586. api.dispatchAction(actuallyPayload);
  60587. }
  60588. }
  60589. function onLeave(record, e, dispatchAction) {
  60590. record.handler('leave', null, dispatchAction);
  60591. }
  60592. function doEnter(currTrigger, record, e, dispatchAction) {
  60593. record.handler(currTrigger, e, dispatchAction);
  60594. }
  60595. function makeDispatchAction(api) {
  60596. var pendings = {
  60597. showTip: [],
  60598. hideTip: []
  60599. };
  60600. // FIXME
  60601. // better approach?
  60602. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  60603. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  60604. // So we have to add "final stage" to merge those dispatched actions.
  60605. var dispatchAction = function (payload) {
  60606. var pendingList = pendings[payload.type];
  60607. if (pendingList) {
  60608. pendingList.push(payload);
  60609. }
  60610. else {
  60611. payload.dispatchAction = dispatchAction;
  60612. api.dispatchAction(payload);
  60613. }
  60614. };
  60615. return {
  60616. dispatchAction: dispatchAction,
  60617. pendings: pendings
  60618. };
  60619. }
  60620. /**
  60621. * @param {string} key
  60622. * @param {module:echarts/ExtensionAPI} api
  60623. */
  60624. function unregister(key, api) {
  60625. if (env$1.node) {
  60626. return;
  60627. }
  60628. var zr = api.getZr();
  60629. var record = (inner$10(zr).records || {})[key];
  60630. if (record) {
  60631. inner$10(zr).records[key] = null;
  60632. }
  60633. }
  60634. /*
  60635. * Licensed to the Apache Software Foundation (ASF) under one
  60636. * or more contributor license agreements. See the NOTICE file
  60637. * distributed with this work for additional information
  60638. * regarding copyright ownership. The ASF licenses this file
  60639. * to you under the Apache License, Version 2.0 (the
  60640. * "License"); you may not use this file except in compliance
  60641. * with the License. You may obtain a copy of the License at
  60642. *
  60643. * http://www.apache.org/licenses/LICENSE-2.0
  60644. *
  60645. * Unless required by applicable law or agreed to in writing,
  60646. * software distributed under the License is distributed on an
  60647. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60648. * KIND, either express or implied. See the License for the
  60649. * specific language governing permissions and limitations
  60650. * under the License.
  60651. */
  60652. var AxisPointerView = extendComponentView({
  60653. type: 'axisPointer',
  60654. render: function (globalAxisPointerModel, ecModel, api) {
  60655. var globalTooltipModel = ecModel.getComponent('tooltip');
  60656. var triggerOn = globalAxisPointerModel.get('triggerOn')
  60657. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  60658. // Register global listener in AxisPointerView to enable
  60659. // AxisPointerView to be independent to Tooltip.
  60660. register(
  60661. 'axisPointer',
  60662. api,
  60663. function (currTrigger, e, dispatchAction) {
  60664. // If 'none', it is not controlled by mouse totally.
  60665. if (triggerOn !== 'none'
  60666. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  60667. ) {
  60668. dispatchAction({
  60669. type: 'updateAxisPointer',
  60670. currTrigger: currTrigger,
  60671. x: e && e.offsetX,
  60672. y: e && e.offsetY
  60673. });
  60674. }
  60675. }
  60676. );
  60677. },
  60678. /**
  60679. * @override
  60680. */
  60681. remove: function (ecModel, api) {
  60682. unregister(api.getZr(), 'axisPointer');
  60683. AxisPointerView.superApply(this._model, 'remove', arguments);
  60684. },
  60685. /**
  60686. * @override
  60687. */
  60688. dispose: function (ecModel, api) {
  60689. unregister('axisPointer', api);
  60690. AxisPointerView.superApply(this._model, 'dispose', arguments);
  60691. }
  60692. });
  60693. /*
  60694. * Licensed to the Apache Software Foundation (ASF) under one
  60695. * or more contributor license agreements. See the NOTICE file
  60696. * distributed with this work for additional information
  60697. * regarding copyright ownership. The ASF licenses this file
  60698. * to you under the Apache License, Version 2.0 (the
  60699. * "License"); you may not use this file except in compliance
  60700. * with the License. You may obtain a copy of the License at
  60701. *
  60702. * http://www.apache.org/licenses/LICENSE-2.0
  60703. *
  60704. * Unless required by applicable law or agreed to in writing,
  60705. * software distributed under the License is distributed on an
  60706. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60707. * KIND, either express or implied. See the License for the
  60708. * specific language governing permissions and limitations
  60709. * under the License.
  60710. */
  60711. var inner$11 = makeInner();
  60712. var clone$4 = clone;
  60713. var bind$2 = bind;
  60714. /**
  60715. * Base axis pointer class in 2D.
  60716. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  60717. */
  60718. function BaseAxisPointer() {
  60719. }
  60720. BaseAxisPointer.prototype = {
  60721. /**
  60722. * @private
  60723. */
  60724. _group: null,
  60725. /**
  60726. * @private
  60727. */
  60728. _lastGraphicKey: null,
  60729. /**
  60730. * @private
  60731. */
  60732. _handle: null,
  60733. /**
  60734. * @private
  60735. */
  60736. _dragging: false,
  60737. /**
  60738. * @private
  60739. */
  60740. _lastValue: null,
  60741. /**
  60742. * @private
  60743. */
  60744. _lastStatus: null,
  60745. /**
  60746. * @private
  60747. */
  60748. _payloadInfo: null,
  60749. /**
  60750. * In px, arbitrary value. Do not set too small,
  60751. * no animation is ok for most cases.
  60752. * @protected
  60753. */
  60754. animationThreshold: 15,
  60755. /**
  60756. * @implement
  60757. */
  60758. render: function (axisModel, axisPointerModel, api, forceRender) {
  60759. var value = axisPointerModel.get('value');
  60760. var status = axisPointerModel.get('status');
  60761. // Bind them to `this`, not in closure, otherwise they will not
  60762. // be replaced when user calling setOption in not merge mode.
  60763. this._axisModel = axisModel;
  60764. this._axisPointerModel = axisPointerModel;
  60765. this._api = api;
  60766. // Optimize: `render` will be called repeatly during mouse move.
  60767. // So it is power consuming if performing `render` each time,
  60768. // especially on mobile device.
  60769. if (!forceRender
  60770. && this._lastValue === value
  60771. && this._lastStatus === status
  60772. ) {
  60773. return;
  60774. }
  60775. this._lastValue = value;
  60776. this._lastStatus = status;
  60777. var group = this._group;
  60778. var handle = this._handle;
  60779. if (!status || status === 'hide') {
  60780. // Do not clear here, for animation better.
  60781. group && group.hide();
  60782. handle && handle.hide();
  60783. return;
  60784. }
  60785. group && group.show();
  60786. handle && handle.show();
  60787. // Otherwise status is 'show'
  60788. var elOption = {};
  60789. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  60790. // Enable change axis pointer type.
  60791. var graphicKey = elOption.graphicKey;
  60792. if (graphicKey !== this._lastGraphicKey) {
  60793. this.clear(api);
  60794. }
  60795. this._lastGraphicKey = graphicKey;
  60796. var moveAnimation = this._moveAnimation =
  60797. this.determineAnimation(axisModel, axisPointerModel);
  60798. if (!group) {
  60799. group = this._group = new Group();
  60800. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  60801. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  60802. api.getZr().add(group);
  60803. }
  60804. else {
  60805. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  60806. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  60807. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  60808. }
  60809. updateMandatoryProps(group, axisPointerModel, true);
  60810. this._renderHandle(value);
  60811. },
  60812. /**
  60813. * @implement
  60814. */
  60815. remove: function (api) {
  60816. this.clear(api);
  60817. },
  60818. /**
  60819. * @implement
  60820. */
  60821. dispose: function (api) {
  60822. this.clear(api);
  60823. },
  60824. /**
  60825. * @protected
  60826. */
  60827. determineAnimation: function (axisModel, axisPointerModel) {
  60828. var animation = axisPointerModel.get('animation');
  60829. var axis = axisModel.axis;
  60830. var isCategoryAxis = axis.type === 'category';
  60831. var useSnap = axisPointerModel.get('snap');
  60832. // Value axis without snap always do not snap.
  60833. if (!useSnap && !isCategoryAxis) {
  60834. return false;
  60835. }
  60836. if (animation === 'auto' || animation == null) {
  60837. var animationThreshold = this.animationThreshold;
  60838. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  60839. return true;
  60840. }
  60841. // It is important to auto animation when snap used. Consider if there is
  60842. // a dataZoom, animation will be disabled when too many points exist, while
  60843. // it will be enabled for better visual effect when little points exist.
  60844. if (useSnap) {
  60845. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  60846. var axisExtent = axis.getExtent();
  60847. // Approximate band width
  60848. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  60849. }
  60850. return false;
  60851. }
  60852. return animation === true;
  60853. },
  60854. /**
  60855. * add {pointer, label, graphicKey} to elOption
  60856. * @protected
  60857. */
  60858. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  60859. // Shoule be implemenented by sub-class.
  60860. },
  60861. /**
  60862. * @protected
  60863. */
  60864. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  60865. var pointerOption = elOption.pointer;
  60866. if (pointerOption) {
  60867. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  60868. clone$4(elOption.pointer)
  60869. );
  60870. group.add(pointerEl);
  60871. }
  60872. },
  60873. /**
  60874. * @protected
  60875. */
  60876. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  60877. if (elOption.label) {
  60878. var labelEl = inner$11(group).labelEl = new Rect(
  60879. clone$4(elOption.label)
  60880. );
  60881. group.add(labelEl);
  60882. updateLabelShowHide(labelEl, axisPointerModel);
  60883. }
  60884. },
  60885. /**
  60886. * @protected
  60887. */
  60888. updatePointerEl: function (group, elOption, updateProps$$1) {
  60889. var pointerEl = inner$11(group).pointerEl;
  60890. if (pointerEl && elOption.pointer) {
  60891. pointerEl.setStyle(elOption.pointer.style);
  60892. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  60893. }
  60894. },
  60895. /**
  60896. * @protected
  60897. */
  60898. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  60899. var labelEl = inner$11(group).labelEl;
  60900. if (labelEl) {
  60901. labelEl.setStyle(elOption.label.style);
  60902. updateProps$$1(labelEl, {
  60903. // Consider text length change in vertical axis, animation should
  60904. // be used on shape, otherwise the effect will be weird.
  60905. shape: elOption.label.shape,
  60906. position: elOption.label.position
  60907. });
  60908. updateLabelShowHide(labelEl, axisPointerModel);
  60909. }
  60910. },
  60911. /**
  60912. * @private
  60913. */
  60914. _renderHandle: function (value) {
  60915. if (this._dragging || !this.updateHandleTransform) {
  60916. return;
  60917. }
  60918. var axisPointerModel = this._axisPointerModel;
  60919. var zr = this._api.getZr();
  60920. var handle = this._handle;
  60921. var handleModel = axisPointerModel.getModel('handle');
  60922. var status = axisPointerModel.get('status');
  60923. if (!handleModel.get('show') || !status || status === 'hide') {
  60924. handle && zr.remove(handle);
  60925. this._handle = null;
  60926. return;
  60927. }
  60928. var isInit;
  60929. if (!this._handle) {
  60930. isInit = true;
  60931. handle = this._handle = createIcon(
  60932. handleModel.get('icon'),
  60933. {
  60934. cursor: 'move',
  60935. draggable: true,
  60936. onmousemove: function (e) {
  60937. // Fot mobile devicem, prevent screen slider on the button.
  60938. stop(e.event);
  60939. },
  60940. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  60941. drift: bind$2(this._onHandleDragMove, this),
  60942. ondragend: bind$2(this._onHandleDragEnd, this)
  60943. }
  60944. );
  60945. zr.add(handle);
  60946. }
  60947. updateMandatoryProps(handle, axisPointerModel, false);
  60948. // update style
  60949. var includeStyles = [
  60950. 'color', 'borderColor', 'borderWidth', 'opacity',
  60951. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  60952. ];
  60953. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  60954. // update position
  60955. var handleSize = handleModel.get('size');
  60956. if (!isArray(handleSize)) {
  60957. handleSize = [handleSize, handleSize];
  60958. }
  60959. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  60960. createOrUpdate(
  60961. this,
  60962. '_doDispatchAxisPointer',
  60963. handleModel.get('throttle') || 0,
  60964. 'fixRate'
  60965. );
  60966. this._moveHandleToValue(value, isInit);
  60967. },
  60968. /**
  60969. * @private
  60970. */
  60971. _moveHandleToValue: function (value, isInit) {
  60972. updateProps$1(
  60973. this._axisPointerModel,
  60974. !isInit && this._moveAnimation,
  60975. this._handle,
  60976. getHandleTransProps(this.getHandleTransform(
  60977. value, this._axisModel, this._axisPointerModel
  60978. ))
  60979. );
  60980. },
  60981. /**
  60982. * @private
  60983. */
  60984. _onHandleDragMove: function (dx, dy) {
  60985. var handle = this._handle;
  60986. if (!handle) {
  60987. return;
  60988. }
  60989. this._dragging = true;
  60990. // Persistent for throttle.
  60991. var trans = this.updateHandleTransform(
  60992. getHandleTransProps(handle),
  60993. [dx, dy],
  60994. this._axisModel,
  60995. this._axisPointerModel
  60996. );
  60997. this._payloadInfo = trans;
  60998. handle.stopAnimation();
  60999. handle.attr(getHandleTransProps(trans));
  61000. inner$11(handle).lastProp = null;
  61001. this._doDispatchAxisPointer();
  61002. },
  61003. /**
  61004. * Throttled method.
  61005. * @private
  61006. */
  61007. _doDispatchAxisPointer: function () {
  61008. var handle = this._handle;
  61009. if (!handle) {
  61010. return;
  61011. }
  61012. var payloadInfo = this._payloadInfo;
  61013. var axisModel = this._axisModel;
  61014. this._api.dispatchAction({
  61015. type: 'updateAxisPointer',
  61016. x: payloadInfo.cursorPoint[0],
  61017. y: payloadInfo.cursorPoint[1],
  61018. tooltipOption: payloadInfo.tooltipOption,
  61019. axesInfo: [{
  61020. axisDim: axisModel.axis.dim,
  61021. axisIndex: axisModel.componentIndex
  61022. }]
  61023. });
  61024. },
  61025. /**
  61026. * @private
  61027. */
  61028. _onHandleDragEnd: function (moveAnimation) {
  61029. this._dragging = false;
  61030. var handle = this._handle;
  61031. if (!handle) {
  61032. return;
  61033. }
  61034. var value = this._axisPointerModel.get('value');
  61035. // Consider snap or categroy axis, handle may be not consistent with
  61036. // axisPointer. So move handle to align the exact value position when
  61037. // drag ended.
  61038. this._moveHandleToValue(value);
  61039. // For the effect: tooltip will be shown when finger holding on handle
  61040. // button, and will be hidden after finger left handle button.
  61041. this._api.dispatchAction({
  61042. type: 'hideTip'
  61043. });
  61044. },
  61045. /**
  61046. * Should be implemenented by sub-class if support `handle`.
  61047. * @protected
  61048. * @param {number} value
  61049. * @param {module:echarts/model/Model} axisModel
  61050. * @param {module:echarts/model/Model} axisPointerModel
  61051. * @return {Object} {position: [x, y], rotation: 0}
  61052. */
  61053. getHandleTransform: null,
  61054. /**
  61055. * * Should be implemenented by sub-class if support `handle`.
  61056. * @protected
  61057. * @param {Object} transform {position, rotation}
  61058. * @param {Array.<number>} delta [dx, dy]
  61059. * @param {module:echarts/model/Model} axisModel
  61060. * @param {module:echarts/model/Model} axisPointerModel
  61061. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  61062. */
  61063. updateHandleTransform: null,
  61064. /**
  61065. * @private
  61066. */
  61067. clear: function (api) {
  61068. this._lastValue = null;
  61069. this._lastStatus = null;
  61070. var zr = api.getZr();
  61071. var group = this._group;
  61072. var handle = this._handle;
  61073. if (zr && group) {
  61074. this._lastGraphicKey = null;
  61075. group && zr.remove(group);
  61076. handle && zr.remove(handle);
  61077. this._group = null;
  61078. this._handle = null;
  61079. this._payloadInfo = null;
  61080. }
  61081. },
  61082. /**
  61083. * @protected
  61084. */
  61085. doClear: function () {
  61086. // Implemented by sub-class if necessary.
  61087. },
  61088. /**
  61089. * @protected
  61090. * @param {Array.<number>} xy
  61091. * @param {Array.<number>} wh
  61092. * @param {number} [xDimIndex=0] or 1
  61093. */
  61094. buildLabel: function (xy, wh, xDimIndex) {
  61095. xDimIndex = xDimIndex || 0;
  61096. return {
  61097. x: xy[xDimIndex],
  61098. y: xy[1 - xDimIndex],
  61099. width: wh[xDimIndex],
  61100. height: wh[1 - xDimIndex]
  61101. };
  61102. }
  61103. };
  61104. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  61105. function updateProps$1(animationModel, moveAnimation, el, props) {
  61106. // Animation optimize.
  61107. if (!propsEqual(inner$11(el).lastProp, props)) {
  61108. inner$11(el).lastProp = props;
  61109. moveAnimation
  61110. ? updateProps(el, props, animationModel)
  61111. : (el.stopAnimation(), el.attr(props));
  61112. }
  61113. }
  61114. function propsEqual(lastProps, newProps) {
  61115. if (isObject$1(lastProps) && isObject$1(newProps)) {
  61116. var equals = true;
  61117. each$1(newProps, function (item, key) {
  61118. equals = equals && propsEqual(lastProps[key], item);
  61119. });
  61120. return !!equals;
  61121. }
  61122. else {
  61123. return lastProps === newProps;
  61124. }
  61125. }
  61126. function updateLabelShowHide(labelEl, axisPointerModel) {
  61127. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  61128. }
  61129. function getHandleTransProps(trans) {
  61130. return {
  61131. position: trans.position.slice(),
  61132. rotation: trans.rotation || 0
  61133. };
  61134. }
  61135. function updateMandatoryProps(group, axisPointerModel, silent) {
  61136. var z = axisPointerModel.get('z');
  61137. var zlevel = axisPointerModel.get('zlevel');
  61138. group && group.traverse(function (el) {
  61139. if (el.type !== 'group') {
  61140. z != null && (el.z = z);
  61141. zlevel != null && (el.zlevel = zlevel);
  61142. el.silent = silent;
  61143. }
  61144. });
  61145. }
  61146. enableClassExtend(BaseAxisPointer);
  61147. /*
  61148. * Licensed to the Apache Software Foundation (ASF) under one
  61149. * or more contributor license agreements. See the NOTICE file
  61150. * distributed with this work for additional information
  61151. * regarding copyright ownership. The ASF licenses this file
  61152. * to you under the Apache License, Version 2.0 (the
  61153. * "License"); you may not use this file except in compliance
  61154. * with the License. You may obtain a copy of the License at
  61155. *
  61156. * http://www.apache.org/licenses/LICENSE-2.0
  61157. *
  61158. * Unless required by applicable law or agreed to in writing,
  61159. * software distributed under the License is distributed on an
  61160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61161. * KIND, either express or implied. See the License for the
  61162. * specific language governing permissions and limitations
  61163. * under the License.
  61164. */
  61165. /**
  61166. * @param {module:echarts/model/Model} axisPointerModel
  61167. */
  61168. function buildElStyle(axisPointerModel) {
  61169. var axisPointerType = axisPointerModel.get('type');
  61170. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  61171. var style;
  61172. if (axisPointerType === 'line') {
  61173. style = styleModel.getLineStyle();
  61174. style.fill = null;
  61175. }
  61176. else if (axisPointerType === 'shadow') {
  61177. style = styleModel.getAreaStyle();
  61178. style.stroke = null;
  61179. }
  61180. return style;
  61181. }
  61182. /**
  61183. * @param {Function} labelPos {align, verticalAlign, position}
  61184. */
  61185. function buildLabelElOption(
  61186. elOption, axisModel, axisPointerModel, api, labelPos
  61187. ) {
  61188. var value = axisPointerModel.get('value');
  61189. var text = getValueLabel(
  61190. value, axisModel.axis, axisModel.ecModel,
  61191. axisPointerModel.get('seriesDataIndices'),
  61192. {
  61193. precision: axisPointerModel.get('label.precision'),
  61194. formatter: axisPointerModel.get('label.formatter')
  61195. }
  61196. );
  61197. var labelModel = axisPointerModel.getModel('label');
  61198. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  61199. var font = labelModel.getFont();
  61200. var textRect = getBoundingRect(text, font);
  61201. var position = labelPos.position;
  61202. var width = textRect.width + paddings[1] + paddings[3];
  61203. var height = textRect.height + paddings[0] + paddings[2];
  61204. // Adjust by align.
  61205. var align = labelPos.align;
  61206. align === 'right' && (position[0] -= width);
  61207. align === 'center' && (position[0] -= width / 2);
  61208. var verticalAlign = labelPos.verticalAlign;
  61209. verticalAlign === 'bottom' && (position[1] -= height);
  61210. verticalAlign === 'middle' && (position[1] -= height / 2);
  61211. // Not overflow ec container
  61212. confineInContainer(position, width, height, api);
  61213. var bgColor = labelModel.get('backgroundColor');
  61214. if (!bgColor || bgColor === 'auto') {
  61215. bgColor = axisModel.get('axisLine.lineStyle.color');
  61216. }
  61217. elOption.label = {
  61218. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  61219. position: position.slice(),
  61220. // TODO: rich
  61221. style: {
  61222. text: text,
  61223. textFont: font,
  61224. textFill: labelModel.getTextColor(),
  61225. textPosition: 'inside',
  61226. textPadding: paddings,
  61227. fill: bgColor,
  61228. stroke: labelModel.get('borderColor') || 'transparent',
  61229. lineWidth: labelModel.get('borderWidth') || 0,
  61230. shadowBlur: labelModel.get('shadowBlur'),
  61231. shadowColor: labelModel.get('shadowColor'),
  61232. shadowOffsetX: labelModel.get('shadowOffsetX'),
  61233. shadowOffsetY: labelModel.get('shadowOffsetY')
  61234. },
  61235. // Lable should be over axisPointer.
  61236. z2: 10
  61237. };
  61238. }
  61239. // Do not overflow ec container
  61240. function confineInContainer(position, width, height, api) {
  61241. var viewWidth = api.getWidth();
  61242. var viewHeight = api.getHeight();
  61243. position[0] = Math.min(position[0] + width, viewWidth) - width;
  61244. position[1] = Math.min(position[1] + height, viewHeight) - height;
  61245. position[0] = Math.max(position[0], 0);
  61246. position[1] = Math.max(position[1], 0);
  61247. }
  61248. /**
  61249. * @param {number} value
  61250. * @param {module:echarts/coord/Axis} axis
  61251. * @param {module:echarts/model/Global} ecModel
  61252. * @param {Object} opt
  61253. * @param {Array.<Object>} seriesDataIndices
  61254. * @param {number|string} opt.precision 'auto' or a number
  61255. * @param {string|Function} opt.formatter label formatter
  61256. */
  61257. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  61258. value = axis.scale.parse(value);
  61259. var text = axis.scale.getLabel(
  61260. // If `precision` is set, width can be fixed (like '12.00500'), which
  61261. // helps to debounce when when moving label.
  61262. value, {precision: opt.precision}
  61263. );
  61264. var formatter = opt.formatter;
  61265. if (formatter) {
  61266. var params = {
  61267. value: getAxisRawValue(axis, value),
  61268. axisDimension: axis.dim,
  61269. axisIndex: axis.index,
  61270. seriesData: []
  61271. };
  61272. each$1(seriesDataIndices, function (idxItem) {
  61273. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61274. var dataIndex = idxItem.dataIndexInside;
  61275. var dataParams = series && series.getDataParams(dataIndex);
  61276. dataParams && params.seriesData.push(dataParams);
  61277. });
  61278. if (isString(formatter)) {
  61279. text = formatter.replace('{value}', text);
  61280. }
  61281. else if (isFunction$1(formatter)) {
  61282. text = formatter(params);
  61283. }
  61284. }
  61285. return text;
  61286. }
  61287. /**
  61288. * @param {module:echarts/coord/Axis} axis
  61289. * @param {number} value
  61290. * @param {Object} layoutInfo {
  61291. * rotation, position, labelOffset, labelDirection, labelMargin
  61292. * }
  61293. */
  61294. function getTransformedPosition(axis, value, layoutInfo) {
  61295. var transform = create$1();
  61296. rotate(transform, transform, layoutInfo.rotation);
  61297. translate(transform, transform, layoutInfo.position);
  61298. return applyTransform$1([
  61299. axis.dataToCoord(value),
  61300. (layoutInfo.labelOffset || 0)
  61301. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  61302. ], transform);
  61303. }
  61304. function buildCartesianSingleLabelElOption(
  61305. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61306. ) {
  61307. var textLayout = AxisBuilder.innerTextLayout(
  61308. layoutInfo.rotation, 0, layoutInfo.labelDirection
  61309. );
  61310. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  61311. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  61312. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61313. align: textLayout.textAlign,
  61314. verticalAlign: textLayout.textVerticalAlign
  61315. });
  61316. }
  61317. /**
  61318. * @param {Array.<number>} p1
  61319. * @param {Array.<number>} p2
  61320. * @param {number} [xDimIndex=0] or 1
  61321. */
  61322. function makeLineShape(p1, p2, xDimIndex) {
  61323. xDimIndex = xDimIndex || 0;
  61324. return {
  61325. x1: p1[xDimIndex],
  61326. y1: p1[1 - xDimIndex],
  61327. x2: p2[xDimIndex],
  61328. y2: p2[1 - xDimIndex]
  61329. };
  61330. }
  61331. /**
  61332. * @param {Array.<number>} xy
  61333. * @param {Array.<number>} wh
  61334. * @param {number} [xDimIndex=0] or 1
  61335. */
  61336. function makeRectShape(xy, wh, xDimIndex) {
  61337. xDimIndex = xDimIndex || 0;
  61338. return {
  61339. x: xy[xDimIndex],
  61340. y: xy[1 - xDimIndex],
  61341. width: wh[xDimIndex],
  61342. height: wh[1 - xDimIndex]
  61343. };
  61344. }
  61345. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  61346. return {
  61347. cx: cx,
  61348. cy: cy,
  61349. r0: r0,
  61350. r: r,
  61351. startAngle: startAngle,
  61352. endAngle: endAngle,
  61353. clockwise: true
  61354. };
  61355. }
  61356. /*
  61357. * Licensed to the Apache Software Foundation (ASF) under one
  61358. * or more contributor license agreements. See the NOTICE file
  61359. * distributed with this work for additional information
  61360. * regarding copyright ownership. The ASF licenses this file
  61361. * to you under the Apache License, Version 2.0 (the
  61362. * "License"); you may not use this file except in compliance
  61363. * with the License. You may obtain a copy of the License at
  61364. *
  61365. * http://www.apache.org/licenses/LICENSE-2.0
  61366. *
  61367. * Unless required by applicable law or agreed to in writing,
  61368. * software distributed under the License is distributed on an
  61369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61370. * KIND, either express or implied. See the License for the
  61371. * specific language governing permissions and limitations
  61372. * under the License.
  61373. */
  61374. var CartesianAxisPointer = BaseAxisPointer.extend({
  61375. /**
  61376. * @override
  61377. */
  61378. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61379. var axis = axisModel.axis;
  61380. var grid = axis.grid;
  61381. var axisPointerType = axisPointerModel.get('type');
  61382. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  61383. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  61384. if (axisPointerType && axisPointerType !== 'none') {
  61385. var elStyle = buildElStyle(axisPointerModel);
  61386. var pointerOption = pointerShapeBuilder[axisPointerType](
  61387. axis, pixelValue, otherExtent
  61388. );
  61389. pointerOption.style = elStyle;
  61390. elOption.graphicKey = pointerOption.type;
  61391. elOption.pointer = pointerOption;
  61392. }
  61393. var layoutInfo = layout$1(grid.model, axisModel);
  61394. buildCartesianSingleLabelElOption(
  61395. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61396. );
  61397. },
  61398. /**
  61399. * @override
  61400. */
  61401. getHandleTransform: function (value, axisModel, axisPointerModel) {
  61402. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  61403. labelInside: false
  61404. });
  61405. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  61406. return {
  61407. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61408. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  61409. };
  61410. },
  61411. /**
  61412. * @override
  61413. */
  61414. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  61415. var axis = axisModel.axis;
  61416. var grid = axis.grid;
  61417. var axisExtent = axis.getGlobalExtent(true);
  61418. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  61419. var dimIndex = axis.dim === 'x' ? 0 : 1;
  61420. var currPosition = transform.position;
  61421. currPosition[dimIndex] += delta[dimIndex];
  61422. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  61423. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  61424. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  61425. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  61426. cursorPoint[dimIndex] = currPosition[dimIndex];
  61427. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  61428. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  61429. return {
  61430. position: currPosition,
  61431. rotation: transform.rotation,
  61432. cursorPoint: cursorPoint,
  61433. tooltipOption: tooltipOptions[dimIndex]
  61434. };
  61435. }
  61436. });
  61437. function getCartesian(grid, axis) {
  61438. var opt = {};
  61439. opt[axis.dim + 'AxisIndex'] = axis.index;
  61440. return grid.getCartesian(opt);
  61441. }
  61442. var pointerShapeBuilder = {
  61443. line: function (axis, pixelValue, otherExtent) {
  61444. var targetShape = makeLineShape(
  61445. [pixelValue, otherExtent[0]],
  61446. [pixelValue, otherExtent[1]],
  61447. getAxisDimIndex(axis)
  61448. );
  61449. return {
  61450. type: 'Line',
  61451. subPixelOptimize: true,
  61452. shape: targetShape
  61453. };
  61454. },
  61455. shadow: function (axis, pixelValue, otherExtent) {
  61456. var bandWidth = Math.max(1, axis.getBandWidth());
  61457. var span = otherExtent[1] - otherExtent[0];
  61458. return {
  61459. type: 'Rect',
  61460. shape: makeRectShape(
  61461. [pixelValue - bandWidth / 2, otherExtent[0]],
  61462. [bandWidth, span],
  61463. getAxisDimIndex(axis)
  61464. )
  61465. };
  61466. }
  61467. };
  61468. function getAxisDimIndex(axis) {
  61469. return axis.dim === 'x' ? 0 : 1;
  61470. }
  61471. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  61472. /*
  61473. * Licensed to the Apache Software Foundation (ASF) under one
  61474. * or more contributor license agreements. See the NOTICE file
  61475. * distributed with this work for additional information
  61476. * regarding copyright ownership. The ASF licenses this file
  61477. * to you under the Apache License, Version 2.0 (the
  61478. * "License"); you may not use this file except in compliance
  61479. * with the License. You may obtain a copy of the License at
  61480. *
  61481. * http://www.apache.org/licenses/LICENSE-2.0
  61482. *
  61483. * Unless required by applicable law or agreed to in writing,
  61484. * software distributed under the License is distributed on an
  61485. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61486. * KIND, either express or implied. See the License for the
  61487. * specific language governing permissions and limitations
  61488. * under the License.
  61489. */
  61490. // CartesianAxisPointer is not supposed to be required here. But consider
  61491. // echarts.simple.js and online build tooltip, which only require gridSimple,
  61492. // CartesianAxisPointer should be able to required somewhere.
  61493. registerPreprocessor(function (option) {
  61494. // Always has a global axisPointerModel for default setting.
  61495. if (option) {
  61496. (!option.axisPointer || option.axisPointer.length === 0)
  61497. && (option.axisPointer = {});
  61498. var link = option.axisPointer.link;
  61499. // Normalize to array to avoid object mergin. But if link
  61500. // is not set, remain null/undefined, otherwise it will
  61501. // override existent link setting.
  61502. if (link && !isArray(link)) {
  61503. option.axisPointer.link = [link];
  61504. }
  61505. }
  61506. });
  61507. // This process should proformed after coordinate systems created
  61508. // and series data processed. So put it on statistic processing stage.
  61509. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  61510. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  61511. // allAxesInfo should be updated when setOption performed.
  61512. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  61513. collect(ecModel, api);
  61514. });
  61515. // Broadcast to all views.
  61516. registerAction({
  61517. type: 'updateAxisPointer',
  61518. event: 'updateAxisPointer',
  61519. update: ':updateAxisPointer'
  61520. }, axisTrigger);
  61521. /*
  61522. * Licensed to the Apache Software Foundation (ASF) under one
  61523. * or more contributor license agreements. See the NOTICE file
  61524. * distributed with this work for additional information
  61525. * regarding copyright ownership. The ASF licenses this file
  61526. * to you under the Apache License, Version 2.0 (the
  61527. * "License"); you may not use this file except in compliance
  61528. * with the License. You may obtain a copy of the License at
  61529. *
  61530. * http://www.apache.org/licenses/LICENSE-2.0
  61531. *
  61532. * Unless required by applicable law or agreed to in writing,
  61533. * software distributed under the License is distributed on an
  61534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61535. * KIND, either express or implied. See the License for the
  61536. * specific language governing permissions and limitations
  61537. * under the License.
  61538. */
  61539. var XY = ['x', 'y'];
  61540. var WH = ['width', 'height'];
  61541. var SingleAxisPointer = BaseAxisPointer.extend({
  61542. /**
  61543. * @override
  61544. */
  61545. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61546. var axis = axisModel.axis;
  61547. var coordSys = axis.coordinateSystem;
  61548. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  61549. var pixelValue = coordSys.dataToPoint(value)[0];
  61550. var axisPointerType = axisPointerModel.get('type');
  61551. if (axisPointerType && axisPointerType !== 'none') {
  61552. var elStyle = buildElStyle(axisPointerModel);
  61553. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  61554. axis, pixelValue, otherExtent
  61555. );
  61556. pointerOption.style = elStyle;
  61557. elOption.graphicKey = pointerOption.type;
  61558. elOption.pointer = pointerOption;
  61559. }
  61560. var layoutInfo = layout$2(axisModel);
  61561. buildCartesianSingleLabelElOption(
  61562. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  61563. );
  61564. },
  61565. /**
  61566. * @override
  61567. */
  61568. getHandleTransform: function (value, axisModel, axisPointerModel) {
  61569. var layoutInfo = layout$2(axisModel, {labelInside: false});
  61570. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  61571. return {
  61572. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  61573. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  61574. };
  61575. },
  61576. /**
  61577. * @override
  61578. */
  61579. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  61580. var axis = axisModel.axis;
  61581. var coordSys = axis.coordinateSystem;
  61582. var dimIndex = getPointDimIndex(axis);
  61583. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  61584. var currPosition = transform.position;
  61585. currPosition[dimIndex] += delta[dimIndex];
  61586. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  61587. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  61588. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  61589. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  61590. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  61591. cursorPoint[dimIndex] = currPosition[dimIndex];
  61592. return {
  61593. position: currPosition,
  61594. rotation: transform.rotation,
  61595. cursorPoint: cursorPoint,
  61596. tooltipOption: {
  61597. verticalAlign: 'middle'
  61598. }
  61599. };
  61600. }
  61601. });
  61602. var pointerShapeBuilder$1 = {
  61603. line: function (axis, pixelValue, otherExtent) {
  61604. var targetShape = makeLineShape(
  61605. [pixelValue, otherExtent[0]],
  61606. [pixelValue, otherExtent[1]],
  61607. getPointDimIndex(axis)
  61608. );
  61609. return {
  61610. type: 'Line',
  61611. subPixelOptimize: true,
  61612. shape: targetShape
  61613. };
  61614. },
  61615. shadow: function (axis, pixelValue, otherExtent) {
  61616. var bandWidth = axis.getBandWidth();
  61617. var span = otherExtent[1] - otherExtent[0];
  61618. return {
  61619. type: 'Rect',
  61620. shape: makeRectShape(
  61621. [pixelValue - bandWidth / 2, otherExtent[0]],
  61622. [bandWidth, span],
  61623. getPointDimIndex(axis)
  61624. )
  61625. };
  61626. }
  61627. };
  61628. function getPointDimIndex(axis) {
  61629. return axis.isHorizontal() ? 0 : 1;
  61630. }
  61631. function getGlobalExtent(coordSys, dimIndex) {
  61632. var rect = coordSys.getRect();
  61633. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  61634. }
  61635. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  61636. /*
  61637. * Licensed to the Apache Software Foundation (ASF) under one
  61638. * or more contributor license agreements. See the NOTICE file
  61639. * distributed with this work for additional information
  61640. * regarding copyright ownership. The ASF licenses this file
  61641. * to you under the Apache License, Version 2.0 (the
  61642. * "License"); you may not use this file except in compliance
  61643. * with the License. You may obtain a copy of the License at
  61644. *
  61645. * http://www.apache.org/licenses/LICENSE-2.0
  61646. *
  61647. * Unless required by applicable law or agreed to in writing,
  61648. * software distributed under the License is distributed on an
  61649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61650. * KIND, either express or implied. See the License for the
  61651. * specific language governing permissions and limitations
  61652. * under the License.
  61653. */
  61654. extendComponentView({
  61655. type: 'single'
  61656. });
  61657. /*
  61658. * Licensed to the Apache Software Foundation (ASF) under one
  61659. * or more contributor license agreements. See the NOTICE file
  61660. * distributed with this work for additional information
  61661. * regarding copyright ownership. The ASF licenses this file
  61662. * to you under the Apache License, Version 2.0 (the
  61663. * "License"); you may not use this file except in compliance
  61664. * with the License. You may obtain a copy of the License at
  61665. *
  61666. * http://www.apache.org/licenses/LICENSE-2.0
  61667. *
  61668. * Unless required by applicable law or agreed to in writing,
  61669. * software distributed under the License is distributed on an
  61670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61671. * KIND, either express or implied. See the License for the
  61672. * specific language governing permissions and limitations
  61673. * under the License.
  61674. */
  61675. var DATA_NAME_INDEX = 2;
  61676. var ThemeRiverSeries = SeriesModel.extend({
  61677. type: 'series.themeRiver',
  61678. dependencies: ['singleAxis'],
  61679. /**
  61680. * @readOnly
  61681. * @type {module:zrender/core/util#HashMap}
  61682. */
  61683. nameMap: null,
  61684. /**
  61685. * @override
  61686. */
  61687. init: function (option) {
  61688. // eslint-disable-next-line
  61689. ThemeRiverSeries.superApply(this, 'init', arguments);
  61690. // Put this function here is for the sake of consistency of code style.
  61691. // Enable legend selection for each data item
  61692. // Use a function instead of direct access because data reference may changed
  61693. this.legendVisualProvider = new LegendVisualProvider(
  61694. bind(this.getData, this), bind(this.getRawData, this)
  61695. );
  61696. },
  61697. /**
  61698. * If there is no value of a certain point in the time for some event,set it value to 0.
  61699. *
  61700. * @param {Array} data initial data in the option
  61701. * @return {Array}
  61702. */
  61703. fixData: function (data) {
  61704. var rawDataLength = data.length;
  61705. // grouped data by name
  61706. var groupResult = groupData(data, function (item) {
  61707. return item[2];
  61708. });
  61709. var layData = [];
  61710. groupResult.buckets.each(function (items, key) {
  61711. layData.push({name: key, dataList: items});
  61712. });
  61713. var layerNum = layData.length;
  61714. var largestLayer = -1;
  61715. var index = -1;
  61716. for (var i = 0; i < layerNum; ++i) {
  61717. var len = layData[i].dataList.length;
  61718. if (len > largestLayer) {
  61719. largestLayer = len;
  61720. index = i;
  61721. }
  61722. }
  61723. for (var k = 0; k < layerNum; ++k) {
  61724. if (k === index) {
  61725. continue;
  61726. }
  61727. var name = layData[k].name;
  61728. for (var j = 0; j < largestLayer; ++j) {
  61729. var timeValue = layData[index].dataList[j][0];
  61730. var length = layData[k].dataList.length;
  61731. var keyIndex = -1;
  61732. for (var l = 0; l < length; ++l) {
  61733. var value = layData[k].dataList[l][0];
  61734. if (value === timeValue) {
  61735. keyIndex = l;
  61736. break;
  61737. }
  61738. }
  61739. if (keyIndex === -1) {
  61740. data[rawDataLength] = [];
  61741. data[rawDataLength][0] = timeValue;
  61742. data[rawDataLength][1] = 0;
  61743. data[rawDataLength][2] = name;
  61744. rawDataLength++;
  61745. }
  61746. }
  61747. }
  61748. return data;
  61749. },
  61750. /**
  61751. * @override
  61752. * @param {Object} option the initial option that user gived
  61753. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  61754. * @return {module:echarts/data/List}
  61755. */
  61756. getInitialData: function (option, ecModel) {
  61757. var singleAxisModel = ecModel.queryComponents({
  61758. mainType: 'singleAxis',
  61759. index: this.get('singleAxisIndex'),
  61760. id: this.get('singleAxisId')
  61761. })[0];
  61762. var axisType = singleAxisModel.get('type');
  61763. // filter the data item with the value of label is undefined
  61764. var filterData = filter(option.data, function (dataItem) {
  61765. return dataItem[2] !== undefined;
  61766. });
  61767. // ??? TODO design a stage to transfer data for themeRiver and lines?
  61768. var data = this.fixData(filterData || []);
  61769. var nameList = [];
  61770. var nameMap = this.nameMap = createHashMap();
  61771. var count = 0;
  61772. for (var i = 0; i < data.length; ++i) {
  61773. nameList.push(data[i][DATA_NAME_INDEX]);
  61774. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  61775. nameMap.set(data[i][DATA_NAME_INDEX], count);
  61776. count++;
  61777. }
  61778. }
  61779. var dimensionsInfo = createDimensions(data, {
  61780. coordDimensions: ['single'],
  61781. dimensionsDefine: [
  61782. {
  61783. name: 'time',
  61784. type: getDimensionTypeByAxis(axisType)
  61785. },
  61786. {
  61787. name: 'value',
  61788. type: 'float'
  61789. },
  61790. {
  61791. name: 'name',
  61792. type: 'ordinal'
  61793. }
  61794. ],
  61795. encodeDefine: {
  61796. single: 0,
  61797. value: 1,
  61798. itemName: 2
  61799. }
  61800. });
  61801. var list = new List(dimensionsInfo, this);
  61802. list.initData(data);
  61803. return list;
  61804. },
  61805. /**
  61806. * The raw data is divided into multiple layers and each layer
  61807. * has same name.
  61808. *
  61809. * @return {Array.<Array.<number>>}
  61810. */
  61811. getLayerSeries: function () {
  61812. var data = this.getData();
  61813. var lenCount = data.count();
  61814. var indexArr = [];
  61815. for (var i = 0; i < lenCount; ++i) {
  61816. indexArr[i] = i;
  61817. }
  61818. var timeDim = data.mapDimension('single');
  61819. // data group by name
  61820. var groupResult = groupData(indexArr, function (index) {
  61821. return data.get('name', index);
  61822. });
  61823. var layerSeries = [];
  61824. groupResult.buckets.each(function (items, key) {
  61825. items.sort(function (index1, index2) {
  61826. return data.get(timeDim, index1) - data.get(timeDim, index2);
  61827. });
  61828. layerSeries.push({name: key, indices: items});
  61829. });
  61830. return layerSeries;
  61831. },
  61832. /**
  61833. * Get data indices for show tooltip content
  61834. * @param {Array.<string>|string} dim single coordinate dimension
  61835. * @param {number} value axis value
  61836. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  61837. * the themeRiver.
  61838. * @return {Object} {dataIndices, nestestValue}
  61839. */
  61840. getAxisTooltipData: function (dim, value, baseAxis) {
  61841. if (!isArray(dim)) {
  61842. dim = dim ? [dim] : [];
  61843. }
  61844. var data = this.getData();
  61845. var layerSeries = this.getLayerSeries();
  61846. var indices = [];
  61847. var layerNum = layerSeries.length;
  61848. var nestestValue;
  61849. for (var i = 0; i < layerNum; ++i) {
  61850. var minDist = Number.MAX_VALUE;
  61851. var nearestIdx = -1;
  61852. var pointNum = layerSeries[i].indices.length;
  61853. for (var j = 0; j < pointNum; ++j) {
  61854. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  61855. var dist = Math.abs(theValue - value);
  61856. if (dist <= minDist) {
  61857. nestestValue = theValue;
  61858. minDist = dist;
  61859. nearestIdx = layerSeries[i].indices[j];
  61860. }
  61861. }
  61862. indices.push(nearestIdx);
  61863. }
  61864. return {dataIndices: indices, nestestValue: nestestValue};
  61865. },
  61866. /**
  61867. * @override
  61868. * @param {number} dataIndex index of data
  61869. */
  61870. formatTooltip: function (dataIndex) {
  61871. var data = this.getData();
  61872. var htmlName = data.getName(dataIndex);
  61873. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  61874. if (isNaN(htmlValue) || htmlValue == null) {
  61875. htmlValue = '-';
  61876. }
  61877. return encodeHTML(htmlName + ' : ' + htmlValue);
  61878. },
  61879. defaultOption: {
  61880. zlevel: 0,
  61881. z: 2,
  61882. coordinateSystem: 'singleAxis',
  61883. // gap in axis's orthogonal orientation
  61884. boundaryGap: ['10%', '10%'],
  61885. // legendHoverLink: true,
  61886. singleAxisIndex: 0,
  61887. animationEasing: 'linear',
  61888. label: {
  61889. margin: 4,
  61890. show: true,
  61891. position: 'left',
  61892. color: '#000',
  61893. fontSize: 11
  61894. },
  61895. emphasis: {
  61896. label: {
  61897. show: true
  61898. }
  61899. }
  61900. }
  61901. });
  61902. /*
  61903. * Licensed to the Apache Software Foundation (ASF) under one
  61904. * or more contributor license agreements. See the NOTICE file
  61905. * distributed with this work for additional information
  61906. * regarding copyright ownership. The ASF licenses this file
  61907. * to you under the Apache License, Version 2.0 (the
  61908. * "License"); you may not use this file except in compliance
  61909. * with the License. You may obtain a copy of the License at
  61910. *
  61911. * http://www.apache.org/licenses/LICENSE-2.0
  61912. *
  61913. * Unless required by applicable law or agreed to in writing,
  61914. * software distributed under the License is distributed on an
  61915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61916. * KIND, either express or implied. See the License for the
  61917. * specific language governing permissions and limitations
  61918. * under the License.
  61919. */
  61920. extendChartView({
  61921. type: 'themeRiver',
  61922. init: function () {
  61923. this._layers = [];
  61924. },
  61925. render: function (seriesModel, ecModel, api) {
  61926. var data = seriesModel.getData();
  61927. var group = this.group;
  61928. var layerSeries = seriesModel.getLayerSeries();
  61929. var layoutInfo = data.getLayout('layoutInfo');
  61930. var rect = layoutInfo.rect;
  61931. var boundaryGap = layoutInfo.boundaryGap;
  61932. group.attr('position', [0, rect.y + boundaryGap[0]]);
  61933. function keyGetter(item) {
  61934. return item.name;
  61935. }
  61936. var dataDiffer = new DataDiffer(
  61937. this._layersSeries || [], layerSeries,
  61938. keyGetter, keyGetter
  61939. );
  61940. var newLayersGroups = {};
  61941. dataDiffer
  61942. .add(bind(process, this, 'add'))
  61943. .update(bind(process, this, 'update'))
  61944. .remove(bind(process, this, 'remove'))
  61945. .execute();
  61946. function process(status, idx, oldIdx) {
  61947. var oldLayersGroups = this._layers;
  61948. if (status === 'remove') {
  61949. group.remove(oldLayersGroups[idx]);
  61950. return;
  61951. }
  61952. var points0 = [];
  61953. var points1 = [];
  61954. var color;
  61955. var indices = layerSeries[idx].indices;
  61956. for (var j = 0; j < indices.length; j++) {
  61957. var layout = data.getItemLayout(indices[j]);
  61958. var x = layout.x;
  61959. var y0 = layout.y0;
  61960. var y = layout.y;
  61961. points0.push([x, y0]);
  61962. points1.push([x, y0 + y]);
  61963. color = data.getItemVisual(indices[j], 'color');
  61964. }
  61965. var polygon;
  61966. var text;
  61967. var textLayout = data.getItemLayout(indices[0]);
  61968. var itemModel = data.getItemModel(indices[j - 1]);
  61969. var labelModel = itemModel.getModel('label');
  61970. var margin = labelModel.get('margin');
  61971. if (status === 'add') {
  61972. var layerGroup = newLayersGroups[idx] = new Group();
  61973. polygon = new Polygon$1({
  61974. shape: {
  61975. points: points0,
  61976. stackedOnPoints: points1,
  61977. smooth: 0.4,
  61978. stackedOnSmooth: 0.4,
  61979. smoothConstraint: false
  61980. },
  61981. z2: 0
  61982. });
  61983. text = new Text({
  61984. style: {
  61985. x: textLayout.x - margin,
  61986. y: textLayout.y0 + textLayout.y / 2
  61987. }
  61988. });
  61989. layerGroup.add(polygon);
  61990. layerGroup.add(text);
  61991. group.add(layerGroup);
  61992. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  61993. polygon.removeClipPath();
  61994. }));
  61995. }
  61996. else {
  61997. var layerGroup = oldLayersGroups[oldIdx];
  61998. polygon = layerGroup.childAt(0);
  61999. text = layerGroup.childAt(1);
  62000. group.add(layerGroup);
  62001. newLayersGroups[idx] = layerGroup;
  62002. updateProps(polygon, {
  62003. shape: {
  62004. points: points0,
  62005. stackedOnPoints: points1
  62006. }
  62007. }, seriesModel);
  62008. updateProps(text, {
  62009. style: {
  62010. x: textLayout.x - margin,
  62011. y: textLayout.y0 + textLayout.y / 2
  62012. }
  62013. }, seriesModel);
  62014. }
  62015. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  62016. var itemStyleModel = itemModel.getModel('itemStyle');
  62017. setTextStyle(text.style, labelModel, {
  62018. text: labelModel.get('show')
  62019. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  62020. || data.getName(indices[j - 1])
  62021. : null,
  62022. textVerticalAlign: 'middle'
  62023. });
  62024. polygon.setStyle(extend({
  62025. fill: color
  62026. }, itemStyleModel.getItemStyle(['color'])));
  62027. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  62028. }
  62029. this._layersSeries = layerSeries;
  62030. this._layers = newLayersGroups;
  62031. },
  62032. dispose: function () {}
  62033. });
  62034. // add animation to the view
  62035. function createGridClipShape$2(rect, seriesModel, cb) {
  62036. var rectEl = new Rect({
  62037. shape: {
  62038. x: rect.x - 10,
  62039. y: rect.y - 10,
  62040. width: 0,
  62041. height: rect.height + 20
  62042. }
  62043. });
  62044. initProps(rectEl, {
  62045. shape: {
  62046. width: rect.width + 20,
  62047. height: rect.height + 20
  62048. }
  62049. }, seriesModel, cb);
  62050. return rectEl;
  62051. }
  62052. /*
  62053. * Licensed to the Apache Software Foundation (ASF) under one
  62054. * or more contributor license agreements. See the NOTICE file
  62055. * distributed with this work for additional information
  62056. * regarding copyright ownership. The ASF licenses this file
  62057. * to you under the Apache License, Version 2.0 (the
  62058. * "License"); you may not use this file except in compliance
  62059. * with the License. You may obtain a copy of the License at
  62060. *
  62061. * http://www.apache.org/licenses/LICENSE-2.0
  62062. *
  62063. * Unless required by applicable law or agreed to in writing,
  62064. * software distributed under the License is distributed on an
  62065. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62066. * KIND, either express or implied. See the License for the
  62067. * specific language governing permissions and limitations
  62068. * under the License.
  62069. */
  62070. var themeRiverLayout = function (ecModel, api) {
  62071. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62072. var data = seriesModel.getData();
  62073. var single = seriesModel.coordinateSystem;
  62074. var layoutInfo = {};
  62075. // use the axis boundingRect for view
  62076. var rect = single.getRect();
  62077. layoutInfo.rect = rect;
  62078. var boundaryGap = seriesModel.get('boundaryGap');
  62079. var axis = single.getAxis();
  62080. layoutInfo.boundaryGap = boundaryGap;
  62081. if (axis.orient === 'horizontal') {
  62082. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62083. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62084. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62085. themeRiverLayout$1(data, seriesModel, height);
  62086. }
  62087. else {
  62088. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62089. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62090. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62091. themeRiverLayout$1(data, seriesModel, width);
  62092. }
  62093. data.setLayout('layoutInfo', layoutInfo);
  62094. });
  62095. };
  62096. /**
  62097. * The layout information about themeriver
  62098. *
  62099. * @param {module:echarts/data/List} data data in the series
  62100. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  62101. * @param {number} height value used to compute every series height
  62102. */
  62103. function themeRiverLayout$1(data, seriesModel, height) {
  62104. if (!data.count()) {
  62105. return;
  62106. }
  62107. var coordSys = seriesModel.coordinateSystem;
  62108. // the data in each layer are organized into a series.
  62109. var layerSeries = seriesModel.getLayerSeries();
  62110. // the points in each layer.
  62111. var timeDim = data.mapDimension('single');
  62112. var valueDim = data.mapDimension('value');
  62113. var layerPoints = map(layerSeries, function (singleLayer) {
  62114. return map(singleLayer.indices, function (idx) {
  62115. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62116. pt[1] = data.get(valueDim, idx);
  62117. return pt;
  62118. });
  62119. });
  62120. var base = computeBaseline(layerPoints);
  62121. var baseLine = base.y0;
  62122. var ky = height / base.max;
  62123. // set layout information for each item.
  62124. var n = layerSeries.length;
  62125. var m = layerSeries[0].indices.length;
  62126. var baseY0;
  62127. for (var j = 0; j < m; ++j) {
  62128. baseY0 = baseLine[j] * ky;
  62129. data.setItemLayout(layerSeries[0].indices[j], {
  62130. layerIndex: 0,
  62131. x: layerPoints[0][j][0],
  62132. y0: baseY0,
  62133. y: layerPoints[0][j][1] * ky
  62134. });
  62135. for (var i = 1; i < n; ++i) {
  62136. baseY0 += layerPoints[i - 1][j][1] * ky;
  62137. data.setItemLayout(layerSeries[i].indices[j], {
  62138. layerIndex: i,
  62139. x: layerPoints[i][j][0],
  62140. y0: baseY0,
  62141. y: layerPoints[i][j][1] * ky
  62142. });
  62143. }
  62144. }
  62145. }
  62146. /**
  62147. * Compute the baseLine of the rawdata
  62148. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62149. *
  62150. * @param {Array.<Array>} data the points in each layer
  62151. * @return {Object}
  62152. */
  62153. function computeBaseline(data) {
  62154. var layerNum = data.length;
  62155. var pointNum = data[0].length;
  62156. var sums = [];
  62157. var y0 = [];
  62158. var max = 0;
  62159. var temp;
  62160. var base = {};
  62161. for (var i = 0; i < pointNum; ++i) {
  62162. for (var j = 0, temp = 0; j < layerNum; ++j) {
  62163. temp += data[j][i][1];
  62164. }
  62165. if (temp > max) {
  62166. max = temp;
  62167. }
  62168. sums.push(temp);
  62169. }
  62170. for (var k = 0; k < pointNum; ++k) {
  62171. y0[k] = (max - sums[k]) / 2;
  62172. }
  62173. max = 0;
  62174. for (var l = 0; l < pointNum; ++l) {
  62175. var sum = sums[l] + y0[l];
  62176. if (sum > max) {
  62177. max = sum;
  62178. }
  62179. }
  62180. base.y0 = y0;
  62181. base.max = max;
  62182. return base;
  62183. }
  62184. /*
  62185. * Licensed to the Apache Software Foundation (ASF) under one
  62186. * or more contributor license agreements. See the NOTICE file
  62187. * distributed with this work for additional information
  62188. * regarding copyright ownership. The ASF licenses this file
  62189. * to you under the Apache License, Version 2.0 (the
  62190. * "License"); you may not use this file except in compliance
  62191. * with the License. You may obtain a copy of the License at
  62192. *
  62193. * http://www.apache.org/licenses/LICENSE-2.0
  62194. *
  62195. * Unless required by applicable law or agreed to in writing,
  62196. * software distributed under the License is distributed on an
  62197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62198. * KIND, either express or implied. See the License for the
  62199. * specific language governing permissions and limitations
  62200. * under the License.
  62201. */
  62202. var themeRiverVisual = function (ecModel) {
  62203. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62204. var data = seriesModel.getData();
  62205. var rawData = seriesModel.getRawData();
  62206. var colorList = seriesModel.get('color');
  62207. var idxMap = createHashMap();
  62208. data.each(function (idx) {
  62209. idxMap.set(data.getRawIndex(idx), idx);
  62210. });
  62211. rawData.each(function (rawIndex) {
  62212. var name = rawData.getName(rawIndex);
  62213. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  62214. rawData.setItemVisual(rawIndex, 'color', color);
  62215. var idx = idxMap.get(rawIndex);
  62216. if (idx != null) {
  62217. data.setItemVisual(idx, 'color', color);
  62218. }
  62219. });
  62220. });
  62221. };
  62222. /*
  62223. * Licensed to the Apache Software Foundation (ASF) under one
  62224. * or more contributor license agreements. See the NOTICE file
  62225. * distributed with this work for additional information
  62226. * regarding copyright ownership. The ASF licenses this file
  62227. * to you under the Apache License, Version 2.0 (the
  62228. * "License"); you may not use this file except in compliance
  62229. * with the License. You may obtain a copy of the License at
  62230. *
  62231. * http://www.apache.org/licenses/LICENSE-2.0
  62232. *
  62233. * Unless required by applicable law or agreed to in writing,
  62234. * software distributed under the License is distributed on an
  62235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62236. * KIND, either express or implied. See the License for the
  62237. * specific language governing permissions and limitations
  62238. * under the License.
  62239. */
  62240. registerLayout(themeRiverLayout);
  62241. registerVisual(themeRiverVisual);
  62242. registerProcessor(dataFilter('themeRiver'));
  62243. /*
  62244. * Licensed to the Apache Software Foundation (ASF) under one
  62245. * or more contributor license agreements. See the NOTICE file
  62246. * distributed with this work for additional information
  62247. * regarding copyright ownership. The ASF licenses this file
  62248. * to you under the Apache License, Version 2.0 (the
  62249. * "License"); you may not use this file except in compliance
  62250. * with the License. You may obtain a copy of the License at
  62251. *
  62252. * http://www.apache.org/licenses/LICENSE-2.0
  62253. *
  62254. * Unless required by applicable law or agreed to in writing,
  62255. * software distributed under the License is distributed on an
  62256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62257. * KIND, either express or implied. See the License for the
  62258. * specific language governing permissions and limitations
  62259. * under the License.
  62260. */
  62261. SeriesModel.extend({
  62262. type: 'series.sunburst',
  62263. /**
  62264. * @type {module:echarts/data/Tree~Node}
  62265. */
  62266. _viewRoot: null,
  62267. getInitialData: function (option, ecModel) {
  62268. // Create a virtual root.
  62269. var root = { name: option.name, children: option.data };
  62270. completeTreeValue$1(root);
  62271. var levels = option.levels || [];
  62272. // levels = option.levels = setDefault(levels, ecModel);
  62273. var treeOption = {};
  62274. treeOption.levels = levels;
  62275. // Make sure always a new tree is created when setOption,
  62276. // in TreemapView, we check whether oldTree === newTree
  62277. // to choose mappings approach among old shapes and new shapes.
  62278. return Tree.createTree(root, this, treeOption).data;
  62279. },
  62280. optionUpdated: function () {
  62281. this.resetViewRoot();
  62282. },
  62283. /*
  62284. * @override
  62285. */
  62286. getDataParams: function (dataIndex) {
  62287. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  62288. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  62289. params.treePathInfo = wrapTreePathInfo(node, this);
  62290. return params;
  62291. },
  62292. defaultOption: {
  62293. zlevel: 0,
  62294. z: 2,
  62295. // 默认全局居中
  62296. center: ['50%', '50%'],
  62297. radius: [0, '75%'],
  62298. // 默认顺时针
  62299. clockwise: true,
  62300. startAngle: 90,
  62301. // 最小角度改为0
  62302. minAngle: 0,
  62303. percentPrecision: 2,
  62304. // If still show when all data zero.
  62305. stillShowZeroSum: true,
  62306. // Policy of highlighting pieces when hover on one
  62307. // Valid values: 'none' (for not downplay others), 'descendant',
  62308. // 'ancestor', 'self'
  62309. highlightPolicy: 'descendant',
  62310. // 'rootToNode', 'link', or false
  62311. nodeClick: 'rootToNode',
  62312. renderLabelForZeroData: false,
  62313. label: {
  62314. // could be: 'radial', 'tangential', or 'none'
  62315. rotate: 'radial',
  62316. show: true,
  62317. opacity: 1,
  62318. // 'left' is for inner side of inside, and 'right' is for outter
  62319. // side for inside
  62320. align: 'center',
  62321. position: 'inside',
  62322. distance: 5,
  62323. silent: true,
  62324. emphasis: {}
  62325. },
  62326. itemStyle: {
  62327. borderWidth: 1,
  62328. borderColor: 'white',
  62329. borderType: 'solid',
  62330. shadowBlur: 0,
  62331. shadowColor: 'rgba(0, 0, 0, 0.2)',
  62332. shadowOffsetX: 0,
  62333. shadowOffsetY: 0,
  62334. opacity: 1,
  62335. emphasis: {},
  62336. highlight: {
  62337. opacity: 1
  62338. },
  62339. downplay: {
  62340. opacity: 0.9
  62341. }
  62342. },
  62343. // Animation type canbe expansion, scale
  62344. animationType: 'expansion',
  62345. animationDuration: 1000,
  62346. animationDurationUpdate: 500,
  62347. animationEasing: 'cubicOut',
  62348. data: [],
  62349. levels: [],
  62350. /**
  62351. * Sort order.
  62352. *
  62353. * Valid values: 'desc', 'asc', null, or callback function.
  62354. * 'desc' and 'asc' for descend and ascendant order;
  62355. * null for not sorting;
  62356. * example of callback function:
  62357. * function(nodeA, nodeB) {
  62358. * return nodeA.getValue() - nodeB.getValue();
  62359. * }
  62360. */
  62361. sort: 'desc'
  62362. },
  62363. getViewRoot: function () {
  62364. return this._viewRoot;
  62365. },
  62366. /**
  62367. * @param {module:echarts/data/Tree~Node} [viewRoot]
  62368. */
  62369. resetViewRoot: function (viewRoot) {
  62370. viewRoot
  62371. ? (this._viewRoot = viewRoot)
  62372. : (viewRoot = this._viewRoot);
  62373. var root = this.getRawData().tree.root;
  62374. if (!viewRoot
  62375. || (viewRoot !== root && !root.contains(viewRoot))
  62376. ) {
  62377. this._viewRoot = root;
  62378. }
  62379. }
  62380. });
  62381. /**
  62382. * @param {Object} dataNode
  62383. */
  62384. function completeTreeValue$1(dataNode) {
  62385. // Postorder travel tree.
  62386. // If value of none-leaf node is not set,
  62387. // calculate it by suming up the value of all children.
  62388. var sum = 0;
  62389. each$1(dataNode.children, function (child) {
  62390. completeTreeValue$1(child);
  62391. var childValue = child.value;
  62392. isArray(childValue) && (childValue = childValue[0]);
  62393. sum += childValue;
  62394. });
  62395. var thisValue = dataNode.value;
  62396. if (isArray(thisValue)) {
  62397. thisValue = thisValue[0];
  62398. }
  62399. if (thisValue == null || isNaN(thisValue)) {
  62400. thisValue = sum;
  62401. }
  62402. // Value should not less than 0.
  62403. if (thisValue < 0) {
  62404. thisValue = 0;
  62405. }
  62406. isArray(dataNode.value)
  62407. ? (dataNode.value[0] = thisValue)
  62408. : (dataNode.value = thisValue);
  62409. }
  62410. /*
  62411. * Licensed to the Apache Software Foundation (ASF) under one
  62412. * or more contributor license agreements. See the NOTICE file
  62413. * distributed with this work for additional information
  62414. * regarding copyright ownership. The ASF licenses this file
  62415. * to you under the Apache License, Version 2.0 (the
  62416. * "License"); you may not use this file except in compliance
  62417. * with the License. You may obtain a copy of the License at
  62418. *
  62419. * http://www.apache.org/licenses/LICENSE-2.0
  62420. *
  62421. * Unless required by applicable law or agreed to in writing,
  62422. * software distributed under the License is distributed on an
  62423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62424. * KIND, either express or implied. See the License for the
  62425. * specific language governing permissions and limitations
  62426. * under the License.
  62427. */
  62428. var NodeHighlightPolicy = {
  62429. NONE: 'none', // not downplay others
  62430. DESCENDANT: 'descendant',
  62431. ANCESTOR: 'ancestor',
  62432. SELF: 'self'
  62433. };
  62434. var DEFAULT_SECTOR_Z = 2;
  62435. var DEFAULT_TEXT_Z = 4;
  62436. /**
  62437. * Sunburstce of Sunburst including Sector, Label, LabelLine
  62438. * @constructor
  62439. * @extends {module:zrender/graphic/Group}
  62440. */
  62441. function SunburstPiece(node, seriesModel, ecModel) {
  62442. Group.call(this);
  62443. var sector = new Sector({
  62444. z2: DEFAULT_SECTOR_Z
  62445. });
  62446. sector.seriesIndex = seriesModel.seriesIndex;
  62447. var text = new Text({
  62448. z2: DEFAULT_TEXT_Z,
  62449. silent: node.getModel('label').get('silent')
  62450. });
  62451. this.add(sector);
  62452. this.add(text);
  62453. this.updateData(true, node, 'normal', seriesModel, ecModel);
  62454. // Hover to change label and labelLine
  62455. function onEmphasis() {
  62456. text.ignore = text.hoverIgnore;
  62457. }
  62458. function onNormal() {
  62459. text.ignore = text.normalIgnore;
  62460. }
  62461. this.on('emphasis', onEmphasis)
  62462. .on('normal', onNormal)
  62463. .on('mouseover', onEmphasis)
  62464. .on('mouseout', onNormal);
  62465. }
  62466. var SunburstPieceProto = SunburstPiece.prototype;
  62467. SunburstPieceProto.updateData = function (
  62468. firstCreate,
  62469. node,
  62470. state,
  62471. seriesModel,
  62472. ecModel
  62473. ) {
  62474. this.node = node;
  62475. node.piece = this;
  62476. seriesModel = seriesModel || this._seriesModel;
  62477. ecModel = ecModel || this._ecModel;
  62478. var sector = this.childAt(0);
  62479. sector.dataIndex = node.dataIndex;
  62480. var itemModel = node.getModel();
  62481. var layout = node.getLayout();
  62482. // if (!layout) {
  62483. // console.log(node.getLayout());
  62484. // }
  62485. var sectorShape = extend({}, layout);
  62486. sectorShape.label = null;
  62487. var visualColor = getNodeColor(node, seriesModel, ecModel);
  62488. fillDefaultColor(node, seriesModel, visualColor);
  62489. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  62490. var style;
  62491. if (state === 'normal') {
  62492. style = normalStyle;
  62493. }
  62494. else {
  62495. var stateStyle = itemModel.getModel(state + '.itemStyle')
  62496. .getItemStyle();
  62497. style = merge(stateStyle, normalStyle);
  62498. }
  62499. style = defaults(
  62500. {
  62501. lineJoin: 'bevel',
  62502. fill: style.fill || visualColor
  62503. },
  62504. style
  62505. );
  62506. if (firstCreate) {
  62507. sector.setShape(sectorShape);
  62508. sector.shape.r = layout.r0;
  62509. updateProps(
  62510. sector,
  62511. {
  62512. shape: {
  62513. r: layout.r
  62514. }
  62515. },
  62516. seriesModel,
  62517. node.dataIndex
  62518. );
  62519. sector.useStyle(style);
  62520. }
  62521. else if (typeof style.fill === 'object' && style.fill.type
  62522. || typeof sector.style.fill === 'object' && sector.style.fill.type
  62523. ) {
  62524. // Disable animation for gradient since no interpolation method
  62525. // is supported for gradient
  62526. updateProps(sector, {
  62527. shape: sectorShape
  62528. }, seriesModel);
  62529. sector.useStyle(style);
  62530. }
  62531. else {
  62532. updateProps(sector, {
  62533. shape: sectorShape,
  62534. style: style
  62535. }, seriesModel);
  62536. }
  62537. this._updateLabel(seriesModel, visualColor, state);
  62538. var cursorStyle = itemModel.getShallow('cursor');
  62539. cursorStyle && sector.attr('cursor', cursorStyle);
  62540. if (firstCreate) {
  62541. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  62542. this._initEvents(sector, node, seriesModel, highlightPolicy);
  62543. }
  62544. this._seriesModel = seriesModel || this._seriesModel;
  62545. this._ecModel = ecModel || this._ecModel;
  62546. };
  62547. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  62548. var that = this;
  62549. this.node.hostTree.root.eachNode(function (n) {
  62550. if (n.piece) {
  62551. if (that.node === n) {
  62552. n.piece.updateData(false, n, 'emphasis');
  62553. }
  62554. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  62555. n.piece.childAt(0).trigger('highlight');
  62556. }
  62557. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  62558. n.piece.childAt(0).trigger('downplay');
  62559. }
  62560. }
  62561. });
  62562. };
  62563. SunburstPieceProto.onNormal = function () {
  62564. this.node.hostTree.root.eachNode(function (n) {
  62565. if (n.piece) {
  62566. n.piece.updateData(false, n, 'normal');
  62567. }
  62568. });
  62569. };
  62570. SunburstPieceProto.onHighlight = function () {
  62571. this.updateData(false, this.node, 'highlight');
  62572. };
  62573. SunburstPieceProto.onDownplay = function () {
  62574. this.updateData(false, this.node, 'downplay');
  62575. };
  62576. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  62577. var itemModel = this.node.getModel();
  62578. var normalModel = itemModel.getModel('label');
  62579. var labelModel = state === 'normal' || state === 'emphasis'
  62580. ? normalModel
  62581. : itemModel.getModel(state + '.label');
  62582. var labelHoverModel = itemModel.getModel('emphasis.label');
  62583. var text = retrieve(
  62584. seriesModel.getFormattedLabel(
  62585. this.node.dataIndex, state, null, null, 'label'
  62586. ),
  62587. this.node.name
  62588. );
  62589. if (getLabelAttr('show') === false) {
  62590. text = '';
  62591. }
  62592. var layout = this.node.getLayout();
  62593. var labelMinAngle = labelModel.get('minAngle');
  62594. if (labelMinAngle == null) {
  62595. labelMinAngle = normalModel.get('minAngle');
  62596. }
  62597. labelMinAngle = labelMinAngle / 180 * Math.PI;
  62598. var angle = layout.endAngle - layout.startAngle;
  62599. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  62600. // Not displaying text when angle is too small
  62601. text = '';
  62602. }
  62603. var label = this.childAt(1);
  62604. setLabelStyle(
  62605. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  62606. {
  62607. defaultText: labelModel.getShallow('show') ? text : null,
  62608. autoColor: visualColor,
  62609. useInsideStyle: true
  62610. }
  62611. );
  62612. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  62613. var dx = Math.cos(midAngle);
  62614. var dy = Math.sin(midAngle);
  62615. var r;
  62616. var labelPosition = getLabelAttr('position');
  62617. var labelPadding = getLabelAttr('distance') || 0;
  62618. var textAlign = getLabelAttr('align');
  62619. if (labelPosition === 'outside') {
  62620. r = layout.r + labelPadding;
  62621. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  62622. }
  62623. else {
  62624. if (!textAlign || textAlign === 'center') {
  62625. r = (layout.r + layout.r0) / 2;
  62626. textAlign = 'center';
  62627. }
  62628. else if (textAlign === 'left') {
  62629. r = layout.r0 + labelPadding;
  62630. if (midAngle > Math.PI / 2) {
  62631. textAlign = 'right';
  62632. }
  62633. }
  62634. else if (textAlign === 'right') {
  62635. r = layout.r - labelPadding;
  62636. if (midAngle > Math.PI / 2) {
  62637. textAlign = 'left';
  62638. }
  62639. }
  62640. }
  62641. label.attr('style', {
  62642. text: text,
  62643. textAlign: textAlign,
  62644. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  62645. opacity: getLabelAttr('opacity')
  62646. });
  62647. var textX = r * dx + layout.cx;
  62648. var textY = r * dy + layout.cy;
  62649. label.attr('position', [textX, textY]);
  62650. var rotateType = getLabelAttr('rotate');
  62651. var rotate = 0;
  62652. if (rotateType === 'radial') {
  62653. rotate = -midAngle;
  62654. if (rotate < -Math.PI / 2) {
  62655. rotate += Math.PI;
  62656. }
  62657. }
  62658. else if (rotateType === 'tangential') {
  62659. rotate = Math.PI / 2 - midAngle;
  62660. if (rotate > Math.PI / 2) {
  62661. rotate -= Math.PI;
  62662. }
  62663. else if (rotate < -Math.PI / 2) {
  62664. rotate += Math.PI;
  62665. }
  62666. }
  62667. else if (typeof rotateType === 'number') {
  62668. rotate = rotateType * Math.PI / 180;
  62669. }
  62670. label.attr('rotation', rotate);
  62671. function getLabelAttr(name) {
  62672. var stateAttr = labelModel.get(name);
  62673. if (stateAttr == null) {
  62674. return normalModel.get(name);
  62675. }
  62676. else {
  62677. return stateAttr;
  62678. }
  62679. }
  62680. };
  62681. SunburstPieceProto._initEvents = function (
  62682. sector,
  62683. node,
  62684. seriesModel,
  62685. highlightPolicy
  62686. ) {
  62687. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  62688. var that = this;
  62689. var onEmphasis = function () {
  62690. that.onEmphasis(highlightPolicy);
  62691. };
  62692. var onNormal = function () {
  62693. that.onNormal();
  62694. };
  62695. var onDownplay = function () {
  62696. that.onDownplay();
  62697. };
  62698. var onHighlight = function () {
  62699. that.onHighlight();
  62700. };
  62701. if (seriesModel.isAnimationEnabled()) {
  62702. sector
  62703. .on('mouseover', onEmphasis)
  62704. .on('mouseout', onNormal)
  62705. .on('emphasis', onEmphasis)
  62706. .on('normal', onNormal)
  62707. .on('downplay', onDownplay)
  62708. .on('highlight', onHighlight);
  62709. }
  62710. };
  62711. inherits(SunburstPiece, Group);
  62712. /**
  62713. * Get node color
  62714. *
  62715. * @param {TreeNode} node the node to get color
  62716. * @param {module:echarts/model/Series} seriesModel series
  62717. * @param {module:echarts/model/Global} ecModel echarts defaults
  62718. */
  62719. function getNodeColor(node, seriesModel, ecModel) {
  62720. // Color from visualMap
  62721. var visualColor = node.getVisual('color');
  62722. var visualMetaList = node.getVisual('visualMeta');
  62723. if (!visualMetaList || visualMetaList.length === 0) {
  62724. // Use first-generation color if has no visualMap
  62725. visualColor = null;
  62726. }
  62727. // Self color or level color
  62728. var color = node.getModel('itemStyle').get('color');
  62729. if (color) {
  62730. return color;
  62731. }
  62732. else if (visualColor) {
  62733. // Color mapping
  62734. return visualColor;
  62735. }
  62736. else if (node.depth === 0) {
  62737. // Virtual root node
  62738. return ecModel.option.color[0];
  62739. }
  62740. else {
  62741. // First-generation color
  62742. var length = ecModel.option.color.length;
  62743. color = ecModel.option.color[getRootId(node) % length];
  62744. }
  62745. return color;
  62746. }
  62747. /**
  62748. * Get index of root in sorted order
  62749. *
  62750. * @param {TreeNode} node current node
  62751. * @return {number} index in root
  62752. */
  62753. function getRootId(node) {
  62754. var ancestor = node;
  62755. while (ancestor.depth > 1) {
  62756. ancestor = ancestor.parentNode;
  62757. }
  62758. var virtualRoot = node.getAncestors()[0];
  62759. return indexOf(virtualRoot.children, ancestor);
  62760. }
  62761. function isNodeHighlighted(node, activeNode, policy) {
  62762. if (policy === NodeHighlightPolicy.NONE) {
  62763. return false;
  62764. }
  62765. else if (policy === NodeHighlightPolicy.SELF) {
  62766. return node === activeNode;
  62767. }
  62768. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  62769. return node === activeNode || node.isAncestorOf(activeNode);
  62770. }
  62771. else {
  62772. return node === activeNode || node.isDescendantOf(activeNode);
  62773. }
  62774. }
  62775. // Fix tooltip callback function params.color incorrect when pick a default color
  62776. function fillDefaultColor(node, seriesModel, color) {
  62777. var data = seriesModel.getData();
  62778. data.setItemVisual(node.dataIndex, 'color', color);
  62779. }
  62780. /*
  62781. * Licensed to the Apache Software Foundation (ASF) under one
  62782. * or more contributor license agreements. See the NOTICE file
  62783. * distributed with this work for additional information
  62784. * regarding copyright ownership. The ASF licenses this file
  62785. * to you under the Apache License, Version 2.0 (the
  62786. * "License"); you may not use this file except in compliance
  62787. * with the License. You may obtain a copy of the License at
  62788. *
  62789. * http://www.apache.org/licenses/LICENSE-2.0
  62790. *
  62791. * Unless required by applicable law or agreed to in writing,
  62792. * software distributed under the License is distributed on an
  62793. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62794. * KIND, either express or implied. See the License for the
  62795. * specific language governing permissions and limitations
  62796. * under the License.
  62797. */
  62798. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  62799. var SunburstView = Chart.extend({
  62800. type: 'sunburst',
  62801. init: function () {
  62802. },
  62803. render: function (seriesModel, ecModel, api, payload) {
  62804. var that = this;
  62805. this.seriesModel = seriesModel;
  62806. this.api = api;
  62807. this.ecModel = ecModel;
  62808. var data = seriesModel.getData();
  62809. var virtualRoot = data.tree.root;
  62810. var newRoot = seriesModel.getViewRoot();
  62811. var group = this.group;
  62812. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  62813. var newChildren = [];
  62814. newRoot.eachNode(function (node) {
  62815. newChildren.push(node);
  62816. });
  62817. var oldChildren = this._oldChildren || [];
  62818. dualTravel(newChildren, oldChildren);
  62819. renderRollUp(virtualRoot, newRoot);
  62820. if (payload && payload.highlight && payload.highlight.piece) {
  62821. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  62822. payload.highlight.piece.onEmphasis(highlightPolicy);
  62823. }
  62824. else if (payload && payload.unhighlight) {
  62825. var piece = this.virtualPiece;
  62826. if (!piece && virtualRoot.children.length) {
  62827. piece = virtualRoot.children[0].piece;
  62828. }
  62829. if (piece) {
  62830. piece.onNormal();
  62831. }
  62832. }
  62833. this._initEvents();
  62834. this._oldChildren = newChildren;
  62835. function dualTravel(newChildren, oldChildren) {
  62836. if (newChildren.length === 0 && oldChildren.length === 0) {
  62837. return;
  62838. }
  62839. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  62840. .add(processNode)
  62841. .update(processNode)
  62842. .remove(curry(processNode, null))
  62843. .execute();
  62844. function getKey(node) {
  62845. return node.getId();
  62846. }
  62847. function processNode(newId, oldId) {
  62848. var newNode = newId == null ? null : newChildren[newId];
  62849. var oldNode = oldId == null ? null : oldChildren[oldId];
  62850. doRenderNode(newNode, oldNode);
  62851. }
  62852. }
  62853. function doRenderNode(newNode, oldNode) {
  62854. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  62855. // Not render data with value 0
  62856. newNode = null;
  62857. }
  62858. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  62859. if (oldNode && oldNode.piece) {
  62860. if (newNode) {
  62861. // Update
  62862. oldNode.piece.updateData(
  62863. false, newNode, 'normal', seriesModel, ecModel);
  62864. // For tooltip
  62865. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  62866. }
  62867. else {
  62868. // Remove
  62869. removeNode(oldNode);
  62870. }
  62871. }
  62872. else if (newNode) {
  62873. // Add
  62874. var piece = new SunburstPiece(
  62875. newNode,
  62876. seriesModel,
  62877. ecModel
  62878. );
  62879. group.add(piece);
  62880. // For tooltip
  62881. data.setItemGraphicEl(newNode.dataIndex, piece);
  62882. }
  62883. }
  62884. }
  62885. function removeNode(node) {
  62886. if (!node) {
  62887. return;
  62888. }
  62889. if (node.piece) {
  62890. group.remove(node.piece);
  62891. node.piece = null;
  62892. }
  62893. }
  62894. function renderRollUp(virtualRoot, viewRoot) {
  62895. if (viewRoot.depth > 0) {
  62896. // Render
  62897. if (that.virtualPiece) {
  62898. // Update
  62899. that.virtualPiece.updateData(
  62900. false, virtualRoot, 'normal', seriesModel, ecModel);
  62901. }
  62902. else {
  62903. // Add
  62904. that.virtualPiece = new SunburstPiece(
  62905. virtualRoot,
  62906. seriesModel,
  62907. ecModel
  62908. );
  62909. group.add(that.virtualPiece);
  62910. }
  62911. if (viewRoot.piece._onclickEvent) {
  62912. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  62913. }
  62914. var event = function (e) {
  62915. that._rootToNode(viewRoot.parentNode);
  62916. };
  62917. viewRoot.piece._onclickEvent = event;
  62918. that.virtualPiece.on('click', event);
  62919. }
  62920. else if (that.virtualPiece) {
  62921. // Remove
  62922. group.remove(that.virtualPiece);
  62923. that.virtualPiece = null;
  62924. }
  62925. }
  62926. },
  62927. dispose: function () {
  62928. },
  62929. /**
  62930. * @private
  62931. */
  62932. _initEvents: function () {
  62933. var that = this;
  62934. var event = function (e) {
  62935. var targetFound = false;
  62936. var viewRoot = that.seriesModel.getViewRoot();
  62937. viewRoot.eachNode(function (node) {
  62938. if (!targetFound
  62939. && node.piece && node.piece.childAt(0) === e.target
  62940. ) {
  62941. var nodeClick = node.getModel().get('nodeClick');
  62942. if (nodeClick === 'rootToNode') {
  62943. that._rootToNode(node);
  62944. }
  62945. else if (nodeClick === 'link') {
  62946. var itemModel = node.getModel();
  62947. var link = itemModel.get('link');
  62948. if (link) {
  62949. var linkTarget = itemModel.get('target', true)
  62950. || '_blank';
  62951. window.open(link, linkTarget);
  62952. }
  62953. }
  62954. targetFound = true;
  62955. }
  62956. });
  62957. };
  62958. if (this.group._onclickEvent) {
  62959. this.group.off('click', this.group._onclickEvent);
  62960. }
  62961. this.group.on('click', event);
  62962. this.group._onclickEvent = event;
  62963. },
  62964. /**
  62965. * @private
  62966. */
  62967. _rootToNode: function (node) {
  62968. if (node !== this.seriesModel.getViewRoot()) {
  62969. this.api.dispatchAction({
  62970. type: ROOT_TO_NODE_ACTION,
  62971. from: this.uid,
  62972. seriesId: this.seriesModel.id,
  62973. targetNode: node
  62974. });
  62975. }
  62976. },
  62977. /**
  62978. * @implement
  62979. */
  62980. containPoint: function (point, seriesModel) {
  62981. var treeRoot = seriesModel.getData();
  62982. var itemLayout = treeRoot.getItemLayout(0);
  62983. if (itemLayout) {
  62984. var dx = point[0] - itemLayout.cx;
  62985. var dy = point[1] - itemLayout.cy;
  62986. var radius = Math.sqrt(dx * dx + dy * dy);
  62987. return radius <= itemLayout.r && radius >= itemLayout.r0;
  62988. }
  62989. }
  62990. });
  62991. /*
  62992. * Licensed to the Apache Software Foundation (ASF) under one
  62993. * or more contributor license agreements. See the NOTICE file
  62994. * distributed with this work for additional information
  62995. * regarding copyright ownership. The ASF licenses this file
  62996. * to you under the Apache License, Version 2.0 (the
  62997. * "License"); you may not use this file except in compliance
  62998. * with the License. You may obtain a copy of the License at
  62999. *
  63000. * http://www.apache.org/licenses/LICENSE-2.0
  63001. *
  63002. * Unless required by applicable law or agreed to in writing,
  63003. * software distributed under the License is distributed on an
  63004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63005. * KIND, either express or implied. See the License for the
  63006. * specific language governing permissions and limitations
  63007. * under the License.
  63008. */
  63009. /**
  63010. * @file Sunburst action
  63011. */
  63012. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  63013. registerAction(
  63014. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  63015. function (payload, ecModel) {
  63016. ecModel.eachComponent(
  63017. {mainType: 'series', subType: 'sunburst', query: payload},
  63018. handleRootToNode
  63019. );
  63020. function handleRootToNode(model, index) {
  63021. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  63022. if (targetInfo) {
  63023. var originViewRoot = model.getViewRoot();
  63024. if (originViewRoot) {
  63025. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  63026. ? 'rollUp' : 'drillDown';
  63027. }
  63028. model.resetViewRoot(targetInfo.node);
  63029. }
  63030. }
  63031. }
  63032. );
  63033. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  63034. registerAction(
  63035. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  63036. function (payload, ecModel) {
  63037. ecModel.eachComponent(
  63038. {mainType: 'series', subType: 'sunburst', query: payload},
  63039. handleHighlight
  63040. );
  63041. function handleHighlight(model, index) {
  63042. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  63043. if (targetInfo) {
  63044. payload.highlight = targetInfo.node;
  63045. }
  63046. }
  63047. }
  63048. );
  63049. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  63050. registerAction(
  63051. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  63052. function (payload, ecModel) {
  63053. ecModel.eachComponent(
  63054. {mainType: 'series', subType: 'sunburst', query: payload},
  63055. handleUnhighlight
  63056. );
  63057. function handleUnhighlight(model, index) {
  63058. payload.unhighlight = true;
  63059. }
  63060. }
  63061. );
  63062. /*
  63063. * Licensed to the Apache Software Foundation (ASF) under one
  63064. * or more contributor license agreements. See the NOTICE file
  63065. * distributed with this work for additional information
  63066. * regarding copyright ownership. The ASF licenses this file
  63067. * to you under the Apache License, Version 2.0 (the
  63068. * "License"); you may not use this file except in compliance
  63069. * with the License. You may obtain a copy of the License at
  63070. *
  63071. * http://www.apache.org/licenses/LICENSE-2.0
  63072. *
  63073. * Unless required by applicable law or agreed to in writing,
  63074. * software distributed under the License is distributed on an
  63075. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63076. * KIND, either express or implied. See the License for the
  63077. * specific language governing permissions and limitations
  63078. * under the License.
  63079. */
  63080. // var PI2 = Math.PI * 2;
  63081. var RADIAN$2 = Math.PI / 180;
  63082. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  63083. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  63084. var center = seriesModel.get('center');
  63085. var radius = seriesModel.get('radius');
  63086. if (!isArray(radius)) {
  63087. radius = [0, radius];
  63088. }
  63089. if (!isArray(center)) {
  63090. center = [center, center];
  63091. }
  63092. var width = api.getWidth();
  63093. var height = api.getHeight();
  63094. var size = Math.min(width, height);
  63095. var cx = parsePercent$1(center[0], width);
  63096. var cy = parsePercent$1(center[1], height);
  63097. var r0 = parsePercent$1(radius[0], size / 2);
  63098. var r = parsePercent$1(radius[1], size / 2);
  63099. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  63100. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  63101. var virtualRoot = seriesModel.getData().tree.root;
  63102. var treeRoot = seriesModel.getViewRoot();
  63103. var rootDepth = treeRoot.depth;
  63104. var sort = seriesModel.get('sort');
  63105. if (sort != null) {
  63106. initChildren$1(treeRoot, sort);
  63107. }
  63108. var validDataCount = 0;
  63109. each$1(treeRoot.children, function (child) {
  63110. !isNaN(child.getValue()) && validDataCount++;
  63111. });
  63112. var sum = treeRoot.getValue();
  63113. // Sum may be 0
  63114. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  63115. var renderRollupNode = treeRoot.depth > 0;
  63116. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  63117. var rPerLevel = (r - r0) / (levels || 1);
  63118. var clockwise = seriesModel.get('clockwise');
  63119. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  63120. // In the case some sector angle is smaller than minAngle
  63121. // var restAngle = PI2;
  63122. // var valueSumLargerThanMinAngle = 0;
  63123. var dir = clockwise ? 1 : -1;
  63124. /**
  63125. * Render a tree
  63126. * @return increased angle
  63127. */
  63128. var renderNode = function (node, startAngle) {
  63129. if (!node) {
  63130. return;
  63131. }
  63132. var endAngle = startAngle;
  63133. // Render self
  63134. if (node !== virtualRoot) {
  63135. // Tree node is virtual, so it doesn't need to be drawn
  63136. var value = node.getValue();
  63137. var angle = (sum === 0 && stillShowZeroSum)
  63138. ? unitRadian : (value * unitRadian);
  63139. if (angle < minAngle) {
  63140. angle = minAngle;
  63141. // restAngle -= minAngle;
  63142. }
  63143. // else {
  63144. // valueSumLargerThanMinAngle += value;
  63145. // }
  63146. endAngle = startAngle + dir * angle;
  63147. var depth = node.depth - rootDepth
  63148. - (renderRollupNode ? -1 : 1);
  63149. var rStart = r0 + rPerLevel * depth;
  63150. var rEnd = r0 + rPerLevel * (depth + 1);
  63151. var itemModel = node.getModel();
  63152. if (itemModel.get('r0') != null) {
  63153. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  63154. }
  63155. if (itemModel.get('r') != null) {
  63156. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  63157. }
  63158. node.setLayout({
  63159. angle: angle,
  63160. startAngle: startAngle,
  63161. endAngle: endAngle,
  63162. clockwise: clockwise,
  63163. cx: cx,
  63164. cy: cy,
  63165. r0: rStart,
  63166. r: rEnd
  63167. });
  63168. }
  63169. // Render children
  63170. if (node.children && node.children.length) {
  63171. // currentAngle = startAngle;
  63172. var siblingAngle = 0;
  63173. each$1(node.children, function (node) {
  63174. siblingAngle += renderNode(node, startAngle + siblingAngle);
  63175. });
  63176. }
  63177. return endAngle - startAngle;
  63178. };
  63179. // Virtual root node for roll up
  63180. if (renderRollupNode) {
  63181. var rStart = r0;
  63182. var rEnd = r0 + rPerLevel;
  63183. var angle = Math.PI * 2;
  63184. virtualRoot.setLayout({
  63185. angle: angle,
  63186. startAngle: startAngle,
  63187. endAngle: startAngle + angle,
  63188. clockwise: clockwise,
  63189. cx: cx,
  63190. cy: cy,
  63191. r0: rStart,
  63192. r: rEnd
  63193. });
  63194. }
  63195. renderNode(treeRoot, startAngle);
  63196. });
  63197. };
  63198. /**
  63199. * Init node children by order and update visual
  63200. *
  63201. * @param {TreeNode} node root node
  63202. * @param {boolean} isAsc if is in ascendant order
  63203. */
  63204. function initChildren$1(node, isAsc) {
  63205. var children = node.children || [];
  63206. node.children = sort$2(children, isAsc);
  63207. // Init children recursively
  63208. if (children.length) {
  63209. each$1(node.children, function (child) {
  63210. initChildren$1(child, isAsc);
  63211. });
  63212. }
  63213. }
  63214. /**
  63215. * Sort children nodes
  63216. *
  63217. * @param {TreeNode[]} children children of node to be sorted
  63218. * @param {string | function | null} sort sort method
  63219. * See SunburstSeries.js for details.
  63220. */
  63221. function sort$2(children, sortOrder) {
  63222. if (typeof sortOrder === 'function') {
  63223. return children.sort(sortOrder);
  63224. }
  63225. else {
  63226. var isAsc = sortOrder === 'asc';
  63227. return children.sort(function (a, b) {
  63228. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  63229. return diff === 0
  63230. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  63231. : diff;
  63232. });
  63233. }
  63234. }
  63235. /*
  63236. * Licensed to the Apache Software Foundation (ASF) under one
  63237. * or more contributor license agreements. See the NOTICE file
  63238. * distributed with this work for additional information
  63239. * regarding copyright ownership. The ASF licenses this file
  63240. * to you under the Apache License, Version 2.0 (the
  63241. * "License"); you may not use this file except in compliance
  63242. * with the License. You may obtain a copy of the License at
  63243. *
  63244. * http://www.apache.org/licenses/LICENSE-2.0
  63245. *
  63246. * Unless required by applicable law or agreed to in writing,
  63247. * software distributed under the License is distributed on an
  63248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63249. * KIND, either express or implied. See the License for the
  63250. * specific language governing permissions and limitations
  63251. * under the License.
  63252. */
  63253. registerVisual(curry(dataColor, 'sunburst'));
  63254. registerLayout(curry(sunburstLayout, 'sunburst'));
  63255. registerProcessor(curry(dataFilter, 'sunburst'));
  63256. /*
  63257. * Licensed to the Apache Software Foundation (ASF) under one
  63258. * or more contributor license agreements. See the NOTICE file
  63259. * distributed with this work for additional information
  63260. * regarding copyright ownership. The ASF licenses this file
  63261. * to you under the Apache License, Version 2.0 (the
  63262. * "License"); you may not use this file except in compliance
  63263. * with the License. You may obtain a copy of the License at
  63264. *
  63265. * http://www.apache.org/licenses/LICENSE-2.0
  63266. *
  63267. * Unless required by applicable law or agreed to in writing,
  63268. * software distributed under the License is distributed on an
  63269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63270. * KIND, either express or implied. See the License for the
  63271. * specific language governing permissions and limitations
  63272. * under the License.
  63273. */
  63274. function dataToCoordSize(dataSize, dataItem) {
  63275. // dataItem is necessary in log axis.
  63276. dataItem = dataItem || [0, 0];
  63277. return map(['x', 'y'], function (dim, dimIdx) {
  63278. var axis = this.getAxis(dim);
  63279. var val = dataItem[dimIdx];
  63280. var halfSize = dataSize[dimIdx] / 2;
  63281. return axis.type === 'category'
  63282. ? axis.getBandWidth()
  63283. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63284. }, this);
  63285. }
  63286. var prepareCartesian2d = function (coordSys) {
  63287. var rect = coordSys.grid.getRect();
  63288. return {
  63289. coordSys: {
  63290. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  63291. type: 'cartesian2d',
  63292. x: rect.x,
  63293. y: rect.y,
  63294. width: rect.width,
  63295. height: rect.height
  63296. },
  63297. api: {
  63298. coord: function (data) {
  63299. // do not provide "out" param
  63300. return coordSys.dataToPoint(data);
  63301. },
  63302. size: bind(dataToCoordSize, coordSys)
  63303. }
  63304. };
  63305. };
  63306. /*
  63307. * Licensed to the Apache Software Foundation (ASF) under one
  63308. * or more contributor license agreements. See the NOTICE file
  63309. * distributed with this work for additional information
  63310. * regarding copyright ownership. The ASF licenses this file
  63311. * to you under the Apache License, Version 2.0 (the
  63312. * "License"); you may not use this file except in compliance
  63313. * with the License. You may obtain a copy of the License at
  63314. *
  63315. * http://www.apache.org/licenses/LICENSE-2.0
  63316. *
  63317. * Unless required by applicable law or agreed to in writing,
  63318. * software distributed under the License is distributed on an
  63319. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63320. * KIND, either express or implied. See the License for the
  63321. * specific language governing permissions and limitations
  63322. * under the License.
  63323. */
  63324. function dataToCoordSize$1(dataSize, dataItem) {
  63325. dataItem = dataItem || [0, 0];
  63326. return map([0, 1], function (dimIdx) {
  63327. var val = dataItem[dimIdx];
  63328. var halfSize = dataSize[dimIdx] / 2;
  63329. var p1 = [];
  63330. var p2 = [];
  63331. p1[dimIdx] = val - halfSize;
  63332. p2[dimIdx] = val + halfSize;
  63333. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  63334. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  63335. }, this);
  63336. }
  63337. var prepareGeo = function (coordSys) {
  63338. var rect = coordSys.getBoundingRect();
  63339. return {
  63340. coordSys: {
  63341. type: 'geo',
  63342. x: rect.x,
  63343. y: rect.y,
  63344. width: rect.width,
  63345. height: rect.height,
  63346. zoom: coordSys.getZoom()
  63347. },
  63348. api: {
  63349. coord: function (data) {
  63350. // do not provide "out" and noRoam param,
  63351. // Compatible with this usage:
  63352. // echarts.util.map(item.points, api.coord)
  63353. return coordSys.dataToPoint(data);
  63354. },
  63355. size: bind(dataToCoordSize$1, coordSys)
  63356. }
  63357. };
  63358. };
  63359. /*
  63360. * Licensed to the Apache Software Foundation (ASF) under one
  63361. * or more contributor license agreements. See the NOTICE file
  63362. * distributed with this work for additional information
  63363. * regarding copyright ownership. The ASF licenses this file
  63364. * to you under the Apache License, Version 2.0 (the
  63365. * "License"); you may not use this file except in compliance
  63366. * with the License. You may obtain a copy of the License at
  63367. *
  63368. * http://www.apache.org/licenses/LICENSE-2.0
  63369. *
  63370. * Unless required by applicable law or agreed to in writing,
  63371. * software distributed under the License is distributed on an
  63372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63373. * KIND, either express or implied. See the License for the
  63374. * specific language governing permissions and limitations
  63375. * under the License.
  63376. */
  63377. function dataToCoordSize$2(dataSize, dataItem) {
  63378. // dataItem is necessary in log axis.
  63379. var axis = this.getAxis();
  63380. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  63381. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  63382. return axis.type === 'category'
  63383. ? axis.getBandWidth()
  63384. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63385. }
  63386. var prepareSingleAxis = function (coordSys) {
  63387. var rect = coordSys.getRect();
  63388. return {
  63389. coordSys: {
  63390. type: 'singleAxis',
  63391. x: rect.x,
  63392. y: rect.y,
  63393. width: rect.width,
  63394. height: rect.height
  63395. },
  63396. api: {
  63397. coord: function (val) {
  63398. // do not provide "out" param
  63399. return coordSys.dataToPoint(val);
  63400. },
  63401. size: bind(dataToCoordSize$2, coordSys)
  63402. }
  63403. };
  63404. };
  63405. /*
  63406. * Licensed to the Apache Software Foundation (ASF) under one
  63407. * or more contributor license agreements. See the NOTICE file
  63408. * distributed with this work for additional information
  63409. * regarding copyright ownership. The ASF licenses this file
  63410. * to you under the Apache License, Version 2.0 (the
  63411. * "License"); you may not use this file except in compliance
  63412. * with the License. You may obtain a copy of the License at
  63413. *
  63414. * http://www.apache.org/licenses/LICENSE-2.0
  63415. *
  63416. * Unless required by applicable law or agreed to in writing,
  63417. * software distributed under the License is distributed on an
  63418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63419. * KIND, either express or implied. See the License for the
  63420. * specific language governing permissions and limitations
  63421. * under the License.
  63422. */
  63423. function dataToCoordSize$3(dataSize, dataItem) {
  63424. // dataItem is necessary in log axis.
  63425. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  63426. var axis = this['get' + dim + 'Axis']();
  63427. var val = dataItem[dimIdx];
  63428. var halfSize = dataSize[dimIdx] / 2;
  63429. var method = 'dataTo' + dim;
  63430. var result = axis.type === 'category'
  63431. ? axis.getBandWidth()
  63432. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  63433. if (dim === 'Angle') {
  63434. result = result * Math.PI / 180;
  63435. }
  63436. return result;
  63437. }, this);
  63438. }
  63439. var preparePolar = function (coordSys) {
  63440. var radiusAxis = coordSys.getRadiusAxis();
  63441. var angleAxis = coordSys.getAngleAxis();
  63442. var radius = radiusAxis.getExtent();
  63443. radius[0] > radius[1] && radius.reverse();
  63444. return {
  63445. coordSys: {
  63446. type: 'polar',
  63447. cx: coordSys.cx,
  63448. cy: coordSys.cy,
  63449. r: radius[1],
  63450. r0: radius[0]
  63451. },
  63452. api: {
  63453. coord: bind(function (data) {
  63454. var radius = radiusAxis.dataToRadius(data[0]);
  63455. var angle = angleAxis.dataToAngle(data[1]);
  63456. var coord = coordSys.coordToPoint([radius, angle]);
  63457. coord.push(radius, angle * Math.PI / 180);
  63458. return coord;
  63459. }),
  63460. size: bind(dataToCoordSize$3, coordSys)
  63461. }
  63462. };
  63463. };
  63464. /*
  63465. * Licensed to the Apache Software Foundation (ASF) under one
  63466. * or more contributor license agreements. See the NOTICE file
  63467. * distributed with this work for additional information
  63468. * regarding copyright ownership. The ASF licenses this file
  63469. * to you under the Apache License, Version 2.0 (the
  63470. * "License"); you may not use this file except in compliance
  63471. * with the License. You may obtain a copy of the License at
  63472. *
  63473. * http://www.apache.org/licenses/LICENSE-2.0
  63474. *
  63475. * Unless required by applicable law or agreed to in writing,
  63476. * software distributed under the License is distributed on an
  63477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63478. * KIND, either express or implied. See the License for the
  63479. * specific language governing permissions and limitations
  63480. * under the License.
  63481. */
  63482. var prepareCalendar = function (coordSys) {
  63483. var rect = coordSys.getRect();
  63484. var rangeInfo = coordSys.getRangeInfo();
  63485. return {
  63486. coordSys: {
  63487. type: 'calendar',
  63488. x: rect.x,
  63489. y: rect.y,
  63490. width: rect.width,
  63491. height: rect.height,
  63492. cellWidth: coordSys.getCellWidth(),
  63493. cellHeight: coordSys.getCellHeight(),
  63494. rangeInfo: {
  63495. start: rangeInfo.start,
  63496. end: rangeInfo.end,
  63497. weeks: rangeInfo.weeks,
  63498. dayCount: rangeInfo.allDay
  63499. }
  63500. },
  63501. api: {
  63502. coord: function (data, clamp) {
  63503. return coordSys.dataToPoint(data, clamp);
  63504. }
  63505. }
  63506. };
  63507. };
  63508. /*
  63509. * Licensed to the Apache Software Foundation (ASF) under one
  63510. * or more contributor license agreements. See the NOTICE file
  63511. * distributed with this work for additional information
  63512. * regarding copyright ownership. The ASF licenses this file
  63513. * to you under the Apache License, Version 2.0 (the
  63514. * "License"); you may not use this file except in compliance
  63515. * with the License. You may obtain a copy of the License at
  63516. *
  63517. * http://www.apache.org/licenses/LICENSE-2.0
  63518. *
  63519. * Unless required by applicable law or agreed to in writing,
  63520. * software distributed under the License is distributed on an
  63521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63522. * KIND, either express or implied. See the License for the
  63523. * specific language governing permissions and limitations
  63524. * under the License.
  63525. */
  63526. var CACHED_LABEL_STYLE_PROPERTIES$1 = CACHED_LABEL_STYLE_PROPERTIES;
  63527. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  63528. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  63529. var LABEL_NORMAL = ['label'];
  63530. var LABEL_EMPHASIS = ['emphasis', 'label'];
  63531. // Use prefix to avoid index to be the same as el.name,
  63532. // which will cause weird udpate animation.
  63533. var GROUP_DIFF_PREFIX = 'e\0\0';
  63534. /**
  63535. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  63536. * of each coordinate systems are not required by each coordinate systems directly, but
  63537. * required by the module `custom`.
  63538. *
  63539. * prepareInfoForCustomSeries {Function}: optional
  63540. * @return {Object} {coordSys: {...}, api: {
  63541. * coord: function (data, clamp) {}, // return point in global.
  63542. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  63543. * }}
  63544. */
  63545. var prepareCustoms = {
  63546. cartesian2d: prepareCartesian2d,
  63547. geo: prepareGeo,
  63548. singleAxis: prepareSingleAxis,
  63549. polar: preparePolar,
  63550. calendar: prepareCalendar
  63551. };
  63552. // ------
  63553. // Model
  63554. // ------
  63555. SeriesModel.extend({
  63556. type: 'series.custom',
  63557. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  63558. defaultOption: {
  63559. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  63560. zlevel: 0,
  63561. z: 2,
  63562. legendHoverLink: true,
  63563. useTransform: true,
  63564. // Custom series will not clip by default.
  63565. // Some case will use custom series to draw label
  63566. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  63567. // Only works on polar and cartesian2d coordinate system.
  63568. clip: false
  63569. // Cartesian coordinate system
  63570. // xAxisIndex: 0,
  63571. // yAxisIndex: 0,
  63572. // Polar coordinate system
  63573. // polarIndex: 0,
  63574. // Geo coordinate system
  63575. // geoIndex: 0,
  63576. // label: {}
  63577. // itemStyle: {}
  63578. },
  63579. /**
  63580. * @override
  63581. */
  63582. getInitialData: function (option, ecModel) {
  63583. return createListFromArray(this.getSource(), this);
  63584. },
  63585. /**
  63586. * @override
  63587. */
  63588. getDataParams: function (dataIndex, dataType, el) {
  63589. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  63590. el && (params.info = el.info);
  63591. return params;
  63592. }
  63593. });
  63594. // -----
  63595. // View
  63596. // -----
  63597. Chart.extend({
  63598. type: 'custom',
  63599. /**
  63600. * @private
  63601. * @type {module:echarts/data/List}
  63602. */
  63603. _data: null,
  63604. /**
  63605. * @override
  63606. */
  63607. render: function (customSeries, ecModel, api, payload) {
  63608. var oldData = this._data;
  63609. var data = customSeries.getData();
  63610. var group = this.group;
  63611. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63612. // By default, merge mode is applied. In most cases, custom series is
  63613. // used in the scenario that data amount is not large but graphic elements
  63614. // is complicated, where merge mode is probably necessary for optimization.
  63615. // For example, reuse graphic elements and only update the transform when
  63616. // roam or data zoom according to `actionType`.
  63617. data.diff(oldData)
  63618. .add(function (newIdx) {
  63619. createOrUpdate$1(
  63620. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  63621. );
  63622. })
  63623. .update(function (newIdx, oldIdx) {
  63624. var el = oldData.getItemGraphicEl(oldIdx);
  63625. createOrUpdate$1(
  63626. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  63627. );
  63628. })
  63629. .remove(function (oldIdx) {
  63630. var el = oldData.getItemGraphicEl(oldIdx);
  63631. el && group.remove(el);
  63632. })
  63633. .execute();
  63634. // Do clipping
  63635. var clipPath = customSeries.get('clip', true)
  63636. ? createClipPath(customSeries.coordinateSystem, false, customSeries)
  63637. : null;
  63638. if (clipPath) {
  63639. group.setClipPath(clipPath);
  63640. }
  63641. else {
  63642. group.removeClipPath();
  63643. }
  63644. this._data = data;
  63645. },
  63646. incrementalPrepareRender: function (customSeries, ecModel, api) {
  63647. this.group.removeAll();
  63648. this._data = null;
  63649. },
  63650. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  63651. var data = customSeries.getData();
  63652. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63653. function setIncrementalAndHoverLayer(el) {
  63654. if (!el.isGroup) {
  63655. el.incremental = true;
  63656. el.useHoverLayer = true;
  63657. }
  63658. }
  63659. for (var idx = params.start; idx < params.end; idx++) {
  63660. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  63661. el.traverse(setIncrementalAndHoverLayer);
  63662. }
  63663. },
  63664. /**
  63665. * @override
  63666. */
  63667. dispose: noop,
  63668. /**
  63669. * @override
  63670. */
  63671. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  63672. var elementName = query.element;
  63673. if (elementName == null || targetEl.name === elementName) {
  63674. return true;
  63675. }
  63676. // Enable to give a name on a group made by `renderItem`, and listen
  63677. // events that triggerd by its descendents.
  63678. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  63679. if (targetEl.name === elementName) {
  63680. return true;
  63681. }
  63682. }
  63683. return false;
  63684. }
  63685. });
  63686. function createEl(elOption) {
  63687. var graphicType = elOption.type;
  63688. var el;
  63689. // Those graphic elements are not shapes. They should not be
  63690. // overwritten by users, so do them first.
  63691. if (graphicType === 'path') {
  63692. var shape = elOption.shape;
  63693. // Using pathRect brings convenience to users sacle svg path.
  63694. var pathRect = (shape.width != null && shape.height != null)
  63695. ? {
  63696. x: shape.x || 0,
  63697. y: shape.y || 0,
  63698. width: shape.width,
  63699. height: shape.height
  63700. }
  63701. : null;
  63702. var pathData = getPathData(shape);
  63703. // Path is also used for icon, so layout 'center' by default.
  63704. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  63705. el.__customPathData = pathData;
  63706. }
  63707. else if (graphicType === 'image') {
  63708. el = new ZImage({});
  63709. el.__customImagePath = elOption.style.image;
  63710. }
  63711. else if (graphicType === 'text') {
  63712. el = new Text({});
  63713. el.__customText = elOption.style.text;
  63714. }
  63715. else if (graphicType === 'group') {
  63716. el = new Group();
  63717. }
  63718. else if (graphicType === 'compoundPath') {
  63719. throw new Error('"compoundPath" is not supported yet.');
  63720. }
  63721. else {
  63722. var Clz = getShapeClass(graphicType);
  63723. if (__DEV__) {
  63724. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  63725. }
  63726. el = new Clz();
  63727. }
  63728. el.__customGraphicType = graphicType;
  63729. el.name = elOption.name;
  63730. return el;
  63731. }
  63732. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  63733. var transitionProps = {};
  63734. var elOptionStyle = elOption.style || {};
  63735. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  63736. elOption.position && (transitionProps.position = elOption.position.slice());
  63737. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  63738. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  63739. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  63740. if (el.type === 'image' && elOption.style) {
  63741. var targetStyle = transitionProps.style = {};
  63742. each$1(['x', 'y', 'width', 'height'], function (prop) {
  63743. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  63744. });
  63745. }
  63746. if (el.type === 'text' && elOption.style) {
  63747. var targetStyle = transitionProps.style = {};
  63748. each$1(['x', 'y'], function (prop) {
  63749. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  63750. });
  63751. // Compatible with previous: both support
  63752. // textFill and fill, textStroke and stroke in 'text' element.
  63753. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  63754. elOptionStyle.textFill = elOptionStyle.fill
  63755. );
  63756. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  63757. elOptionStyle.textStroke = elOptionStyle.stroke
  63758. );
  63759. }
  63760. if (el.type !== 'group') {
  63761. el.useStyle(elOptionStyle);
  63762. // Init animation.
  63763. if (isInit) {
  63764. el.style.opacity = 0;
  63765. var targetOpacity = elOptionStyle.opacity;
  63766. targetOpacity == null && (targetOpacity = 1);
  63767. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  63768. }
  63769. }
  63770. if (isInit) {
  63771. el.attr(transitionProps);
  63772. }
  63773. else {
  63774. updateProps(el, transitionProps, animatableModel, dataIndex);
  63775. }
  63776. // Merge by default.
  63777. // z2 must not be null/undefined, otherwise sort error may occur.
  63778. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  63779. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  63780. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  63781. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  63782. // `elOption.info` enables user to mount some info on
  63783. // elements and use them in event handlers.
  63784. // Update them only when user specified, otherwise, remain.
  63785. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  63786. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  63787. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  63788. var styleEmphasis = elOption.styleEmphasis;
  63789. // hoverStyle should always be set here, because if the hover style
  63790. // may already be changed, where the inner cache should be reset.
  63791. setElementHoverStyle(el, styleEmphasis);
  63792. if (isRoot) {
  63793. setAsHighDownDispatcher(el, styleEmphasis !== false);
  63794. }
  63795. }
  63796. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  63797. if (elOptionStyle[prop] != null && !isInit) {
  63798. targetStyle[prop] = elOptionStyle[prop];
  63799. elOptionStyle[prop] = oldElStyle[prop];
  63800. }
  63801. }
  63802. function makeRenderItem(customSeries, data, ecModel, api) {
  63803. var renderItem = customSeries.get('renderItem');
  63804. var coordSys = customSeries.coordinateSystem;
  63805. var prepareResult = {};
  63806. if (coordSys) {
  63807. if (__DEV__) {
  63808. assert$1(renderItem, 'series.render is required.');
  63809. assert$1(
  63810. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  63811. 'This coordSys does not support custom series.'
  63812. );
  63813. }
  63814. prepareResult = coordSys.prepareCustoms
  63815. ? coordSys.prepareCustoms()
  63816. : prepareCustoms[coordSys.type](coordSys);
  63817. }
  63818. var userAPI = defaults({
  63819. getWidth: api.getWidth,
  63820. getHeight: api.getHeight,
  63821. getZr: api.getZr,
  63822. getDevicePixelRatio: api.getDevicePixelRatio,
  63823. value: value,
  63824. style: style,
  63825. styleEmphasis: styleEmphasis,
  63826. visual: visual,
  63827. barLayout: barLayout,
  63828. currentSeriesIndices: currentSeriesIndices,
  63829. font: font
  63830. }, prepareResult.api || {});
  63831. var userParams = {
  63832. // The life cycle of context: current round of rendering.
  63833. // The global life cycle is probably not necessary, because
  63834. // user can store global status by themselves.
  63835. context: {},
  63836. seriesId: customSeries.id,
  63837. seriesName: customSeries.name,
  63838. seriesIndex: customSeries.seriesIndex,
  63839. coordSys: prepareResult.coordSys,
  63840. dataInsideLength: data.count(),
  63841. encode: wrapEncodeDef(customSeries.getData())
  63842. };
  63843. // Do not support call `api` asynchronously without dataIndexInside input.
  63844. var currDataIndexInside;
  63845. var currDirty = true;
  63846. var currItemModel;
  63847. var currLabelNormalModel;
  63848. var currLabelEmphasisModel;
  63849. var currVisualColor;
  63850. return function (dataIndexInside, payload) {
  63851. currDataIndexInside = dataIndexInside;
  63852. currDirty = true;
  63853. return renderItem && renderItem(
  63854. defaults({
  63855. dataIndexInside: dataIndexInside,
  63856. dataIndex: data.getRawIndex(dataIndexInside),
  63857. // Can be used for optimization when zoom or roam.
  63858. actionType: payload ? payload.type : null
  63859. }, userParams),
  63860. userAPI
  63861. );
  63862. };
  63863. // Do not update cache until api called.
  63864. function updateCache(dataIndexInside) {
  63865. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63866. if (currDirty) {
  63867. currItemModel = data.getItemModel(dataIndexInside);
  63868. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  63869. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  63870. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  63871. currDirty = false;
  63872. }
  63873. }
  63874. /**
  63875. * @public
  63876. * @param {number|string} dim
  63877. * @param {number} [dataIndexInside=currDataIndexInside]
  63878. * @return {number|string} value
  63879. */
  63880. function value(dim, dataIndexInside) {
  63881. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63882. return data.get(data.getDimension(dim || 0), dataIndexInside);
  63883. }
  63884. /**
  63885. * By default, `visual` is applied to style (to support visualMap).
  63886. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  63887. * it can be implemented as:
  63888. * `api.style({stroke: api.visual('color'), fill: null})`;
  63889. * @public
  63890. * @param {Object} [extra]
  63891. * @param {number} [dataIndexInside=currDataIndexInside]
  63892. */
  63893. function style(extra, dataIndexInside) {
  63894. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63895. updateCache(dataIndexInside);
  63896. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  63897. currVisualColor != null && (itemStyle.fill = currVisualColor);
  63898. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  63899. opacity != null && (itemStyle.opacity = opacity);
  63900. var labelModel = extra
  63901. ? applyExtraBefore(extra, currLabelNormalModel)
  63902. : currLabelNormalModel;
  63903. setTextStyle(itemStyle, labelModel, null, {
  63904. autoColor: currVisualColor,
  63905. isRectText: true
  63906. });
  63907. itemStyle.text = labelModel.getShallow('show')
  63908. ? retrieve2(
  63909. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  63910. getDefaultLabel(data, dataIndexInside)
  63911. )
  63912. : null;
  63913. extra && applyExtraAfter(itemStyle, extra);
  63914. return itemStyle;
  63915. }
  63916. /**
  63917. * @public
  63918. * @param {Object} [extra]
  63919. * @param {number} [dataIndexInside=currDataIndexInside]
  63920. */
  63921. function styleEmphasis(extra, dataIndexInside) {
  63922. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63923. updateCache(dataIndexInside);
  63924. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  63925. var labelModel = extra
  63926. ? applyExtraBefore(extra, currLabelEmphasisModel)
  63927. : currLabelEmphasisModel;
  63928. setTextStyle(itemStyle, labelModel, null, {
  63929. isRectText: true
  63930. }, true);
  63931. itemStyle.text = labelModel.getShallow('show')
  63932. ? retrieve3(
  63933. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  63934. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  63935. getDefaultLabel(data, dataIndexInside)
  63936. )
  63937. : null;
  63938. extra && applyExtraAfter(itemStyle, extra);
  63939. return itemStyle;
  63940. }
  63941. /**
  63942. * @public
  63943. * @param {string} visualType
  63944. * @param {number} [dataIndexInside=currDataIndexInside]
  63945. */
  63946. function visual(visualType, dataIndexInside) {
  63947. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  63948. return data.getItemVisual(dataIndexInside, visualType);
  63949. }
  63950. /**
  63951. * @public
  63952. * @param {number} opt.count Positive interger.
  63953. * @param {number} [opt.barWidth]
  63954. * @param {number} [opt.barMaxWidth]
  63955. * @param {number} [opt.barMinWidth]
  63956. * @param {number} [opt.barGap]
  63957. * @param {number} [opt.barCategoryGap]
  63958. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  63959. */
  63960. function barLayout(opt) {
  63961. if (coordSys.getBaseAxis) {
  63962. var baseAxis = coordSys.getBaseAxis();
  63963. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  63964. }
  63965. }
  63966. /**
  63967. * @public
  63968. * @return {Array.<number>}
  63969. */
  63970. function currentSeriesIndices() {
  63971. return ecModel.getCurrentSeriesIndices();
  63972. }
  63973. /**
  63974. * @public
  63975. * @param {Object} opt
  63976. * @param {string} [opt.fontStyle]
  63977. * @param {number} [opt.fontWeight]
  63978. * @param {number} [opt.fontSize]
  63979. * @param {string} [opt.fontFamily]
  63980. * @return {string} font string
  63981. */
  63982. function font(opt) {
  63983. return getFont(opt, ecModel);
  63984. }
  63985. }
  63986. function wrapEncodeDef(data) {
  63987. var encodeDef = {};
  63988. each$1(data.dimensions, function (dimName, dataDimIndex) {
  63989. var dimInfo = data.getDimensionInfo(dimName);
  63990. if (!dimInfo.isExtraCoord) {
  63991. var coordDim = dimInfo.coordDim;
  63992. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  63993. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  63994. }
  63995. });
  63996. return encodeDef;
  63997. }
  63998. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  63999. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  64000. el && data.setItemGraphicEl(dataIndex, el);
  64001. return el;
  64002. }
  64003. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  64004. // [Rule]
  64005. // By default, follow merge mode.
  64006. // (It probably brings benifit for performance in some cases of large data, where
  64007. // user program can be optimized to that only updated props needed to be re-calculated,
  64008. // or according to `actionType` some calculation can be skipped.)
  64009. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  64010. // (It seems that violate the "merge" principle, but most of users probably intuitively
  64011. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  64012. // most cases.)
  64013. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  64014. elOption = elOption || {};
  64015. var elOptionType = elOption.type;
  64016. var elOptionShape = elOption.shape;
  64017. var elOptionStyle = elOption.style;
  64018. if (el && (
  64019. simplyRemove
  64020. // || elOption.$merge === false
  64021. // If `elOptionType` is `null`, follow the merge principle.
  64022. || (elOptionType != null
  64023. && elOptionType !== el.__customGraphicType
  64024. )
  64025. || (elOptionType === 'path'
  64026. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  64027. )
  64028. || (elOptionType === 'image'
  64029. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  64030. )
  64031. // FIXME test and remove this restriction?
  64032. || (elOptionType === 'text'
  64033. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  64034. )
  64035. )) {
  64036. group.remove(el);
  64037. el = null;
  64038. }
  64039. // `elOption.type` is undefined when `renderItem` returns nothing.
  64040. if (simplyRemove) {
  64041. return;
  64042. }
  64043. var isInit = !el;
  64044. !el && (el = createEl(elOption));
  64045. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  64046. if (elOptionType === 'group') {
  64047. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  64048. }
  64049. // Always add whatever already added to ensure sequence.
  64050. group.add(el);
  64051. return el;
  64052. }
  64053. // Usage:
  64054. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  64055. // the existing children will not be removed, and enables the feature that
  64056. // update some of the props of some of the children simply by construct
  64057. // the returned children of `renderItem` like:
  64058. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64059. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64060. // by child.name. But that might be lower performance.
  64061. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64062. // replaced totally.
  64063. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  64064. //
  64065. // For implementation simpleness, do not provide a direct way to remove sinlge
  64066. // child (otherwise the total indicies of the children array have to be modified).
  64067. // User can remove a single child by set its `ignore` as `true` or replace
  64068. // it by another element, where its `$merge` can be set as `true` if necessary.
  64069. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  64070. var newChildren = elOption.children;
  64071. var newLen = newChildren ? newChildren.length : 0;
  64072. var mergeChildren = elOption.$mergeChildren;
  64073. // `diffChildrenByName` has been deprecated.
  64074. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64075. var notMerge = mergeChildren === false;
  64076. // For better performance on roam update, only enter if necessary.
  64077. if (!newLen && !byName && !notMerge) {
  64078. return;
  64079. }
  64080. if (byName) {
  64081. diffGroupChildren({
  64082. oldChildren: el.children() || [],
  64083. newChildren: newChildren || [],
  64084. dataIndex: dataIndex,
  64085. animatableModel: animatableModel,
  64086. group: el,
  64087. data: data
  64088. });
  64089. return;
  64090. }
  64091. notMerge && el.removeAll();
  64092. // Mapping children of a group simply by index, which
  64093. // might be better performance.
  64094. var index = 0;
  64095. for (; index < newLen; index++) {
  64096. newChildren[index] && doCreateOrUpdate(
  64097. el.childAt(index),
  64098. dataIndex,
  64099. newChildren[index],
  64100. animatableModel,
  64101. el,
  64102. data
  64103. );
  64104. }
  64105. if (__DEV__) {
  64106. assert$1(
  64107. !notMerge || el.childCount() === index,
  64108. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  64109. );
  64110. }
  64111. }
  64112. function diffGroupChildren(context) {
  64113. (new DataDiffer(
  64114. context.oldChildren,
  64115. context.newChildren,
  64116. getKey,
  64117. getKey,
  64118. context
  64119. ))
  64120. .add(processAddUpdate)
  64121. .update(processAddUpdate)
  64122. .remove(processRemove)
  64123. .execute();
  64124. }
  64125. function getKey(item, idx) {
  64126. var name = item && item.name;
  64127. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64128. }
  64129. function processAddUpdate(newIndex, oldIndex) {
  64130. var context = this.context;
  64131. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64132. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64133. doCreateOrUpdate(
  64134. child,
  64135. context.dataIndex,
  64136. childOption,
  64137. context.animatableModel,
  64138. context.group,
  64139. context.data
  64140. );
  64141. }
  64142. // `graphic#applyDefaultTextStyle` will cache
  64143. // textFill, textStroke, textStrokeWidth.
  64144. // We have to do this trick.
  64145. function applyExtraBefore(extra, model) {
  64146. var dummyModel = new Model({}, model);
  64147. each$1(CACHED_LABEL_STYLE_PROPERTIES$1, function (stylePropName, modelPropName) {
  64148. if (extra.hasOwnProperty(stylePropName)) {
  64149. dummyModel.option[modelPropName] = extra[stylePropName];
  64150. }
  64151. });
  64152. return dummyModel;
  64153. }
  64154. function applyExtraAfter(itemStyle, extra) {
  64155. for (var key in extra) {
  64156. if (extra.hasOwnProperty(key)
  64157. || !CACHED_LABEL_STYLE_PROPERTIES$1.hasOwnProperty(key)
  64158. ) {
  64159. itemStyle[key] = extra[key];
  64160. }
  64161. }
  64162. }
  64163. function processRemove(oldIndex) {
  64164. var context = this.context;
  64165. var child = context.oldChildren[oldIndex];
  64166. child && context.group.remove(child);
  64167. }
  64168. function getPathData(shape) {
  64169. // "d" follows the SVG convention.
  64170. return shape && (shape.pathData || shape.d);
  64171. }
  64172. function hasOwnPathData(shape) {
  64173. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  64174. }
  64175. function hasOwn(host, prop) {
  64176. return host && host.hasOwnProperty(prop);
  64177. }
  64178. /*
  64179. * Licensed to the Apache Software Foundation (ASF) under one
  64180. * or more contributor license agreements. See the NOTICE file
  64181. * distributed with this work for additional information
  64182. * regarding copyright ownership. The ASF licenses this file
  64183. * to you under the Apache License, Version 2.0 (the
  64184. * "License"); you may not use this file except in compliance
  64185. * with the License. You may obtain a copy of the License at
  64186. *
  64187. * http://www.apache.org/licenses/LICENSE-2.0
  64188. *
  64189. * Unless required by applicable law or agreed to in writing,
  64190. * software distributed under the License is distributed on an
  64191. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64192. * KIND, either express or implied. See the License for the
  64193. * specific language governing permissions and limitations
  64194. * under the License.
  64195. */
  64196. /*
  64197. * Licensed to the Apache Software Foundation (ASF) under one
  64198. * or more contributor license agreements. See the NOTICE file
  64199. * distributed with this work for additional information
  64200. * regarding copyright ownership. The ASF licenses this file
  64201. * to you under the Apache License, Version 2.0 (the
  64202. * "License"); you may not use this file except in compliance
  64203. * with the License. You may obtain a copy of the License at
  64204. *
  64205. * http://www.apache.org/licenses/LICENSE-2.0
  64206. *
  64207. * Unless required by applicable law or agreed to in writing,
  64208. * software distributed under the License is distributed on an
  64209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64210. * KIND, either express or implied. See the License for the
  64211. * specific language governing permissions and limitations
  64212. * under the License.
  64213. */
  64214. function getSeriesStackId$1(seriesModel) {
  64215. return seriesModel.get('stack')
  64216. || '__ec_stack_' + seriesModel.seriesIndex;
  64217. }
  64218. function getAxisKey$1(polar, axis) {
  64219. return axis.dim + polar.model.componentIndex;
  64220. }
  64221. /**
  64222. * @param {string} seriesType
  64223. * @param {module:echarts/model/Global} ecModel
  64224. * @param {module:echarts/ExtensionAPI} api
  64225. */
  64226. function barLayoutPolar(seriesType, ecModel, api) {
  64227. var lastStackCoords = {};
  64228. var barWidthAndOffset = calRadialBar(
  64229. filter(
  64230. ecModel.getSeriesByType(seriesType),
  64231. function (seriesModel) {
  64232. return !ecModel.isSeriesFiltered(seriesModel)
  64233. && seriesModel.coordinateSystem
  64234. && seriesModel.coordinateSystem.type === 'polar';
  64235. }
  64236. )
  64237. );
  64238. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64239. // Check series coordinate, do layout for polar only
  64240. if (seriesModel.coordinateSystem.type !== 'polar') {
  64241. return;
  64242. }
  64243. var data = seriesModel.getData();
  64244. var polar = seriesModel.coordinateSystem;
  64245. var baseAxis = polar.getBaseAxis();
  64246. var axisKey = getAxisKey$1(polar, baseAxis);
  64247. var stackId = getSeriesStackId$1(seriesModel);
  64248. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  64249. var columnOffset = columnLayoutInfo.offset;
  64250. var columnWidth = columnLayoutInfo.width;
  64251. var valueAxis = polar.getOtherAxis(baseAxis);
  64252. var cx = seriesModel.coordinateSystem.cx;
  64253. var cy = seriesModel.coordinateSystem.cy;
  64254. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64255. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64256. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64257. var valueDim = data.mapDimension(valueAxis.dim);
  64258. var baseDim = data.mapDimension(baseAxis.dim);
  64259. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64260. var clampLayout = baseAxis.dim !== 'radius'
  64261. || !seriesModel.get('roundCap', true);
  64262. var valueAxisStart = valueAxis.getExtent()[0];
  64263. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64264. var value = data.get(valueDim, idx);
  64265. var baseValue = data.get(baseDim, idx);
  64266. if (isNaN(value)) {
  64267. continue;
  64268. }
  64269. var sign = value >= 0 ? 'p' : 'n';
  64270. var baseCoord = valueAxisStart;
  64271. // Because of the barMinHeight, we can not use the value in
  64272. // stackResultDimension directly.
  64273. // Only ordinal axis can be stacked.
  64274. if (stacked) {
  64275. if (!lastStackCoords[stackId][baseValue]) {
  64276. lastStackCoords[stackId][baseValue] = {
  64277. p: valueAxisStart, // Positive stack
  64278. n: valueAxisStart // Negative stack
  64279. };
  64280. }
  64281. // Should also consider #4243
  64282. baseCoord = lastStackCoords[stackId][baseValue][sign];
  64283. }
  64284. var r0;
  64285. var r;
  64286. var startAngle;
  64287. var endAngle;
  64288. // radial sector
  64289. if (valueAxis.dim === 'radius') {
  64290. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  64291. var angle = baseAxis.dataToAngle(baseValue);
  64292. if (Math.abs(radiusSpan) < barMinHeight) {
  64293. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  64294. }
  64295. r0 = baseCoord;
  64296. r = baseCoord + radiusSpan;
  64297. startAngle = angle - columnOffset;
  64298. endAngle = startAngle - columnWidth;
  64299. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  64300. }
  64301. // tangential sector
  64302. else {
  64303. var angleSpan = valueAxis.dataToAngle(value, clampLayout) - valueAxisStart;
  64304. var radius = baseAxis.dataToRadius(baseValue);
  64305. if (Math.abs(angleSpan) < barMinAngle) {
  64306. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  64307. }
  64308. r0 = radius + columnOffset;
  64309. r = r0 + columnWidth;
  64310. startAngle = baseCoord;
  64311. endAngle = baseCoord + angleSpan;
  64312. // if the previous stack is at the end of the ring,
  64313. // add a round to differentiate it from origin
  64314. // var extent = angleAxis.getExtent();
  64315. // var stackCoord = angle;
  64316. // if (stackCoord === extent[0] && value > 0) {
  64317. // stackCoord = extent[1];
  64318. // }
  64319. // else if (stackCoord === extent[1] && value < 0) {
  64320. // stackCoord = extent[0];
  64321. // }
  64322. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  64323. }
  64324. data.setItemLayout(idx, {
  64325. cx: cx,
  64326. cy: cy,
  64327. r0: r0,
  64328. r: r,
  64329. // Consider that positive angle is anti-clockwise,
  64330. // while positive radian of sector is clockwise
  64331. startAngle: -startAngle * Math.PI / 180,
  64332. endAngle: -endAngle * Math.PI / 180
  64333. });
  64334. }
  64335. }, this);
  64336. }
  64337. /**
  64338. * Calculate bar width and offset for radial bar charts
  64339. */
  64340. function calRadialBar(barSeries, api) {
  64341. // Columns info on each category axis. Key is polar name
  64342. var columnsMap = {};
  64343. each$1(barSeries, function (seriesModel, idx) {
  64344. var data = seriesModel.getData();
  64345. var polar = seriesModel.coordinateSystem;
  64346. var baseAxis = polar.getBaseAxis();
  64347. var axisKey = getAxisKey$1(polar, baseAxis);
  64348. var axisExtent = baseAxis.getExtent();
  64349. var bandWidth = baseAxis.type === 'category'
  64350. ? baseAxis.getBandWidth()
  64351. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  64352. var columnsOnAxis = columnsMap[axisKey] || {
  64353. bandWidth: bandWidth,
  64354. remainedWidth: bandWidth,
  64355. autoWidthCount: 0,
  64356. categoryGap: '20%',
  64357. gap: '30%',
  64358. stacks: {}
  64359. };
  64360. var stacks = columnsOnAxis.stacks;
  64361. columnsMap[axisKey] = columnsOnAxis;
  64362. var stackId = getSeriesStackId$1(seriesModel);
  64363. if (!stacks[stackId]) {
  64364. columnsOnAxis.autoWidthCount++;
  64365. }
  64366. stacks[stackId] = stacks[stackId] || {
  64367. width: 0,
  64368. maxWidth: 0
  64369. };
  64370. var barWidth = parsePercent$1(
  64371. seriesModel.get('barWidth'),
  64372. bandWidth
  64373. );
  64374. var barMaxWidth = parsePercent$1(
  64375. seriesModel.get('barMaxWidth'),
  64376. bandWidth
  64377. );
  64378. var barGap = seriesModel.get('barGap');
  64379. var barCategoryGap = seriesModel.get('barCategoryGap');
  64380. if (barWidth && !stacks[stackId].width) {
  64381. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  64382. stacks[stackId].width = barWidth;
  64383. columnsOnAxis.remainedWidth -= barWidth;
  64384. }
  64385. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  64386. (barGap != null) && (columnsOnAxis.gap = barGap);
  64387. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  64388. });
  64389. var result = {};
  64390. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  64391. result[coordSysName] = {};
  64392. var stacks = columnsOnAxis.stacks;
  64393. var bandWidth = columnsOnAxis.bandWidth;
  64394. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  64395. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  64396. var remainedWidth = columnsOnAxis.remainedWidth;
  64397. var autoWidthCount = columnsOnAxis.autoWidthCount;
  64398. var autoWidth = (remainedWidth - categoryGap)
  64399. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64400. autoWidth = Math.max(autoWidth, 0);
  64401. // Find if any auto calculated bar exceeded maxBarWidth
  64402. each$1(stacks, function (column, stack) {
  64403. var maxWidth = column.maxWidth;
  64404. if (maxWidth && maxWidth < autoWidth) {
  64405. maxWidth = Math.min(maxWidth, remainedWidth);
  64406. if (column.width) {
  64407. maxWidth = Math.min(maxWidth, column.width);
  64408. }
  64409. remainedWidth -= maxWidth;
  64410. column.width = maxWidth;
  64411. autoWidthCount--;
  64412. }
  64413. });
  64414. // Recalculate width again
  64415. autoWidth = (remainedWidth - categoryGap)
  64416. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64417. autoWidth = Math.max(autoWidth, 0);
  64418. var widthSum = 0;
  64419. var lastColumn;
  64420. each$1(stacks, function (column, idx) {
  64421. if (!column.width) {
  64422. column.width = autoWidth;
  64423. }
  64424. lastColumn = column;
  64425. widthSum += column.width * (1 + barGapPercent);
  64426. });
  64427. if (lastColumn) {
  64428. widthSum -= lastColumn.width * barGapPercent;
  64429. }
  64430. var offset = -widthSum / 2;
  64431. each$1(stacks, function (column, stackId) {
  64432. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  64433. offset: offset,
  64434. width: column.width
  64435. };
  64436. offset += column.width * (1 + barGapPercent);
  64437. });
  64438. });
  64439. return result;
  64440. }
  64441. /*
  64442. * Licensed to the Apache Software Foundation (ASF) under one
  64443. * or more contributor license agreements. See the NOTICE file
  64444. * distributed with this work for additional information
  64445. * regarding copyright ownership. The ASF licenses this file
  64446. * to you under the Apache License, Version 2.0 (the
  64447. * "License"); you may not use this file except in compliance
  64448. * with the License. You may obtain a copy of the License at
  64449. *
  64450. * http://www.apache.org/licenses/LICENSE-2.0
  64451. *
  64452. * Unless required by applicable law or agreed to in writing,
  64453. * software distributed under the License is distributed on an
  64454. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64455. * KIND, either express or implied. See the License for the
  64456. * specific language governing permissions and limitations
  64457. * under the License.
  64458. */
  64459. function RadiusAxis(scale, radiusExtent) {
  64460. Axis.call(this, 'radius', scale, radiusExtent);
  64461. /**
  64462. * Axis type
  64463. * - 'category'
  64464. * - 'value'
  64465. * - 'time'
  64466. * - 'log'
  64467. * @type {string}
  64468. */
  64469. this.type = 'category';
  64470. }
  64471. RadiusAxis.prototype = {
  64472. constructor: RadiusAxis,
  64473. /**
  64474. * @override
  64475. */
  64476. pointToData: function (point, clamp) {
  64477. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64478. },
  64479. dataToRadius: Axis.prototype.dataToCoord,
  64480. radiusToData: Axis.prototype.coordToData
  64481. };
  64482. inherits(RadiusAxis, Axis);
  64483. /*
  64484. * Licensed to the Apache Software Foundation (ASF) under one
  64485. * or more contributor license agreements. See the NOTICE file
  64486. * distributed with this work for additional information
  64487. * regarding copyright ownership. The ASF licenses this file
  64488. * to you under the Apache License, Version 2.0 (the
  64489. * "License"); you may not use this file except in compliance
  64490. * with the License. You may obtain a copy of the License at
  64491. *
  64492. * http://www.apache.org/licenses/LICENSE-2.0
  64493. *
  64494. * Unless required by applicable law or agreed to in writing,
  64495. * software distributed under the License is distributed on an
  64496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64497. * KIND, either express or implied. See the License for the
  64498. * specific language governing permissions and limitations
  64499. * under the License.
  64500. */
  64501. var inner$12 = makeInner();
  64502. function AngleAxis(scale, angleExtent) {
  64503. angleExtent = angleExtent || [0, 360];
  64504. Axis.call(this, 'angle', scale, angleExtent);
  64505. /**
  64506. * Axis type
  64507. * - 'category'
  64508. * - 'value'
  64509. * - 'time'
  64510. * - 'log'
  64511. * @type {string}
  64512. */
  64513. this.type = 'category';
  64514. }
  64515. AngleAxis.prototype = {
  64516. constructor: AngleAxis,
  64517. /**
  64518. * @override
  64519. */
  64520. pointToData: function (point, clamp) {
  64521. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64522. },
  64523. dataToAngle: Axis.prototype.dataToCoord,
  64524. angleToData: Axis.prototype.coordToData,
  64525. /**
  64526. * Only be called in category axis.
  64527. * Angle axis uses text height to decide interval
  64528. *
  64529. * @override
  64530. * @return {number} Auto interval for cateogry axis tick and label
  64531. */
  64532. calculateCategoryInterval: function () {
  64533. var axis = this;
  64534. var labelModel = axis.getLabelModel();
  64535. var ordinalScale = axis.scale;
  64536. var ordinalExtent = ordinalScale.getExtent();
  64537. // Providing this method is for optimization:
  64538. // avoid generating a long array by `getTicks`
  64539. // in large category data case.
  64540. var tickCount = ordinalScale.count();
  64541. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  64542. return 0;
  64543. }
  64544. var tickValue = ordinalExtent[0];
  64545. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  64546. var unitH = Math.abs(unitSpan);
  64547. // Not precise, just use height as text width
  64548. // and each distance from axis line yet.
  64549. var rect = getBoundingRect(
  64550. tickValue, labelModel.getFont(), 'center', 'top'
  64551. );
  64552. var maxH = Math.max(rect.height, 7);
  64553. var dh = maxH / unitH;
  64554. // 0/0 is NaN, 1/0 is Infinity.
  64555. isNaN(dh) && (dh = Infinity);
  64556. var interval = Math.max(0, Math.floor(dh));
  64557. var cache = inner$12(axis.model);
  64558. var lastAutoInterval = cache.lastAutoInterval;
  64559. var lastTickCount = cache.lastTickCount;
  64560. // Use cache to keep interval stable while moving zoom window,
  64561. // otherwise the calculated interval might jitter when the zoom
  64562. // window size is close to the interval-changing size.
  64563. if (lastAutoInterval != null
  64564. && lastTickCount != null
  64565. && Math.abs(lastAutoInterval - interval) <= 1
  64566. && Math.abs(lastTickCount - tickCount) <= 1
  64567. // Always choose the bigger one, otherwise the critical
  64568. // point is not the same when zooming in or zooming out.
  64569. && lastAutoInterval > interval
  64570. ) {
  64571. interval = lastAutoInterval;
  64572. }
  64573. // Only update cache if cache not used, otherwise the
  64574. // changing of interval is too insensitive.
  64575. else {
  64576. cache.lastTickCount = tickCount;
  64577. cache.lastAutoInterval = interval;
  64578. }
  64579. return interval;
  64580. }
  64581. };
  64582. inherits(AngleAxis, Axis);
  64583. /*
  64584. * Licensed to the Apache Software Foundation (ASF) under one
  64585. * or more contributor license agreements. See the NOTICE file
  64586. * distributed with this work for additional information
  64587. * regarding copyright ownership. The ASF licenses this file
  64588. * to you under the Apache License, Version 2.0 (the
  64589. * "License"); you may not use this file except in compliance
  64590. * with the License. You may obtain a copy of the License at
  64591. *
  64592. * http://www.apache.org/licenses/LICENSE-2.0
  64593. *
  64594. * Unless required by applicable law or agreed to in writing,
  64595. * software distributed under the License is distributed on an
  64596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64597. * KIND, either express or implied. See the License for the
  64598. * specific language governing permissions and limitations
  64599. * under the License.
  64600. */
  64601. /**
  64602. * @module echarts/coord/polar/Polar
  64603. */
  64604. /**
  64605. * @alias {module:echarts/coord/polar/Polar}
  64606. * @constructor
  64607. * @param {string} name
  64608. */
  64609. var Polar = function (name) {
  64610. /**
  64611. * @type {string}
  64612. */
  64613. this.name = name || '';
  64614. /**
  64615. * x of polar center
  64616. * @type {number}
  64617. */
  64618. this.cx = 0;
  64619. /**
  64620. * y of polar center
  64621. * @type {number}
  64622. */
  64623. this.cy = 0;
  64624. /**
  64625. * @type {module:echarts/coord/polar/RadiusAxis}
  64626. * @private
  64627. */
  64628. this._radiusAxis = new RadiusAxis();
  64629. /**
  64630. * @type {module:echarts/coord/polar/AngleAxis}
  64631. * @private
  64632. */
  64633. this._angleAxis = new AngleAxis();
  64634. this._radiusAxis.polar = this._angleAxis.polar = this;
  64635. };
  64636. Polar.prototype = {
  64637. type: 'polar',
  64638. axisPointerEnabled: true,
  64639. constructor: Polar,
  64640. /**
  64641. * @param {Array.<string>}
  64642. * @readOnly
  64643. */
  64644. dimensions: ['radius', 'angle'],
  64645. /**
  64646. * @type {module:echarts/coord/PolarModel}
  64647. */
  64648. model: null,
  64649. /**
  64650. * If contain coord
  64651. * @param {Array.<number>} point
  64652. * @return {boolean}
  64653. */
  64654. containPoint: function (point) {
  64655. var coord = this.pointToCoord(point);
  64656. return this._radiusAxis.contain(coord[0])
  64657. && this._angleAxis.contain(coord[1]);
  64658. },
  64659. /**
  64660. * If contain data
  64661. * @param {Array.<number>} data
  64662. * @return {boolean}
  64663. */
  64664. containData: function (data) {
  64665. return this._radiusAxis.containData(data[0])
  64666. && this._angleAxis.containData(data[1]);
  64667. },
  64668. /**
  64669. * @param {string} dim
  64670. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64671. */
  64672. getAxis: function (dim) {
  64673. return this['_' + dim + 'Axis'];
  64674. },
  64675. /**
  64676. * @return {Array.<module:echarts/coord/Axis>}
  64677. */
  64678. getAxes: function () {
  64679. return [this._radiusAxis, this._angleAxis];
  64680. },
  64681. /**
  64682. * Get axes by type of scale
  64683. * @param {string} scaleType
  64684. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64685. */
  64686. getAxesByScale: function (scaleType) {
  64687. var axes = [];
  64688. var angleAxis = this._angleAxis;
  64689. var radiusAxis = this._radiusAxis;
  64690. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  64691. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  64692. return axes;
  64693. },
  64694. /**
  64695. * @return {module:echarts/coord/polar/AngleAxis}
  64696. */
  64697. getAngleAxis: function () {
  64698. return this._angleAxis;
  64699. },
  64700. /**
  64701. * @return {module:echarts/coord/polar/RadiusAxis}
  64702. */
  64703. getRadiusAxis: function () {
  64704. return this._radiusAxis;
  64705. },
  64706. /**
  64707. * @param {module:echarts/coord/polar/Axis}
  64708. * @return {module:echarts/coord/polar/Axis}
  64709. */
  64710. getOtherAxis: function (axis) {
  64711. var angleAxis = this._angleAxis;
  64712. return axis === angleAxis ? this._radiusAxis : angleAxis;
  64713. },
  64714. /**
  64715. * Base axis will be used on stacking.
  64716. *
  64717. * @return {module:echarts/coord/polar/Axis}
  64718. */
  64719. getBaseAxis: function () {
  64720. return this.getAxesByScale('ordinal')[0]
  64721. || this.getAxesByScale('time')[0]
  64722. || this.getAngleAxis();
  64723. },
  64724. /**
  64725. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  64726. * @return {Object} {baseAxes: [], otherAxes: []}
  64727. */
  64728. getTooltipAxes: function (dim) {
  64729. var baseAxis = (dim != null && dim !== 'auto')
  64730. ? this.getAxis(dim) : this.getBaseAxis();
  64731. return {
  64732. baseAxes: [baseAxis],
  64733. otherAxes: [this.getOtherAxis(baseAxis)]
  64734. };
  64735. },
  64736. /**
  64737. * Convert a single data item to (x, y) point.
  64738. * Parameter data is an array which the first element is radius and the second is angle
  64739. * @param {Array.<number>} data
  64740. * @param {boolean} [clamp=false]
  64741. * @return {Array.<number>}
  64742. */
  64743. dataToPoint: function (data, clamp) {
  64744. return this.coordToPoint([
  64745. this._radiusAxis.dataToRadius(data[0], clamp),
  64746. this._angleAxis.dataToAngle(data[1], clamp)
  64747. ]);
  64748. },
  64749. /**
  64750. * Convert a (x, y) point to data
  64751. * @param {Array.<number>} point
  64752. * @param {boolean} [clamp=false]
  64753. * @return {Array.<number>}
  64754. */
  64755. pointToData: function (point, clamp) {
  64756. var coord = this.pointToCoord(point);
  64757. return [
  64758. this._radiusAxis.radiusToData(coord[0], clamp),
  64759. this._angleAxis.angleToData(coord[1], clamp)
  64760. ];
  64761. },
  64762. /**
  64763. * Convert a (x, y) point to (radius, angle) coord
  64764. * @param {Array.<number>} point
  64765. * @return {Array.<number>}
  64766. */
  64767. pointToCoord: function (point) {
  64768. var dx = point[0] - this.cx;
  64769. var dy = point[1] - this.cy;
  64770. var angleAxis = this.getAngleAxis();
  64771. var extent = angleAxis.getExtent();
  64772. var minAngle = Math.min(extent[0], extent[1]);
  64773. var maxAngle = Math.max(extent[0], extent[1]);
  64774. // Fix fixed extent in polarCreator
  64775. // FIXME
  64776. angleAxis.inverse
  64777. ? (minAngle = maxAngle - 360)
  64778. : (maxAngle = minAngle + 360);
  64779. var radius = Math.sqrt(dx * dx + dy * dy);
  64780. dx /= radius;
  64781. dy /= radius;
  64782. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  64783. // move to angleExtent
  64784. var dir = radian < minAngle ? 1 : -1;
  64785. while (radian < minAngle || radian > maxAngle) {
  64786. radian += dir * 360;
  64787. }
  64788. return [radius, radian];
  64789. },
  64790. /**
  64791. * Convert a (radius, angle) coord to (x, y) point
  64792. * @param {Array.<number>} coord
  64793. * @return {Array.<number>}
  64794. */
  64795. coordToPoint: function (coord) {
  64796. var radius = coord[0];
  64797. var radian = coord[1] / 180 * Math.PI;
  64798. var x = Math.cos(radian) * radius + this.cx;
  64799. // Inverse the y
  64800. var y = -Math.sin(radian) * radius + this.cy;
  64801. return [x, y];
  64802. },
  64803. /**
  64804. * Get ring area of cartesian.
  64805. * Area will have a contain function to determine if a point is in the coordinate system.
  64806. * @return {Ring}
  64807. */
  64808. getArea: function () {
  64809. var angleAxis = this.getAngleAxis();
  64810. var radiusAxis = this.getRadiusAxis();
  64811. var radiusExtent = radiusAxis.getExtent().slice();
  64812. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  64813. var angleExtent = angleAxis.getExtent();
  64814. var RADIAN = Math.PI / 180;
  64815. return {
  64816. cx: this.cx,
  64817. cy: this.cy,
  64818. r0: radiusExtent[0],
  64819. r: radiusExtent[1],
  64820. startAngle: -angleExtent[0] * RADIAN,
  64821. endAngle: -angleExtent[1] * RADIAN,
  64822. clockwise: angleAxis.inverse,
  64823. contain: function (x, y) {
  64824. // It's a ring shape.
  64825. // Start angle and end angle don't matter
  64826. var dx = x - this.cx;
  64827. var dy = y - this.cy;
  64828. var d2 = dx * dx + dy * dy;
  64829. var r = this.r;
  64830. var r0 = this.r0;
  64831. return d2 <= r * r && d2 >= r0 * r0;
  64832. }
  64833. };
  64834. }
  64835. };
  64836. /*
  64837. * Licensed to the Apache Software Foundation (ASF) under one
  64838. * or more contributor license agreements. See the NOTICE file
  64839. * distributed with this work for additional information
  64840. * regarding copyright ownership. The ASF licenses this file
  64841. * to you under the Apache License, Version 2.0 (the
  64842. * "License"); you may not use this file except in compliance
  64843. * with the License. You may obtain a copy of the License at
  64844. *
  64845. * http://www.apache.org/licenses/LICENSE-2.0
  64846. *
  64847. * Unless required by applicable law or agreed to in writing,
  64848. * software distributed under the License is distributed on an
  64849. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64850. * KIND, either express or implied. See the License for the
  64851. * specific language governing permissions and limitations
  64852. * under the License.
  64853. */
  64854. var PolarAxisModel = ComponentModel.extend({
  64855. type: 'polarAxis',
  64856. /**
  64857. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  64858. */
  64859. axis: null,
  64860. /**
  64861. * @override
  64862. */
  64863. getCoordSysModel: function () {
  64864. return this.ecModel.queryComponents({
  64865. mainType: 'polar',
  64866. index: this.option.polarIndex,
  64867. id: this.option.polarId
  64868. })[0];
  64869. }
  64870. });
  64871. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  64872. var polarAxisDefaultExtendedOption = {
  64873. angle: {
  64874. // polarIndex: 0,
  64875. // polarId: '',
  64876. startAngle: 90,
  64877. clockwise: true,
  64878. splitNumber: 12,
  64879. axisLabel: {
  64880. rotate: false
  64881. }
  64882. },
  64883. radius: {
  64884. // polarIndex: 0,
  64885. // polarId: '',
  64886. splitNumber: 5
  64887. }
  64888. };
  64889. function getAxisType$3(axisDim, option) {
  64890. // Default axis with data is category axis
  64891. return option.type || (option.data ? 'category' : 'value');
  64892. }
  64893. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  64894. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  64895. /*
  64896. * Licensed to the Apache Software Foundation (ASF) under one
  64897. * or more contributor license agreements. See the NOTICE file
  64898. * distributed with this work for additional information
  64899. * regarding copyright ownership. The ASF licenses this file
  64900. * to you under the Apache License, Version 2.0 (the
  64901. * "License"); you may not use this file except in compliance
  64902. * with the License. You may obtain a copy of the License at
  64903. *
  64904. * http://www.apache.org/licenses/LICENSE-2.0
  64905. *
  64906. * Unless required by applicable law or agreed to in writing,
  64907. * software distributed under the License is distributed on an
  64908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64909. * KIND, either express or implied. See the License for the
  64910. * specific language governing permissions and limitations
  64911. * under the License.
  64912. */
  64913. extendComponentModel({
  64914. type: 'polar',
  64915. dependencies: ['polarAxis', 'angleAxis'],
  64916. /**
  64917. * @type {module:echarts/coord/polar/Polar}
  64918. */
  64919. coordinateSystem: null,
  64920. /**
  64921. * @param {string} axisType
  64922. * @return {module:echarts/coord/polar/AxisModel}
  64923. */
  64924. findAxisModel: function (axisType) {
  64925. var foundAxisModel;
  64926. var ecModel = this.ecModel;
  64927. ecModel.eachComponent(axisType, function (axisModel) {
  64928. if (axisModel.getCoordSysModel() === this) {
  64929. foundAxisModel = axisModel;
  64930. }
  64931. }, this);
  64932. return foundAxisModel;
  64933. },
  64934. defaultOption: {
  64935. zlevel: 0,
  64936. z: 0,
  64937. center: ['50%', '50%'],
  64938. radius: '80%'
  64939. }
  64940. });
  64941. /*
  64942. * Licensed to the Apache Software Foundation (ASF) under one
  64943. * or more contributor license agreements. See the NOTICE file
  64944. * distributed with this work for additional information
  64945. * regarding copyright ownership. The ASF licenses this file
  64946. * to you under the Apache License, Version 2.0 (the
  64947. * "License"); you may not use this file except in compliance
  64948. * with the License. You may obtain a copy of the License at
  64949. *
  64950. * http://www.apache.org/licenses/LICENSE-2.0
  64951. *
  64952. * Unless required by applicable law or agreed to in writing,
  64953. * software distributed under the License is distributed on an
  64954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64955. * KIND, either express or implied. See the License for the
  64956. * specific language governing permissions and limitations
  64957. * under the License.
  64958. */
  64959. // TODO Axis scale
  64960. /**
  64961. * Resize method bound to the polar
  64962. * @param {module:echarts/coord/polar/PolarModel} polarModel
  64963. * @param {module:echarts/ExtensionAPI} api
  64964. */
  64965. function resizePolar(polar, polarModel, api) {
  64966. var center = polarModel.get('center');
  64967. var width = api.getWidth();
  64968. var height = api.getHeight();
  64969. polar.cx = parsePercent$1(center[0], width);
  64970. polar.cy = parsePercent$1(center[1], height);
  64971. var radiusAxis = polar.getRadiusAxis();
  64972. var size = Math.min(width, height) / 2;
  64973. var radius = polarModel.get('radius');
  64974. if (radius == null) {
  64975. radius = [0, '100%'];
  64976. }
  64977. else if (!isArray(radius)) {
  64978. // r0 = 0
  64979. radius = [0, radius];
  64980. }
  64981. radius = [
  64982. parsePercent$1(radius[0], size),
  64983. parsePercent$1(radius[1], size)
  64984. ];
  64985. radiusAxis.inverse
  64986. ? radiusAxis.setExtent(radius[1], radius[0])
  64987. : radiusAxis.setExtent(radius[0], radius[1]);
  64988. }
  64989. /**
  64990. * Update polar
  64991. */
  64992. function updatePolarScale(ecModel, api) {
  64993. var polar = this;
  64994. var angleAxis = polar.getAngleAxis();
  64995. var radiusAxis = polar.getRadiusAxis();
  64996. // Reset scale
  64997. angleAxis.scale.setExtent(Infinity, -Infinity);
  64998. radiusAxis.scale.setExtent(Infinity, -Infinity);
  64999. ecModel.eachSeries(function (seriesModel) {
  65000. if (seriesModel.coordinateSystem === polar) {
  65001. var data = seriesModel.getData();
  65002. each$1(data.mapDimension('radius', true), function (dim) {
  65003. radiusAxis.scale.unionExtentFromData(
  65004. data, getStackedDimension(data, dim)
  65005. );
  65006. });
  65007. each$1(data.mapDimension('angle', true), function (dim) {
  65008. angleAxis.scale.unionExtentFromData(
  65009. data, getStackedDimension(data, dim)
  65010. );
  65011. });
  65012. }
  65013. });
  65014. niceScaleExtent(angleAxis.scale, angleAxis.model);
  65015. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  65016. // Fix extent of category angle axis
  65017. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  65018. var extent = angleAxis.getExtent();
  65019. var diff = 360 / angleAxis.scale.count();
  65020. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  65021. angleAxis.setExtent(extent[0], extent[1]);
  65022. }
  65023. }
  65024. /**
  65025. * Set common axis properties
  65026. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65027. * @param {module:echarts/coord/polar/AxisModel}
  65028. * @inner
  65029. */
  65030. function setAxis(axis, axisModel) {
  65031. axis.type = axisModel.get('type');
  65032. axis.scale = createScaleByModel(axisModel);
  65033. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65034. axis.inverse = axisModel.get('inverse');
  65035. if (axisModel.mainType === 'angleAxis') {
  65036. axis.inverse ^= axisModel.get('clockwise');
  65037. var startAngle = axisModel.get('startAngle');
  65038. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65039. }
  65040. // Inject axis instance
  65041. axisModel.axis = axis;
  65042. axis.model = axisModel;
  65043. }
  65044. var polarCreator = {
  65045. dimensions: Polar.prototype.dimensions,
  65046. create: function (ecModel, api) {
  65047. var polarList = [];
  65048. ecModel.eachComponent('polar', function (polarModel, idx) {
  65049. var polar = new Polar(idx);
  65050. // Inject resize and update method
  65051. polar.update = updatePolarScale;
  65052. var radiusAxis = polar.getRadiusAxis();
  65053. var angleAxis = polar.getAngleAxis();
  65054. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65055. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65056. setAxis(radiusAxis, radiusAxisModel);
  65057. setAxis(angleAxis, angleAxisModel);
  65058. resizePolar(polar, polarModel, api);
  65059. polarList.push(polar);
  65060. polarModel.coordinateSystem = polar;
  65061. polar.model = polarModel;
  65062. });
  65063. // Inject coordinateSystem to series
  65064. ecModel.eachSeries(function (seriesModel) {
  65065. if (seriesModel.get('coordinateSystem') === 'polar') {
  65066. var polarModel = ecModel.queryComponents({
  65067. mainType: 'polar',
  65068. index: seriesModel.get('polarIndex'),
  65069. id: seriesModel.get('polarId')
  65070. })[0];
  65071. if (__DEV__) {
  65072. if (!polarModel) {
  65073. throw new Error(
  65074. 'Polar "' + retrieve(
  65075. seriesModel.get('polarIndex'),
  65076. seriesModel.get('polarId'),
  65077. 0
  65078. ) + '" not found'
  65079. );
  65080. }
  65081. }
  65082. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65083. }
  65084. });
  65085. return polarList;
  65086. }
  65087. };
  65088. CoordinateSystemManager.register('polar', polarCreator);
  65089. /*
  65090. * Licensed to the Apache Software Foundation (ASF) under one
  65091. * or more contributor license agreements. See the NOTICE file
  65092. * distributed with this work for additional information
  65093. * regarding copyright ownership. The ASF licenses this file
  65094. * to you under the Apache License, Version 2.0 (the
  65095. * "License"); you may not use this file except in compliance
  65096. * with the License. You may obtain a copy of the License at
  65097. *
  65098. * http://www.apache.org/licenses/LICENSE-2.0
  65099. *
  65100. * Unless required by applicable law or agreed to in writing,
  65101. * software distributed under the License is distributed on an
  65102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65103. * KIND, either express or implied. See the License for the
  65104. * specific language governing permissions and limitations
  65105. * under the License.
  65106. */
  65107. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  65108. function getAxisLineShape(polar, rExtent, angle) {
  65109. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65110. var start = polar.coordToPoint([rExtent[0], angle]);
  65111. var end = polar.coordToPoint([rExtent[1], angle]);
  65112. return {
  65113. x1: start[0],
  65114. y1: start[1],
  65115. x2: end[0],
  65116. y2: end[1]
  65117. };
  65118. }
  65119. function getRadiusIdx(polar) {
  65120. var radiusAxis = polar.getRadiusAxis();
  65121. return radiusAxis.inverse ? 0 : 1;
  65122. }
  65123. // Remove the last tick which will overlap the first tick
  65124. function fixAngleOverlap(list) {
  65125. var firstItem = list[0];
  65126. var lastItem = list[list.length - 1];
  65127. if (firstItem
  65128. && lastItem
  65129. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65130. ) {
  65131. list.pop();
  65132. }
  65133. }
  65134. AxisView.extend({
  65135. type: 'angleAxis',
  65136. axisPointerClass: 'PolarAxisPointer',
  65137. render: function (angleAxisModel, ecModel) {
  65138. this.group.removeAll();
  65139. if (!angleAxisModel.get('show')) {
  65140. return;
  65141. }
  65142. var angleAxis = angleAxisModel.axis;
  65143. var polar = angleAxis.polar;
  65144. var radiusExtent = polar.getRadiusAxis().getExtent();
  65145. var ticksAngles = angleAxis.getTicksCoords();
  65146. var minorTickAngles = angleAxis.getMinorTicksCoords();
  65147. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65148. var labelItem = clone(labelItem);
  65149. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65150. return labelItem;
  65151. });
  65152. fixAngleOverlap(labels);
  65153. fixAngleOverlap(ticksAngles);
  65154. each$1(elementList$1, function (name) {
  65155. if (angleAxisModel.get(name + '.show')
  65156. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65157. ) {
  65158. this['_' + name](angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  65159. }
  65160. }, this);
  65161. },
  65162. /**
  65163. * @private
  65164. */
  65165. _axisLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65166. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65167. // extent id of the axis radius (r0 and r)
  65168. var rId = getRadiusIdx(polar);
  65169. var r0Id = rId ? 0 : 1;
  65170. var shape;
  65171. if (radiusExtent[r0Id] === 0) {
  65172. shape = new Circle({
  65173. shape: {
  65174. cx: polar.cx,
  65175. cy: polar.cy,
  65176. r: radiusExtent[rId]
  65177. },
  65178. style: lineStyleModel.getLineStyle(),
  65179. z2: 1,
  65180. silent: true
  65181. });
  65182. }
  65183. else {
  65184. shape = new Ring({
  65185. shape: {
  65186. cx: polar.cx,
  65187. cy: polar.cy,
  65188. r: radiusExtent[rId],
  65189. r0: radiusExtent[r0Id]
  65190. },
  65191. style: lineStyleModel.getLineStyle(),
  65192. z2: 1,
  65193. silent: true
  65194. });
  65195. }
  65196. shape.style.fill = null;
  65197. this.group.add(shape);
  65198. },
  65199. /**
  65200. * @private
  65201. */
  65202. _axisTick: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65203. var tickModel = angleAxisModel.getModel('axisTick');
  65204. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65205. var radius = radiusExtent[getRadiusIdx(polar)];
  65206. var lines = map(ticksAngles, function (tickAngleItem) {
  65207. return new Line({
  65208. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65209. });
  65210. });
  65211. this.group.add(mergePath(
  65212. lines, {
  65213. style: defaults(
  65214. tickModel.getModel('lineStyle').getLineStyle(),
  65215. {
  65216. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65217. }
  65218. )
  65219. }
  65220. ));
  65221. },
  65222. /**
  65223. * @private
  65224. */
  65225. _minorTick: function (angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  65226. if (!minorTickAngles.length) {
  65227. return;
  65228. }
  65229. var tickModel = angleAxisModel.getModel('axisTick');
  65230. var minorTickModel = angleAxisModel.getModel('minorTick');
  65231. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  65232. var radius = radiusExtent[getRadiusIdx(polar)];
  65233. var lines = [];
  65234. for (var i = 0; i < minorTickAngles.length; i++) {
  65235. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65236. lines.push(new Line({
  65237. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  65238. }));
  65239. }
  65240. }
  65241. this.group.add(mergePath(
  65242. lines, {
  65243. style: defaults(
  65244. minorTickModel.getModel('lineStyle').getLineStyle(),
  65245. defaults(
  65246. tickModel.getLineStyle(), {
  65247. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65248. }
  65249. )
  65250. )
  65251. }
  65252. ));
  65253. },
  65254. /**
  65255. * @private
  65256. */
  65257. _axisLabel: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  65258. var rawCategoryData = angleAxisModel.getCategories(true);
  65259. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65260. var labelMargin = commonLabelModel.get('margin');
  65261. var triggerEvent = angleAxisModel.get('triggerEvent');
  65262. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65263. each$1(labels, function (labelItem, idx) {
  65264. var labelModel = commonLabelModel;
  65265. var tickValue = labelItem.tickValue;
  65266. var r = radiusExtent[getRadiusIdx(polar)];
  65267. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65268. var cx = polar.cx;
  65269. var cy = polar.cy;
  65270. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65271. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65272. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  65273. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  65274. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  65275. labelModel = new Model(
  65276. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  65277. );
  65278. }
  65279. var textEl = new Text({
  65280. silent: AxisBuilder.isLabelSilent(angleAxisModel)
  65281. });
  65282. this.group.add(textEl);
  65283. setTextStyle(textEl.style, labelModel, {
  65284. x: p[0],
  65285. y: p[1],
  65286. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  65287. text: labelItem.formattedLabel,
  65288. textAlign: labelTextAlign,
  65289. textVerticalAlign: labelTextVerticalAlign
  65290. });
  65291. // Pack data for mouse event
  65292. if (triggerEvent) {
  65293. textEl.eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  65294. textEl.eventData.targetType = 'axisLabel';
  65295. textEl.eventData.value = labelItem.rawLabel;
  65296. }
  65297. }, this);
  65298. },
  65299. /**
  65300. * @private
  65301. */
  65302. _splitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65303. var splitLineModel = angleAxisModel.getModel('splitLine');
  65304. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65305. var lineColors = lineStyleModel.get('color');
  65306. var lineCount = 0;
  65307. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65308. var splitLines = [];
  65309. for (var i = 0; i < ticksAngles.length; i++) {
  65310. var colorIndex = (lineCount++) % lineColors.length;
  65311. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65312. splitLines[colorIndex].push(new Line({
  65313. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65314. }));
  65315. }
  65316. // Simple optimization
  65317. // Batching the lines if color are the same
  65318. for (var i = 0; i < splitLines.length; i++) {
  65319. this.group.add(mergePath(splitLines[i], {
  65320. style: defaults({
  65321. stroke: lineColors[i % lineColors.length]
  65322. }, lineStyleModel.getLineStyle()),
  65323. silent: true,
  65324. z: angleAxisModel.get('z')
  65325. }));
  65326. }
  65327. },
  65328. /**
  65329. * @private
  65330. */
  65331. _minorSplitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65332. if (!minorTickAngles.length) {
  65333. return;
  65334. }
  65335. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  65336. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65337. var lines = [];
  65338. for (var i = 0; i < minorTickAngles.length; i++) {
  65339. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65340. lines.push(new Line({
  65341. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  65342. }));
  65343. }
  65344. }
  65345. this.group.add(mergePath(lines, {
  65346. style: lineStyleModel.getLineStyle(),
  65347. silent: true,
  65348. z: angleAxisModel.get('z')
  65349. }));
  65350. },
  65351. /**
  65352. * @private
  65353. */
  65354. _splitArea: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65355. if (!ticksAngles.length) {
  65356. return;
  65357. }
  65358. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65359. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65360. var areaColors = areaStyleModel.get('color');
  65361. var lineCount = 0;
  65362. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65363. var splitAreas = [];
  65364. var RADIAN = Math.PI / 180;
  65365. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65366. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65367. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65368. var clockwise = angleAxisModel.get('clockwise');
  65369. for (var i = 1; i < ticksAngles.length; i++) {
  65370. var colorIndex = (lineCount++) % areaColors.length;
  65371. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65372. splitAreas[colorIndex].push(new Sector({
  65373. shape: {
  65374. cx: polar.cx,
  65375. cy: polar.cy,
  65376. r0: r0,
  65377. r: r1,
  65378. startAngle: prevAngle,
  65379. endAngle: -ticksAngles[i].coord * RADIAN,
  65380. clockwise: clockwise
  65381. },
  65382. silent: true
  65383. }));
  65384. prevAngle = -ticksAngles[i].coord * RADIAN;
  65385. }
  65386. // Simple optimization
  65387. // Batching the lines if color are the same
  65388. for (var i = 0; i < splitAreas.length; i++) {
  65389. this.group.add(mergePath(splitAreas[i], {
  65390. style: defaults({
  65391. fill: areaColors[i % areaColors.length]
  65392. }, areaStyleModel.getAreaStyle()),
  65393. silent: true
  65394. }));
  65395. }
  65396. }
  65397. });
  65398. /*
  65399. * Licensed to the Apache Software Foundation (ASF) under one
  65400. * or more contributor license agreements. See the NOTICE file
  65401. * distributed with this work for additional information
  65402. * regarding copyright ownership. The ASF licenses this file
  65403. * to you under the Apache License, Version 2.0 (the
  65404. * "License"); you may not use this file except in compliance
  65405. * with the License. You may obtain a copy of the License at
  65406. *
  65407. * http://www.apache.org/licenses/LICENSE-2.0
  65408. *
  65409. * Unless required by applicable law or agreed to in writing,
  65410. * software distributed under the License is distributed on an
  65411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65412. * KIND, either express or implied. See the License for the
  65413. * specific language governing permissions and limitations
  65414. * under the License.
  65415. */
  65416. /*
  65417. * Licensed to the Apache Software Foundation (ASF) under one
  65418. * or more contributor license agreements. See the NOTICE file
  65419. * distributed with this work for additional information
  65420. * regarding copyright ownership. The ASF licenses this file
  65421. * to you under the Apache License, Version 2.0 (the
  65422. * "License"); you may not use this file except in compliance
  65423. * with the License. You may obtain a copy of the License at
  65424. *
  65425. * http://www.apache.org/licenses/LICENSE-2.0
  65426. *
  65427. * Unless required by applicable law or agreed to in writing,
  65428. * software distributed under the License is distributed on an
  65429. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65430. * KIND, either express or implied. See the License for the
  65431. * specific language governing permissions and limitations
  65432. * under the License.
  65433. */
  65434. var axisBuilderAttrs$3 = [
  65435. 'axisLine', 'axisTickLabel', 'axisName'
  65436. ];
  65437. var selfBuilderAttrs$1 = [
  65438. 'splitLine', 'splitArea', 'minorSplitLine'
  65439. ];
  65440. AxisView.extend({
  65441. type: 'radiusAxis',
  65442. axisPointerClass: 'PolarAxisPointer',
  65443. render: function (radiusAxisModel, ecModel) {
  65444. this.group.removeAll();
  65445. if (!radiusAxisModel.get('show')) {
  65446. return;
  65447. }
  65448. var radiusAxis = radiusAxisModel.axis;
  65449. var polar = radiusAxis.polar;
  65450. var angleAxis = polar.getAngleAxis();
  65451. var ticksCoords = radiusAxis.getTicksCoords();
  65452. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  65453. var axisAngle = angleAxis.getExtent()[0];
  65454. var radiusExtent = radiusAxis.getExtent();
  65455. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  65456. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  65457. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  65458. this.group.add(axisBuilder.getGroup());
  65459. each$1(selfBuilderAttrs$1, function (name) {
  65460. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  65461. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  65462. }
  65463. }, this);
  65464. },
  65465. /**
  65466. * @private
  65467. */
  65468. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65469. var splitLineModel = radiusAxisModel.getModel('splitLine');
  65470. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65471. var lineColors = lineStyleModel.get('color');
  65472. var lineCount = 0;
  65473. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65474. var splitLines = [];
  65475. for (var i = 0; i < ticksCoords.length; i++) {
  65476. var colorIndex = (lineCount++) % lineColors.length;
  65477. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65478. splitLines[colorIndex].push(new Circle({
  65479. shape: {
  65480. cx: polar.cx,
  65481. cy: polar.cy,
  65482. r: ticksCoords[i].coord
  65483. }
  65484. }));
  65485. }
  65486. // Simple optimization
  65487. // Batching the lines if color are the same
  65488. for (var i = 0; i < splitLines.length; i++) {
  65489. this.group.add(mergePath(splitLines[i], {
  65490. style: defaults({
  65491. stroke: lineColors[i % lineColors.length],
  65492. fill: null
  65493. }, lineStyleModel.getLineStyle()),
  65494. silent: true
  65495. }));
  65496. }
  65497. },
  65498. /**
  65499. * @private
  65500. */
  65501. _minorSplitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  65502. if (!minorTicksCoords.length) {
  65503. return;
  65504. }
  65505. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  65506. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65507. var lines = [];
  65508. for (var i = 0; i < minorTicksCoords.length; i++) {
  65509. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  65510. lines.push(new Circle({
  65511. shape: {
  65512. cx: polar.cx,
  65513. cy: polar.cy,
  65514. r: minorTicksCoords[i][k].coord
  65515. }
  65516. }));
  65517. }
  65518. }
  65519. this.group.add(mergePath(lines, {
  65520. style: defaults({
  65521. fill: null
  65522. }, lineStyleModel.getLineStyle()),
  65523. silent: true
  65524. }));
  65525. },
  65526. /**
  65527. * @private
  65528. */
  65529. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65530. if (!ticksCoords.length) {
  65531. return;
  65532. }
  65533. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  65534. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65535. var areaColors = areaStyleModel.get('color');
  65536. var lineCount = 0;
  65537. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65538. var splitAreas = [];
  65539. var prevRadius = ticksCoords[0].coord;
  65540. for (var i = 1; i < ticksCoords.length; i++) {
  65541. var colorIndex = (lineCount++) % areaColors.length;
  65542. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65543. splitAreas[colorIndex].push(new Sector({
  65544. shape: {
  65545. cx: polar.cx,
  65546. cy: polar.cy,
  65547. r0: prevRadius,
  65548. r: ticksCoords[i].coord,
  65549. startAngle: 0,
  65550. endAngle: Math.PI * 2
  65551. },
  65552. silent: true
  65553. }));
  65554. prevRadius = ticksCoords[i].coord;
  65555. }
  65556. // Simple optimization
  65557. // Batching the lines if color are the same
  65558. for (var i = 0; i < splitAreas.length; i++) {
  65559. this.group.add(mergePath(splitAreas[i], {
  65560. style: defaults({
  65561. fill: areaColors[i % areaColors.length]
  65562. }, areaStyleModel.getAreaStyle()),
  65563. silent: true
  65564. }));
  65565. }
  65566. }
  65567. });
  65568. /**
  65569. * @inner
  65570. */
  65571. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  65572. return {
  65573. position: [polar.cx, polar.cy],
  65574. rotation: axisAngle / 180 * Math.PI,
  65575. labelDirection: -1,
  65576. tickDirection: -1,
  65577. nameDirection: 1,
  65578. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  65579. // Over splitLine and splitArea
  65580. z2: 1
  65581. };
  65582. }
  65583. /*
  65584. * Licensed to the Apache Software Foundation (ASF) under one
  65585. * or more contributor license agreements. See the NOTICE file
  65586. * distributed with this work for additional information
  65587. * regarding copyright ownership. The ASF licenses this file
  65588. * to you under the Apache License, Version 2.0 (the
  65589. * "License"); you may not use this file except in compliance
  65590. * with the License. You may obtain a copy of the License at
  65591. *
  65592. * http://www.apache.org/licenses/LICENSE-2.0
  65593. *
  65594. * Unless required by applicable law or agreed to in writing,
  65595. * software distributed under the License is distributed on an
  65596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65597. * KIND, either express or implied. See the License for the
  65598. * specific language governing permissions and limitations
  65599. * under the License.
  65600. */
  65601. /*
  65602. * Licensed to the Apache Software Foundation (ASF) under one
  65603. * or more contributor license agreements. See the NOTICE file
  65604. * distributed with this work for additional information
  65605. * regarding copyright ownership. The ASF licenses this file
  65606. * to you under the Apache License, Version 2.0 (the
  65607. * "License"); you may not use this file except in compliance
  65608. * with the License. You may obtain a copy of the License at
  65609. *
  65610. * http://www.apache.org/licenses/LICENSE-2.0
  65611. *
  65612. * Unless required by applicable law or agreed to in writing,
  65613. * software distributed under the License is distributed on an
  65614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65615. * KIND, either express or implied. See the License for the
  65616. * specific language governing permissions and limitations
  65617. * under the License.
  65618. */
  65619. var PolarAxisPointer = BaseAxisPointer.extend({
  65620. /**
  65621. * @override
  65622. */
  65623. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  65624. var axis = axisModel.axis;
  65625. if (axis.dim === 'angle') {
  65626. this.animationThreshold = Math.PI / 18;
  65627. }
  65628. var polar = axis.polar;
  65629. var otherAxis = polar.getOtherAxis(axis);
  65630. var otherExtent = otherAxis.getExtent();
  65631. var coordValue;
  65632. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  65633. var axisPointerType = axisPointerModel.get('type');
  65634. if (axisPointerType && axisPointerType !== 'none') {
  65635. var elStyle = buildElStyle(axisPointerModel);
  65636. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  65637. axis, polar, coordValue, otherExtent, elStyle
  65638. );
  65639. pointerOption.style = elStyle;
  65640. elOption.graphicKey = pointerOption.type;
  65641. elOption.pointer = pointerOption;
  65642. }
  65643. var labelMargin = axisPointerModel.get('label.margin');
  65644. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65645. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65646. }
  65647. // Do not support handle, utill any user requires it.
  65648. });
  65649. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65650. var axis = axisModel.axis;
  65651. var coord = axis.dataToCoord(value);
  65652. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65653. axisAngle = axisAngle / 180 * Math.PI;
  65654. var radiusExtent = polar.getRadiusAxis().getExtent();
  65655. var position;
  65656. var align;
  65657. var verticalAlign;
  65658. if (axis.dim === 'radius') {
  65659. var transform = create$1();
  65660. rotate(transform, transform, axisAngle);
  65661. translate(transform, transform, [polar.cx, polar.cy]);
  65662. position = applyTransform$1([coord, -labelMargin], transform);
  65663. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  65664. var labelLayout = AxisBuilder.innerTextLayout(
  65665. axisAngle, labelRotation * Math.PI / 180, -1
  65666. );
  65667. align = labelLayout.textAlign;
  65668. verticalAlign = labelLayout.textVerticalAlign;
  65669. }
  65670. else { // angle axis
  65671. var r = radiusExtent[1];
  65672. position = polar.coordToPoint([r + labelMargin, coord]);
  65673. var cx = polar.cx;
  65674. var cy = polar.cy;
  65675. align = Math.abs(position[0] - cx) / r < 0.3
  65676. ? 'center' : (position[0] > cx ? 'left' : 'right');
  65677. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  65678. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  65679. }
  65680. return {
  65681. position: position,
  65682. align: align,
  65683. verticalAlign: verticalAlign
  65684. };
  65685. }
  65686. var pointerShapeBuilder$2 = {
  65687. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  65688. return axis.dim === 'angle'
  65689. ? {
  65690. type: 'Line',
  65691. shape: makeLineShape(
  65692. polar.coordToPoint([otherExtent[0], coordValue]),
  65693. polar.coordToPoint([otherExtent[1], coordValue])
  65694. )
  65695. }
  65696. : {
  65697. type: 'Circle',
  65698. shape: {
  65699. cx: polar.cx,
  65700. cy: polar.cy,
  65701. r: coordValue
  65702. }
  65703. };
  65704. },
  65705. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  65706. var bandWidth = Math.max(1, axis.getBandWidth());
  65707. var radian = Math.PI / 180;
  65708. return axis.dim === 'angle'
  65709. ? {
  65710. type: 'Sector',
  65711. shape: makeSectorShape(
  65712. polar.cx, polar.cy,
  65713. otherExtent[0], otherExtent[1],
  65714. // In ECharts y is negative if angle is positive
  65715. (-coordValue - bandWidth / 2) * radian,
  65716. (-coordValue + bandWidth / 2) * radian
  65717. )
  65718. }
  65719. : {
  65720. type: 'Sector',
  65721. shape: makeSectorShape(
  65722. polar.cx, polar.cy,
  65723. coordValue - bandWidth / 2,
  65724. coordValue + bandWidth / 2,
  65725. 0, Math.PI * 2
  65726. )
  65727. };
  65728. }
  65729. };
  65730. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  65731. /*
  65732. * Licensed to the Apache Software Foundation (ASF) under one
  65733. * or more contributor license agreements. See the NOTICE file
  65734. * distributed with this work for additional information
  65735. * regarding copyright ownership. The ASF licenses this file
  65736. * to you under the Apache License, Version 2.0 (the
  65737. * "License"); you may not use this file except in compliance
  65738. * with the License. You may obtain a copy of the License at
  65739. *
  65740. * http://www.apache.org/licenses/LICENSE-2.0
  65741. *
  65742. * Unless required by applicable law or agreed to in writing,
  65743. * software distributed under the License is distributed on an
  65744. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65745. * KIND, either express or implied. See the License for the
  65746. * specific language governing permissions and limitations
  65747. * under the License.
  65748. */
  65749. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  65750. registerLayout(curry(barLayoutPolar, 'bar'));
  65751. // Polar view
  65752. extendComponentView({
  65753. type: 'polar'
  65754. });
  65755. /*
  65756. * Licensed to the Apache Software Foundation (ASF) under one
  65757. * or more contributor license agreements. See the NOTICE file
  65758. * distributed with this work for additional information
  65759. * regarding copyright ownership. The ASF licenses this file
  65760. * to you under the Apache License, Version 2.0 (the
  65761. * "License"); you may not use this file except in compliance
  65762. * with the License. You may obtain a copy of the License at
  65763. *
  65764. * http://www.apache.org/licenses/LICENSE-2.0
  65765. *
  65766. * Unless required by applicable law or agreed to in writing,
  65767. * software distributed under the License is distributed on an
  65768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65769. * KIND, either express or implied. See the License for the
  65770. * specific language governing permissions and limitations
  65771. * under the License.
  65772. */
  65773. var GeoModel = ComponentModel.extend({
  65774. type: 'geo',
  65775. /**
  65776. * @type {module:echarts/coord/geo/Geo}
  65777. */
  65778. coordinateSystem: null,
  65779. layoutMode: 'box',
  65780. init: function (option) {
  65781. ComponentModel.prototype.init.apply(this, arguments);
  65782. // Default label emphasis `show`
  65783. defaultEmphasis(option, 'label', ['show']);
  65784. },
  65785. optionUpdated: function () {
  65786. var option = this.option;
  65787. var self = this;
  65788. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  65789. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  65790. if (regionOpt.name) {
  65791. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  65792. }
  65793. return optionModelMap;
  65794. }, createHashMap());
  65795. this.updateSelectedMap(option.regions);
  65796. },
  65797. defaultOption: {
  65798. zlevel: 0,
  65799. z: 0,
  65800. show: true,
  65801. left: 'center',
  65802. top: 'center',
  65803. // width:,
  65804. // height:,
  65805. // right
  65806. // bottom
  65807. // Aspect is width / height. Inited to be geoJson bbox aspect
  65808. // This parameter is used for scale this aspect
  65809. // If svg used, aspectScale is 1 by default.
  65810. // aspectScale: 0.75,
  65811. aspectScale: null,
  65812. ///// Layout with center and size
  65813. // If you wan't to put map in a fixed size box with right aspect ratio
  65814. // This two properties may more conveninet
  65815. // layoutCenter: [50%, 50%]
  65816. // layoutSize: 100
  65817. silent: false,
  65818. // Map type
  65819. map: '',
  65820. // Define left-top, right-bottom coords to control view
  65821. // For example, [ [180, 90], [-180, -90] ]
  65822. boundingCoords: null,
  65823. // Default on center of map
  65824. center: null,
  65825. zoom: 1,
  65826. scaleLimit: null,
  65827. // selectedMode: false
  65828. label: {
  65829. show: false,
  65830. color: '#000'
  65831. },
  65832. itemStyle: {
  65833. // color: 各异,
  65834. borderWidth: 0.5,
  65835. borderColor: '#444',
  65836. color: '#eee'
  65837. },
  65838. emphasis: {
  65839. label: {
  65840. show: true,
  65841. color: 'rgb(100,0,0)'
  65842. },
  65843. itemStyle: {
  65844. color: 'rgba(255,215,0,0.8)'
  65845. }
  65846. },
  65847. regions: []
  65848. },
  65849. /**
  65850. * Get model of region
  65851. * @param {string} name
  65852. * @return {module:echarts/model/Model}
  65853. */
  65854. getRegionModel: function (name) {
  65855. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  65856. },
  65857. /**
  65858. * Format label
  65859. * @param {string} name Region name
  65860. * @param {string} [status='normal'] 'normal' or 'emphasis'
  65861. * @return {string}
  65862. */
  65863. getFormattedLabel: function (name, status) {
  65864. var regionModel = this.getRegionModel(name);
  65865. var formatter = regionModel.get(
  65866. 'label'
  65867. + (status === 'normal' ? '.' : status + '.')
  65868. + 'formatter'
  65869. );
  65870. var params = {
  65871. name: name
  65872. };
  65873. if (typeof formatter === 'function') {
  65874. params.status = status;
  65875. return formatter(params);
  65876. }
  65877. else if (typeof formatter === 'string') {
  65878. return formatter.replace('{a}', name != null ? name : '');
  65879. }
  65880. },
  65881. setZoom: function (zoom) {
  65882. this.option.zoom = zoom;
  65883. },
  65884. setCenter: function (center) {
  65885. this.option.center = center;
  65886. }
  65887. });
  65888. mixin(GeoModel, selectableMixin);
  65889. /*
  65890. * Licensed to the Apache Software Foundation (ASF) under one
  65891. * or more contributor license agreements. See the NOTICE file
  65892. * distributed with this work for additional information
  65893. * regarding copyright ownership. The ASF licenses this file
  65894. * to you under the Apache License, Version 2.0 (the
  65895. * "License"); you may not use this file except in compliance
  65896. * with the License. You may obtain a copy of the License at
  65897. *
  65898. * http://www.apache.org/licenses/LICENSE-2.0
  65899. *
  65900. * Unless required by applicable law or agreed to in writing,
  65901. * software distributed under the License is distributed on an
  65902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65903. * KIND, either express or implied. See the License for the
  65904. * specific language governing permissions and limitations
  65905. * under the License.
  65906. */
  65907. extendComponentView({
  65908. type: 'geo',
  65909. init: function (ecModel, api) {
  65910. var mapDraw = new MapDraw(api, true);
  65911. this._mapDraw = mapDraw;
  65912. this.group.add(mapDraw.group);
  65913. },
  65914. render: function (geoModel, ecModel, api, payload) {
  65915. // Not render if it is an toggleSelect action from self
  65916. if (payload && payload.type === 'geoToggleSelect'
  65917. && payload.from === this.uid
  65918. ) {
  65919. return;
  65920. }
  65921. var mapDraw = this._mapDraw;
  65922. if (geoModel.get('show')) {
  65923. mapDraw.draw(geoModel, ecModel, api, this, payload);
  65924. }
  65925. else {
  65926. this._mapDraw.group.removeAll();
  65927. }
  65928. this.group.silent = geoModel.get('silent');
  65929. },
  65930. dispose: function () {
  65931. this._mapDraw && this._mapDraw.remove();
  65932. }
  65933. });
  65934. /*
  65935. * Licensed to the Apache Software Foundation (ASF) under one
  65936. * or more contributor license agreements. See the NOTICE file
  65937. * distributed with this work for additional information
  65938. * regarding copyright ownership. The ASF licenses this file
  65939. * to you under the Apache License, Version 2.0 (the
  65940. * "License"); you may not use this file except in compliance
  65941. * with the License. You may obtain a copy of the License at
  65942. *
  65943. * http://www.apache.org/licenses/LICENSE-2.0
  65944. *
  65945. * Unless required by applicable law or agreed to in writing,
  65946. * software distributed under the License is distributed on an
  65947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65948. * KIND, either express or implied. See the License for the
  65949. * specific language governing permissions and limitations
  65950. * under the License.
  65951. */
  65952. function makeAction(method, actionInfo) {
  65953. actionInfo.update = 'updateView';
  65954. registerAction(actionInfo, function (payload, ecModel) {
  65955. var selected = {};
  65956. ecModel.eachComponent(
  65957. { mainType: 'geo', query: payload},
  65958. function (geoModel) {
  65959. geoModel[method](payload.name);
  65960. var geo = geoModel.coordinateSystem;
  65961. each$1(geo.regions, function (region) {
  65962. selected[region.name] = geoModel.isSelected(region.name) || false;
  65963. });
  65964. }
  65965. );
  65966. return {
  65967. selected: selected,
  65968. name: payload.name
  65969. };
  65970. });
  65971. }
  65972. makeAction('toggleSelected', {
  65973. type: 'geoToggleSelect',
  65974. event: 'geoselectchanged'
  65975. });
  65976. makeAction('select', {
  65977. type: 'geoSelect',
  65978. event: 'geoselected'
  65979. });
  65980. makeAction('unSelect', {
  65981. type: 'geoUnSelect',
  65982. event: 'geounselected'
  65983. });
  65984. /*
  65985. * Licensed to the Apache Software Foundation (ASF) under one
  65986. * or more contributor license agreements. See the NOTICE file
  65987. * distributed with this work for additional information
  65988. * regarding copyright ownership. The ASF licenses this file
  65989. * to you under the Apache License, Version 2.0 (the
  65990. * "License"); you may not use this file except in compliance
  65991. * with the License. You may obtain a copy of the License at
  65992. *
  65993. * http://www.apache.org/licenses/LICENSE-2.0
  65994. *
  65995. * Unless required by applicable law or agreed to in writing,
  65996. * software distributed under the License is distributed on an
  65997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65998. * KIND, either express or implied. See the License for the
  65999. * specific language governing permissions and limitations
  66000. * under the License.
  66001. */
  66002. // (24*60*60*1000)
  66003. var PROXIMATE_ONE_DAY = 86400000;
  66004. /**
  66005. * Calendar
  66006. *
  66007. * @constructor
  66008. *
  66009. * @param {Object} calendarModel calendarModel
  66010. * @param {Object} ecModel ecModel
  66011. * @param {Object} api api
  66012. */
  66013. function Calendar(calendarModel, ecModel, api) {
  66014. this._model = calendarModel;
  66015. }
  66016. Calendar.prototype = {
  66017. constructor: Calendar,
  66018. type: 'calendar',
  66019. dimensions: ['time', 'value'],
  66020. // Required in createListFromData
  66021. getDimensionsInfo: function () {
  66022. return [{name: 'time', type: 'time'}, 'value'];
  66023. },
  66024. getRangeInfo: function () {
  66025. return this._rangeInfo;
  66026. },
  66027. getModel: function () {
  66028. return this._model;
  66029. },
  66030. getRect: function () {
  66031. return this._rect;
  66032. },
  66033. getCellWidth: function () {
  66034. return this._sw;
  66035. },
  66036. getCellHeight: function () {
  66037. return this._sh;
  66038. },
  66039. getOrient: function () {
  66040. return this._orient;
  66041. },
  66042. /**
  66043. * getFirstDayOfWeek
  66044. *
  66045. * @example
  66046. * 0 : start at Sunday
  66047. * 1 : start at Monday
  66048. *
  66049. * @return {number}
  66050. */
  66051. getFirstDayOfWeek: function () {
  66052. return this._firstDayOfWeek;
  66053. },
  66054. /**
  66055. * get date info
  66056. *
  66057. * @param {string|number} date date
  66058. * @return {Object}
  66059. * {
  66060. * y: string, local full year, eg., '1940',
  66061. * m: string, local month, from '01' ot '12',
  66062. * d: string, local date, from '01' to '31' (if exists),
  66063. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  66064. * time: timestamp,
  66065. * formatedDate: string, yyyy-MM-dd,
  66066. * date: original date object.
  66067. * }
  66068. */
  66069. getDateInfo: function (date) {
  66070. date = parseDate(date);
  66071. var y = date.getFullYear();
  66072. var m = date.getMonth() + 1;
  66073. m = m < 10 ? '0' + m : m;
  66074. var d = date.getDate();
  66075. d = d < 10 ? '0' + d : d;
  66076. var day = date.getDay();
  66077. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  66078. return {
  66079. y: y,
  66080. m: m,
  66081. d: d,
  66082. day: day,
  66083. time: date.getTime(),
  66084. formatedDate: y + '-' + m + '-' + d,
  66085. date: date
  66086. };
  66087. },
  66088. getNextNDay: function (date, n) {
  66089. n = n || 0;
  66090. if (n === 0) {
  66091. return this.getDateInfo(date);
  66092. }
  66093. date = new Date(this.getDateInfo(date).time);
  66094. date.setDate(date.getDate() + n);
  66095. return this.getDateInfo(date);
  66096. },
  66097. update: function (ecModel, api) {
  66098. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  66099. this._orient = this._model.get('orient');
  66100. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  66101. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  66102. var weeks = this._rangeInfo.weeks || 1;
  66103. var whNames = ['width', 'height'];
  66104. var cellSize = this._model.get('cellSize').slice();
  66105. var layoutParams = this._model.getBoxLayoutParams();
  66106. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  66107. each$1([0, 1], function (idx) {
  66108. if (cellSizeSpecified(cellSize, idx)) {
  66109. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  66110. }
  66111. });
  66112. var whGlobal = {
  66113. width: api.getWidth(),
  66114. height: api.getHeight()
  66115. };
  66116. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  66117. each$1([0, 1], function (idx) {
  66118. if (!cellSizeSpecified(cellSize, idx)) {
  66119. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  66120. }
  66121. });
  66122. function cellSizeSpecified(cellSize, idx) {
  66123. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  66124. }
  66125. this._sw = cellSize[0];
  66126. this._sh = cellSize[1];
  66127. },
  66128. /**
  66129. * Convert a time data(time, value) item to (x, y) point.
  66130. *
  66131. * @override
  66132. * @param {Array|number} data data
  66133. * @param {boolean} [clamp=true] out of range
  66134. * @return {Array} point
  66135. */
  66136. dataToPoint: function (data, clamp) {
  66137. isArray(data) && (data = data[0]);
  66138. clamp == null && (clamp = true);
  66139. var dayInfo = this.getDateInfo(data);
  66140. var range = this._rangeInfo;
  66141. var date = dayInfo.formatedDate;
  66142. // if not in range return [NaN, NaN]
  66143. if (clamp && !(
  66144. dayInfo.time >= range.start.time
  66145. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  66146. )) {
  66147. return [NaN, NaN];
  66148. }
  66149. var week = dayInfo.day;
  66150. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  66151. if (this._orient === 'vertical') {
  66152. return [
  66153. this._rect.x + week * this._sw + this._sw / 2,
  66154. this._rect.y + nthWeek * this._sh + this._sh / 2
  66155. ];
  66156. }
  66157. return [
  66158. this._rect.x + nthWeek * this._sw + this._sw / 2,
  66159. this._rect.y + week * this._sh + this._sh / 2
  66160. ];
  66161. },
  66162. /**
  66163. * Convert a (x, y) point to time data
  66164. *
  66165. * @override
  66166. * @param {string} point point
  66167. * @return {string} data
  66168. */
  66169. pointToData: function (point) {
  66170. var date = this.pointToDate(point);
  66171. return date && date.time;
  66172. },
  66173. /**
  66174. * Convert a time date item to (x, y) four point.
  66175. *
  66176. * @param {Array} data date[0] is date
  66177. * @param {boolean} [clamp=true] out of range
  66178. * @return {Object} point
  66179. */
  66180. dataToRect: function (data, clamp) {
  66181. var point = this.dataToPoint(data, clamp);
  66182. return {
  66183. contentShape: {
  66184. x: point[0] - (this._sw - this._lineWidth) / 2,
  66185. y: point[1] - (this._sh - this._lineWidth) / 2,
  66186. width: this._sw - this._lineWidth,
  66187. height: this._sh - this._lineWidth
  66188. },
  66189. center: point,
  66190. tl: [
  66191. point[0] - this._sw / 2,
  66192. point[1] - this._sh / 2
  66193. ],
  66194. tr: [
  66195. point[0] + this._sw / 2,
  66196. point[1] - this._sh / 2
  66197. ],
  66198. br: [
  66199. point[0] + this._sw / 2,
  66200. point[1] + this._sh / 2
  66201. ],
  66202. bl: [
  66203. point[0] - this._sw / 2,
  66204. point[1] + this._sh / 2
  66205. ]
  66206. };
  66207. },
  66208. /**
  66209. * Convert a (x, y) point to time date
  66210. *
  66211. * @param {Array} point point
  66212. * @return {Object} date
  66213. */
  66214. pointToDate: function (point) {
  66215. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  66216. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  66217. var range = this._rangeInfo.range;
  66218. if (this._orient === 'vertical') {
  66219. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  66220. }
  66221. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  66222. },
  66223. /**
  66224. * @inheritDoc
  66225. */
  66226. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  66227. /**
  66228. * @inheritDoc
  66229. */
  66230. convertFromPixel: curry(doConvert$2, 'pointToData'),
  66231. /**
  66232. * initRange
  66233. *
  66234. * @private
  66235. * @return {Array} [start, end]
  66236. */
  66237. _initRangeOption: function () {
  66238. var range = this._model.get('range');
  66239. var rg = range;
  66240. if (isArray(rg) && rg.length === 1) {
  66241. rg = rg[0];
  66242. }
  66243. if (/^\d{4}$/.test(rg)) {
  66244. range = [rg + '-01-01', rg + '-12-31'];
  66245. }
  66246. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  66247. var start = this.getDateInfo(rg);
  66248. var firstDay = start.date;
  66249. firstDay.setMonth(firstDay.getMonth() + 1);
  66250. var end = this.getNextNDay(firstDay, -1);
  66251. range = [start.formatedDate, end.formatedDate];
  66252. }
  66253. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  66254. range = [rg, rg];
  66255. }
  66256. var tmp = this._getRangeInfo(range);
  66257. if (tmp.start.time > tmp.end.time) {
  66258. range.reverse();
  66259. }
  66260. return range;
  66261. },
  66262. /**
  66263. * range info
  66264. *
  66265. * @private
  66266. * @param {Array} range range ['2017-01-01', '2017-07-08']
  66267. * If range[0] > range[1], they will not be reversed.
  66268. * @return {Object} obj
  66269. */
  66270. _getRangeInfo: function (range) {
  66271. range = [
  66272. this.getDateInfo(range[0]),
  66273. this.getDateInfo(range[1])
  66274. ];
  66275. var reversed;
  66276. if (range[0].time > range[1].time) {
  66277. reversed = true;
  66278. range.reverse();
  66279. }
  66280. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  66281. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  66282. // Consider case:
  66283. // Firstly set system timezone as "Time Zone: America/Toronto",
  66284. // ```
  66285. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  66286. // var second = new Date(1478412000000);
  66287. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  66288. // ```
  66289. // will get wrong result because of DST. So we should fix it.
  66290. var date = new Date(range[0].time);
  66291. var startDateNum = date.getDate();
  66292. var endDateNum = range[1].date.getDate();
  66293. date.setDate(startDateNum + allDay - 1);
  66294. // The bias can not over a month, so just compare date.
  66295. if (date.getDate() !== endDateNum) {
  66296. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  66297. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  66298. allDay -= sign;
  66299. date.setDate(startDateNum + allDay - 1);
  66300. }
  66301. }
  66302. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  66303. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  66304. reversed && range.reverse();
  66305. return {
  66306. range: [range[0].formatedDate, range[1].formatedDate],
  66307. start: range[0],
  66308. end: range[1],
  66309. allDay: allDay,
  66310. weeks: weeks,
  66311. // From 0.
  66312. nthWeek: nthWeek,
  66313. fweek: range[0].day,
  66314. lweek: range[1].day
  66315. };
  66316. },
  66317. /**
  66318. * get date by nthWeeks and week day in range
  66319. *
  66320. * @private
  66321. * @param {number} nthWeek the week
  66322. * @param {number} day the week day
  66323. * @param {Array} range [d1, d2]
  66324. * @return {Object}
  66325. */
  66326. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  66327. var rangeInfo = this._getRangeInfo(range);
  66328. if (nthWeek > rangeInfo.weeks
  66329. || (nthWeek === 0 && day < rangeInfo.fweek)
  66330. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  66331. ) {
  66332. return false;
  66333. }
  66334. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  66335. var date = new Date(rangeInfo.start.time);
  66336. date.setDate(rangeInfo.start.d + nthDay);
  66337. return this.getDateInfo(date);
  66338. }
  66339. };
  66340. Calendar.dimensions = Calendar.prototype.dimensions;
  66341. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  66342. Calendar.create = function (ecModel, api) {
  66343. var calendarList = [];
  66344. ecModel.eachComponent('calendar', function (calendarModel) {
  66345. var calendar = new Calendar(calendarModel, ecModel, api);
  66346. calendarList.push(calendar);
  66347. calendarModel.coordinateSystem = calendar;
  66348. });
  66349. ecModel.eachSeries(function (calendarSeries) {
  66350. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  66351. // Inject coordinate system
  66352. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  66353. }
  66354. });
  66355. return calendarList;
  66356. };
  66357. function doConvert$2(methodName, ecModel, finder, value) {
  66358. var calendarModel = finder.calendarModel;
  66359. var seriesModel = finder.seriesModel;
  66360. var coordSys = calendarModel
  66361. ? calendarModel.coordinateSystem
  66362. : seriesModel
  66363. ? seriesModel.coordinateSystem
  66364. : null;
  66365. return coordSys === this ? coordSys[methodName](value) : null;
  66366. }
  66367. CoordinateSystemManager.register('calendar', Calendar);
  66368. /*
  66369. * Licensed to the Apache Software Foundation (ASF) under one
  66370. * or more contributor license agreements. See the NOTICE file
  66371. * distributed with this work for additional information
  66372. * regarding copyright ownership. The ASF licenses this file
  66373. * to you under the Apache License, Version 2.0 (the
  66374. * "License"); you may not use this file except in compliance
  66375. * with the License. You may obtain a copy of the License at
  66376. *
  66377. * http://www.apache.org/licenses/LICENSE-2.0
  66378. *
  66379. * Unless required by applicable law or agreed to in writing,
  66380. * software distributed under the License is distributed on an
  66381. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66382. * KIND, either express or implied. See the License for the
  66383. * specific language governing permissions and limitations
  66384. * under the License.
  66385. */
  66386. var CalendarModel = ComponentModel.extend({
  66387. type: 'calendar',
  66388. /**
  66389. * @type {module:echarts/coord/calendar/Calendar}
  66390. */
  66391. coordinateSystem: null,
  66392. defaultOption: {
  66393. zlevel: 0,
  66394. z: 2,
  66395. left: 80,
  66396. top: 60,
  66397. cellSize: 20,
  66398. // horizontal vertical
  66399. orient: 'horizontal',
  66400. // month separate line style
  66401. splitLine: {
  66402. show: true,
  66403. lineStyle: {
  66404. color: '#000',
  66405. width: 1,
  66406. type: 'solid'
  66407. }
  66408. },
  66409. // rect style temporarily unused emphasis
  66410. itemStyle: {
  66411. color: '#fff',
  66412. borderWidth: 1,
  66413. borderColor: '#ccc'
  66414. },
  66415. // week text style
  66416. dayLabel: {
  66417. show: true,
  66418. // a week first day
  66419. firstDay: 0,
  66420. // start end
  66421. position: 'start',
  66422. margin: '50%', // 50% of cellSize
  66423. nameMap: 'en',
  66424. color: '#000'
  66425. },
  66426. // month text style
  66427. monthLabel: {
  66428. show: true,
  66429. // start end
  66430. position: 'start',
  66431. margin: 5,
  66432. // center or left
  66433. align: 'center',
  66434. // cn en []
  66435. nameMap: 'en',
  66436. formatter: null,
  66437. color: '#000'
  66438. },
  66439. // year text style
  66440. yearLabel: {
  66441. show: true,
  66442. // top bottom left right
  66443. position: null,
  66444. margin: 30,
  66445. formatter: null,
  66446. color: '#ccc',
  66447. fontFamily: 'sans-serif',
  66448. fontWeight: 'bolder',
  66449. fontSize: 20
  66450. }
  66451. },
  66452. /**
  66453. * @override
  66454. */
  66455. init: function (option, parentModel, ecModel, extraOpt) {
  66456. var inputPositionParams = getLayoutParams(option);
  66457. CalendarModel.superApply(this, 'init', arguments);
  66458. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  66459. },
  66460. /**
  66461. * @override
  66462. */
  66463. mergeOption: function (option, extraOpt) {
  66464. CalendarModel.superApply(this, 'mergeOption', arguments);
  66465. mergeAndNormalizeLayoutParams(this.option, option);
  66466. }
  66467. });
  66468. function mergeAndNormalizeLayoutParams(target, raw) {
  66469. // Normalize cellSize
  66470. var cellSize = target.cellSize;
  66471. if (!isArray(cellSize)) {
  66472. cellSize = target.cellSize = [cellSize, cellSize];
  66473. }
  66474. else if (cellSize.length === 1) {
  66475. cellSize[1] = cellSize[0];
  66476. }
  66477. var ignoreSize = map([0, 1], function (hvIdx) {
  66478. // If user have set `width` or both `left` and `right`, cellSize
  66479. // will be automatically set to 'auto', otherwise the default
  66480. // setting of cellSize will make `width` setting not work.
  66481. if (sizeCalculable(raw, hvIdx)) {
  66482. cellSize[hvIdx] = 'auto';
  66483. }
  66484. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  66485. });
  66486. mergeLayoutParam(target, raw, {
  66487. type: 'box', ignoreSize: ignoreSize
  66488. });
  66489. }
  66490. /*
  66491. * Licensed to the Apache Software Foundation (ASF) under one
  66492. * or more contributor license agreements. See the NOTICE file
  66493. * distributed with this work for additional information
  66494. * regarding copyright ownership. The ASF licenses this file
  66495. * to you under the Apache License, Version 2.0 (the
  66496. * "License"); you may not use this file except in compliance
  66497. * with the License. You may obtain a copy of the License at
  66498. *
  66499. * http://www.apache.org/licenses/LICENSE-2.0
  66500. *
  66501. * Unless required by applicable law or agreed to in writing,
  66502. * software distributed under the License is distributed on an
  66503. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66504. * KIND, either express or implied. See the License for the
  66505. * specific language governing permissions and limitations
  66506. * under the License.
  66507. */
  66508. var MONTH_TEXT = {
  66509. EN: [
  66510. 'Jan', 'Feb', 'Mar',
  66511. 'Apr', 'May', 'Jun',
  66512. 'Jul', 'Aug', 'Sep',
  66513. 'Oct', 'Nov', 'Dec'
  66514. ],
  66515. CN: [
  66516. '一月', '二月', '三月',
  66517. '四月', '五月', '六月',
  66518. '七月', '八月', '九月',
  66519. '十月', '十一月', '十二月'
  66520. ]
  66521. };
  66522. var WEEK_TEXT = {
  66523. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  66524. CN: ['日', '一', '二', '三', '四', '五', '六']
  66525. };
  66526. extendComponentView({
  66527. type: 'calendar',
  66528. /**
  66529. * top/left line points
  66530. * @private
  66531. */
  66532. _tlpoints: null,
  66533. /**
  66534. * bottom/right line points
  66535. * @private
  66536. */
  66537. _blpoints: null,
  66538. /**
  66539. * first day of month
  66540. * @private
  66541. */
  66542. _firstDayOfMonth: null,
  66543. /**
  66544. * first day point of month
  66545. * @private
  66546. */
  66547. _firstDayPoints: null,
  66548. render: function (calendarModel, ecModel, api) {
  66549. var group = this.group;
  66550. group.removeAll();
  66551. var coordSys = calendarModel.coordinateSystem;
  66552. // range info
  66553. var rangeData = coordSys.getRangeInfo();
  66554. var orient = coordSys.getOrient();
  66555. this._renderDayRect(calendarModel, rangeData, group);
  66556. // _renderLines must be called prior to following function
  66557. this._renderLines(calendarModel, rangeData, orient, group);
  66558. this._renderYearText(calendarModel, rangeData, orient, group);
  66559. this._renderMonthText(calendarModel, orient, group);
  66560. this._renderWeekText(calendarModel, rangeData, orient, group);
  66561. },
  66562. // render day rect
  66563. _renderDayRect: function (calendarModel, rangeData, group) {
  66564. var coordSys = calendarModel.coordinateSystem;
  66565. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  66566. var sw = coordSys.getCellWidth();
  66567. var sh = coordSys.getCellHeight();
  66568. for (var i = rangeData.start.time;
  66569. i <= rangeData.end.time;
  66570. i = coordSys.getNextNDay(i, 1).time
  66571. ) {
  66572. var point = coordSys.dataToRect([i], false).tl;
  66573. // every rect
  66574. var rect = new Rect({
  66575. shape: {
  66576. x: point[0],
  66577. y: point[1],
  66578. width: sw,
  66579. height: sh
  66580. },
  66581. cursor: 'default',
  66582. style: itemRectStyleModel
  66583. });
  66584. group.add(rect);
  66585. }
  66586. },
  66587. // render separate line
  66588. _renderLines: function (calendarModel, rangeData, orient, group) {
  66589. var self = this;
  66590. var coordSys = calendarModel.coordinateSystem;
  66591. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  66592. var show = calendarModel.get('splitLine.show');
  66593. var lineWidth = lineStyleModel.lineWidth;
  66594. this._tlpoints = [];
  66595. this._blpoints = [];
  66596. this._firstDayOfMonth = [];
  66597. this._firstDayPoints = [];
  66598. var firstDay = rangeData.start;
  66599. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  66600. addPoints(firstDay.formatedDate);
  66601. if (i === 0) {
  66602. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  66603. }
  66604. var date = firstDay.date;
  66605. date.setMonth(date.getMonth() + 1);
  66606. firstDay = coordSys.getDateInfo(date);
  66607. }
  66608. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  66609. function addPoints(date) {
  66610. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  66611. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  66612. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  66613. self._tlpoints.push(points[0]);
  66614. self._blpoints.push(points[points.length - 1]);
  66615. show && self._drawSplitline(points, lineStyleModel, group);
  66616. }
  66617. // render top/left line
  66618. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  66619. // render bottom/right line
  66620. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  66621. },
  66622. // get points at both ends
  66623. _getEdgesPoints: function (points, lineWidth, orient) {
  66624. var rs = [points[0].slice(), points[points.length - 1].slice()];
  66625. var idx = orient === 'horizontal' ? 0 : 1;
  66626. // both ends of the line are extend half lineWidth
  66627. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  66628. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  66629. return rs;
  66630. },
  66631. // render split line
  66632. _drawSplitline: function (points, lineStyleModel, group) {
  66633. var poyline = new Polyline({
  66634. z2: 20,
  66635. shape: {
  66636. points: points
  66637. },
  66638. style: lineStyleModel
  66639. });
  66640. group.add(poyline);
  66641. },
  66642. // render month line of one week points
  66643. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  66644. var coordSys = calendarModel.coordinateSystem;
  66645. date = coordSys.getDateInfo(date);
  66646. var points = [];
  66647. for (var i = 0; i < 7; i++) {
  66648. var tmpD = coordSys.getNextNDay(date.time, i);
  66649. var point = coordSys.dataToRect([tmpD.time], false);
  66650. points[2 * tmpD.day] = point.tl;
  66651. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  66652. }
  66653. return points;
  66654. },
  66655. _formatterLabel: function (formatter, params) {
  66656. if (typeof formatter === 'string' && formatter) {
  66657. return formatTplSimple(formatter, params);
  66658. }
  66659. if (typeof formatter === 'function') {
  66660. return formatter(params);
  66661. }
  66662. return params.nameMap;
  66663. },
  66664. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  66665. point = point.slice();
  66666. var aligns = ['center', 'bottom'];
  66667. if (position === 'bottom') {
  66668. point[1] += margin;
  66669. aligns = ['center', 'top'];
  66670. }
  66671. else if (position === 'left') {
  66672. point[0] -= margin;
  66673. }
  66674. else if (position === 'right') {
  66675. point[0] += margin;
  66676. aligns = ['center', 'top'];
  66677. }
  66678. else { // top
  66679. point[1] -= margin;
  66680. }
  66681. var rotate = 0;
  66682. if (position === 'left' || position === 'right') {
  66683. rotate = Math.PI / 2;
  66684. }
  66685. return {
  66686. rotation: rotate,
  66687. position: point,
  66688. style: {
  66689. textAlign: aligns[0],
  66690. textVerticalAlign: aligns[1]
  66691. }
  66692. };
  66693. },
  66694. // render year
  66695. _renderYearText: function (calendarModel, rangeData, orient, group) {
  66696. var yearLabel = calendarModel.getModel('yearLabel');
  66697. if (!yearLabel.get('show')) {
  66698. return;
  66699. }
  66700. var margin = yearLabel.get('margin');
  66701. var pos = yearLabel.get('position');
  66702. if (!pos) {
  66703. pos = orient !== 'horizontal' ? 'top' : 'left';
  66704. }
  66705. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  66706. var xc = (points[0][0] + points[1][0]) / 2;
  66707. var yc = (points[0][1] + points[1][1]) / 2;
  66708. var idx = orient === 'horizontal' ? 0 : 1;
  66709. var posPoints = {
  66710. top: [xc, points[idx][1]],
  66711. bottom: [xc, points[1 - idx][1]],
  66712. left: [points[1 - idx][0], yc],
  66713. right: [points[idx][0], yc]
  66714. };
  66715. var name = rangeData.start.y;
  66716. if (+rangeData.end.y > +rangeData.start.y) {
  66717. name = name + '-' + rangeData.end.y;
  66718. }
  66719. var formatter = yearLabel.get('formatter');
  66720. var params = {
  66721. start: rangeData.start.y,
  66722. end: rangeData.end.y,
  66723. nameMap: name
  66724. };
  66725. var content = this._formatterLabel(formatter, params);
  66726. var yearText = new Text({z2: 30});
  66727. setTextStyle(yearText.style, yearLabel, {text: content}),
  66728. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  66729. group.add(yearText);
  66730. },
  66731. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  66732. var align = 'left';
  66733. var vAlign = 'top';
  66734. var x = point[0];
  66735. var y = point[1];
  66736. if (orient === 'horizontal') {
  66737. y = y + margin;
  66738. if (isCenter) {
  66739. align = 'center';
  66740. }
  66741. if (position === 'start') {
  66742. vAlign = 'bottom';
  66743. }
  66744. }
  66745. else {
  66746. x = x + margin;
  66747. if (isCenter) {
  66748. vAlign = 'middle';
  66749. }
  66750. if (position === 'start') {
  66751. align = 'right';
  66752. }
  66753. }
  66754. return {
  66755. x: x,
  66756. y: y,
  66757. textAlign: align,
  66758. textVerticalAlign: vAlign
  66759. };
  66760. },
  66761. // render month and year text
  66762. _renderMonthText: function (calendarModel, orient, group) {
  66763. var monthLabel = calendarModel.getModel('monthLabel');
  66764. if (!monthLabel.get('show')) {
  66765. return;
  66766. }
  66767. var nameMap = monthLabel.get('nameMap');
  66768. var margin = monthLabel.get('margin');
  66769. var pos = monthLabel.get('position');
  66770. var align = monthLabel.get('align');
  66771. var termPoints = [this._tlpoints, this._blpoints];
  66772. if (isString(nameMap)) {
  66773. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  66774. }
  66775. var idx = pos === 'start' ? 0 : 1;
  66776. var axis = orient === 'horizontal' ? 0 : 1;
  66777. margin = pos === 'start' ? -margin : margin;
  66778. var isCenter = (align === 'center');
  66779. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  66780. var tmp = termPoints[idx][i].slice();
  66781. var firstDay = this._firstDayOfMonth[i];
  66782. if (isCenter) {
  66783. var firstDayPoints = this._firstDayPoints[i];
  66784. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  66785. }
  66786. var formatter = monthLabel.get('formatter');
  66787. var name = nameMap[+firstDay.m - 1];
  66788. var params = {
  66789. yyyy: firstDay.y,
  66790. yy: (firstDay.y + '').slice(2),
  66791. MM: firstDay.m,
  66792. M: +firstDay.m,
  66793. nameMap: name
  66794. };
  66795. var content = this._formatterLabel(formatter, params);
  66796. var monthText = new Text({z2: 30});
  66797. extend(
  66798. setTextStyle(monthText.style, monthLabel, {text: content}),
  66799. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  66800. );
  66801. group.add(monthText);
  66802. }
  66803. },
  66804. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  66805. var align = 'center';
  66806. var vAlign = 'middle';
  66807. var x = point[0];
  66808. var y = point[1];
  66809. var isStart = position === 'start';
  66810. if (orient === 'horizontal') {
  66811. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  66812. align = isStart ? 'right' : 'left';
  66813. }
  66814. else {
  66815. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  66816. vAlign = isStart ? 'bottom' : 'top';
  66817. }
  66818. return {
  66819. x: x,
  66820. y: y,
  66821. textAlign: align,
  66822. textVerticalAlign: vAlign
  66823. };
  66824. },
  66825. // render weeks
  66826. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  66827. var dayLabel = calendarModel.getModel('dayLabel');
  66828. if (!dayLabel.get('show')) {
  66829. return;
  66830. }
  66831. var coordSys = calendarModel.coordinateSystem;
  66832. var pos = dayLabel.get('position');
  66833. var nameMap = dayLabel.get('nameMap');
  66834. var margin = dayLabel.get('margin');
  66835. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  66836. if (isString(nameMap)) {
  66837. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  66838. }
  66839. var start = coordSys.getNextNDay(
  66840. rangeData.end.time, (7 - rangeData.lweek)
  66841. ).time;
  66842. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  66843. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  66844. if (pos === 'start') {
  66845. start = coordSys.getNextNDay(
  66846. rangeData.start.time, -(7 + rangeData.fweek)
  66847. ).time;
  66848. margin = -margin;
  66849. }
  66850. for (var i = 0; i < 7; i++) {
  66851. var tmpD = coordSys.getNextNDay(start, i);
  66852. var point = coordSys.dataToRect([tmpD.time], false).center;
  66853. var day = i;
  66854. day = Math.abs((i + firstDayOfWeek) % 7);
  66855. var weekText = new Text({z2: 30});
  66856. extend(
  66857. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  66858. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  66859. );
  66860. group.add(weekText);
  66861. }
  66862. }
  66863. });
  66864. /*
  66865. * Licensed to the Apache Software Foundation (ASF) under one
  66866. * or more contributor license agreements. See the NOTICE file
  66867. * distributed with this work for additional information
  66868. * regarding copyright ownership. The ASF licenses this file
  66869. * to you under the Apache License, Version 2.0 (the
  66870. * "License"); you may not use this file except in compliance
  66871. * with the License. You may obtain a copy of the License at
  66872. *
  66873. * http://www.apache.org/licenses/LICENSE-2.0
  66874. *
  66875. * Unless required by applicable law or agreed to in writing,
  66876. * software distributed under the License is distributed on an
  66877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66878. * KIND, either express or implied. See the License for the
  66879. * specific language governing permissions and limitations
  66880. * under the License.
  66881. */
  66882. /*
  66883. * Licensed to the Apache Software Foundation (ASF) under one
  66884. * or more contributor license agreements. See the NOTICE file
  66885. * distributed with this work for additional information
  66886. * regarding copyright ownership. The ASF licenses this file
  66887. * to you under the Apache License, Version 2.0 (the
  66888. * "License"); you may not use this file except in compliance
  66889. * with the License. You may obtain a copy of the License at
  66890. *
  66891. * http://www.apache.org/licenses/LICENSE-2.0
  66892. *
  66893. * Unless required by applicable law or agreed to in writing,
  66894. * software distributed under the License is distributed on an
  66895. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66896. * KIND, either express or implied. See the License for the
  66897. * specific language governing permissions and limitations
  66898. * under the License.
  66899. */
  66900. var _nonShapeGraphicElements = {
  66901. // Reserved but not supported in graphic component.
  66902. path: null,
  66903. compoundPath: null,
  66904. // Supported in graphic component.
  66905. group: Group,
  66906. image: ZImage,
  66907. text: Text
  66908. };
  66909. // -------------
  66910. // Preprocessor
  66911. // -------------
  66912. registerPreprocessor(function (option) {
  66913. var graphicOption = option.graphic;
  66914. // Convert
  66915. // {graphic: [{left: 10, type: 'circle'}, ...]}
  66916. // or
  66917. // {graphic: {left: 10, type: 'circle'}}
  66918. // to
  66919. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  66920. if (isArray(graphicOption)) {
  66921. if (!graphicOption[0] || !graphicOption[0].elements) {
  66922. option.graphic = [{elements: graphicOption}];
  66923. }
  66924. else {
  66925. // Only one graphic instance can be instantiated. (We dont
  66926. // want that too many views are created in echarts._viewMap)
  66927. option.graphic = [option.graphic[0]];
  66928. }
  66929. }
  66930. else if (graphicOption && !graphicOption.elements) {
  66931. option.graphic = [{elements: [graphicOption]}];
  66932. }
  66933. });
  66934. // ------
  66935. // Model
  66936. // ------
  66937. var GraphicModel = extendComponentModel({
  66938. type: 'graphic',
  66939. defaultOption: {
  66940. // Extra properties for each elements:
  66941. //
  66942. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  66943. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  66944. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  66945. // This mechanism is useful when you want to position a group/element
  66946. // against the right side or the center of this container.
  66947. //
  66948. // width/height: (can only be pixel value, default 0)
  66949. // Only be used to specify contianer(group) size, if needed. And
  66950. // can not be percentage value (like '33%'). See the reason in the
  66951. // layout algorithm below.
  66952. //
  66953. // bounding: (enum: 'all' (default) | 'raw')
  66954. // Specify how to calculate boundingRect when locating.
  66955. // 'all': Get uioned and transformed boundingRect
  66956. // from both itself and its descendants.
  66957. // This mode simplies confining a group of elements in the bounding
  66958. // of their ancester container (e.g., using 'right: 0').
  66959. // 'raw': Only use the boundingRect of itself and before transformed.
  66960. // This mode is similar to css behavior, which is useful when you
  66961. // want an element to be able to overflow its container. (Consider
  66962. // a rotated circle needs to be located in a corner.)
  66963. // info: custom info. enables user to mount some info on elements and use them
  66964. // in event handlers. Update them only when user specified, otherwise, remain.
  66965. // Note: elements is always behind its ancestors in this elements array.
  66966. elements: [],
  66967. parentId: null
  66968. },
  66969. /**
  66970. * Save el options for the sake of the performance (only update modified graphics).
  66971. * The order is the same as those in option. (ancesters -> descendants)
  66972. *
  66973. * @private
  66974. * @type {Array.<Object>}
  66975. */
  66976. _elOptionsToUpdate: null,
  66977. /**
  66978. * @override
  66979. */
  66980. mergeOption: function (option) {
  66981. // Prevent default merge to elements
  66982. var elements = this.option.elements;
  66983. this.option.elements = null;
  66984. GraphicModel.superApply(this, 'mergeOption', arguments);
  66985. this.option.elements = elements;
  66986. },
  66987. /**
  66988. * @override
  66989. */
  66990. optionUpdated: function (newOption, isInit) {
  66991. var thisOption = this.option;
  66992. var newList = (isInit ? thisOption : newOption).elements;
  66993. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  66994. var flattenedList = [];
  66995. this._flatten(newList, flattenedList);
  66996. var mappingResult = mappingToExists(existList, flattenedList);
  66997. makeIdAndName(mappingResult);
  66998. // Clear elOptionsToUpdate
  66999. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  67000. each$1(mappingResult, function (resultItem, index) {
  67001. var newElOption = resultItem.option;
  67002. if (__DEV__) {
  67003. assert$1(
  67004. isObject$1(newElOption) || resultItem.exist,
  67005. 'Empty graphic option definition'
  67006. );
  67007. }
  67008. if (!newElOption) {
  67009. return;
  67010. }
  67011. elOptionsToUpdate.push(newElOption);
  67012. setKeyInfoToNewElOption(resultItem, newElOption);
  67013. mergeNewElOptionToExist(existList, index, newElOption);
  67014. setLayoutInfoToExist(existList[index], newElOption);
  67015. }, this);
  67016. // Clean
  67017. for (var i = existList.length - 1; i >= 0; i--) {
  67018. if (existList[i] == null) {
  67019. existList.splice(i, 1);
  67020. }
  67021. else {
  67022. // $action should be volatile, otherwise option gotten from
  67023. // `getOption` will contain unexpected $action.
  67024. delete existList[i].$action;
  67025. }
  67026. }
  67027. },
  67028. /**
  67029. * Convert
  67030. * [{
  67031. * type: 'group',
  67032. * id: 'xx',
  67033. * children: [{type: 'circle'}, {type: 'polygon'}]
  67034. * }]
  67035. * to
  67036. * [
  67037. * {type: 'group', id: 'xx'},
  67038. * {type: 'circle', parentId: 'xx'},
  67039. * {type: 'polygon', parentId: 'xx'}
  67040. * ]
  67041. *
  67042. * @private
  67043. * @param {Array.<Object>} optionList option list
  67044. * @param {Array.<Object>} result result of flatten
  67045. * @param {Object} parentOption parent option
  67046. */
  67047. _flatten: function (optionList, result, parentOption) {
  67048. each$1(optionList, function (option) {
  67049. if (!option) {
  67050. return;
  67051. }
  67052. if (parentOption) {
  67053. option.parentOption = parentOption;
  67054. }
  67055. result.push(option);
  67056. var children = option.children;
  67057. if (option.type === 'group' && children) {
  67058. this._flatten(children, result, option);
  67059. }
  67060. // Deleting for JSON output, and for not affecting group creation.
  67061. delete option.children;
  67062. }, this);
  67063. },
  67064. // FIXME
  67065. // Pass to view using payload? setOption has a payload?
  67066. useElOptionsToUpdate: function () {
  67067. var els = this._elOptionsToUpdate;
  67068. // Clear to avoid render duplicately when zooming.
  67069. this._elOptionsToUpdate = null;
  67070. return els;
  67071. }
  67072. });
  67073. // -----
  67074. // View
  67075. // -----
  67076. extendComponentView({
  67077. type: 'graphic',
  67078. /**
  67079. * @override
  67080. */
  67081. init: function (ecModel, api) {
  67082. /**
  67083. * @private
  67084. * @type {module:zrender/core/util.HashMap}
  67085. */
  67086. this._elMap = createHashMap();
  67087. /**
  67088. * @private
  67089. * @type {module:echarts/graphic/GraphicModel}
  67090. */
  67091. this._lastGraphicModel;
  67092. },
  67093. /**
  67094. * @override
  67095. */
  67096. render: function (graphicModel, ecModel, api) {
  67097. // Having leveraged between use cases and algorithm complexity, a very
  67098. // simple layout mechanism is used:
  67099. // The size(width/height) can be determined by itself or its parent (not
  67100. // implemented yet), but can not by its children. (Top-down travel)
  67101. // The location(x/y) can be determined by the bounding rect of itself
  67102. // (can including its descendants or not) and the size of its parent.
  67103. // (Bottom-up travel)
  67104. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  67105. // view will be reused.
  67106. if (graphicModel !== this._lastGraphicModel) {
  67107. this._clear();
  67108. }
  67109. this._lastGraphicModel = graphicModel;
  67110. this._updateElements(graphicModel);
  67111. this._relocate(graphicModel, api);
  67112. },
  67113. /**
  67114. * Update graphic elements.
  67115. *
  67116. * @private
  67117. * @param {Object} graphicModel graphic model
  67118. */
  67119. _updateElements: function (graphicModel) {
  67120. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  67121. if (!elOptionsToUpdate) {
  67122. return;
  67123. }
  67124. var elMap = this._elMap;
  67125. var rootGroup = this.group;
  67126. // Top-down tranverse to assign graphic settings to each elements.
  67127. each$1(elOptionsToUpdate, function (elOption) {
  67128. var $action = elOption.$action;
  67129. var id = elOption.id;
  67130. var existEl = elMap.get(id);
  67131. var parentId = elOption.parentId;
  67132. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  67133. var elOptionStyle = elOption.style;
  67134. if (elOption.type === 'text' && elOptionStyle) {
  67135. // In top/bottom mode, textVerticalAlign should not be used, which cause
  67136. // inaccurately locating.
  67137. if (elOption.hv && elOption.hv[1]) {
  67138. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  67139. }
  67140. // Compatible with previous setting: both support fill and textFill,
  67141. // stroke and textStroke.
  67142. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  67143. elOptionStyle.textFill = elOptionStyle.fill
  67144. );
  67145. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  67146. elOptionStyle.textStroke = elOptionStyle.stroke
  67147. );
  67148. }
  67149. // Remove unnecessary props to avoid potential problems.
  67150. var elOptionCleaned = getCleanedElOption(elOption);
  67151. // For simple, do not support parent change, otherwise reorder is needed.
  67152. if (__DEV__) {
  67153. existEl && assert$1(
  67154. targetElParent === existEl.parent,
  67155. 'Changing parent is not supported.'
  67156. );
  67157. }
  67158. if (!$action || $action === 'merge') {
  67159. existEl
  67160. ? existEl.attr(elOptionCleaned)
  67161. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67162. }
  67163. else if ($action === 'replace') {
  67164. removeEl(existEl, elMap);
  67165. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67166. }
  67167. else if ($action === 'remove') {
  67168. removeEl(existEl, elMap);
  67169. }
  67170. var el = elMap.get(id);
  67171. if (el) {
  67172. el.__ecGraphicWidthOption = elOption.width;
  67173. el.__ecGraphicHeightOption = elOption.height;
  67174. setEventData(el, graphicModel, elOption);
  67175. }
  67176. });
  67177. },
  67178. /**
  67179. * Locate graphic elements.
  67180. *
  67181. * @private
  67182. * @param {Object} graphicModel graphic model
  67183. * @param {module:echarts/ExtensionAPI} api extension API
  67184. */
  67185. _relocate: function (graphicModel, api) {
  67186. var elOptions = graphicModel.option.elements;
  67187. var rootGroup = this.group;
  67188. var elMap = this._elMap;
  67189. var apiWidth = api.getWidth();
  67190. var apiHeight = api.getHeight();
  67191. // Top-down to calculate percentage width/height of group
  67192. for (var i = 0; i < elOptions.length; i++) {
  67193. var elOption = elOptions[i];
  67194. var el = elMap.get(elOption.id);
  67195. if (!el || !el.isGroup) {
  67196. continue;
  67197. }
  67198. var parentEl = el.parent;
  67199. var isParentRoot = parentEl === rootGroup;
  67200. // Like 'position:absolut' in css, default 0.
  67201. el.__ecGraphicWidth = parsePercent$1(
  67202. el.__ecGraphicWidthOption,
  67203. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  67204. ) || 0;
  67205. el.__ecGraphicHeight = parsePercent$1(
  67206. el.__ecGraphicHeightOption,
  67207. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  67208. ) || 0;
  67209. }
  67210. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  67211. for (var i = elOptions.length - 1; i >= 0; i--) {
  67212. var elOption = elOptions[i];
  67213. var el = elMap.get(elOption.id);
  67214. if (!el) {
  67215. continue;
  67216. }
  67217. var parentEl = el.parent;
  67218. var containerInfo = parentEl === rootGroup
  67219. ? {
  67220. width: apiWidth,
  67221. height: apiHeight
  67222. }
  67223. : {
  67224. width: parentEl.__ecGraphicWidth,
  67225. height: parentEl.__ecGraphicHeight
  67226. };
  67227. // PENDING
  67228. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  67229. // does not include the rect of [0, 0, group.width, group.height], which
  67230. // is probably weird for users. Should we make a break change for it?
  67231. positionElement(
  67232. el, elOption, containerInfo, null,
  67233. {hv: elOption.hv, boundingMode: elOption.bounding}
  67234. );
  67235. }
  67236. },
  67237. /**
  67238. * Clear all elements.
  67239. *
  67240. * @private
  67241. */
  67242. _clear: function () {
  67243. var elMap = this._elMap;
  67244. elMap.each(function (el) {
  67245. removeEl(el, elMap);
  67246. });
  67247. this._elMap = createHashMap();
  67248. },
  67249. /**
  67250. * @override
  67251. */
  67252. dispose: function () {
  67253. this._clear();
  67254. }
  67255. });
  67256. function createEl$1(id, targetElParent, elOption, elMap) {
  67257. var graphicType = elOption.type;
  67258. if (__DEV__) {
  67259. assert$1(graphicType, 'graphic type MUST be set');
  67260. }
  67261. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  67262. // Those graphic elements are not shapes. They should not be
  67263. // overwritten by users, so do them first.
  67264. ? _nonShapeGraphicElements[graphicType]
  67265. : getShapeClass(graphicType);
  67266. if (__DEV__) {
  67267. assert$1(Clz, 'graphic type can not be found');
  67268. }
  67269. var el = new Clz(elOption);
  67270. targetElParent.add(el);
  67271. elMap.set(id, el);
  67272. el.__ecGraphicId = id;
  67273. }
  67274. function removeEl(existEl, elMap) {
  67275. var existElParent = existEl && existEl.parent;
  67276. if (existElParent) {
  67277. existEl.type === 'group' && existEl.traverse(function (el) {
  67278. removeEl(el, elMap);
  67279. });
  67280. elMap.removeKey(existEl.__ecGraphicId);
  67281. existElParent.remove(existEl);
  67282. }
  67283. }
  67284. // Remove unnecessary props to avoid potential problems.
  67285. function getCleanedElOption(elOption) {
  67286. elOption = extend({}, elOption);
  67287. each$1(
  67288. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  67289. function (name) {
  67290. delete elOption[name];
  67291. }
  67292. );
  67293. return elOption;
  67294. }
  67295. function isSetLoc(obj, props) {
  67296. var isSet;
  67297. each$1(props, function (prop) {
  67298. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  67299. });
  67300. return isSet;
  67301. }
  67302. function setKeyInfoToNewElOption(resultItem, newElOption) {
  67303. var existElOption = resultItem.exist;
  67304. // Set id and type after id assigned.
  67305. newElOption.id = resultItem.keyInfo.id;
  67306. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  67307. // Set parent id if not specified
  67308. if (newElOption.parentId == null) {
  67309. var newElParentOption = newElOption.parentOption;
  67310. if (newElParentOption) {
  67311. newElOption.parentId = newElParentOption.id;
  67312. }
  67313. else if (existElOption) {
  67314. newElOption.parentId = existElOption.parentId;
  67315. }
  67316. }
  67317. // Clear
  67318. newElOption.parentOption = null;
  67319. }
  67320. function mergeNewElOptionToExist(existList, index, newElOption) {
  67321. // Update existing options, for `getOption` feature.
  67322. var newElOptCopy = extend({}, newElOption);
  67323. var existElOption = existList[index];
  67324. var $action = newElOption.$action || 'merge';
  67325. if ($action === 'merge') {
  67326. if (existElOption) {
  67327. if (__DEV__) {
  67328. var newType = newElOption.type;
  67329. assert$1(
  67330. !newType || existElOption.type === newType,
  67331. 'Please set $action: "replace" to change `type`'
  67332. );
  67333. }
  67334. // We can ensure that newElOptCopy and existElOption are not
  67335. // the same object, so `merge` will not change newElOptCopy.
  67336. merge(existElOption, newElOptCopy, true);
  67337. // Rigid body, use ignoreSize.
  67338. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  67339. // Will be used in render.
  67340. copyLayoutParams(newElOption, existElOption);
  67341. }
  67342. else {
  67343. existList[index] = newElOptCopy;
  67344. }
  67345. }
  67346. else if ($action === 'replace') {
  67347. existList[index] = newElOptCopy;
  67348. }
  67349. else if ($action === 'remove') {
  67350. // null will be cleaned later.
  67351. existElOption && (existList[index] = null);
  67352. }
  67353. }
  67354. function setLayoutInfoToExist(existItem, newElOption) {
  67355. if (!existItem) {
  67356. return;
  67357. }
  67358. existItem.hv = newElOption.hv = [
  67359. // Rigid body, dont care `width`.
  67360. isSetLoc(newElOption, ['left', 'right']),
  67361. // Rigid body, dont care `height`.
  67362. isSetLoc(newElOption, ['top', 'bottom'])
  67363. ];
  67364. // Give default group size. Otherwise layout error may occur.
  67365. if (existItem.type === 'group') {
  67366. existItem.width == null && (existItem.width = newElOption.width = 0);
  67367. existItem.height == null && (existItem.height = newElOption.height = 0);
  67368. }
  67369. }
  67370. function setEventData(el, graphicModel, elOption) {
  67371. var eventData = el.eventData;
  67372. // Simple optimize for large amount of elements that no need event.
  67373. if (!el.silent && !el.ignore && !eventData) {
  67374. eventData = el.eventData = {
  67375. componentType: 'graphic',
  67376. componentIndex: graphicModel.componentIndex,
  67377. name: el.name
  67378. };
  67379. }
  67380. // `elOption.info` enables user to mount some info on
  67381. // elements and use them in event handlers.
  67382. if (eventData) {
  67383. eventData.info = el.info;
  67384. }
  67385. }
  67386. /*
  67387. * Licensed to the Apache Software Foundation (ASF) under one
  67388. * or more contributor license agreements. See the NOTICE file
  67389. * distributed with this work for additional information
  67390. * regarding copyright ownership. The ASF licenses this file
  67391. * to you under the Apache License, Version 2.0 (the
  67392. * "License"); you may not use this file except in compliance
  67393. * with the License. You may obtain a copy of the License at
  67394. *
  67395. * http://www.apache.org/licenses/LICENSE-2.0
  67396. *
  67397. * Unless required by applicable law or agreed to in writing,
  67398. * software distributed under the License is distributed on an
  67399. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67400. * KIND, either express or implied. See the License for the
  67401. * specific language governing permissions and limitations
  67402. * under the License.
  67403. */
  67404. var features = {};
  67405. function register$1(name, ctor) {
  67406. features[name] = ctor;
  67407. }
  67408. function get$1(name) {
  67409. return features[name];
  67410. }
  67411. /*
  67412. * Licensed to the Apache Software Foundation (ASF) under one
  67413. * or more contributor license agreements. See the NOTICE file
  67414. * distributed with this work for additional information
  67415. * regarding copyright ownership. The ASF licenses this file
  67416. * to you under the Apache License, Version 2.0 (the
  67417. * "License"); you may not use this file except in compliance
  67418. * with the License. You may obtain a copy of the License at
  67419. *
  67420. * http://www.apache.org/licenses/LICENSE-2.0
  67421. *
  67422. * Unless required by applicable law or agreed to in writing,
  67423. * software distributed under the License is distributed on an
  67424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67425. * KIND, either express or implied. See the License for the
  67426. * specific language governing permissions and limitations
  67427. * under the License.
  67428. */
  67429. var ToolboxModel = extendComponentModel({
  67430. type: 'toolbox',
  67431. layoutMode: {
  67432. type: 'box',
  67433. ignoreSize: true
  67434. },
  67435. optionUpdated: function () {
  67436. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  67437. each$1(this.option.feature, function (featureOpt, featureName) {
  67438. var Feature = get$1(featureName);
  67439. Feature && merge(featureOpt, Feature.defaultOption);
  67440. });
  67441. },
  67442. defaultOption: {
  67443. show: true,
  67444. z: 6,
  67445. zlevel: 0,
  67446. orient: 'horizontal',
  67447. left: 'right',
  67448. top: 'top',
  67449. // right
  67450. // bottom
  67451. backgroundColor: 'transparent',
  67452. borderColor: '#ccc',
  67453. borderRadius: 0,
  67454. borderWidth: 0,
  67455. padding: 5,
  67456. itemSize: 15,
  67457. itemGap: 8,
  67458. showTitle: true,
  67459. iconStyle: {
  67460. borderColor: '#666',
  67461. color: 'none'
  67462. },
  67463. emphasis: {
  67464. iconStyle: {
  67465. borderColor: '#3E98C5'
  67466. }
  67467. },
  67468. // textStyle: {},
  67469. // feature
  67470. tooltip: {
  67471. show: false
  67472. }
  67473. }
  67474. });
  67475. /*
  67476. * Licensed to the Apache Software Foundation (ASF) under one
  67477. * or more contributor license agreements. See the NOTICE file
  67478. * distributed with this work for additional information
  67479. * regarding copyright ownership. The ASF licenses this file
  67480. * to you under the Apache License, Version 2.0 (the
  67481. * "License"); you may not use this file except in compliance
  67482. * with the License. You may obtain a copy of the License at
  67483. *
  67484. * http://www.apache.org/licenses/LICENSE-2.0
  67485. *
  67486. * Unless required by applicable law or agreed to in writing,
  67487. * software distributed under the License is distributed on an
  67488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67489. * KIND, either express or implied. See the License for the
  67490. * specific language governing permissions and limitations
  67491. * under the License.
  67492. */
  67493. /**
  67494. * Layout list like component.
  67495. * It will box layout each items in group of component and then position the whole group in the viewport
  67496. * @param {module:zrender/group/Group} group
  67497. * @param {module:echarts/model/Component} componentModel
  67498. * @param {module:echarts/ExtensionAPI}
  67499. */
  67500. function layout$3(group, componentModel, api) {
  67501. var boxLayoutParams = componentModel.getBoxLayoutParams();
  67502. var padding = componentModel.get('padding');
  67503. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  67504. var rect = getLayoutRect(
  67505. boxLayoutParams,
  67506. viewportSize,
  67507. padding
  67508. );
  67509. box(
  67510. componentModel.get('orient'),
  67511. group,
  67512. componentModel.get('itemGap'),
  67513. rect.width,
  67514. rect.height
  67515. );
  67516. positionElement(
  67517. group,
  67518. boxLayoutParams,
  67519. viewportSize,
  67520. padding
  67521. );
  67522. }
  67523. function makeBackground(rect, componentModel) {
  67524. var padding = normalizeCssArray$1(
  67525. componentModel.get('padding')
  67526. );
  67527. var style = componentModel.getItemStyle(['color', 'opacity']);
  67528. style.fill = componentModel.get('backgroundColor');
  67529. var rect = new Rect({
  67530. shape: {
  67531. x: rect.x - padding[3],
  67532. y: rect.y - padding[0],
  67533. width: rect.width + padding[1] + padding[3],
  67534. height: rect.height + padding[0] + padding[2],
  67535. r: componentModel.get('borderRadius')
  67536. },
  67537. style: style,
  67538. silent: true,
  67539. z2: -1
  67540. });
  67541. // FIXME
  67542. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  67543. // and background rect when setting like `left: 0`, `top: 0`.
  67544. // graphic.subPixelOptimizeRect(rect);
  67545. return rect;
  67546. }
  67547. /*
  67548. * Licensed to the Apache Software Foundation (ASF) under one
  67549. * or more contributor license agreements. See the NOTICE file
  67550. * distributed with this work for additional information
  67551. * regarding copyright ownership. The ASF licenses this file
  67552. * to you under the Apache License, Version 2.0 (the
  67553. * "License"); you may not use this file except in compliance
  67554. * with the License. You may obtain a copy of the License at
  67555. *
  67556. * http://www.apache.org/licenses/LICENSE-2.0
  67557. *
  67558. * Unless required by applicable law or agreed to in writing,
  67559. * software distributed under the License is distributed on an
  67560. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67561. * KIND, either express or implied. See the License for the
  67562. * specific language governing permissions and limitations
  67563. * under the License.
  67564. */
  67565. extendComponentView({
  67566. type: 'toolbox',
  67567. render: function (toolboxModel, ecModel, api, payload) {
  67568. var group = this.group;
  67569. group.removeAll();
  67570. if (!toolboxModel.get('show')) {
  67571. return;
  67572. }
  67573. var itemSize = +toolboxModel.get('itemSize');
  67574. var featureOpts = toolboxModel.get('feature') || {};
  67575. var features = this._features || (this._features = {});
  67576. var featureNames = [];
  67577. each$1(featureOpts, function (opt, name) {
  67578. featureNames.push(name);
  67579. });
  67580. (new DataDiffer(this._featureNames || [], featureNames))
  67581. .add(processFeature)
  67582. .update(processFeature)
  67583. .remove(curry(processFeature, null))
  67584. .execute();
  67585. // Keep for diff.
  67586. this._featureNames = featureNames;
  67587. function processFeature(newIndex, oldIndex) {
  67588. var featureName = featureNames[newIndex];
  67589. var oldName = featureNames[oldIndex];
  67590. var featureOpt = featureOpts[featureName];
  67591. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  67592. var feature;
  67593. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  67594. if (payload && payload.newTitle != null) {
  67595. featureOpt.title = payload.newTitle;
  67596. }
  67597. if (featureName && !oldName) { // Create
  67598. if (isUserFeatureName(featureName)) {
  67599. feature = {
  67600. model: featureModel,
  67601. onclick: featureModel.option.onclick,
  67602. featureName: featureName
  67603. };
  67604. }
  67605. else {
  67606. var Feature = get$1(featureName);
  67607. if (!Feature) {
  67608. return;
  67609. }
  67610. feature = new Feature(featureModel, ecModel, api);
  67611. }
  67612. features[featureName] = feature;
  67613. }
  67614. else {
  67615. feature = features[oldName];
  67616. // If feature does not exsit.
  67617. if (!feature) {
  67618. return;
  67619. }
  67620. feature.model = featureModel;
  67621. feature.ecModel = ecModel;
  67622. feature.api = api;
  67623. }
  67624. if (!featureName && oldName) {
  67625. feature.dispose && feature.dispose(ecModel, api);
  67626. return;
  67627. }
  67628. if (!featureModel.get('show') || feature.unusable) {
  67629. feature.remove && feature.remove(ecModel, api);
  67630. return;
  67631. }
  67632. createIconPaths(featureModel, feature, featureName);
  67633. featureModel.setIconStatus = function (iconName, status) {
  67634. var option = this.option;
  67635. var iconPaths = this.iconPaths;
  67636. option.iconStatus = option.iconStatus || {};
  67637. option.iconStatus[iconName] = status;
  67638. // FIXME
  67639. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  67640. };
  67641. if (feature.render) {
  67642. feature.render(featureModel, ecModel, api, payload);
  67643. }
  67644. }
  67645. function createIconPaths(featureModel, feature, featureName) {
  67646. var iconStyleModel = featureModel.getModel('iconStyle');
  67647. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  67648. // If one feature has mutiple icon. they are orginaized as
  67649. // {
  67650. // icon: {
  67651. // foo: '',
  67652. // bar: ''
  67653. // },
  67654. // title: {
  67655. // foo: '',
  67656. // bar: ''
  67657. // }
  67658. // }
  67659. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  67660. var titles = featureModel.get('title') || {};
  67661. if (typeof icons === 'string') {
  67662. var icon = icons;
  67663. var title = titles;
  67664. icons = {};
  67665. titles = {};
  67666. icons[featureName] = icon;
  67667. titles[featureName] = title;
  67668. }
  67669. var iconPaths = featureModel.iconPaths = {};
  67670. each$1(icons, function (iconStr, iconName) {
  67671. var path = createIcon(
  67672. iconStr,
  67673. {},
  67674. {
  67675. x: -itemSize / 2,
  67676. y: -itemSize / 2,
  67677. width: itemSize,
  67678. height: itemSize
  67679. }
  67680. );
  67681. path.setStyle(iconStyleModel.getItemStyle());
  67682. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  67683. // Text position calculation
  67684. path.setStyle({
  67685. text: titles[iconName],
  67686. textAlign: iconStyleEmphasisModel.get('textAlign'),
  67687. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  67688. textPadding: iconStyleEmphasisModel.get('textPadding'),
  67689. textFill: null
  67690. });
  67691. var tooltipModel = toolboxModel.getModel('tooltip');
  67692. if (tooltipModel && tooltipModel.get('show')) {
  67693. path.attr('tooltip', extend({
  67694. content: titles[iconName],
  67695. formatter: tooltipModel.get('formatter', true)
  67696. || function () {
  67697. return titles[iconName];
  67698. },
  67699. formatterParams: {
  67700. componentType: 'toolbox',
  67701. name: iconName,
  67702. title: titles[iconName],
  67703. $vars: ['name', 'title']
  67704. },
  67705. position: tooltipModel.get('position', true) || 'bottom'
  67706. }, tooltipModel.option));
  67707. }
  67708. setHoverStyle(path);
  67709. if (toolboxModel.get('showTitle')) {
  67710. path.__title = titles[iconName];
  67711. path.on('mouseover', function () {
  67712. // Should not reuse above hoverStyle, which might be modified.
  67713. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  67714. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  67715. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  67716. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  67717. path.setStyle({
  67718. textFill: iconStyleEmphasisModel.get('textFill')
  67719. || hoverStyle.fill || hoverStyle.stroke || '#000',
  67720. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  67721. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  67722. });
  67723. })
  67724. .on('mouseout', function () {
  67725. path.setStyle({
  67726. textFill: null,
  67727. textBackgroundColor: null
  67728. });
  67729. });
  67730. }
  67731. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  67732. group.add(path);
  67733. path.on('click', bind(
  67734. feature.onclick, feature, ecModel, api, iconName
  67735. ));
  67736. iconPaths[iconName] = path;
  67737. });
  67738. }
  67739. layout$3(group, toolboxModel, api);
  67740. // Render background after group is layout
  67741. // FIXME
  67742. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  67743. // Adjust icon title positions to avoid them out of screen
  67744. group.eachChild(function (icon) {
  67745. var titleText = icon.__title;
  67746. var hoverStyle = icon.hoverStyle;
  67747. // May be background element
  67748. if (hoverStyle && titleText) {
  67749. var rect = getBoundingRect(
  67750. titleText, makeFont(hoverStyle)
  67751. );
  67752. var offsetX = icon.position[0] + group.position[0];
  67753. var offsetY = icon.position[1] + group.position[1] + itemSize;
  67754. var needPutOnTop = false;
  67755. if (offsetY + rect.height > api.getHeight()) {
  67756. hoverStyle.textPosition = 'top';
  67757. needPutOnTop = true;
  67758. }
  67759. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  67760. if (offsetX + rect.width / 2 > api.getWidth()) {
  67761. hoverStyle.textPosition = ['100%', topOffset];
  67762. hoverStyle.textAlign = 'right';
  67763. }
  67764. else if (offsetX - rect.width / 2 < 0) {
  67765. hoverStyle.textPosition = [0, topOffset];
  67766. hoverStyle.textAlign = 'left';
  67767. }
  67768. }
  67769. });
  67770. },
  67771. updateView: function (toolboxModel, ecModel, api, payload) {
  67772. each$1(this._features, function (feature) {
  67773. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  67774. });
  67775. },
  67776. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  67777. // zrUtil.each(this._features, function (feature) {
  67778. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  67779. // });
  67780. // },
  67781. remove: function (ecModel, api) {
  67782. each$1(this._features, function (feature) {
  67783. feature.remove && feature.remove(ecModel, api);
  67784. });
  67785. this.group.removeAll();
  67786. },
  67787. dispose: function (ecModel, api) {
  67788. each$1(this._features, function (feature) {
  67789. feature.dispose && feature.dispose(ecModel, api);
  67790. });
  67791. }
  67792. });
  67793. function isUserFeatureName(featureName) {
  67794. return featureName.indexOf('my') === 0;
  67795. }
  67796. /*
  67797. * Licensed to the Apache Software Foundation (ASF) under one
  67798. * or more contributor license agreements. See the NOTICE file
  67799. * distributed with this work for additional information
  67800. * regarding copyright ownership. The ASF licenses this file
  67801. * to you under the Apache License, Version 2.0 (the
  67802. * "License"); you may not use this file except in compliance
  67803. * with the License. You may obtain a copy of the License at
  67804. *
  67805. * http://www.apache.org/licenses/LICENSE-2.0
  67806. *
  67807. * Unless required by applicable law or agreed to in writing,
  67808. * software distributed under the License is distributed on an
  67809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67810. * KIND, either express or implied. See the License for the
  67811. * specific language governing permissions and limitations
  67812. * under the License.
  67813. */
  67814. /* global Uint8Array */
  67815. var saveAsImageLang = lang.toolbox.saveAsImage;
  67816. function SaveAsImage(model) {
  67817. this.model = model;
  67818. }
  67819. SaveAsImage.defaultOption = {
  67820. show: true,
  67821. 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',
  67822. title: saveAsImageLang.title,
  67823. type: 'png',
  67824. // Default use option.backgroundColor
  67825. // backgroundColor: '#fff',
  67826. connectedBackgroundColor: '#fff',
  67827. name: '',
  67828. excludeComponents: ['toolbox'],
  67829. pixelRatio: 1,
  67830. lang: saveAsImageLang.lang.slice()
  67831. };
  67832. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  67833. var proto$2 = SaveAsImage.prototype;
  67834. proto$2.onclick = function (ecModel, api) {
  67835. var model = this.model;
  67836. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  67837. var type = model.get('type', true) || 'png';
  67838. var url = api.getConnectedDataURL({
  67839. type: type,
  67840. backgroundColor: model.get('backgroundColor', true)
  67841. || ecModel.get('backgroundColor') || '#fff',
  67842. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  67843. excludeComponents: model.get('excludeComponents'),
  67844. pixelRatio: model.get('pixelRatio')
  67845. });
  67846. // Chrome and Firefox
  67847. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  67848. var $a = document.createElement('a');
  67849. $a.download = title + '.' + type;
  67850. $a.target = '_blank';
  67851. $a.href = url;
  67852. var evt = new MouseEvent('click', {
  67853. view: window,
  67854. bubbles: true,
  67855. cancelable: false
  67856. });
  67857. $a.dispatchEvent(evt);
  67858. }
  67859. // IE
  67860. else {
  67861. if (window.navigator.msSaveOrOpenBlob) {
  67862. var bstr = atob(url.split(',')[1]);
  67863. var n = bstr.length;
  67864. var u8arr = new Uint8Array(n);
  67865. while (n--) {
  67866. u8arr[n] = bstr.charCodeAt(n);
  67867. }
  67868. var blob = new Blob([u8arr]);
  67869. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  67870. }
  67871. else {
  67872. var lang$$1 = model.get('lang');
  67873. var html = ''
  67874. + '<body style="margin:0;">'
  67875. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  67876. + '</body>';
  67877. var tab = window.open();
  67878. tab.document.write(html);
  67879. }
  67880. }
  67881. };
  67882. register$1(
  67883. 'saveAsImage', SaveAsImage
  67884. );
  67885. /*
  67886. * Licensed to the Apache Software Foundation (ASF) under one
  67887. * or more contributor license agreements. See the NOTICE file
  67888. * distributed with this work for additional information
  67889. * regarding copyright ownership. The ASF licenses this file
  67890. * to you under the Apache License, Version 2.0 (the
  67891. * "License"); you may not use this file except in compliance
  67892. * with the License. You may obtain a copy of the License at
  67893. *
  67894. * http://www.apache.org/licenses/LICENSE-2.0
  67895. *
  67896. * Unless required by applicable law or agreed to in writing,
  67897. * software distributed under the License is distributed on an
  67898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67899. * KIND, either express or implied. See the License for the
  67900. * specific language governing permissions and limitations
  67901. * under the License.
  67902. */
  67903. var magicTypeLang = lang.toolbox.magicType;
  67904. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  67905. function MagicType(model) {
  67906. this.model = model;
  67907. }
  67908. MagicType.defaultOption = {
  67909. show: true,
  67910. type: [],
  67911. // Icon group
  67912. icon: {
  67913. /* eslint-disable */
  67914. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  67915. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  67916. 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
  67917. /* eslint-enable */
  67918. },
  67919. // `line`, `bar`, `stack`, `tiled`
  67920. title: clone(magicTypeLang.title),
  67921. option: {},
  67922. seriesIndex: {}
  67923. };
  67924. var proto$3 = MagicType.prototype;
  67925. proto$3.getIcons = function () {
  67926. var model = this.model;
  67927. var availableIcons = model.get('icon');
  67928. var icons = {};
  67929. each$1(model.get('type'), function (type) {
  67930. if (availableIcons[type]) {
  67931. icons[type] = availableIcons[type];
  67932. }
  67933. });
  67934. return icons;
  67935. };
  67936. var seriesOptGenreator = {
  67937. 'line': function (seriesType, seriesId, seriesModel, model) {
  67938. if (seriesType === 'bar') {
  67939. return merge({
  67940. id: seriesId,
  67941. type: 'line',
  67942. // Preserve data related option
  67943. data: seriesModel.get('data'),
  67944. stack: seriesModel.get('stack'),
  67945. markPoint: seriesModel.get('markPoint'),
  67946. markLine: seriesModel.get('markLine')
  67947. }, model.get('option.line') || {}, true);
  67948. }
  67949. },
  67950. 'bar': function (seriesType, seriesId, seriesModel, model) {
  67951. if (seriesType === 'line') {
  67952. return merge({
  67953. id: seriesId,
  67954. type: 'bar',
  67955. // Preserve data related option
  67956. data: seriesModel.get('data'),
  67957. stack: seriesModel.get('stack'),
  67958. markPoint: seriesModel.get('markPoint'),
  67959. markLine: seriesModel.get('markLine')
  67960. }, model.get('option.bar') || {}, true);
  67961. }
  67962. },
  67963. 'stack': function (seriesType, seriesId, seriesModel, model) {
  67964. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  67965. if (seriesType === 'line' || seriesType === 'bar') {
  67966. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  67967. return merge({
  67968. id: seriesId,
  67969. stack: isStack ? '' : INNER_STACK_KEYWORD
  67970. }, model.get('option.stack') || {}, true);
  67971. }
  67972. }
  67973. };
  67974. var radioTypes = [
  67975. ['line', 'bar'],
  67976. ['stack']
  67977. ];
  67978. proto$3.onclick = function (ecModel, api, type) {
  67979. var model = this.model;
  67980. var seriesIndex = model.get('seriesIndex.' + type);
  67981. // Not supported magicType
  67982. if (!seriesOptGenreator[type]) {
  67983. return;
  67984. }
  67985. var newOption = {
  67986. series: []
  67987. };
  67988. var generateNewSeriesTypes = function (seriesModel) {
  67989. var seriesType = seriesModel.subType;
  67990. var seriesId = seriesModel.id;
  67991. var newSeriesOpt = seriesOptGenreator[type](
  67992. seriesType, seriesId, seriesModel, model
  67993. );
  67994. if (newSeriesOpt) {
  67995. // PENDING If merge original option?
  67996. defaults(newSeriesOpt, seriesModel.option);
  67997. newOption.series.push(newSeriesOpt);
  67998. }
  67999. // Modify boundaryGap
  68000. var coordSys = seriesModel.coordinateSystem;
  68001. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  68002. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  68003. if (categoryAxis) {
  68004. var axisDim = categoryAxis.dim;
  68005. var axisType = axisDim + 'Axis';
  68006. var axisModel = ecModel.queryComponents({
  68007. mainType: axisType,
  68008. index: seriesModel.get(name + 'Index'),
  68009. id: seriesModel.get(name + 'Id')
  68010. })[0];
  68011. var axisIndex = axisModel.componentIndex;
  68012. newOption[axisType] = newOption[axisType] || [];
  68013. for (var i = 0; i <= axisIndex; i++) {
  68014. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  68015. }
  68016. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  68017. }
  68018. }
  68019. };
  68020. each$1(radioTypes, function (radio) {
  68021. if (indexOf(radio, type) >= 0) {
  68022. each$1(radio, function (item) {
  68023. model.setIconStatus(item, 'normal');
  68024. });
  68025. }
  68026. });
  68027. model.setIconStatus(type, 'emphasis');
  68028. ecModel.eachComponent(
  68029. {
  68030. mainType: 'series',
  68031. query: seriesIndex == null ? null : {
  68032. seriesIndex: seriesIndex
  68033. }
  68034. }, generateNewSeriesTypes
  68035. );
  68036. var newTitle;
  68037. // Change title of stack
  68038. if (type === 'stack') {
  68039. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  68040. newTitle = isStack
  68041. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  68042. : clone(magicTypeLang.title);
  68043. }
  68044. api.dispatchAction({
  68045. type: 'changeMagicType',
  68046. currentType: type,
  68047. newOption: newOption,
  68048. newTitle: newTitle
  68049. });
  68050. };
  68051. registerAction({
  68052. type: 'changeMagicType',
  68053. event: 'magicTypeChanged',
  68054. update: 'prepareAndUpdate'
  68055. }, function (payload, ecModel) {
  68056. ecModel.mergeOption(payload.newOption);
  68057. });
  68058. register$1('magicType', MagicType);
  68059. /*
  68060. * Licensed to the Apache Software Foundation (ASF) under one
  68061. * or more contributor license agreements. See the NOTICE file
  68062. * distributed with this work for additional information
  68063. * regarding copyright ownership. The ASF licenses this file
  68064. * to you under the Apache License, Version 2.0 (the
  68065. * "License"); you may not use this file except in compliance
  68066. * with the License. You may obtain a copy of the License at
  68067. *
  68068. * http://www.apache.org/licenses/LICENSE-2.0
  68069. *
  68070. * Unless required by applicable law or agreed to in writing,
  68071. * software distributed under the License is distributed on an
  68072. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68073. * KIND, either express or implied. See the License for the
  68074. * specific language governing permissions and limitations
  68075. * under the License.
  68076. */
  68077. var dataViewLang = lang.toolbox.dataView;
  68078. var BLOCK_SPLITER = new Array(60).join('-');
  68079. var ITEM_SPLITER = '\t';
  68080. /**
  68081. * Group series into two types
  68082. * 1. on category axis, like line, bar
  68083. * 2. others, like scatter, pie
  68084. * @param {module:echarts/model/Global} ecModel
  68085. * @return {Object}
  68086. * @inner
  68087. */
  68088. function groupSeries(ecModel) {
  68089. var seriesGroupByCategoryAxis = {};
  68090. var otherSeries = [];
  68091. var meta = [];
  68092. ecModel.eachRawSeries(function (seriesModel) {
  68093. var coordSys = seriesModel.coordinateSystem;
  68094. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  68095. var baseAxis = coordSys.getBaseAxis();
  68096. if (baseAxis.type === 'category') {
  68097. var key = baseAxis.dim + '_' + baseAxis.index;
  68098. if (!seriesGroupByCategoryAxis[key]) {
  68099. seriesGroupByCategoryAxis[key] = {
  68100. categoryAxis: baseAxis,
  68101. valueAxis: coordSys.getOtherAxis(baseAxis),
  68102. series: []
  68103. };
  68104. meta.push({
  68105. axisDim: baseAxis.dim,
  68106. axisIndex: baseAxis.index
  68107. });
  68108. }
  68109. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  68110. }
  68111. else {
  68112. otherSeries.push(seriesModel);
  68113. }
  68114. }
  68115. else {
  68116. otherSeries.push(seriesModel);
  68117. }
  68118. });
  68119. return {
  68120. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  68121. other: otherSeries,
  68122. meta: meta
  68123. };
  68124. }
  68125. /**
  68126. * Assemble content of series on cateogory axis
  68127. * @param {Array.<module:echarts/model/Series>} series
  68128. * @return {string}
  68129. * @inner
  68130. */
  68131. function assembleSeriesWithCategoryAxis(series) {
  68132. var tables = [];
  68133. each$1(series, function (group, key) {
  68134. var categoryAxis = group.categoryAxis;
  68135. var valueAxis = group.valueAxis;
  68136. var valueAxisDim = valueAxis.dim;
  68137. var headers = [' '].concat(map(group.series, function (series) {
  68138. return series.name;
  68139. }));
  68140. var columns = [categoryAxis.model.getCategories()];
  68141. each$1(group.series, function (series) {
  68142. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  68143. return val;
  68144. }));
  68145. });
  68146. // Assemble table content
  68147. var lines = [headers.join(ITEM_SPLITER)];
  68148. for (var i = 0; i < columns[0].length; i++) {
  68149. var items = [];
  68150. for (var j = 0; j < columns.length; j++) {
  68151. items.push(columns[j][i]);
  68152. }
  68153. lines.push(items.join(ITEM_SPLITER));
  68154. }
  68155. tables.push(lines.join('\n'));
  68156. });
  68157. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  68158. }
  68159. /**
  68160. * Assemble content of other series
  68161. * @param {Array.<module:echarts/model/Series>} series
  68162. * @return {string}
  68163. * @inner
  68164. */
  68165. function assembleOtherSeries(series) {
  68166. return map(series, function (series) {
  68167. var data = series.getRawData();
  68168. var lines = [series.name];
  68169. var vals = [];
  68170. data.each(data.dimensions, function () {
  68171. var argLen = arguments.length;
  68172. var dataIndex = arguments[argLen - 1];
  68173. var name = data.getName(dataIndex);
  68174. for (var i = 0; i < argLen - 1; i++) {
  68175. vals[i] = arguments[i];
  68176. }
  68177. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  68178. });
  68179. return lines.join('\n');
  68180. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  68181. }
  68182. /**
  68183. * @param {module:echarts/model/Global}
  68184. * @return {Object}
  68185. * @inner
  68186. */
  68187. function getContentFromModel(ecModel) {
  68188. var result = groupSeries(ecModel);
  68189. return {
  68190. value: filter([
  68191. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  68192. assembleOtherSeries(result.other)
  68193. ], function (str) {
  68194. return str.replace(/[\n\t\s]/g, '');
  68195. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  68196. meta: result.meta
  68197. };
  68198. }
  68199. function trim$1(str) {
  68200. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  68201. }
  68202. /**
  68203. * If a block is tsv format
  68204. */
  68205. function isTSVFormat(block) {
  68206. // Simple method to find out if a block is tsv format
  68207. var firstLine = block.slice(0, block.indexOf('\n'));
  68208. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  68209. return true;
  68210. }
  68211. }
  68212. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  68213. /**
  68214. * @param {string} tsv
  68215. * @return {Object}
  68216. */
  68217. function parseTSVContents(tsv) {
  68218. var tsvLines = tsv.split(/\n+/g);
  68219. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  68220. var categories = [];
  68221. var series = map(headers, function (header) {
  68222. return {
  68223. name: header,
  68224. data: []
  68225. };
  68226. });
  68227. for (var i = 0; i < tsvLines.length; i++) {
  68228. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  68229. categories.push(items.shift());
  68230. for (var j = 0; j < items.length; j++) {
  68231. series[j] && (series[j].data[i] = items[j]);
  68232. }
  68233. }
  68234. return {
  68235. series: series,
  68236. categories: categories
  68237. };
  68238. }
  68239. /**
  68240. * @param {string} str
  68241. * @return {Array.<Object>}
  68242. * @inner
  68243. */
  68244. function parseListContents(str) {
  68245. var lines = str.split(/\n+/g);
  68246. var seriesName = trim$1(lines.shift());
  68247. var data = [];
  68248. for (var i = 0; i < lines.length; i++) {
  68249. var items = trim$1(lines[i]).split(itemSplitRegex);
  68250. var name = '';
  68251. var value;
  68252. var hasName = false;
  68253. if (isNaN(items[0])) { // First item is name
  68254. hasName = true;
  68255. name = items[0];
  68256. items = items.slice(1);
  68257. data[i] = {
  68258. name: name,
  68259. value: []
  68260. };
  68261. value = data[i].value;
  68262. }
  68263. else {
  68264. value = data[i] = [];
  68265. }
  68266. for (var j = 0; j < items.length; j++) {
  68267. value.push(+items[j]);
  68268. }
  68269. if (value.length === 1) {
  68270. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  68271. }
  68272. }
  68273. return {
  68274. name: seriesName,
  68275. data: data
  68276. };
  68277. }
  68278. /**
  68279. * @param {string} str
  68280. * @param {Array.<Object>} blockMetaList
  68281. * @return {Object}
  68282. * @inner
  68283. */
  68284. function parseContents(str, blockMetaList) {
  68285. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  68286. var newOption = {
  68287. series: []
  68288. };
  68289. each$1(blocks, function (block, idx) {
  68290. if (isTSVFormat(block)) {
  68291. var result = parseTSVContents(block);
  68292. var blockMeta = blockMetaList[idx];
  68293. var axisKey = blockMeta.axisDim + 'Axis';
  68294. if (blockMeta) {
  68295. newOption[axisKey] = newOption[axisKey] || [];
  68296. newOption[axisKey][blockMeta.axisIndex] = {
  68297. data: result.categories
  68298. };
  68299. newOption.series = newOption.series.concat(result.series);
  68300. }
  68301. }
  68302. else {
  68303. var result = parseListContents(block);
  68304. newOption.series.push(result);
  68305. }
  68306. });
  68307. return newOption;
  68308. }
  68309. /**
  68310. * @alias {module:echarts/component/toolbox/feature/DataView}
  68311. * @constructor
  68312. * @param {module:echarts/model/Model} model
  68313. */
  68314. function DataView(model) {
  68315. this._dom = null;
  68316. this.model = model;
  68317. }
  68318. DataView.defaultOption = {
  68319. show: true,
  68320. readOnly: false,
  68321. optionToContent: null,
  68322. contentToOption: null,
  68323. 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',
  68324. title: clone(dataViewLang.title),
  68325. lang: clone(dataViewLang.lang),
  68326. backgroundColor: '#fff',
  68327. textColor: '#000',
  68328. textareaColor: '#fff',
  68329. textareaBorderColor: '#333',
  68330. buttonColor: '#c23531',
  68331. buttonTextColor: '#fff'
  68332. };
  68333. DataView.prototype.onclick = function (ecModel, api) {
  68334. var container = api.getDom();
  68335. var model = this.model;
  68336. if (this._dom) {
  68337. container.removeChild(this._dom);
  68338. }
  68339. var root = document.createElement('div');
  68340. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  68341. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  68342. // Create elements
  68343. var header = document.createElement('h4');
  68344. var lang$$1 = model.get('lang') || [];
  68345. header.innerHTML = lang$$1[0] || model.get('title');
  68346. header.style.cssText = 'margin: 10px 20px;';
  68347. header.style.color = model.get('textColor');
  68348. var viewMain = document.createElement('div');
  68349. var textarea = document.createElement('textarea');
  68350. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  68351. var optionToContent = model.get('optionToContent');
  68352. var contentToOption = model.get('contentToOption');
  68353. var result = getContentFromModel(ecModel);
  68354. if (typeof optionToContent === 'function') {
  68355. var htmlOrDom = optionToContent(api.getOption());
  68356. if (typeof htmlOrDom === 'string') {
  68357. viewMain.innerHTML = htmlOrDom;
  68358. }
  68359. else if (isDom(htmlOrDom)) {
  68360. viewMain.appendChild(htmlOrDom);
  68361. }
  68362. }
  68363. else {
  68364. // Use default textarea
  68365. viewMain.appendChild(textarea);
  68366. textarea.readOnly = model.get('readOnly');
  68367. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  68368. textarea.style.color = model.get('textColor');
  68369. textarea.style.borderColor = model.get('textareaBorderColor');
  68370. textarea.style.backgroundColor = model.get('textareaColor');
  68371. textarea.value = result.value;
  68372. }
  68373. var blockMetaList = result.meta;
  68374. var buttonContainer = document.createElement('div');
  68375. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  68376. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  68377. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  68378. var closeButton = document.createElement('div');
  68379. var refreshButton = document.createElement('div');
  68380. buttonStyle += ';background-color:' + model.get('buttonColor');
  68381. buttonStyle += ';color:' + model.get('buttonTextColor');
  68382. var self = this;
  68383. function close() {
  68384. container.removeChild(root);
  68385. self._dom = null;
  68386. }
  68387. addEventListener(closeButton, 'click', close);
  68388. addEventListener(refreshButton, 'click', function () {
  68389. var newOption;
  68390. try {
  68391. if (typeof contentToOption === 'function') {
  68392. newOption = contentToOption(viewMain, api.getOption());
  68393. }
  68394. else {
  68395. newOption = parseContents(textarea.value, blockMetaList);
  68396. }
  68397. }
  68398. catch (e) {
  68399. close();
  68400. throw new Error('Data view format error ' + e);
  68401. }
  68402. if (newOption) {
  68403. api.dispatchAction({
  68404. type: 'changeDataView',
  68405. newOption: newOption
  68406. });
  68407. }
  68408. close();
  68409. });
  68410. closeButton.innerHTML = lang$$1[1];
  68411. refreshButton.innerHTML = lang$$1[2];
  68412. refreshButton.style.cssText = buttonStyle;
  68413. closeButton.style.cssText = buttonStyle;
  68414. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  68415. buttonContainer.appendChild(closeButton);
  68416. root.appendChild(header);
  68417. root.appendChild(viewMain);
  68418. root.appendChild(buttonContainer);
  68419. viewMain.style.height = (container.clientHeight - 80) + 'px';
  68420. container.appendChild(root);
  68421. this._dom = root;
  68422. };
  68423. DataView.prototype.remove = function (ecModel, api) {
  68424. this._dom && api.getDom().removeChild(this._dom);
  68425. };
  68426. DataView.prototype.dispose = function (ecModel, api) {
  68427. this.remove(ecModel, api);
  68428. };
  68429. /**
  68430. * @inner
  68431. */
  68432. function tryMergeDataOption(newData, originalData) {
  68433. return map(newData, function (newVal, idx) {
  68434. var original = originalData && originalData[idx];
  68435. if (isObject$1(original) && !isArray(original)) {
  68436. if (isObject$1(newVal) && !isArray(newVal)) {
  68437. newVal = newVal.value;
  68438. }
  68439. // Original data has option
  68440. return defaults({
  68441. value: newVal
  68442. }, original);
  68443. }
  68444. else {
  68445. return newVal;
  68446. }
  68447. });
  68448. }
  68449. register$1('dataView', DataView);
  68450. registerAction({
  68451. type: 'changeDataView',
  68452. event: 'dataViewChanged',
  68453. update: 'prepareAndUpdate'
  68454. }, function (payload, ecModel) {
  68455. var newSeriesOptList = [];
  68456. each$1(payload.newOption.series, function (seriesOpt) {
  68457. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  68458. if (!seriesModel) {
  68459. // New created series
  68460. // Geuss the series type
  68461. newSeriesOptList.push(extend({
  68462. // Default is scatter
  68463. type: 'scatter'
  68464. }, seriesOpt));
  68465. }
  68466. else {
  68467. var originalData = seriesModel.get('data');
  68468. newSeriesOptList.push({
  68469. name: seriesOpt.name,
  68470. data: tryMergeDataOption(seriesOpt.data, originalData)
  68471. });
  68472. }
  68473. });
  68474. ecModel.mergeOption(defaults({
  68475. series: newSeriesOptList
  68476. }, payload.newOption));
  68477. });
  68478. /*
  68479. * Licensed to the Apache Software Foundation (ASF) under one
  68480. * or more contributor license agreements. See the NOTICE file
  68481. * distributed with this work for additional information
  68482. * regarding copyright ownership. The ASF licenses this file
  68483. * to you under the Apache License, Version 2.0 (the
  68484. * "License"); you may not use this file except in compliance
  68485. * with the License. You may obtain a copy of the License at
  68486. *
  68487. * http://www.apache.org/licenses/LICENSE-2.0
  68488. *
  68489. * Unless required by applicable law or agreed to in writing,
  68490. * software distributed under the License is distributed on an
  68491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68492. * KIND, either express or implied. See the License for the
  68493. * specific language governing permissions and limitations
  68494. * under the License.
  68495. */
  68496. var each$17 = each$1;
  68497. var indexOf$1 = indexOf;
  68498. var curry$4 = curry;
  68499. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  68500. // FIXME
  68501. // how to genarialize to more coordinate systems.
  68502. var INCLUDE_FINDER_MAIN_TYPES = [
  68503. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  68504. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  68505. ];
  68506. /**
  68507. * [option in constructor]:
  68508. * {
  68509. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  68510. * }
  68511. *
  68512. *
  68513. * [targetInfo]:
  68514. *
  68515. * There can be multiple axes in a single targetInfo. Consider the case
  68516. * of `grid` component, a targetInfo represents a grid which contains one or more
  68517. * cartesian and one or more axes. And consider the case of parallel system,
  68518. * which has multiple axes in a coordinate system.
  68519. * Can be {
  68520. * panelId: ...,
  68521. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  68522. * coordSyses: all cartesians.
  68523. * gridModel: <grid component>
  68524. * xAxes: correspond to coordSyses on index
  68525. * yAxes: correspond to coordSyses on index
  68526. * }
  68527. * or {
  68528. * panelId: ...,
  68529. * coordSys: <geo coord sys>
  68530. * coordSyses: [<geo coord sys>]
  68531. * geoModel: <geo component>
  68532. * }
  68533. *
  68534. *
  68535. * [panelOpt]:
  68536. *
  68537. * Make from targetInfo. Input to BrushController.
  68538. * {
  68539. * panelId: ...,
  68540. * rect: ...
  68541. * }
  68542. *
  68543. *
  68544. * [area]:
  68545. *
  68546. * Generated by BrushController or user input.
  68547. * {
  68548. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  68549. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  68550. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  68551. * range: pixel range.
  68552. * coordRange: representitive coord range (the first one of coordRanges).
  68553. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  68554. * }
  68555. */
  68556. /**
  68557. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  68558. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  68559. * @param {module:echarts/model/Global} ecModel
  68560. * @param {Object} [opt]
  68561. * @param {Array.<string>} [opt.include] include coordinate system types.
  68562. */
  68563. function BrushTargetManager(option, ecModel, opt) {
  68564. /**
  68565. * @private
  68566. * @type {Array.<Object>}
  68567. */
  68568. var targetInfoList = this._targetInfoList = [];
  68569. var info = {};
  68570. var foundCpts = parseFinder$1(ecModel, option);
  68571. each$17(targetInfoBuilders, function (builder, type) {
  68572. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  68573. builder(foundCpts, targetInfoList, info);
  68574. }
  68575. });
  68576. }
  68577. var proto$5 = BrushTargetManager.prototype;
  68578. proto$5.setOutputRanges = function (areas, ecModel) {
  68579. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  68580. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  68581. // area.coordRange is the first of area.coordRanges
  68582. if (!area.coordRange) {
  68583. area.coordRange = coordRange;
  68584. // In 'category' axis, coord to pixel is not reversible, so we can not
  68585. // rebuild range by coordRange accrately, which may bring trouble when
  68586. // brushing only one item. So we use __rangeOffset to rebuilding range
  68587. // by coordRange. And this it only used in brush component so it is no
  68588. // need to be adapted to coordRanges.
  68589. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  68590. area.__rangeOffset = {
  68591. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  68592. xyMinMax: result.xyMinMax
  68593. };
  68594. }
  68595. });
  68596. };
  68597. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  68598. each$17(areas, function (area) {
  68599. var targetInfo = this.findTargetInfo(area, ecModel);
  68600. if (targetInfo && targetInfo !== true) {
  68601. each$1(
  68602. targetInfo.coordSyses,
  68603. function (coordSys) {
  68604. var result = coordConvert[area.brushType](1, coordSys, area.range);
  68605. cb(area, result.values, coordSys, ecModel);
  68606. }
  68607. );
  68608. }
  68609. }, this);
  68610. };
  68611. proto$5.setInputRanges = function (areas, ecModel) {
  68612. each$17(areas, function (area) {
  68613. var targetInfo = this.findTargetInfo(area, ecModel);
  68614. if (__DEV__) {
  68615. assert$1(
  68616. !targetInfo || targetInfo === true || area.coordRange,
  68617. 'coordRange must be specified when coord index specified.'
  68618. );
  68619. assert$1(
  68620. !targetInfo || targetInfo !== true || area.range,
  68621. 'range must be specified in global brush.'
  68622. );
  68623. }
  68624. area.range = area.range || [];
  68625. // convert coordRange to global range and set panelId.
  68626. if (targetInfo && targetInfo !== true) {
  68627. area.panelId = targetInfo.panelId;
  68628. // (1) area.range shoule always be calculate from coordRange but does
  68629. // not keep its original value, for the sake of the dataZoom scenario,
  68630. // where area.coordRange remains unchanged but area.range may be changed.
  68631. // (2) Only support converting one coordRange to pixel range in brush
  68632. // component. So do not consider `coordRanges`.
  68633. // (3) About __rangeOffset, see comment above.
  68634. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  68635. var rangeOffset = area.__rangeOffset;
  68636. area.range = rangeOffset
  68637. ? diffProcessor[area.brushType](
  68638. result.values,
  68639. rangeOffset.offset,
  68640. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  68641. )
  68642. : result.values;
  68643. }
  68644. }, this);
  68645. };
  68646. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  68647. return map(this._targetInfoList, function (targetInfo) {
  68648. var rect = targetInfo.getPanelRect();
  68649. return {
  68650. panelId: targetInfo.panelId,
  68651. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  68652. clipPath: makeRectPanelClipPath(rect),
  68653. isTargetByCursor: makeRectIsTargetByCursor(
  68654. rect, api, targetInfo.coordSysModel
  68655. ),
  68656. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  68657. };
  68658. });
  68659. };
  68660. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  68661. // Check whether area is bound in coord, and series do not belong to that coord.
  68662. // If do not do this check, some brush (like lineX) will controll all axes.
  68663. var targetInfo = this.findTargetInfo(area, ecModel);
  68664. return targetInfo === true || (
  68665. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  68666. );
  68667. };
  68668. /**
  68669. * If return Object, a coord found.
  68670. * If reutrn true, global found.
  68671. * Otherwise nothing found.
  68672. *
  68673. * @param {Object} area
  68674. * @param {Array} targetInfoList
  68675. * @return {Object|boolean}
  68676. */
  68677. proto$5.findTargetInfo = function (area, ecModel) {
  68678. var targetInfoList = this._targetInfoList;
  68679. var foundCpts = parseFinder$1(ecModel, area);
  68680. for (var i = 0; i < targetInfoList.length; i++) {
  68681. var targetInfo = targetInfoList[i];
  68682. var areaPanelId = area.panelId;
  68683. if (areaPanelId) {
  68684. if (targetInfo.panelId === areaPanelId) {
  68685. return targetInfo;
  68686. }
  68687. }
  68688. else {
  68689. for (var i = 0; i < targetInfoMatchers.length; i++) {
  68690. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  68691. return targetInfo;
  68692. }
  68693. }
  68694. }
  68695. }
  68696. return true;
  68697. };
  68698. function formatMinMax(minMax) {
  68699. minMax[0] > minMax[1] && minMax.reverse();
  68700. return minMax;
  68701. }
  68702. function parseFinder$1(ecModel, option) {
  68703. return parseFinder(
  68704. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  68705. );
  68706. }
  68707. var targetInfoBuilders = {
  68708. grid: function (foundCpts, targetInfoList) {
  68709. var xAxisModels = foundCpts.xAxisModels;
  68710. var yAxisModels = foundCpts.yAxisModels;
  68711. var gridModels = foundCpts.gridModels;
  68712. // Remove duplicated.
  68713. var gridModelMap = createHashMap();
  68714. var xAxesHas = {};
  68715. var yAxesHas = {};
  68716. if (!xAxisModels && !yAxisModels && !gridModels) {
  68717. return;
  68718. }
  68719. each$17(xAxisModels, function (axisModel) {
  68720. var gridModel = axisModel.axis.grid.model;
  68721. gridModelMap.set(gridModel.id, gridModel);
  68722. xAxesHas[gridModel.id] = true;
  68723. });
  68724. each$17(yAxisModels, function (axisModel) {
  68725. var gridModel = axisModel.axis.grid.model;
  68726. gridModelMap.set(gridModel.id, gridModel);
  68727. yAxesHas[gridModel.id] = true;
  68728. });
  68729. each$17(gridModels, function (gridModel) {
  68730. gridModelMap.set(gridModel.id, gridModel);
  68731. xAxesHas[gridModel.id] = true;
  68732. yAxesHas[gridModel.id] = true;
  68733. });
  68734. gridModelMap.each(function (gridModel) {
  68735. var grid = gridModel.coordinateSystem;
  68736. var cartesians = [];
  68737. each$17(grid.getCartesians(), function (cartesian, index) {
  68738. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  68739. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  68740. ) {
  68741. cartesians.push(cartesian);
  68742. }
  68743. });
  68744. targetInfoList.push({
  68745. panelId: 'grid--' + gridModel.id,
  68746. gridModel: gridModel,
  68747. coordSysModel: gridModel,
  68748. // Use the first one as the representitive coordSys.
  68749. coordSys: cartesians[0],
  68750. coordSyses: cartesians,
  68751. getPanelRect: panelRectBuilder.grid,
  68752. xAxisDeclared: xAxesHas[gridModel.id],
  68753. yAxisDeclared: yAxesHas[gridModel.id]
  68754. });
  68755. });
  68756. },
  68757. geo: function (foundCpts, targetInfoList) {
  68758. each$17(foundCpts.geoModels, function (geoModel) {
  68759. var coordSys = geoModel.coordinateSystem;
  68760. targetInfoList.push({
  68761. panelId: 'geo--' + geoModel.id,
  68762. geoModel: geoModel,
  68763. coordSysModel: geoModel,
  68764. coordSys: coordSys,
  68765. coordSyses: [coordSys],
  68766. getPanelRect: panelRectBuilder.geo
  68767. });
  68768. });
  68769. }
  68770. };
  68771. var targetInfoMatchers = [
  68772. // grid
  68773. function (foundCpts, targetInfo) {
  68774. var xAxisModel = foundCpts.xAxisModel;
  68775. var yAxisModel = foundCpts.yAxisModel;
  68776. var gridModel = foundCpts.gridModel;
  68777. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  68778. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  68779. return gridModel && gridModel === targetInfo.gridModel;
  68780. },
  68781. // geo
  68782. function (foundCpts, targetInfo) {
  68783. var geoModel = foundCpts.geoModel;
  68784. return geoModel && geoModel === targetInfo.geoModel;
  68785. }
  68786. ];
  68787. var panelRectBuilder = {
  68788. grid: function () {
  68789. // grid is not Transformable.
  68790. return this.coordSys.grid.getRect().clone();
  68791. },
  68792. geo: function () {
  68793. var coordSys = this.coordSys;
  68794. var rect = coordSys.getBoundingRect().clone();
  68795. // geo roam and zoom transform
  68796. rect.applyTransform(getTransform(coordSys));
  68797. return rect;
  68798. }
  68799. };
  68800. var coordConvert = {
  68801. lineX: curry$4(axisConvert, 0),
  68802. lineY: curry$4(axisConvert, 1),
  68803. rect: function (to, coordSys, rangeOrCoordRange) {
  68804. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  68805. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  68806. var values = [
  68807. formatMinMax([xminymin[0], xmaxymax[0]]),
  68808. formatMinMax([xminymin[1], xmaxymax[1]])
  68809. ];
  68810. return {values: values, xyMinMax: values};
  68811. },
  68812. polygon: function (to, coordSys, rangeOrCoordRange) {
  68813. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  68814. var values = map(rangeOrCoordRange, function (item) {
  68815. var p = coordSys[COORD_CONVERTS[to]](item);
  68816. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  68817. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  68818. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  68819. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  68820. return p;
  68821. });
  68822. return {values: values, xyMinMax: xyMinMax};
  68823. }
  68824. };
  68825. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  68826. if (__DEV__) {
  68827. assert$1(
  68828. coordSys.type === 'cartesian2d',
  68829. 'lineX/lineY brush is available only in cartesian2d.'
  68830. );
  68831. }
  68832. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  68833. var values = formatMinMax(map([0, 1], function (i) {
  68834. return to
  68835. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  68836. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  68837. }));
  68838. var xyMinMax = [];
  68839. xyMinMax[axisNameIndex] = values;
  68840. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  68841. return {values: values, xyMinMax: xyMinMax};
  68842. }
  68843. var diffProcessor = {
  68844. lineX: curry$4(axisDiffProcessor, 0),
  68845. lineY: curry$4(axisDiffProcessor, 1),
  68846. rect: function (values, refer, scales) {
  68847. return [
  68848. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  68849. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  68850. ];
  68851. },
  68852. polygon: function (values, refer, scales) {
  68853. return map(values, function (item, idx) {
  68854. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  68855. });
  68856. }
  68857. };
  68858. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  68859. return [
  68860. values[0] - scales[axisNameIndex] * refer[0],
  68861. values[1] - scales[axisNameIndex] * refer[1]
  68862. ];
  68863. }
  68864. // We have to process scale caused by dataZoom manually,
  68865. // although it might be not accurate.
  68866. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  68867. var sizeCurr = getSize(xyMinMaxCurr);
  68868. var sizeOrigin = getSize(xyMinMaxOrigin);
  68869. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  68870. isNaN(scales[0]) && (scales[0] = 1);
  68871. isNaN(scales[1]) && (scales[1] = 1);
  68872. return scales;
  68873. }
  68874. function getSize(xyMinMax) {
  68875. return xyMinMax
  68876. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  68877. : [NaN, NaN];
  68878. }
  68879. /*
  68880. * Licensed to the Apache Software Foundation (ASF) under one
  68881. * or more contributor license agreements. See the NOTICE file
  68882. * distributed with this work for additional information
  68883. * regarding copyright ownership. The ASF licenses this file
  68884. * to you under the Apache License, Version 2.0 (the
  68885. * "License"); you may not use this file except in compliance
  68886. * with the License. You may obtain a copy of the License at
  68887. *
  68888. * http://www.apache.org/licenses/LICENSE-2.0
  68889. *
  68890. * Unless required by applicable law or agreed to in writing,
  68891. * software distributed under the License is distributed on an
  68892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68893. * KIND, either express or implied. See the License for the
  68894. * specific language governing permissions and limitations
  68895. * under the License.
  68896. */
  68897. var each$18 = each$1;
  68898. var ATTR$1 = '\0_ec_hist_store';
  68899. /**
  68900. * @param {module:echarts/model/Global} ecModel
  68901. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  68902. */
  68903. function push(ecModel, newSnapshot) {
  68904. var store = giveStore(ecModel);
  68905. // If previous dataZoom can not be found,
  68906. // complete an range with current range.
  68907. each$18(newSnapshot, function (batchItem, dataZoomId) {
  68908. var i = store.length - 1;
  68909. for (; i >= 0; i--) {
  68910. var snapshot = store[i];
  68911. if (snapshot[dataZoomId]) {
  68912. break;
  68913. }
  68914. }
  68915. if (i < 0) {
  68916. // No origin range set, create one by current range.
  68917. var dataZoomModel = ecModel.queryComponents(
  68918. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  68919. )[0];
  68920. if (dataZoomModel) {
  68921. var percentRange = dataZoomModel.getPercentRange();
  68922. store[0][dataZoomId] = {
  68923. dataZoomId: dataZoomId,
  68924. start: percentRange[0],
  68925. end: percentRange[1]
  68926. };
  68927. }
  68928. }
  68929. });
  68930. store.push(newSnapshot);
  68931. }
  68932. /**
  68933. * @param {module:echarts/model/Global} ecModel
  68934. * @return {Object} snapshot
  68935. */
  68936. function pop(ecModel) {
  68937. var store = giveStore(ecModel);
  68938. var head = store[store.length - 1];
  68939. store.length > 1 && store.pop();
  68940. // Find top for all dataZoom.
  68941. var snapshot = {};
  68942. each$18(head, function (batchItem, dataZoomId) {
  68943. for (var i = store.length - 1; i >= 0; i--) {
  68944. var batchItem = store[i][dataZoomId];
  68945. if (batchItem) {
  68946. snapshot[dataZoomId] = batchItem;
  68947. break;
  68948. }
  68949. }
  68950. });
  68951. return snapshot;
  68952. }
  68953. /**
  68954. * @param {module:echarts/model/Global} ecModel
  68955. */
  68956. function clear$1(ecModel) {
  68957. ecModel[ATTR$1] = null;
  68958. }
  68959. /**
  68960. * @param {module:echarts/model/Global} ecModel
  68961. * @return {number} records. always >= 1.
  68962. */
  68963. function count(ecModel) {
  68964. return giveStore(ecModel).length;
  68965. }
  68966. /**
  68967. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  68968. * History length of each dataZoom may be different.
  68969. * this._history[0] is used to store origin range.
  68970. * @type {Array.<Object>}
  68971. */
  68972. function giveStore(ecModel) {
  68973. var store = ecModel[ATTR$1];
  68974. if (!store) {
  68975. store = ecModel[ATTR$1] = [{}];
  68976. }
  68977. return store;
  68978. }
  68979. /*
  68980. * Licensed to the Apache Software Foundation (ASF) under one
  68981. * or more contributor license agreements. See the NOTICE file
  68982. * distributed with this work for additional information
  68983. * regarding copyright ownership. The ASF licenses this file
  68984. * to you under the Apache License, Version 2.0 (the
  68985. * "License"); you may not use this file except in compliance
  68986. * with the License. You may obtain a copy of the License at
  68987. *
  68988. * http://www.apache.org/licenses/LICENSE-2.0
  68989. *
  68990. * Unless required by applicable law or agreed to in writing,
  68991. * software distributed under the License is distributed on an
  68992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68993. * KIND, either express or implied. See the License for the
  68994. * specific language governing permissions and limitations
  68995. * under the License.
  68996. */
  68997. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  68998. // Default 'slider' when no type specified.
  68999. return 'slider';
  69000. });
  69001. /*
  69002. * Licensed to the Apache Software Foundation (ASF) under one
  69003. * or more contributor license agreements. See the NOTICE file
  69004. * distributed with this work for additional information
  69005. * regarding copyright ownership. The ASF licenses this file
  69006. * to you under the Apache License, Version 2.0 (the
  69007. * "License"); you may not use this file except in compliance
  69008. * with the License. You may obtain a copy of the License at
  69009. *
  69010. * http://www.apache.org/licenses/LICENSE-2.0
  69011. *
  69012. * Unless required by applicable law or agreed to in writing,
  69013. * software distributed under the License is distributed on an
  69014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69015. * KIND, either express or implied. See the License for the
  69016. * specific language governing permissions and limitations
  69017. * under the License.
  69018. */
  69019. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  69020. // Supported coords.
  69021. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  69022. /**
  69023. * @param {string} coordType
  69024. * @return {boolean}
  69025. */
  69026. function isCoordSupported(coordType) {
  69027. return indexOf(COORDS, coordType) >= 0;
  69028. }
  69029. /**
  69030. * Create "each" method to iterate names.
  69031. *
  69032. * @pubilc
  69033. * @param {Array.<string>} names
  69034. * @param {Array.<string>=} attrs
  69035. * @return {Function}
  69036. */
  69037. function createNameEach(names, attrs) {
  69038. names = names.slice();
  69039. var capitalNames = map(names, capitalFirst);
  69040. attrs = (attrs || []).slice();
  69041. var capitalAttrs = map(attrs, capitalFirst);
  69042. return function (callback, context) {
  69043. each$1(names, function (name, index) {
  69044. var nameObj = {name: name, capital: capitalNames[index]};
  69045. for (var j = 0; j < attrs.length; j++) {
  69046. nameObj[attrs[j]] = name + capitalAttrs[j];
  69047. }
  69048. callback.call(context, nameObj);
  69049. });
  69050. };
  69051. }
  69052. /**
  69053. * Iterate each dimension name.
  69054. *
  69055. * @public
  69056. * @param {Function} callback The parameter is like:
  69057. * {
  69058. * name: 'angle',
  69059. * capital: 'Angle',
  69060. * axis: 'angleAxis',
  69061. * axisIndex: 'angleAixs',
  69062. * index: 'angleIndex'
  69063. * }
  69064. * @param {Object} context
  69065. */
  69066. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  69067. /**
  69068. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  69069. * dataZoomModels and 'links' make up one or more graphics.
  69070. * This function finds the graphic where the source dataZoomModel is in.
  69071. *
  69072. * @public
  69073. * @param {Function} forEachNode Node iterator.
  69074. * @param {Function} forEachEdgeType edgeType iterator
  69075. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  69076. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  69077. */
  69078. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  69079. return function (sourceNode) {
  69080. var result = {
  69081. nodes: [],
  69082. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  69083. };
  69084. forEachEdgeType(function (edgeType) {
  69085. result.records[edgeType.name] = {};
  69086. });
  69087. if (!sourceNode) {
  69088. return result;
  69089. }
  69090. absorb(sourceNode, result);
  69091. var existsLink;
  69092. do {
  69093. existsLink = false;
  69094. forEachNode(processSingleNode);
  69095. }
  69096. while (existsLink);
  69097. function processSingleNode(node) {
  69098. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  69099. absorb(node, result);
  69100. existsLink = true;
  69101. }
  69102. }
  69103. return result;
  69104. };
  69105. function isNodeAbsorded(node, result) {
  69106. return indexOf(result.nodes, node) >= 0;
  69107. }
  69108. function isLinked(node, result) {
  69109. var hasLink = false;
  69110. forEachEdgeType(function (edgeType) {
  69111. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69112. result.records[edgeType.name][edgeId] && (hasLink = true);
  69113. });
  69114. });
  69115. return hasLink;
  69116. }
  69117. function absorb(node, result) {
  69118. result.nodes.push(node);
  69119. forEachEdgeType(function (edgeType) {
  69120. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69121. result.records[edgeType.name][edgeId] = true;
  69122. });
  69123. });
  69124. }
  69125. }
  69126. /*
  69127. * Licensed to the Apache Software Foundation (ASF) under one
  69128. * or more contributor license agreements. See the NOTICE file
  69129. * distributed with this work for additional information
  69130. * regarding copyright ownership. The ASF licenses this file
  69131. * to you under the Apache License, Version 2.0 (the
  69132. * "License"); you may not use this file except in compliance
  69133. * with the License. You may obtain a copy of the License at
  69134. *
  69135. * http://www.apache.org/licenses/LICENSE-2.0
  69136. *
  69137. * Unless required by applicable law or agreed to in writing,
  69138. * software distributed under the License is distributed on an
  69139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69140. * KIND, either express or implied. See the License for the
  69141. * specific language governing permissions and limitations
  69142. * under the License.
  69143. */
  69144. var each$20 = each$1;
  69145. var asc$1 = asc;
  69146. /**
  69147. * Operate single axis.
  69148. * One axis can only operated by one axis operator.
  69149. * Different dataZoomModels may be defined to operate the same axis.
  69150. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69151. * So dataZoomModels share one axisProxy in that case.
  69152. *
  69153. * @class
  69154. */
  69155. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  69156. /**
  69157. * @private
  69158. * @type {string}
  69159. */
  69160. this._dimName = dimName;
  69161. /**
  69162. * @private
  69163. */
  69164. this._axisIndex = axisIndex;
  69165. /**
  69166. * @private
  69167. * @type {Array.<number>}
  69168. */
  69169. this._valueWindow;
  69170. /**
  69171. * @private
  69172. * @type {Array.<number>}
  69173. */
  69174. this._percentWindow;
  69175. /**
  69176. * @private
  69177. * @type {Array.<number>}
  69178. */
  69179. this._dataExtent;
  69180. /**
  69181. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  69182. * @private
  69183. * @type {Object}
  69184. */
  69185. this._minMaxSpan;
  69186. /**
  69187. * @readOnly
  69188. * @type {module: echarts/model/Global}
  69189. */
  69190. this.ecModel = ecModel;
  69191. /**
  69192. * @private
  69193. * @type {module: echarts/component/dataZoom/DataZoomModel}
  69194. */
  69195. this._dataZoomModel = dataZoomModel;
  69196. // /**
  69197. // * @readOnly
  69198. // * @private
  69199. // */
  69200. // this.hasSeriesStacked;
  69201. };
  69202. AxisProxy.prototype = {
  69203. constructor: AxisProxy,
  69204. /**
  69205. * Whether the axisProxy is hosted by dataZoomModel.
  69206. *
  69207. * @public
  69208. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69209. * @return {boolean}
  69210. */
  69211. hostedBy: function (dataZoomModel) {
  69212. return this._dataZoomModel === dataZoomModel;
  69213. },
  69214. /**
  69215. * @return {Array.<number>} Value can only be NaN or finite value.
  69216. */
  69217. getDataValueWindow: function () {
  69218. return this._valueWindow.slice();
  69219. },
  69220. /**
  69221. * @return {Array.<number>}
  69222. */
  69223. getDataPercentWindow: function () {
  69224. return this._percentWindow.slice();
  69225. },
  69226. /**
  69227. * @public
  69228. * @param {number} axisIndex
  69229. * @return {Array} seriesModels
  69230. */
  69231. getTargetSeriesModels: function () {
  69232. var seriesModels = [];
  69233. var ecModel = this.ecModel;
  69234. ecModel.eachSeries(function (seriesModel) {
  69235. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  69236. var dimName = this._dimName;
  69237. var axisModel = ecModel.queryComponents({
  69238. mainType: dimName + 'Axis',
  69239. index: seriesModel.get(dimName + 'AxisIndex'),
  69240. id: seriesModel.get(dimName + 'AxisId')
  69241. })[0];
  69242. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  69243. seriesModels.push(seriesModel);
  69244. }
  69245. }
  69246. }, this);
  69247. return seriesModels;
  69248. },
  69249. getAxisModel: function () {
  69250. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69251. },
  69252. getOtherAxisModel: function () {
  69253. var axisDim = this._dimName;
  69254. var ecModel = this.ecModel;
  69255. var axisModel = this.getAxisModel();
  69256. var isCartesian = axisDim === 'x' || axisDim === 'y';
  69257. var otherAxisDim;
  69258. var coordSysIndexName;
  69259. if (isCartesian) {
  69260. coordSysIndexName = 'gridIndex';
  69261. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  69262. }
  69263. else {
  69264. coordSysIndexName = 'polarIndex';
  69265. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  69266. }
  69267. var foundOtherAxisModel;
  69268. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  69269. if ((otherAxisModel.get(coordSysIndexName) || 0)
  69270. === (axisModel.get(coordSysIndexName) || 0)
  69271. ) {
  69272. foundOtherAxisModel = otherAxisModel;
  69273. }
  69274. });
  69275. return foundOtherAxisModel;
  69276. },
  69277. getMinMaxSpan: function () {
  69278. return clone(this._minMaxSpan);
  69279. },
  69280. /**
  69281. * Only calculate by given range and this._dataExtent, do not change anything.
  69282. *
  69283. * @param {Object} opt
  69284. * @param {number} [opt.start]
  69285. * @param {number} [opt.end]
  69286. * @param {number} [opt.startValue]
  69287. * @param {number} [opt.endValue]
  69288. */
  69289. calculateDataWindow: function (opt) {
  69290. var dataExtent = this._dataExtent;
  69291. var axisModel = this.getAxisModel();
  69292. var scale = axisModel.axis.scale;
  69293. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69294. var percentExtent = [0, 100];
  69295. var percentWindow = [];
  69296. var valueWindow = [];
  69297. var hasPropModeValue;
  69298. each$20(['start', 'end'], function (prop, idx) {
  69299. var boundPercent = opt[prop];
  69300. var boundValue = opt[prop + 'Value'];
  69301. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69302. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  69303. // but not min/max of axis, which will be calculated by data window then).
  69304. // The former one is suitable for cases that a dataZoom component controls multiple
  69305. // axes with different unit or extent, and the latter one is suitable for accurate
  69306. // zoom by pixel (e.g., in dataZoomSelect).
  69307. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  69308. // only when setOption or dispatchAction, otherwise it remains its original value.
  69309. // (Why not only record `percentProp` and always map to `valueProp`? Because
  69310. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  69311. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  69312. // data extent. All of values that are overflow the `dataExtent` will be calculated
  69313. // to percent '100%').
  69314. if (rangePropMode[idx] === 'percent') {
  69315. boundPercent == null && (boundPercent = percentExtent[idx]);
  69316. // Use scale.parse to math round for category or time axis.
  69317. boundValue = scale.parse(linearMap(
  69318. boundPercent, percentExtent, dataExtent
  69319. ));
  69320. }
  69321. else {
  69322. hasPropModeValue = true;
  69323. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  69324. // Calculating `percent` from `value` may be not accurate, because
  69325. // This calculation can not be inversed, because all of values that
  69326. // are overflow the `dataExtent` will be calculated to percent '100%'
  69327. boundPercent = linearMap(
  69328. boundValue, dataExtent, percentExtent
  69329. );
  69330. }
  69331. // valueWindow[idx] = round(boundValue);
  69332. // percentWindow[idx] = round(boundPercent);
  69333. valueWindow[idx] = boundValue;
  69334. percentWindow[idx] = boundPercent;
  69335. });
  69336. asc$1(valueWindow);
  69337. asc$1(percentWindow);
  69338. // The windows from user calling of `dispatchAction` might be out of the extent,
  69339. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  69340. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  69341. // where API is able to initialize/modify the window size even though `zoomLock`
  69342. // specified.
  69343. var spans = this._minMaxSpan;
  69344. hasPropModeValue
  69345. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  69346. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  69347. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  69348. var suffix = toValue ? 'Span' : 'ValueSpan';
  69349. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  69350. for (var i = 0; i < 2; i++) {
  69351. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  69352. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  69353. }
  69354. }
  69355. return {
  69356. valueWindow: valueWindow,
  69357. percentWindow: percentWindow
  69358. };
  69359. },
  69360. /**
  69361. * Notice: reset should not be called before series.restoreData() called,
  69362. * so it is recommanded to be called in "process stage" but not "model init
  69363. * stage".
  69364. *
  69365. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69366. */
  69367. reset: function (dataZoomModel) {
  69368. if (dataZoomModel !== this._dataZoomModel) {
  69369. return;
  69370. }
  69371. var targetSeries = this.getTargetSeriesModels();
  69372. // Culculate data window and data extent, and record them.
  69373. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  69374. // this.hasSeriesStacked = false;
  69375. // each(targetSeries, function (series) {
  69376. // var data = series.getData();
  69377. // var dataDim = data.mapDimension(this._dimName);
  69378. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  69379. // if (stackedDimension && stackedDimension === dataDim) {
  69380. // this.hasSeriesStacked = true;
  69381. // }
  69382. // }, this);
  69383. // `calculateDataWindow` uses min/maxSpan.
  69384. setMinMaxSpan(this);
  69385. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  69386. this._valueWindow = dataWindow.valueWindow;
  69387. this._percentWindow = dataWindow.percentWindow;
  69388. // Update axis setting then.
  69389. setAxisModel(this);
  69390. },
  69391. /**
  69392. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69393. */
  69394. restore: function (dataZoomModel) {
  69395. if (dataZoomModel !== this._dataZoomModel) {
  69396. return;
  69397. }
  69398. this._valueWindow = this._percentWindow = null;
  69399. setAxisModel(this, true);
  69400. },
  69401. /**
  69402. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69403. */
  69404. filterData: function (dataZoomModel, api) {
  69405. if (dataZoomModel !== this._dataZoomModel) {
  69406. return;
  69407. }
  69408. var axisDim = this._dimName;
  69409. var seriesModels = this.getTargetSeriesModels();
  69410. var filterMode = dataZoomModel.get('filterMode');
  69411. var valueWindow = this._valueWindow;
  69412. if (filterMode === 'none') {
  69413. return;
  69414. }
  69415. // FIXME
  69416. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69417. // with NaN data, NaN will be filtered and stack will be wrong.
  69418. // So we need to force the mode to be set empty.
  69419. // In fect, it is not a big deal that do not support filterMode-'filter'
  69420. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69421. // selection" some day, which might need "adapt to data extent on the
  69422. // otherAxis", which is disabled by filterMode-'empty'.
  69423. // But currently, stack has been fixed to based on value but not index,
  69424. // so this is not an issue any more.
  69425. // var otherAxisModel = this.getOtherAxisModel();
  69426. // if (dataZoomModel.get('$fromToolbox')
  69427. // && otherAxisModel
  69428. // && otherAxisModel.hasSeriesStacked
  69429. // ) {
  69430. // filterMode = 'empty';
  69431. // }
  69432. // TODO
  69433. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69434. each$20(seriesModels, function (seriesModel) {
  69435. var seriesData = seriesModel.getData();
  69436. var dataDims = seriesData.mapDimension(axisDim, true);
  69437. if (!dataDims.length) {
  69438. return;
  69439. }
  69440. if (filterMode === 'weakFilter') {
  69441. seriesData.filterSelf(function (dataIndex) {
  69442. var leftOut;
  69443. var rightOut;
  69444. var hasValue;
  69445. for (var i = 0; i < dataDims.length; i++) {
  69446. var value = seriesData.get(dataDims[i], dataIndex);
  69447. var thisHasValue = !isNaN(value);
  69448. var thisLeftOut = value < valueWindow[0];
  69449. var thisRightOut = value > valueWindow[1];
  69450. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69451. return true;
  69452. }
  69453. thisHasValue && (hasValue = true);
  69454. thisLeftOut && (leftOut = true);
  69455. thisRightOut && (rightOut = true);
  69456. }
  69457. // If both left out and right out, do not filter.
  69458. return hasValue && leftOut && rightOut;
  69459. });
  69460. }
  69461. else {
  69462. each$20(dataDims, function (dim) {
  69463. if (filterMode === 'empty') {
  69464. seriesModel.setData(
  69465. seriesData = seriesData.map(dim, function (value) {
  69466. return !isInWindow(value) ? NaN : value;
  69467. })
  69468. );
  69469. }
  69470. else {
  69471. var range = {};
  69472. range[dim] = valueWindow;
  69473. // console.time('select');
  69474. seriesData.selectRange(range);
  69475. // console.timeEnd('select');
  69476. }
  69477. });
  69478. }
  69479. each$20(dataDims, function (dim) {
  69480. seriesData.setApproximateExtent(valueWindow, dim);
  69481. });
  69482. });
  69483. function isInWindow(value) {
  69484. return value >= valueWindow[0] && value <= valueWindow[1];
  69485. }
  69486. }
  69487. };
  69488. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69489. var dataExtent = [Infinity, -Infinity];
  69490. each$20(seriesModels, function (seriesModel) {
  69491. var seriesData = seriesModel.getData();
  69492. if (seriesData) {
  69493. each$20(seriesData.mapDimension(axisDim, true), function (dim) {
  69494. var seriesExtent = seriesData.getApproximateExtent(dim);
  69495. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  69496. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  69497. });
  69498. }
  69499. });
  69500. if (dataExtent[1] < dataExtent[0]) {
  69501. dataExtent = [NaN, NaN];
  69502. }
  69503. // It is important to get "consistent" extent when more then one axes is
  69504. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69505. // when zooming. But it is difficult to know what is "consistent", considering
  69506. // axes have different type or even different meanings (For example, two
  69507. // time axes are used to compare data of the same date in different years).
  69508. // So basically dataZoom just obtains extent by series.data (in category axis
  69509. // extent can be obtained from axis.data).
  69510. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69511. // consistent.
  69512. fixExtentByAxis(axisProxy, dataExtent);
  69513. return dataExtent;
  69514. }
  69515. function fixExtentByAxis(axisProxy, dataExtent) {
  69516. var axisModel = axisProxy.getAxisModel();
  69517. var min = axisModel.getMin(true);
  69518. // For category axis, if min/max/scale are not set, extent is determined
  69519. // by axis.data by default.
  69520. var isCategoryAxis = axisModel.get('type') === 'category';
  69521. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  69522. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  69523. dataExtent[0] = min;
  69524. }
  69525. else if (isCategoryAxis) {
  69526. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  69527. }
  69528. var max = axisModel.getMax(true);
  69529. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  69530. dataExtent[1] = max;
  69531. }
  69532. else if (isCategoryAxis) {
  69533. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  69534. }
  69535. if (!axisModel.get('scale', true)) {
  69536. dataExtent[0] > 0 && (dataExtent[0] = 0);
  69537. dataExtent[1] < 0 && (dataExtent[1] = 0);
  69538. }
  69539. // For value axis, if min/max/scale are not set, we just use the extent obtained
  69540. // by series data, which may be a little different from the extent calculated by
  69541. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69542. // little when zooming. So it will not be fixed until some users require it strongly.
  69543. return dataExtent;
  69544. }
  69545. function setAxisModel(axisProxy, isRestore) {
  69546. var axisModel = axisProxy.getAxisModel();
  69547. var percentWindow = axisProxy._percentWindow;
  69548. var valueWindow = axisProxy._valueWindow;
  69549. if (!percentWindow) {
  69550. return;
  69551. }
  69552. // [0, 500]: arbitrary value, guess axis extent.
  69553. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69554. precision = Math.min(precision, 20);
  69555. // isRestore or isFull
  69556. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  69557. axisModel.setRange(
  69558. useOrigin ? null : +valueWindow[0].toFixed(precision),
  69559. useOrigin ? null : +valueWindow[1].toFixed(precision)
  69560. );
  69561. }
  69562. function setMinMaxSpan(axisProxy) {
  69563. var minMaxSpan = axisProxy._minMaxSpan = {};
  69564. var dataZoomModel = axisProxy._dataZoomModel;
  69565. var dataExtent = axisProxy._dataExtent;
  69566. each$20(['min', 'max'], function (minMax) {
  69567. var percentSpan = dataZoomModel.get(minMax + 'Span');
  69568. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69569. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  69570. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69571. if (valueSpan != null) {
  69572. percentSpan = linearMap(
  69573. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  69574. );
  69575. }
  69576. else if (percentSpan != null) {
  69577. valueSpan = linearMap(
  69578. percentSpan, [0, 100], dataExtent, true
  69579. ) - dataExtent[0];
  69580. }
  69581. minMaxSpan[minMax + 'Span'] = percentSpan;
  69582. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69583. });
  69584. }
  69585. /*
  69586. * Licensed to the Apache Software Foundation (ASF) under one
  69587. * or more contributor license agreements. See the NOTICE file
  69588. * distributed with this work for additional information
  69589. * regarding copyright ownership. The ASF licenses this file
  69590. * to you under the Apache License, Version 2.0 (the
  69591. * "License"); you may not use this file except in compliance
  69592. * with the License. You may obtain a copy of the License at
  69593. *
  69594. * http://www.apache.org/licenses/LICENSE-2.0
  69595. *
  69596. * Unless required by applicable law or agreed to in writing,
  69597. * software distributed under the License is distributed on an
  69598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69599. * KIND, either express or implied. See the License for the
  69600. * specific language governing permissions and limitations
  69601. * under the License.
  69602. */
  69603. var each$19 = each$1;
  69604. var eachAxisDim = eachAxisDim$1;
  69605. var DataZoomModel = extendComponentModel({
  69606. type: 'dataZoom',
  69607. dependencies: [
  69608. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  69609. ],
  69610. /**
  69611. * @protected
  69612. */
  69613. defaultOption: {
  69614. zlevel: 0,
  69615. z: 4, // Higher than normal component (z: 2).
  69616. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  69617. xAxisIndex: null, // Default the first horizontal category axis.
  69618. yAxisIndex: null, // Default the first vertical category axis.
  69619. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  69620. // 'filter': data items which are out of window will be removed. This option is
  69621. // applicable when filtering outliers. For each data item, it will be
  69622. // filtered if one of the relevant dimensions is out of the window.
  69623. // 'weakFilter': data items which are out of window will be removed. This option
  69624. // is applicable when filtering outliers. For each data item, it will be
  69625. // filtered only if all of the relevant dimensions are out of the same
  69626. // side of the window.
  69627. // 'empty': data items which are out of window will be set to empty.
  69628. // This option is applicable when user should not neglect
  69629. // that there are some data items out of window.
  69630. // 'none': Do not filter.
  69631. // Taking line chart as an example, line will be broken in
  69632. // the filtered points when filterModel is set to 'empty', but
  69633. // be connected when set to 'filter'.
  69634. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  69635. // default 100. Do not throttle when use null/undefined.
  69636. // If animation === true and animationDurationUpdate > 0,
  69637. // default value is 100, otherwise 20.
  69638. start: 0, // Start percent. 0 ~ 100
  69639. end: 100, // End percent. 0 ~ 100
  69640. startValue: null, // Start value. If startValue specified, start is ignored.
  69641. endValue: null, // End value. If endValue specified, end is ignored.
  69642. minSpan: null, // 0 ~ 100
  69643. maxSpan: null, // 0 ~ 100
  69644. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  69645. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  69646. rangeMode: null // Array, can be 'value' or 'percent'.
  69647. },
  69648. /**
  69649. * @override
  69650. */
  69651. init: function (option, parentModel, ecModel) {
  69652. /**
  69653. * key like x_0, y_1
  69654. * @private
  69655. * @type {Object}
  69656. */
  69657. this._dataIntervalByAxis = {};
  69658. /**
  69659. * @private
  69660. */
  69661. this._dataInfo = {};
  69662. /**
  69663. * key like x_0, y_1
  69664. * @private
  69665. */
  69666. this._axisProxies = {};
  69667. /**
  69668. * @readOnly
  69669. */
  69670. this.textStyleModel;
  69671. /**
  69672. * @private
  69673. */
  69674. this._autoThrottle = true;
  69675. /**
  69676. * It is `[rangeModeForMin, rangeModeForMax]`.
  69677. * The optional values for `rangeMode`:
  69678. * + `'value'` mode: the axis extent will always be determined by
  69679. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  69680. * how data like and how `axis.min` and `axis.max` are.
  69681. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  69682. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  69683. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  69684. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  69685. *
  69686. * For example, when users are using dynamic data (update data periodically via `setOption`),
  69687. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  69688. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  69689. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  69690. *
  69691. * @private
  69692. */
  69693. this._rangePropMode = ['percent', 'percent'];
  69694. var inputRawOption = retrieveRawOption(option);
  69695. /**
  69696. * Suppose a "main process" start at the point that model prepared (that is,
  69697. * model initialized or merged or method called in `action`).
  69698. * We should keep the `main process` idempotent, that is, given a set of values
  69699. * on `option`, we get the same result.
  69700. *
  69701. * But sometimes, values on `option` will be updated for providing users
  69702. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  69703. * should not be the base/input of the `main process`.
  69704. *
  69705. * So in that case we should save and keep the input of the `main process`
  69706. * separately, called `settledOption`.
  69707. *
  69708. * For example, consider the case:
  69709. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  69710. * where the original input `option.startValue`, `option.endValue` are earsed by
  69711. * calculated value.
  69712. * (Step)2) click the legend to hide and show a series,
  69713. * where the new range is calculated by the earsed `startValue` and `endValue`,
  69714. * which brings incorrect result.
  69715. *
  69716. * @readOnly
  69717. */
  69718. this.settledOption = inputRawOption;
  69719. this.mergeDefaultAndTheme(option, ecModel);
  69720. this.doInit(inputRawOption);
  69721. },
  69722. /**
  69723. * @override
  69724. */
  69725. mergeOption: function (newOption) {
  69726. var inputRawOption = retrieveRawOption(newOption);
  69727. //FIX #2591
  69728. merge(this.option, newOption, true);
  69729. merge(this.settledOption, inputRawOption, true);
  69730. this.doInit(inputRawOption);
  69731. },
  69732. /**
  69733. * @protected
  69734. */
  69735. doInit: function (inputRawOption) {
  69736. var thisOption = this.option;
  69737. // Disable realtime view update if canvas is not supported.
  69738. if (!env$1.canvasSupported) {
  69739. thisOption.realtime = false;
  69740. }
  69741. this._setDefaultThrottle(inputRawOption);
  69742. updateRangeUse(this, inputRawOption);
  69743. var settledOption = this.settledOption;
  69744. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69745. // start/end has higher priority over startValue/endValue if they
  69746. // both set, but we should make chart.setOption({endValue: 1000})
  69747. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69748. if (this._rangePropMode[index] === 'value') {
  69749. thisOption[names[0]] = settledOption[names[0]] = null;
  69750. }
  69751. // Otherwise do nothing and use the merge result.
  69752. }, this);
  69753. this.textStyleModel = this.getModel('textStyle');
  69754. this._resetTarget();
  69755. this._giveAxisProxies();
  69756. },
  69757. /**
  69758. * @private
  69759. */
  69760. _giveAxisProxies: function () {
  69761. var axisProxies = this._axisProxies;
  69762. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  69763. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  69764. // If exists, share axisProxy with other dataZoomModels.
  69765. var axisProxy = axisModel.__dzAxisProxy || (
  69766. // Use the first dataZoomModel as the main model of axisProxy.
  69767. axisModel.__dzAxisProxy = new AxisProxy(
  69768. dimNames.name, axisIndex, this, ecModel
  69769. )
  69770. );
  69771. // FIXME
  69772. // dispose __dzAxisProxy
  69773. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  69774. }, this);
  69775. },
  69776. /**
  69777. * @private
  69778. */
  69779. _resetTarget: function () {
  69780. var thisOption = this.option;
  69781. var autoMode = this._judgeAutoMode();
  69782. eachAxisDim(function (dimNames) {
  69783. var axisIndexName = dimNames.axisIndex;
  69784. thisOption[axisIndexName] = normalizeToArray(
  69785. thisOption[axisIndexName]
  69786. );
  69787. }, this);
  69788. if (autoMode === 'axisIndex') {
  69789. this._autoSetAxisIndex();
  69790. }
  69791. else if (autoMode === 'orient') {
  69792. this._autoSetOrient();
  69793. }
  69794. },
  69795. /**
  69796. * @private
  69797. */
  69798. _judgeAutoMode: function () {
  69799. // Auto set only works for setOption at the first time.
  69800. // The following is user's reponsibility. So using merged
  69801. // option is OK.
  69802. var thisOption = this.option;
  69803. var hasIndexSpecified = false;
  69804. eachAxisDim(function (dimNames) {
  69805. // When user set axisIndex as a empty array, we think that user specify axisIndex
  69806. // but do not want use auto mode. Because empty array may be encountered when
  69807. // some error occured.
  69808. if (thisOption[dimNames.axisIndex] != null) {
  69809. hasIndexSpecified = true;
  69810. }
  69811. }, this);
  69812. var orient = thisOption.orient;
  69813. if (orient == null && hasIndexSpecified) {
  69814. return 'orient';
  69815. }
  69816. else if (!hasIndexSpecified) {
  69817. if (orient == null) {
  69818. thisOption.orient = 'horizontal';
  69819. }
  69820. return 'axisIndex';
  69821. }
  69822. },
  69823. /**
  69824. * @private
  69825. */
  69826. _autoSetAxisIndex: function () {
  69827. var autoAxisIndex = true;
  69828. var orient = this.get('orient', true);
  69829. var thisOption = this.option;
  69830. var dependentModels = this.dependentModels;
  69831. if (autoAxisIndex) {
  69832. // Find axis that parallel to dataZoom as default.
  69833. var dimName = orient === 'vertical' ? 'y' : 'x';
  69834. if (dependentModels[dimName + 'Axis'].length) {
  69835. thisOption[dimName + 'AxisIndex'] = [0];
  69836. autoAxisIndex = false;
  69837. }
  69838. else {
  69839. each$19(dependentModels.singleAxis, function (singleAxisModel) {
  69840. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  69841. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  69842. autoAxisIndex = false;
  69843. }
  69844. });
  69845. }
  69846. }
  69847. if (autoAxisIndex) {
  69848. // Find the first category axis as default. (consider polar)
  69849. eachAxisDim(function (dimNames) {
  69850. if (!autoAxisIndex) {
  69851. return;
  69852. }
  69853. var axisIndices = [];
  69854. var axisModels = this.dependentModels[dimNames.axis];
  69855. if (axisModels.length && !axisIndices.length) {
  69856. for (var i = 0, len = axisModels.length; i < len; i++) {
  69857. if (axisModels[i].get('type') === 'category') {
  69858. axisIndices.push(i);
  69859. }
  69860. }
  69861. }
  69862. thisOption[dimNames.axisIndex] = axisIndices;
  69863. if (axisIndices.length) {
  69864. autoAxisIndex = false;
  69865. }
  69866. }, this);
  69867. }
  69868. if (autoAxisIndex) {
  69869. // FIXME
  69870. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  69871. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  69872. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  69873. // dataZoom component auto adopts series that reference to
  69874. // both xAxis and yAxis which type is 'value'.
  69875. this.ecModel.eachSeries(function (seriesModel) {
  69876. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  69877. eachAxisDim(function (dimNames) {
  69878. var axisIndices = thisOption[dimNames.axisIndex];
  69879. var axisIndex = seriesModel.get(dimNames.axisIndex);
  69880. var axisId = seriesModel.get(dimNames.axisId);
  69881. var axisModel = seriesModel.ecModel.queryComponents({
  69882. mainType: dimNames.axis,
  69883. index: axisIndex,
  69884. id: axisId
  69885. })[0];
  69886. if (__DEV__) {
  69887. if (!axisModel) {
  69888. throw new Error(
  69889. dimNames.axis + ' "' + retrieve(
  69890. axisIndex,
  69891. axisId,
  69892. 0
  69893. ) + '" not found'
  69894. );
  69895. }
  69896. }
  69897. axisIndex = axisModel.componentIndex;
  69898. if (indexOf(axisIndices, axisIndex) < 0) {
  69899. axisIndices.push(axisIndex);
  69900. }
  69901. });
  69902. }
  69903. }, this);
  69904. }
  69905. },
  69906. /**
  69907. * @private
  69908. */
  69909. _autoSetOrient: function () {
  69910. var dim;
  69911. // Find the first axis
  69912. this.eachTargetAxis(function (dimNames) {
  69913. !dim && (dim = dimNames.name);
  69914. }, this);
  69915. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  69916. },
  69917. /**
  69918. * @private
  69919. */
  69920. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  69921. // FIXME
  69922. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  69923. // 例如series.type === scatter时。
  69924. var is = true;
  69925. eachAxisDim(function (dimNames) {
  69926. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  69927. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  69928. if (!axisModel || axisModel.get('type') !== axisType) {
  69929. is = false;
  69930. }
  69931. }, this);
  69932. return is;
  69933. },
  69934. /**
  69935. * @private
  69936. */
  69937. _setDefaultThrottle: function (inputRawOption) {
  69938. // When first time user set throttle, auto throttle ends.
  69939. if (inputRawOption.hasOwnProperty('throttle')) {
  69940. this._autoThrottle = false;
  69941. }
  69942. if (this._autoThrottle) {
  69943. var globalOption = this.ecModel.option;
  69944. this.option.throttle = (
  69945. globalOption.animation && globalOption.animationDurationUpdate > 0
  69946. ) ? 100 : 20;
  69947. }
  69948. },
  69949. /**
  69950. * @public
  69951. */
  69952. getFirstTargetAxisModel: function () {
  69953. var firstAxisModel;
  69954. eachAxisDim(function (dimNames) {
  69955. if (firstAxisModel == null) {
  69956. var indices = this.get(dimNames.axisIndex);
  69957. if (indices.length) {
  69958. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  69959. }
  69960. }
  69961. }, this);
  69962. return firstAxisModel;
  69963. },
  69964. /**
  69965. * @public
  69966. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69967. */
  69968. eachTargetAxis: function (callback, context) {
  69969. var ecModel = this.ecModel;
  69970. eachAxisDim(function (dimNames) {
  69971. each$19(
  69972. this.get(dimNames.axisIndex),
  69973. function (axisIndex) {
  69974. callback.call(context, dimNames, axisIndex, this, ecModel);
  69975. },
  69976. this
  69977. );
  69978. }, this);
  69979. },
  69980. /**
  69981. * @param {string} dimName
  69982. * @param {number} axisIndex
  69983. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  69984. */
  69985. getAxisProxy: function (dimName, axisIndex) {
  69986. return this._axisProxies[dimName + '_' + axisIndex];
  69987. },
  69988. /**
  69989. * @param {string} dimName
  69990. * @param {number} axisIndex
  69991. * @return {module:echarts/model/Model} If not found, return null/undefined.
  69992. */
  69993. getAxisModel: function (dimName, axisIndex) {
  69994. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  69995. return axisProxy && axisProxy.getAxisModel();
  69996. },
  69997. /**
  69998. * If not specified, set to undefined.
  69999. *
  70000. * @public
  70001. * @param {Object} opt
  70002. * @param {number} [opt.start]
  70003. * @param {number} [opt.end]
  70004. * @param {number} [opt.startValue]
  70005. * @param {number} [opt.endValue]
  70006. */
  70007. setRawRange: function (opt) {
  70008. var thisOption = this.option;
  70009. var settledOption = this.settledOption;
  70010. each$19([['start', 'startValue'], ['end', 'endValue']], function (names) {
  70011. // Consider the pair <start, startValue>:
  70012. // If one has value and the other one is `null/undefined`, we both set them
  70013. // to `settledOption`. This strategy enables the feature to clear the original
  70014. // value in `settledOption` to `null/undefined`.
  70015. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  70016. // and keep `settledOption` with the original value. This strategy enables users to
  70017. // only set <end or endValue> but not set <start or startValue> when calling
  70018. // `dispatchAction`.
  70019. // The pair <end, endValue> is treated in the same way.
  70020. if (opt[names[0]] != null || opt[names[1]] != null) {
  70021. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  70022. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  70023. }
  70024. }, this);
  70025. updateRangeUse(this, opt);
  70026. },
  70027. /**
  70028. * @public
  70029. * @param {Object} opt
  70030. * @param {number} [opt.start]
  70031. * @param {number} [opt.end]
  70032. * @param {number} [opt.startValue]
  70033. * @param {number} [opt.endValue]
  70034. */
  70035. setCalculatedRange: function (opt) {
  70036. var option = this.option;
  70037. each$19(['start', 'startValue', 'end', 'endValue'], function (name) {
  70038. option[name] = opt[name];
  70039. });
  70040. },
  70041. /**
  70042. * @public
  70043. * @return {Array.<number>} [startPercent, endPercent]
  70044. */
  70045. getPercentRange: function () {
  70046. var axisProxy = this.findRepresentativeAxisProxy();
  70047. if (axisProxy) {
  70048. return axisProxy.getDataPercentWindow();
  70049. }
  70050. },
  70051. /**
  70052. * @public
  70053. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  70054. *
  70055. * @param {string} [axisDimName]
  70056. * @param {number} [axisIndex]
  70057. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  70058. */
  70059. getValueRange: function (axisDimName, axisIndex) {
  70060. if (axisDimName == null && axisIndex == null) {
  70061. var axisProxy = this.findRepresentativeAxisProxy();
  70062. if (axisProxy) {
  70063. return axisProxy.getDataValueWindow();
  70064. }
  70065. }
  70066. else {
  70067. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  70068. }
  70069. },
  70070. /**
  70071. * @public
  70072. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  70073. * corresponding to the axisModel
  70074. * @return {module:echarts/component/dataZoom/AxisProxy}
  70075. */
  70076. findRepresentativeAxisProxy: function (axisModel) {
  70077. if (axisModel) {
  70078. return axisModel.__dzAxisProxy;
  70079. }
  70080. // Find the first hosted axisProxy
  70081. var axisProxies = this._axisProxies;
  70082. for (var key in axisProxies) {
  70083. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  70084. return axisProxies[key];
  70085. }
  70086. }
  70087. // If no hosted axis find not hosted axisProxy.
  70088. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  70089. // and the option.start or option.end settings are different. The percentRange
  70090. // should follow axisProxy.
  70091. // (We encounter this problem in toolbox data zoom.)
  70092. for (var key in axisProxies) {
  70093. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  70094. return axisProxies[key];
  70095. }
  70096. }
  70097. },
  70098. /**
  70099. * @return {Array.<string>}
  70100. */
  70101. getRangePropMode: function () {
  70102. return this._rangePropMode.slice();
  70103. }
  70104. });
  70105. /**
  70106. * Retrieve the those raw params from option, which will be cached separately.
  70107. * becasue they will be overwritten by normalized/calculated values in the main
  70108. * process.
  70109. */
  70110. function retrieveRawOption(option) {
  70111. var ret = {};
  70112. each$19(
  70113. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  70114. function (name) {
  70115. option.hasOwnProperty(name) && (ret[name] = option[name]);
  70116. }
  70117. );
  70118. return ret;
  70119. }
  70120. function updateRangeUse(dataZoomModel, inputRawOption) {
  70121. var rangePropMode = dataZoomModel._rangePropMode;
  70122. var rangeModeInOption = dataZoomModel.get('rangeMode');
  70123. each$19([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70124. var percentSpecified = inputRawOption[names[0]] != null;
  70125. var valueSpecified = inputRawOption[names[1]] != null;
  70126. if (percentSpecified && !valueSpecified) {
  70127. rangePropMode[index] = 'percent';
  70128. }
  70129. else if (!percentSpecified && valueSpecified) {
  70130. rangePropMode[index] = 'value';
  70131. }
  70132. else if (rangeModeInOption) {
  70133. rangePropMode[index] = rangeModeInOption[index];
  70134. }
  70135. else if (percentSpecified) { // percentSpecified && valueSpecified
  70136. rangePropMode[index] = 'percent';
  70137. }
  70138. // else remain its original setting.
  70139. });
  70140. }
  70141. /*
  70142. * Licensed to the Apache Software Foundation (ASF) under one
  70143. * or more contributor license agreements. See the NOTICE file
  70144. * distributed with this work for additional information
  70145. * regarding copyright ownership. The ASF licenses this file
  70146. * to you under the Apache License, Version 2.0 (the
  70147. * "License"); you may not use this file except in compliance
  70148. * with the License. You may obtain a copy of the License at
  70149. *
  70150. * http://www.apache.org/licenses/LICENSE-2.0
  70151. *
  70152. * Unless required by applicable law or agreed to in writing,
  70153. * software distributed under the License is distributed on an
  70154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70155. * KIND, either express or implied. See the License for the
  70156. * specific language governing permissions and limitations
  70157. * under the License.
  70158. */
  70159. var DataZoomView = Component$1.extend({
  70160. type: 'dataZoom',
  70161. render: function (dataZoomModel, ecModel, api, payload) {
  70162. this.dataZoomModel = dataZoomModel;
  70163. this.ecModel = ecModel;
  70164. this.api = api;
  70165. },
  70166. /**
  70167. * Find the first target coordinate system.
  70168. *
  70169. * @protected
  70170. * @return {Object} {
  70171. * grid: [
  70172. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  70173. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  70174. * ...
  70175. * ], // cartesians must not be null/undefined.
  70176. * polar: [
  70177. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  70178. * ...
  70179. * ], // polars must not be null/undefined.
  70180. * singleAxis: [
  70181. * {model: coord0, axisModels: [], coordIndex: 0}
  70182. * ]
  70183. */
  70184. getTargetCoordInfo: function () {
  70185. var dataZoomModel = this.dataZoomModel;
  70186. var ecModel = this.ecModel;
  70187. var coordSysLists = {};
  70188. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70189. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  70190. if (axisModel) {
  70191. var coordModel = axisModel.getCoordSysModel();
  70192. coordModel && save(
  70193. coordModel,
  70194. axisModel,
  70195. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  70196. coordModel.componentIndex
  70197. );
  70198. }
  70199. }, this);
  70200. function save(coordModel, axisModel, store, coordIndex) {
  70201. var item;
  70202. for (var i = 0; i < store.length; i++) {
  70203. if (store[i].model === coordModel) {
  70204. item = store[i];
  70205. break;
  70206. }
  70207. }
  70208. if (!item) {
  70209. store.push(item = {
  70210. model: coordModel, axisModels: [], coordIndex: coordIndex
  70211. });
  70212. }
  70213. item.axisModels.push(axisModel);
  70214. }
  70215. return coordSysLists;
  70216. }
  70217. });
  70218. /*
  70219. * Licensed to the Apache Software Foundation (ASF) under one
  70220. * or more contributor license agreements. See the NOTICE file
  70221. * distributed with this work for additional information
  70222. * regarding copyright ownership. The ASF licenses this file
  70223. * to you under the Apache License, Version 2.0 (the
  70224. * "License"); you may not use this file except in compliance
  70225. * with the License. You may obtain a copy of the License at
  70226. *
  70227. * http://www.apache.org/licenses/LICENSE-2.0
  70228. *
  70229. * Unless required by applicable law or agreed to in writing,
  70230. * software distributed under the License is distributed on an
  70231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70232. * KIND, either express or implied. See the License for the
  70233. * specific language governing permissions and limitations
  70234. * under the License.
  70235. */
  70236. DataZoomModel.extend({
  70237. type: 'dataZoom.select'
  70238. });
  70239. /*
  70240. * Licensed to the Apache Software Foundation (ASF) under one
  70241. * or more contributor license agreements. See the NOTICE file
  70242. * distributed with this work for additional information
  70243. * regarding copyright ownership. The ASF licenses this file
  70244. * to you under the Apache License, Version 2.0 (the
  70245. * "License"); you may not use this file except in compliance
  70246. * with the License. You may obtain a copy of the License at
  70247. *
  70248. * http://www.apache.org/licenses/LICENSE-2.0
  70249. *
  70250. * Unless required by applicable law or agreed to in writing,
  70251. * software distributed under the License is distributed on an
  70252. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70253. * KIND, either express or implied. See the License for the
  70254. * specific language governing permissions and limitations
  70255. * under the License.
  70256. */
  70257. DataZoomView.extend({
  70258. type: 'dataZoom.select'
  70259. });
  70260. /*
  70261. * Licensed to the Apache Software Foundation (ASF) under one
  70262. * or more contributor license agreements. See the NOTICE file
  70263. * distributed with this work for additional information
  70264. * regarding copyright ownership. The ASF licenses this file
  70265. * to you under the Apache License, Version 2.0 (the
  70266. * "License"); you may not use this file except in compliance
  70267. * with the License. You may obtain a copy of the License at
  70268. *
  70269. * http://www.apache.org/licenses/LICENSE-2.0
  70270. *
  70271. * Unless required by applicable law or agreed to in writing,
  70272. * software distributed under the License is distributed on an
  70273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70274. * KIND, either express or implied. See the License for the
  70275. * specific language governing permissions and limitations
  70276. * under the License.
  70277. */
  70278. registerProcessor({
  70279. // `dataZoomProcessor` will only be performed in needed series. Consider if
  70280. // there is a line series and a pie series, it is better not to update the
  70281. // line series if only pie series is needed to be updated.
  70282. getTargetSeries: function (ecModel) {
  70283. var seriesModelMap = createHashMap();
  70284. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70285. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70286. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  70287. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  70288. seriesModelMap.set(seriesModel.uid, seriesModel);
  70289. });
  70290. });
  70291. });
  70292. return seriesModelMap;
  70293. },
  70294. modifyOutputEnd: true,
  70295. // Consider appendData, where filter should be performed. Because data process is
  70296. // in block mode currently, it is not need to worry about that the overallProgress
  70297. // execute every frame.
  70298. overallReset: function (ecModel, api) {
  70299. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70300. // We calculate window and reset axis here but not in model
  70301. // init stage and not after action dispatch handler, because
  70302. // reset should be called after seriesData.restoreData.
  70303. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70304. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  70305. });
  70306. // Caution: data zoom filtering is order sensitive when using
  70307. // percent range and no min/max/scale set on axis.
  70308. // For example, we have dataZoom definition:
  70309. // [
  70310. // {xAxisIndex: 0, start: 30, end: 70},
  70311. // {yAxisIndex: 0, start: 20, end: 80}
  70312. // ]
  70313. // In this case, [20, 80] of y-dataZoom should be based on data
  70314. // that have filtered by x-dataZoom using range of [30, 70],
  70315. // but should not be based on full raw data. Thus sliding
  70316. // x-dataZoom will change both ranges of xAxis and yAxis,
  70317. // while sliding y-dataZoom will only change the range of yAxis.
  70318. // So we should filter x-axis after reset x-axis immediately,
  70319. // and then reset y-axis and filter y-axis.
  70320. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  70321. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  70322. });
  70323. });
  70324. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  70325. // Fullfill all of the range props so that user
  70326. // is able to get them from chart.getOption().
  70327. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  70328. var percentRange = axisProxy.getDataPercentWindow();
  70329. var valueRange = axisProxy.getDataValueWindow();
  70330. dataZoomModel.setCalculatedRange({
  70331. start: percentRange[0],
  70332. end: percentRange[1],
  70333. startValue: valueRange[0],
  70334. endValue: valueRange[1]
  70335. });
  70336. });
  70337. }
  70338. });
  70339. /*
  70340. * Licensed to the Apache Software Foundation (ASF) under one
  70341. * or more contributor license agreements. See the NOTICE file
  70342. * distributed with this work for additional information
  70343. * regarding copyright ownership. The ASF licenses this file
  70344. * to you under the Apache License, Version 2.0 (the
  70345. * "License"); you may not use this file except in compliance
  70346. * with the License. You may obtain a copy of the License at
  70347. *
  70348. * http://www.apache.org/licenses/LICENSE-2.0
  70349. *
  70350. * Unless required by applicable law or agreed to in writing,
  70351. * software distributed under the License is distributed on an
  70352. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70353. * KIND, either express or implied. See the License for the
  70354. * specific language governing permissions and limitations
  70355. * under the License.
  70356. */
  70357. registerAction('dataZoom', function (payload, ecModel) {
  70358. var linkedNodesFinder = createLinkedNodesFinder(
  70359. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  70360. eachAxisDim$1,
  70361. function (model, dimNames) {
  70362. return model.get(dimNames.axisIndex);
  70363. }
  70364. );
  70365. var effectedModels = [];
  70366. ecModel.eachComponent(
  70367. {mainType: 'dataZoom', query: payload},
  70368. function (model, index) {
  70369. effectedModels.push.apply(
  70370. effectedModels, linkedNodesFinder(model).nodes
  70371. );
  70372. }
  70373. );
  70374. each$1(effectedModels, function (dataZoomModel, index) {
  70375. dataZoomModel.setRawRange({
  70376. start: payload.start,
  70377. end: payload.end,
  70378. startValue: payload.startValue,
  70379. endValue: payload.endValue
  70380. });
  70381. });
  70382. });
  70383. /*
  70384. * Licensed to the Apache Software Foundation (ASF) under one
  70385. * or more contributor license agreements. See the NOTICE file
  70386. * distributed with this work for additional information
  70387. * regarding copyright ownership. The ASF licenses this file
  70388. * to you under the Apache License, Version 2.0 (the
  70389. * "License"); you may not use this file except in compliance
  70390. * with the License. You may obtain a copy of the License at
  70391. *
  70392. * http://www.apache.org/licenses/LICENSE-2.0
  70393. *
  70394. * Unless required by applicable law or agreed to in writing,
  70395. * software distributed under the License is distributed on an
  70396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70397. * KIND, either express or implied. See the License for the
  70398. * specific language governing permissions and limitations
  70399. * under the License.
  70400. */
  70401. /**
  70402. * Only work for toolbox dataZoom. User
  70403. * MUST NOT import this module directly.
  70404. */
  70405. /*
  70406. * Licensed to the Apache Software Foundation (ASF) under one
  70407. * or more contributor license agreements. See the NOTICE file
  70408. * distributed with this work for additional information
  70409. * regarding copyright ownership. The ASF licenses this file
  70410. * to you under the Apache License, Version 2.0 (the
  70411. * "License"); you may not use this file except in compliance
  70412. * with the License. You may obtain a copy of the License at
  70413. *
  70414. * http://www.apache.org/licenses/LICENSE-2.0
  70415. *
  70416. * Unless required by applicable law or agreed to in writing,
  70417. * software distributed under the License is distributed on an
  70418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70419. * KIND, either express or implied. See the License for the
  70420. * specific language governing permissions and limitations
  70421. * under the License.
  70422. */
  70423. // Use dataZoomSelect
  70424. var dataZoomLang = lang.toolbox.dataZoom;
  70425. var each$16 = each$1;
  70426. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  70427. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  70428. function DataZoom(model, ecModel, api) {
  70429. /**
  70430. * @private
  70431. * @type {module:echarts/component/helper/BrushController}
  70432. */
  70433. (this._brushController = new BrushController(api.getZr()))
  70434. .on('brush', bind(this._onBrush, this))
  70435. .mount();
  70436. /**
  70437. * @private
  70438. * @type {boolean}
  70439. */
  70440. this._isZoomActive;
  70441. }
  70442. DataZoom.defaultOption = {
  70443. show: true,
  70444. filterMode: 'filter',
  70445. // Icon group
  70446. icon: {
  70447. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  70448. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  70449. },
  70450. // `zoom`, `back`
  70451. title: clone(dataZoomLang.title)
  70452. };
  70453. var proto$4 = DataZoom.prototype;
  70454. proto$4.render = function (featureModel, ecModel, api, payload) {
  70455. this.model = featureModel;
  70456. this.ecModel = ecModel;
  70457. this.api = api;
  70458. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  70459. updateBackBtnStatus(featureModel, ecModel);
  70460. };
  70461. proto$4.onclick = function (ecModel, api, type) {
  70462. handlers$1[type].call(this);
  70463. };
  70464. proto$4.remove = function (ecModel, api) {
  70465. this._brushController.unmount();
  70466. };
  70467. proto$4.dispose = function (ecModel, api) {
  70468. this._brushController.dispose();
  70469. };
  70470. /**
  70471. * @private
  70472. */
  70473. var handlers$1 = {
  70474. zoom: function () {
  70475. var nextActive = !this._isZoomActive;
  70476. this.api.dispatchAction({
  70477. type: 'takeGlobalCursor',
  70478. key: 'dataZoomSelect',
  70479. dataZoomSelectActive: nextActive
  70480. });
  70481. },
  70482. back: function () {
  70483. this._dispatchZoomAction(pop(this.ecModel));
  70484. }
  70485. };
  70486. /**
  70487. * @private
  70488. */
  70489. proto$4._onBrush = function (areas, opt) {
  70490. if (!opt.isEnd || !areas.length) {
  70491. return;
  70492. }
  70493. var snapshot = {};
  70494. var ecModel = this.ecModel;
  70495. this._brushController.updateCovers([]); // remove cover
  70496. var brushTargetManager = new BrushTargetManager(
  70497. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  70498. );
  70499. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70500. if (coordSys.type !== 'cartesian2d') {
  70501. return;
  70502. }
  70503. var brushType = area.brushType;
  70504. if (brushType === 'rect') {
  70505. setBatch('x', coordSys, coordRange[0]);
  70506. setBatch('y', coordSys, coordRange[1]);
  70507. }
  70508. else {
  70509. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  70510. }
  70511. });
  70512. push(ecModel, snapshot);
  70513. this._dispatchZoomAction(snapshot);
  70514. function setBatch(dimName, coordSys, minMax) {
  70515. var axis = coordSys.getAxis(dimName);
  70516. var axisModel = axis.model;
  70517. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  70518. // Restrict range.
  70519. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  70520. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  70521. minMax = sliderMove(
  70522. 0, minMax.slice(), axis.scale.getExtent(), 0,
  70523. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  70524. );
  70525. }
  70526. dataZoomModel && (snapshot[dataZoomModel.id] = {
  70527. dataZoomId: dataZoomModel.id,
  70528. startValue: minMax[0],
  70529. endValue: minMax[1]
  70530. });
  70531. }
  70532. function findDataZoom(dimName, axisModel, ecModel) {
  70533. var found;
  70534. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  70535. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  70536. has && (found = dzModel);
  70537. });
  70538. return found;
  70539. }
  70540. };
  70541. /**
  70542. * @private
  70543. */
  70544. proto$4._dispatchZoomAction = function (snapshot) {
  70545. var batch = [];
  70546. // Convert from hash map to array.
  70547. each$16(snapshot, function (batchItem, dataZoomId) {
  70548. batch.push(clone(batchItem));
  70549. });
  70550. batch.length && this.api.dispatchAction({
  70551. type: 'dataZoom',
  70552. from: this.uid,
  70553. batch: batch
  70554. });
  70555. };
  70556. function retrieveAxisSetting(option) {
  70557. var setting = {};
  70558. // Compatible with previous setting: null => all axis, false => no axis.
  70559. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  70560. setting[name] = option[name];
  70561. setting[name] == null && (setting[name] = 'all');
  70562. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  70563. });
  70564. return setting;
  70565. }
  70566. function updateBackBtnStatus(featureModel, ecModel) {
  70567. featureModel.setIconStatus(
  70568. 'back',
  70569. count(ecModel) > 1 ? 'emphasis' : 'normal'
  70570. );
  70571. }
  70572. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  70573. var zoomActive = view._isZoomActive;
  70574. if (payload && payload.type === 'takeGlobalCursor') {
  70575. zoomActive = payload.key === 'dataZoomSelect'
  70576. ? payload.dataZoomSelectActive : false;
  70577. }
  70578. view._isZoomActive = zoomActive;
  70579. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  70580. var brushTargetManager = new BrushTargetManager(
  70581. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  70582. );
  70583. view._brushController
  70584. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  70585. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  70586. ? 'lineX'
  70587. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  70588. ? 'lineY'
  70589. : 'rect';
  70590. }))
  70591. .enableBrush(
  70592. zoomActive
  70593. ? {
  70594. brushType: 'auto',
  70595. brushStyle: {
  70596. // FIXME user customized?
  70597. lineWidth: 0,
  70598. fill: 'rgba(0,0,0,0.2)'
  70599. }
  70600. }
  70601. : false
  70602. );
  70603. }
  70604. register$1('dataZoom', DataZoom);
  70605. // Create special dataZoom option for select
  70606. // FIXME consider the case of merge option, where axes options are not exists.
  70607. registerPreprocessor(function (option) {
  70608. if (!option) {
  70609. return;
  70610. }
  70611. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  70612. if (!isArray(dataZoomOpts)) {
  70613. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  70614. }
  70615. var toolboxOpt = option.toolbox;
  70616. if (toolboxOpt) {
  70617. // Assume there is only one toolbox
  70618. if (isArray(toolboxOpt)) {
  70619. toolboxOpt = toolboxOpt[0];
  70620. }
  70621. if (toolboxOpt && toolboxOpt.feature) {
  70622. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  70623. // FIXME: If add dataZoom when setOption in merge mode,
  70624. // no axis info to be added. See `test/dataZoom-extreme.html`
  70625. addForAxis('xAxis', dataZoomOpt);
  70626. addForAxis('yAxis', dataZoomOpt);
  70627. }
  70628. }
  70629. function addForAxis(axisName, dataZoomOpt) {
  70630. if (!dataZoomOpt) {
  70631. return;
  70632. }
  70633. // Try not to modify model, because it is not merged yet.
  70634. var axisIndicesName = axisName + 'Index';
  70635. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  70636. if (givenAxisIndices != null
  70637. && givenAxisIndices !== 'all'
  70638. && !isArray(givenAxisIndices)
  70639. ) {
  70640. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  70641. }
  70642. forEachComponent(axisName, function (axisOpt, axisIndex) {
  70643. if (givenAxisIndices != null
  70644. && givenAxisIndices !== 'all'
  70645. && indexOf(givenAxisIndices, axisIndex) === -1
  70646. ) {
  70647. return;
  70648. }
  70649. var newOpt = {
  70650. type: 'select',
  70651. $fromToolbox: true,
  70652. // Default to be filter
  70653. filterMode: dataZoomOpt.filterMode || 'filter',
  70654. // Id for merge mapping.
  70655. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  70656. };
  70657. // FIXME
  70658. // Only support one axis now.
  70659. newOpt[axisIndicesName] = axisIndex;
  70660. dataZoomOpts.push(newOpt);
  70661. });
  70662. }
  70663. function forEachComponent(mainType, cb) {
  70664. var opts = option[mainType];
  70665. if (!isArray(opts)) {
  70666. opts = opts ? [opts] : [];
  70667. }
  70668. each$16(opts, cb);
  70669. }
  70670. });
  70671. /*
  70672. * Licensed to the Apache Software Foundation (ASF) under one
  70673. * or more contributor license agreements. See the NOTICE file
  70674. * distributed with this work for additional information
  70675. * regarding copyright ownership. The ASF licenses this file
  70676. * to you under the Apache License, Version 2.0 (the
  70677. * "License"); you may not use this file except in compliance
  70678. * with the License. You may obtain a copy of the License at
  70679. *
  70680. * http://www.apache.org/licenses/LICENSE-2.0
  70681. *
  70682. * Unless required by applicable law or agreed to in writing,
  70683. * software distributed under the License is distributed on an
  70684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70685. * KIND, either express or implied. See the License for the
  70686. * specific language governing permissions and limitations
  70687. * under the License.
  70688. */
  70689. var restoreLang = lang.toolbox.restore;
  70690. function Restore(model) {
  70691. this.model = model;
  70692. }
  70693. Restore.defaultOption = {
  70694. show: true,
  70695. /* eslint-disable */
  70696. 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',
  70697. /* eslint-enable */
  70698. title: restoreLang.title
  70699. };
  70700. var proto$6 = Restore.prototype;
  70701. proto$6.onclick = function (ecModel, api, type) {
  70702. clear$1(ecModel);
  70703. api.dispatchAction({
  70704. type: 'restore',
  70705. from: this.uid
  70706. });
  70707. };
  70708. register$1('restore', Restore);
  70709. registerAction(
  70710. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  70711. function (payload, ecModel) {
  70712. ecModel.resetOption('recreate');
  70713. }
  70714. );
  70715. /*
  70716. * Licensed to the Apache Software Foundation (ASF) under one
  70717. * or more contributor license agreements. See the NOTICE file
  70718. * distributed with this work for additional information
  70719. * regarding copyright ownership. The ASF licenses this file
  70720. * to you under the Apache License, Version 2.0 (the
  70721. * "License"); you may not use this file except in compliance
  70722. * with the License. You may obtain a copy of the License at
  70723. *
  70724. * http://www.apache.org/licenses/LICENSE-2.0
  70725. *
  70726. * Unless required by applicable law or agreed to in writing,
  70727. * software distributed under the License is distributed on an
  70728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70729. * KIND, either express or implied. See the License for the
  70730. * specific language governing permissions and limitations
  70731. * under the License.
  70732. */
  70733. /*
  70734. * Licensed to the Apache Software Foundation (ASF) under one
  70735. * or more contributor license agreements. See the NOTICE file
  70736. * distributed with this work for additional information
  70737. * regarding copyright ownership. The ASF licenses this file
  70738. * to you under the Apache License, Version 2.0 (the
  70739. * "License"); you may not use this file except in compliance
  70740. * with the License. You may obtain a copy of the License at
  70741. *
  70742. * http://www.apache.org/licenses/LICENSE-2.0
  70743. *
  70744. * Unless required by applicable law or agreed to in writing,
  70745. * software distributed under the License is distributed on an
  70746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70747. * KIND, either express or implied. See the License for the
  70748. * specific language governing permissions and limitations
  70749. * under the License.
  70750. */
  70751. extendComponentModel({
  70752. type: 'tooltip',
  70753. dependencies: ['axisPointer'],
  70754. defaultOption: {
  70755. zlevel: 0,
  70756. z: 60,
  70757. show: true,
  70758. // tooltip主体内容
  70759. showContent: true,
  70760. // 'trigger' only works on coordinate system.
  70761. // 'item' | 'axis' | 'none'
  70762. trigger: 'item',
  70763. // 'click' | 'mousemove' | 'none'
  70764. triggerOn: 'mousemove|click',
  70765. alwaysShowContent: false,
  70766. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  70767. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  70768. // 'auto': use html by default, and use non-html if `document` is not defined
  70769. // 'html': use html for tooltip
  70770. // 'richText': use canvas, svg, and etc. for tooltip
  70771. // 位置 {Array} | {Function}
  70772. // position: null
  70773. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  70774. // align: null,
  70775. // verticalAlign: null,
  70776. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  70777. confine: false,
  70778. // 内容格式器:{string}(Template) ¦ {Function}
  70779. // formatter: null
  70780. showDelay: 0,
  70781. // 隐藏延迟,单位ms
  70782. hideDelay: 100,
  70783. // 动画变换时间,单位s
  70784. transitionDuration: 0.4,
  70785. enterable: false,
  70786. // 提示背景颜色,默认为透明度为0.7的黑色
  70787. backgroundColor: 'rgba(50,50,50,0.7)',
  70788. // 提示边框颜色
  70789. borderColor: '#333',
  70790. // 提示边框圆角,单位px,默认为4
  70791. borderRadius: 4,
  70792. // 提示边框线宽,单位px,默认为0(无边框)
  70793. borderWidth: 0,
  70794. // 提示内边距,单位px,默认各方向内边距为5,
  70795. // 接受数组分别设定上右下左边距,同css
  70796. padding: 5,
  70797. // Extra css text
  70798. extraCssText: '',
  70799. // 坐标轴指示器,坐标轴触发有效
  70800. axisPointer: {
  70801. // 默认为直线
  70802. // 可选为:'line' | 'shadow' | 'cross'
  70803. type: 'line',
  70804. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  70805. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  70806. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  70807. // 极坐标系会默认选择 angle 轴
  70808. axis: 'auto',
  70809. animation: 'auto',
  70810. animationDurationUpdate: 200,
  70811. animationEasingUpdate: 'exponentialOut',
  70812. crossStyle: {
  70813. color: '#999',
  70814. width: 1,
  70815. type: 'dashed',
  70816. // TODO formatter
  70817. textStyle: {}
  70818. }
  70819. // lineStyle and shadowStyle should not be specified here,
  70820. // otherwise it will always override those styles on option.axisPointer.
  70821. },
  70822. textStyle: {
  70823. color: '#fff',
  70824. fontSize: 14
  70825. }
  70826. }
  70827. });
  70828. /*
  70829. * Licensed to the Apache Software Foundation (ASF) under one
  70830. * or more contributor license agreements. See the NOTICE file
  70831. * distributed with this work for additional information
  70832. * regarding copyright ownership. The ASF licenses this file
  70833. * to you under the Apache License, Version 2.0 (the
  70834. * "License"); you may not use this file except in compliance
  70835. * with the License. You may obtain a copy of the License at
  70836. *
  70837. * http://www.apache.org/licenses/LICENSE-2.0
  70838. *
  70839. * Unless required by applicable law or agreed to in writing,
  70840. * software distributed under the License is distributed on an
  70841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70842. * KIND, either express or implied. See the License for the
  70843. * specific language governing permissions and limitations
  70844. * under the License.
  70845. */
  70846. var each$22 = each$1;
  70847. var toCamelCase$1 = toCamelCase;
  70848. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  70849. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  70850. /**
  70851. * @param {number} duration
  70852. * @return {string}
  70853. * @inner
  70854. */
  70855. function assembleTransition(duration) {
  70856. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  70857. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  70858. + 'top ' + duration + 's ' + transitionCurve;
  70859. return map(vendors, function (vendorPrefix) {
  70860. return vendorPrefix + 'transition:' + transitionText;
  70861. }).join(';');
  70862. }
  70863. /**
  70864. * @param {Object} textStyle
  70865. * @return {string}
  70866. * @inner
  70867. */
  70868. function assembleFont(textStyleModel) {
  70869. var cssText = [];
  70870. var fontSize = textStyleModel.get('fontSize');
  70871. var color = textStyleModel.getTextColor();
  70872. color && cssText.push('color:' + color);
  70873. cssText.push('font:' + textStyleModel.getFont());
  70874. fontSize
  70875. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  70876. each$22(['decoration', 'align'], function (name) {
  70877. var val = textStyleModel.get(name);
  70878. val && cssText.push('text-' + name + ':' + val);
  70879. });
  70880. return cssText.join(';');
  70881. }
  70882. /**
  70883. * @param {Object} tooltipModel
  70884. * @return {string}
  70885. * @inner
  70886. */
  70887. function assembleCssText(tooltipModel) {
  70888. var cssText = [];
  70889. var transitionDuration = tooltipModel.get('transitionDuration');
  70890. var backgroundColor = tooltipModel.get('backgroundColor');
  70891. var textStyleModel = tooltipModel.getModel('textStyle');
  70892. var padding = tooltipModel.get('padding');
  70893. // Animation transition. Do not animate when transitionDuration is 0.
  70894. transitionDuration
  70895. && cssText.push(assembleTransition(transitionDuration));
  70896. if (backgroundColor) {
  70897. if (env$1.canvasSupported) {
  70898. cssText.push('background-Color:' + backgroundColor);
  70899. }
  70900. else {
  70901. // for ie
  70902. cssText.push(
  70903. 'background-Color:#' + toHex(backgroundColor)
  70904. );
  70905. cssText.push('filter:alpha(opacity=70)');
  70906. }
  70907. }
  70908. // Border style
  70909. each$22(['width', 'color', 'radius'], function (name) {
  70910. var borderName = 'border-' + name;
  70911. var camelCase = toCamelCase$1(borderName);
  70912. var val = tooltipModel.get(camelCase);
  70913. val != null
  70914. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  70915. });
  70916. // Text style
  70917. cssText.push(assembleFont(textStyleModel));
  70918. // Padding
  70919. if (padding != null) {
  70920. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  70921. }
  70922. return cssText.join(';') + ';';
  70923. }
  70924. /**
  70925. * @alias module:echarts/component/tooltip/TooltipContent
  70926. * @constructor
  70927. */
  70928. function TooltipContent(container, api) {
  70929. if (env$1.wxa) {
  70930. return null;
  70931. }
  70932. var el = document.createElement('div');
  70933. var zr = this._zr = api.getZr();
  70934. this.el = el;
  70935. this._x = api.getWidth() / 2;
  70936. this._y = api.getHeight() / 2;
  70937. container.appendChild(el);
  70938. this._container = container;
  70939. this._show = false;
  70940. /**
  70941. * @private
  70942. */
  70943. this._hideTimeout;
  70944. // FIXME
  70945. // Is it needed to trigger zr event manually if
  70946. // the browser do not support `pointer-events: none`.
  70947. var self = this;
  70948. el.onmouseenter = function () {
  70949. // clear the timeout in hideLater and keep showing tooltip
  70950. if (self._enterable) {
  70951. clearTimeout(self._hideTimeout);
  70952. self._show = true;
  70953. }
  70954. self._inContent = true;
  70955. };
  70956. el.onmousemove = function (e) {
  70957. e = e || window.event;
  70958. if (!self._enterable) {
  70959. // `pointer-events: none` is set to tooltip content div
  70960. // if `enterable` is set as `false`, and `el.onmousemove`
  70961. // can not be triggered. But in browser that do not
  70962. // support `pointer-events`, we need to do this:
  70963. // Try trigger zrender event to avoid mouse
  70964. // in and out shape too frequently
  70965. var handler = zr.handler;
  70966. normalizeEvent(container, e, true);
  70967. handler.dispatch('mousemove', e);
  70968. }
  70969. };
  70970. el.onmouseleave = function () {
  70971. if (self._enterable) {
  70972. if (self._show) {
  70973. self.hideLater(self._hideDelay);
  70974. }
  70975. }
  70976. self._inContent = false;
  70977. };
  70978. }
  70979. TooltipContent.prototype = {
  70980. constructor: TooltipContent,
  70981. /**
  70982. * @private
  70983. * @type {boolean}
  70984. */
  70985. _enterable: true,
  70986. /**
  70987. * Update when tooltip is rendered
  70988. */
  70989. update: function () {
  70990. // FIXME
  70991. // Move this logic to ec main?
  70992. var container = this._container;
  70993. var stl = container.currentStyle
  70994. || document.defaultView.getComputedStyle(container);
  70995. var domStyle = container.style;
  70996. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  70997. domStyle.position = 'relative';
  70998. }
  70999. // Hide the tooltip
  71000. // PENDING
  71001. // this.hide();
  71002. },
  71003. show: function (tooltipModel) {
  71004. clearTimeout(this._hideTimeout);
  71005. var el = this.el;
  71006. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  71007. // Because of the reason described in:
  71008. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  71009. // we should set initial value to `left` and `top`.
  71010. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  71011. + (tooltipModel.get('extraCssText') || '');
  71012. el.style.display = el.innerHTML ? 'block' : 'none';
  71013. // If mouse occsionally move over the tooltip, a mouseout event will be
  71014. // triggered by canvas, and cuase some unexpectable result like dragging
  71015. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  71016. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  71017. // scenario.
  71018. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  71019. this._show = true;
  71020. },
  71021. setContent: function (content) {
  71022. this.el.innerHTML = content == null ? '' : content;
  71023. },
  71024. setEnterable: function (enterable) {
  71025. this._enterable = enterable;
  71026. },
  71027. getSize: function () {
  71028. var el = this.el;
  71029. return [el.clientWidth, el.clientHeight];
  71030. },
  71031. moveTo: function (x, y) {
  71032. // xy should be based on canvas root. But tooltipContent is
  71033. // the sibling of canvas root. So padding of ec container
  71034. // should be considered here.
  71035. var zr = this._zr;
  71036. var viewportRootOffset;
  71037. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  71038. x += viewportRootOffset.offsetLeft;
  71039. y += viewportRootOffset.offsetTop;
  71040. }
  71041. var style = this.el.style;
  71042. style.left = x + 'px';
  71043. style.top = y + 'px';
  71044. this._x = x;
  71045. this._y = y;
  71046. },
  71047. hide: function () {
  71048. this.el.style.display = 'none';
  71049. this._show = false;
  71050. },
  71051. hideLater: function (time) {
  71052. if (this._show && !(this._inContent && this._enterable)) {
  71053. if (time) {
  71054. this._hideDelay = time;
  71055. // Set show false to avoid invoke hideLater mutiple times
  71056. this._show = false;
  71057. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71058. }
  71059. else {
  71060. this.hide();
  71061. }
  71062. }
  71063. },
  71064. isShow: function () {
  71065. return this._show;
  71066. },
  71067. getOuterSize: function () {
  71068. var width = this.el.clientWidth;
  71069. var height = this.el.clientHeight;
  71070. // Consider browser compatibility.
  71071. // IE8 does not support getComputedStyle.
  71072. if (document.defaultView && document.defaultView.getComputedStyle) {
  71073. var stl = document.defaultView.getComputedStyle(this.el);
  71074. if (stl) {
  71075. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  71076. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  71077. }
  71078. }
  71079. return {width: width, height: height};
  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. // import Group from 'zrender/src/container/Group';
  71101. /**
  71102. * @alias module:echarts/component/tooltip/TooltipRichContent
  71103. * @constructor
  71104. */
  71105. function TooltipRichContent(api) {
  71106. this._zr = api.getZr();
  71107. this._show = false;
  71108. /**
  71109. * @private
  71110. */
  71111. this._hideTimeout;
  71112. }
  71113. TooltipRichContent.prototype = {
  71114. constructor: TooltipRichContent,
  71115. /**
  71116. * @private
  71117. * @type {boolean}
  71118. */
  71119. _enterable: true,
  71120. /**
  71121. * Update when tooltip is rendered
  71122. */
  71123. update: function () {
  71124. // noop
  71125. },
  71126. show: function (tooltipModel) {
  71127. if (this._hideTimeout) {
  71128. clearTimeout(this._hideTimeout);
  71129. }
  71130. this.el.attr('show', true);
  71131. this._show = true;
  71132. },
  71133. /**
  71134. * Set tooltip content
  71135. *
  71136. * @param {string} content rich text string of content
  71137. * @param {Object} markerRich rich text style
  71138. * @param {Object} tooltipModel tooltip model
  71139. */
  71140. setContent: function (content, markerRich, tooltipModel) {
  71141. if (this.el) {
  71142. this._zr.remove(this.el);
  71143. }
  71144. var markers = {};
  71145. var text = content;
  71146. var prefix = '{marker';
  71147. var suffix = '|}';
  71148. var startId = text.indexOf(prefix);
  71149. while (startId >= 0) {
  71150. var endId = text.indexOf(suffix);
  71151. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  71152. if (name.indexOf('sub') > -1) {
  71153. markers['marker' + name] = {
  71154. textWidth: 4,
  71155. textHeight: 4,
  71156. textBorderRadius: 2,
  71157. textBackgroundColor: markerRich[name],
  71158. // TODO: textOffset is not implemented for rich text
  71159. textOffset: [3, 0]
  71160. };
  71161. }
  71162. else {
  71163. markers['marker' + name] = {
  71164. textWidth: 10,
  71165. textHeight: 10,
  71166. textBorderRadius: 5,
  71167. textBackgroundColor: markerRich[name]
  71168. };
  71169. }
  71170. text = text.substr(endId + 1);
  71171. startId = text.indexOf('{marker');
  71172. }
  71173. this.el = new Text({
  71174. style: {
  71175. rich: markers,
  71176. text: content,
  71177. textLineHeight: 20,
  71178. textBackgroundColor: tooltipModel.get('backgroundColor'),
  71179. textBorderRadius: tooltipModel.get('borderRadius'),
  71180. textFill: tooltipModel.get('textStyle.color'),
  71181. textPadding: tooltipModel.get('padding')
  71182. },
  71183. z: tooltipModel.get('z')
  71184. });
  71185. this._zr.add(this.el);
  71186. var self = this;
  71187. this.el.on('mouseover', function () {
  71188. // clear the timeout in hideLater and keep showing tooltip
  71189. if (self._enterable) {
  71190. clearTimeout(self._hideTimeout);
  71191. self._show = true;
  71192. }
  71193. self._inContent = true;
  71194. });
  71195. this.el.on('mouseout', function () {
  71196. if (self._enterable) {
  71197. if (self._show) {
  71198. self.hideLater(self._hideDelay);
  71199. }
  71200. }
  71201. self._inContent = false;
  71202. });
  71203. },
  71204. setEnterable: function (enterable) {
  71205. this._enterable = enterable;
  71206. },
  71207. getSize: function () {
  71208. var bounding = this.el.getBoundingRect();
  71209. return [bounding.width, bounding.height];
  71210. },
  71211. moveTo: function (x, y) {
  71212. if (this.el) {
  71213. this.el.attr('position', [x, y]);
  71214. }
  71215. },
  71216. hide: function () {
  71217. if (this.el) {
  71218. this.el.hide();
  71219. }
  71220. this._show = false;
  71221. },
  71222. hideLater: function (time) {
  71223. if (this._show && !(this._inContent && this._enterable)) {
  71224. if (time) {
  71225. this._hideDelay = time;
  71226. // Set show false to avoid invoke hideLater mutiple times
  71227. this._show = false;
  71228. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71229. }
  71230. else {
  71231. this.hide();
  71232. }
  71233. }
  71234. },
  71235. isShow: function () {
  71236. return this._show;
  71237. },
  71238. getOuterSize: function () {
  71239. var size = this.getSize();
  71240. return {
  71241. width: size[0],
  71242. height: size[1]
  71243. };
  71244. }
  71245. };
  71246. /*
  71247. * Licensed to the Apache Software Foundation (ASF) under one
  71248. * or more contributor license agreements. See the NOTICE file
  71249. * distributed with this work for additional information
  71250. * regarding copyright ownership. The ASF licenses this file
  71251. * to you under the Apache License, Version 2.0 (the
  71252. * "License"); you may not use this file except in compliance
  71253. * with the License. You may obtain a copy of the License at
  71254. *
  71255. * http://www.apache.org/licenses/LICENSE-2.0
  71256. *
  71257. * Unless required by applicable law or agreed to in writing,
  71258. * software distributed under the License is distributed on an
  71259. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71260. * KIND, either express or implied. See the License for the
  71261. * specific language governing permissions and limitations
  71262. * under the License.
  71263. */
  71264. var bind$3 = bind;
  71265. var each$21 = each$1;
  71266. var parsePercent$2 = parsePercent$1;
  71267. var proxyRect = new Rect({
  71268. shape: {x: -1, y: -1, width: 2, height: 2}
  71269. });
  71270. extendComponentView({
  71271. type: 'tooltip',
  71272. init: function (ecModel, api) {
  71273. if (env$1.node) {
  71274. return;
  71275. }
  71276. var tooltipModel = ecModel.getComponent('tooltip');
  71277. var renderMode = tooltipModel.get('renderMode');
  71278. this._renderMode = getTooltipRenderMode(renderMode);
  71279. var tooltipContent;
  71280. if (this._renderMode === 'html') {
  71281. tooltipContent = new TooltipContent(api.getDom(), api);
  71282. this._newLine = '<br/>';
  71283. }
  71284. else {
  71285. tooltipContent = new TooltipRichContent(api);
  71286. this._newLine = '\n';
  71287. }
  71288. this._tooltipContent = tooltipContent;
  71289. },
  71290. render: function (tooltipModel, ecModel, api) {
  71291. if (env$1.node) {
  71292. return;
  71293. }
  71294. // Reset
  71295. this.group.removeAll();
  71296. /**
  71297. * @private
  71298. * @type {module:echarts/component/tooltip/TooltipModel}
  71299. */
  71300. this._tooltipModel = tooltipModel;
  71301. /**
  71302. * @private
  71303. * @type {module:echarts/model/Global}
  71304. */
  71305. this._ecModel = ecModel;
  71306. /**
  71307. * @private
  71308. * @type {module:echarts/ExtensionAPI}
  71309. */
  71310. this._api = api;
  71311. /**
  71312. * Should be cleaned when render.
  71313. * @private
  71314. * @type {Array.<Array.<Object>>}
  71315. */
  71316. this._lastDataByCoordSys = null;
  71317. /**
  71318. * @private
  71319. * @type {boolean}
  71320. */
  71321. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71322. var tooltipContent = this._tooltipContent;
  71323. tooltipContent.update();
  71324. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  71325. this._initGlobalListener();
  71326. this._keepShow();
  71327. },
  71328. _initGlobalListener: function () {
  71329. var tooltipModel = this._tooltipModel;
  71330. var triggerOn = tooltipModel.get('triggerOn');
  71331. register(
  71332. 'itemTooltip',
  71333. this._api,
  71334. bind$3(function (currTrigger, e, dispatchAction) {
  71335. // If 'none', it is not controlled by mouse totally.
  71336. if (triggerOn !== 'none') {
  71337. if (triggerOn.indexOf(currTrigger) >= 0) {
  71338. this._tryShow(e, dispatchAction);
  71339. }
  71340. else if (currTrigger === 'leave') {
  71341. this._hide(dispatchAction);
  71342. }
  71343. }
  71344. }, this)
  71345. );
  71346. },
  71347. _keepShow: function () {
  71348. var tooltipModel = this._tooltipModel;
  71349. var ecModel = this._ecModel;
  71350. var api = this._api;
  71351. // Try to keep the tooltip show when refreshing
  71352. if (this._lastX != null
  71353. && this._lastY != null
  71354. // When user is willing to control tooltip totally using API,
  71355. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  71356. // which is not expected.
  71357. && tooltipModel.get('triggerOn') !== 'none'
  71358. ) {
  71359. var self = this;
  71360. clearTimeout(this._refreshUpdateTimeout);
  71361. this._refreshUpdateTimeout = setTimeout(function () {
  71362. // Show tip next tick after other charts are rendered
  71363. // In case highlight action has wrong result
  71364. // FIXME
  71365. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  71366. x: self._lastX,
  71367. y: self._lastY
  71368. });
  71369. });
  71370. }
  71371. },
  71372. /**
  71373. * Show tip manually by
  71374. * dispatchAction({
  71375. * type: 'showTip',
  71376. * x: 10,
  71377. * y: 10
  71378. * });
  71379. * Or
  71380. * dispatchAction({
  71381. * type: 'showTip',
  71382. * seriesIndex: 0,
  71383. * dataIndex or dataIndexInside or name
  71384. * });
  71385. *
  71386. * TODO Batch
  71387. */
  71388. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  71389. if (payload.from === this.uid || env$1.node) {
  71390. return;
  71391. }
  71392. var dispatchAction = makeDispatchAction$1(payload, api);
  71393. // Reset ticket
  71394. this._ticket = '';
  71395. // When triggered from axisPointer.
  71396. var dataByCoordSys = payload.dataByCoordSys;
  71397. if (payload.tooltip && payload.x != null && payload.y != null) {
  71398. var el = proxyRect;
  71399. el.position = [payload.x, payload.y];
  71400. el.update();
  71401. el.tooltip = payload.tooltip;
  71402. // Manually show tooltip while view is not using zrender elements.
  71403. this._tryShow({
  71404. offsetX: payload.x,
  71405. offsetY: payload.y,
  71406. target: el
  71407. }, dispatchAction);
  71408. }
  71409. else if (dataByCoordSys) {
  71410. this._tryShow({
  71411. offsetX: payload.x,
  71412. offsetY: payload.y,
  71413. position: payload.position,
  71414. event: {},
  71415. dataByCoordSys: payload.dataByCoordSys,
  71416. tooltipOption: payload.tooltipOption
  71417. }, dispatchAction);
  71418. }
  71419. else if (payload.seriesIndex != null) {
  71420. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  71421. return;
  71422. }
  71423. var pointInfo = findPointFromSeries(payload, ecModel);
  71424. var cx = pointInfo.point[0];
  71425. var cy = pointInfo.point[1];
  71426. if (cx != null && cy != null) {
  71427. this._tryShow({
  71428. offsetX: cx,
  71429. offsetY: cy,
  71430. position: payload.position,
  71431. target: pointInfo.el,
  71432. event: {}
  71433. }, dispatchAction);
  71434. }
  71435. }
  71436. else if (payload.x != null && payload.y != null) {
  71437. // FIXME
  71438. // should wrap dispatchAction like `axisPointer/globalListener` ?
  71439. api.dispatchAction({
  71440. type: 'updateAxisPointer',
  71441. x: payload.x,
  71442. y: payload.y
  71443. });
  71444. this._tryShow({
  71445. offsetX: payload.x,
  71446. offsetY: payload.y,
  71447. position: payload.position,
  71448. target: api.getZr().findHover(payload.x, payload.y).target,
  71449. event: {}
  71450. }, dispatchAction);
  71451. }
  71452. },
  71453. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  71454. var tooltipContent = this._tooltipContent;
  71455. if (!this._alwaysShowContent && this._tooltipModel) {
  71456. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  71457. }
  71458. this._lastX = this._lastY = null;
  71459. if (payload.from !== this.uid) {
  71460. this._hide(makeDispatchAction$1(payload, api));
  71461. }
  71462. },
  71463. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  71464. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  71465. // and tooltip.
  71466. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  71467. var seriesIndex = payload.seriesIndex;
  71468. var dataIndex = payload.dataIndex;
  71469. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  71470. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  71471. return;
  71472. }
  71473. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  71474. if (!seriesModel) {
  71475. return;
  71476. }
  71477. var data = seriesModel.getData();
  71478. var tooltipModel = buildTooltipModel([
  71479. data.getItemModel(dataIndex),
  71480. seriesModel,
  71481. (seriesModel.coordinateSystem || {}).model,
  71482. tooltipModel
  71483. ]);
  71484. if (tooltipModel.get('trigger') !== 'axis') {
  71485. return;
  71486. }
  71487. api.dispatchAction({
  71488. type: 'updateAxisPointer',
  71489. seriesIndex: seriesIndex,
  71490. dataIndex: dataIndex,
  71491. position: payload.position
  71492. });
  71493. return true;
  71494. },
  71495. _tryShow: function (e, dispatchAction) {
  71496. var el = e.target;
  71497. var tooltipModel = this._tooltipModel;
  71498. if (!tooltipModel) {
  71499. return;
  71500. }
  71501. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  71502. this._lastX = e.offsetX;
  71503. this._lastY = e.offsetY;
  71504. var dataByCoordSys = e.dataByCoordSys;
  71505. if (dataByCoordSys && dataByCoordSys.length) {
  71506. this._showAxisTooltip(dataByCoordSys, e);
  71507. }
  71508. // Always show item tooltip if mouse is on the element with dataIndex
  71509. else if (el && el.dataIndex != null) {
  71510. this._lastDataByCoordSys = null;
  71511. this._showSeriesItemTooltip(e, el, dispatchAction);
  71512. }
  71513. // Tooltip provided directly. Like legend.
  71514. else if (el && el.tooltip) {
  71515. this._lastDataByCoordSys = null;
  71516. this._showComponentItemTooltip(e, el, dispatchAction);
  71517. }
  71518. else {
  71519. this._lastDataByCoordSys = null;
  71520. this._hide(dispatchAction);
  71521. }
  71522. },
  71523. _showOrMove: function (tooltipModel, cb) {
  71524. // showDelay is used in this case: tooltip.enterable is set
  71525. // as true. User intent to move mouse into tooltip and click
  71526. // something. `showDelay` makes it easyer to enter the content
  71527. // but tooltip do not move immediately.
  71528. var delay = tooltipModel.get('showDelay');
  71529. cb = bind(cb, this);
  71530. clearTimeout(this._showTimout);
  71531. delay > 0
  71532. ? (this._showTimout = setTimeout(cb, delay))
  71533. : cb();
  71534. },
  71535. _showAxisTooltip: function (dataByCoordSys, e) {
  71536. var ecModel = this._ecModel;
  71537. var globalTooltipModel = this._tooltipModel;
  71538. var point = [e.offsetX, e.offsetY];
  71539. var singleDefaultHTML = [];
  71540. var singleParamsList = [];
  71541. var singleTooltipModel = buildTooltipModel([
  71542. e.tooltipOption,
  71543. globalTooltipModel
  71544. ]);
  71545. var renderMode = this._renderMode;
  71546. var newLine = this._newLine;
  71547. var markers = {};
  71548. each$21(dataByCoordSys, function (itemCoordSys) {
  71549. // var coordParamList = [];
  71550. // var coordDefaultHTML = [];
  71551. // var coordTooltipModel = buildTooltipModel([
  71552. // e.tooltipOption,
  71553. // itemCoordSys.tooltipOption,
  71554. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  71555. // globalTooltipModel
  71556. // ]);
  71557. // var displayMode = coordTooltipModel.get('displayMode');
  71558. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  71559. each$21(itemCoordSys.dataByAxis, function (item) {
  71560. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  71561. var axisValue = item.value;
  71562. var seriesDefaultHTML = [];
  71563. if (!axisModel || axisValue == null) {
  71564. return;
  71565. }
  71566. var valueLabel = getValueLabel(
  71567. axisValue, axisModel.axis, ecModel,
  71568. item.seriesDataIndices,
  71569. item.valueLabelOpt
  71570. );
  71571. each$1(item.seriesDataIndices, function (idxItem) {
  71572. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  71573. var dataIndex = idxItem.dataIndexInside;
  71574. var dataParams = series && series.getDataParams(dataIndex);
  71575. dataParams.axisDim = item.axisDim;
  71576. dataParams.axisIndex = item.axisIndex;
  71577. dataParams.axisType = item.axisType;
  71578. dataParams.axisId = item.axisId;
  71579. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  71580. dataParams.axisValueLabel = valueLabel;
  71581. if (dataParams) {
  71582. singleParamsList.push(dataParams);
  71583. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  71584. var html;
  71585. if (isObject$1(seriesTooltip)) {
  71586. html = seriesTooltip.html;
  71587. var newMarkers = seriesTooltip.markers;
  71588. merge(markers, newMarkers);
  71589. }
  71590. else {
  71591. html = seriesTooltip;
  71592. }
  71593. seriesDefaultHTML.push(html);
  71594. }
  71595. });
  71596. // Default tooltip content
  71597. // FIXME
  71598. // (1) shold be the first data which has name?
  71599. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  71600. var firstLine = valueLabel;
  71601. if (renderMode !== 'html') {
  71602. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  71603. }
  71604. else {
  71605. singleDefaultHTML.push(
  71606. (firstLine ? encodeHTML(firstLine) + newLine : '')
  71607. + seriesDefaultHTML.join(newLine)
  71608. );
  71609. }
  71610. });
  71611. }, this);
  71612. // In most case, the second axis is shown upper than the first one.
  71613. singleDefaultHTML.reverse();
  71614. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  71615. var positionExpr = e.position;
  71616. this._showOrMove(singleTooltipModel, function () {
  71617. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  71618. this._updatePosition(
  71619. singleTooltipModel,
  71620. positionExpr,
  71621. point[0], point[1],
  71622. this._tooltipContent,
  71623. singleParamsList
  71624. );
  71625. }
  71626. else {
  71627. this._showTooltipContent(
  71628. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  71629. point[0], point[1], positionExpr, undefined, markers
  71630. );
  71631. }
  71632. });
  71633. // Do not trigger events here, because this branch only be entered
  71634. // from dispatchAction.
  71635. },
  71636. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  71637. var ecModel = this._ecModel;
  71638. // Use dataModel in element if possible
  71639. // Used when mouseover on a element like markPoint or edge
  71640. // In which case, the data is not main data in series.
  71641. var seriesIndex = el.seriesIndex;
  71642. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  71643. // For example, graph link.
  71644. var dataModel = el.dataModel || seriesModel;
  71645. var dataIndex = el.dataIndex;
  71646. var dataType = el.dataType;
  71647. var data = dataModel.getData();
  71648. var tooltipModel = buildTooltipModel([
  71649. data.getItemModel(dataIndex),
  71650. dataModel,
  71651. seriesModel && (seriesModel.coordinateSystem || {}).model,
  71652. this._tooltipModel
  71653. ]);
  71654. var tooltipTrigger = tooltipModel.get('trigger');
  71655. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  71656. return;
  71657. }
  71658. var params = dataModel.getDataParams(dataIndex, dataType);
  71659. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  71660. var defaultHtml;
  71661. var markers;
  71662. if (isObject$1(seriesTooltip)) {
  71663. defaultHtml = seriesTooltip.html;
  71664. markers = seriesTooltip.markers;
  71665. }
  71666. else {
  71667. defaultHtml = seriesTooltip;
  71668. markers = null;
  71669. }
  71670. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  71671. this._showOrMove(tooltipModel, function () {
  71672. this._showTooltipContent(
  71673. tooltipModel, defaultHtml, params, asyncTicket,
  71674. e.offsetX, e.offsetY, e.position, e.target, markers
  71675. );
  71676. });
  71677. // FIXME
  71678. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  71679. dispatchAction({
  71680. type: 'showTip',
  71681. dataIndexInside: dataIndex,
  71682. dataIndex: data.getRawIndex(dataIndex),
  71683. seriesIndex: seriesIndex,
  71684. from: this.uid
  71685. });
  71686. },
  71687. _showComponentItemTooltip: function (e, el, dispatchAction) {
  71688. var tooltipOpt = el.tooltip;
  71689. if (typeof tooltipOpt === 'string') {
  71690. var content = tooltipOpt;
  71691. tooltipOpt = {
  71692. content: content,
  71693. // Fixed formatter
  71694. formatter: content
  71695. };
  71696. }
  71697. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  71698. var defaultHtml = subTooltipModel.get('content');
  71699. var asyncTicket = Math.random();
  71700. // Do not check whether `trigger` is 'none' here, because `trigger`
  71701. // only works on cooridinate system. In fact, we have not found case
  71702. // that requires setting `trigger` nothing on component yet.
  71703. this._showOrMove(subTooltipModel, function () {
  71704. this._showTooltipContent(
  71705. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  71706. asyncTicket, e.offsetX, e.offsetY, e.position, el
  71707. );
  71708. });
  71709. // If not dispatch showTip, tip may be hide triggered by axis.
  71710. dispatchAction({
  71711. type: 'showTip',
  71712. from: this.uid
  71713. });
  71714. },
  71715. _showTooltipContent: function (
  71716. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  71717. ) {
  71718. // Reset ticket
  71719. this._ticket = '';
  71720. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  71721. return;
  71722. }
  71723. var tooltipContent = this._tooltipContent;
  71724. var formatter = tooltipModel.get('formatter');
  71725. positionExpr = positionExpr || tooltipModel.get('position');
  71726. var html = defaultHtml;
  71727. if (formatter && typeof formatter === 'string') {
  71728. html = formatTpl(formatter, params, true);
  71729. }
  71730. else if (typeof formatter === 'function') {
  71731. var callback = bind$3(function (cbTicket, html) {
  71732. if (cbTicket === this._ticket) {
  71733. tooltipContent.setContent(html, markers, tooltipModel);
  71734. this._updatePosition(
  71735. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  71736. );
  71737. }
  71738. }, this);
  71739. this._ticket = asyncTicket;
  71740. html = formatter(params, asyncTicket, callback);
  71741. }
  71742. tooltipContent.setContent(html, markers, tooltipModel);
  71743. tooltipContent.show(tooltipModel);
  71744. this._updatePosition(
  71745. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  71746. );
  71747. },
  71748. /**
  71749. * @param {string|Function|Array.<number>|Object} positionExpr
  71750. * @param {number} x Mouse x
  71751. * @param {number} y Mouse y
  71752. * @param {boolean} confine Whether confine tooltip content in view rect.
  71753. * @param {Object|<Array.<Object>} params
  71754. * @param {module:zrender/Element} el target element
  71755. * @param {module:echarts/ExtensionAPI} api
  71756. * @return {Array.<number>}
  71757. */
  71758. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  71759. var viewWidth = this._api.getWidth();
  71760. var viewHeight = this._api.getHeight();
  71761. positionExpr = positionExpr || tooltipModel.get('position');
  71762. var contentSize = content.getSize();
  71763. var align = tooltipModel.get('align');
  71764. var vAlign = tooltipModel.get('verticalAlign');
  71765. var rect = el && el.getBoundingRect().clone();
  71766. el && rect.applyTransform(el.transform);
  71767. if (typeof positionExpr === 'function') {
  71768. // Callback of position can be an array or a string specify the position
  71769. positionExpr = positionExpr([x, y], params, content.el, rect, {
  71770. viewSize: [viewWidth, viewHeight],
  71771. contentSize: contentSize.slice()
  71772. });
  71773. }
  71774. if (isArray(positionExpr)) {
  71775. x = parsePercent$2(positionExpr[0], viewWidth);
  71776. y = parsePercent$2(positionExpr[1], viewHeight);
  71777. }
  71778. else if (isObject$1(positionExpr)) {
  71779. positionExpr.width = contentSize[0];
  71780. positionExpr.height = contentSize[1];
  71781. var layoutRect = getLayoutRect(
  71782. positionExpr, {width: viewWidth, height: viewHeight}
  71783. );
  71784. x = layoutRect.x;
  71785. y = layoutRect.y;
  71786. align = null;
  71787. // When positionExpr is left/top/right/bottom,
  71788. // align and verticalAlign will not work.
  71789. vAlign = null;
  71790. }
  71791. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  71792. else if (typeof positionExpr === 'string' && el) {
  71793. var pos = calcTooltipPosition(
  71794. positionExpr, rect, contentSize
  71795. );
  71796. x = pos[0];
  71797. y = pos[1];
  71798. }
  71799. else {
  71800. var pos = refixTooltipPosition(
  71801. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  71802. );
  71803. x = pos[0];
  71804. y = pos[1];
  71805. }
  71806. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  71807. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  71808. if (tooltipModel.get('confine')) {
  71809. var pos = confineTooltipPosition(
  71810. x, y, content, viewWidth, viewHeight
  71811. );
  71812. x = pos[0];
  71813. y = pos[1];
  71814. }
  71815. content.moveTo(x, y);
  71816. },
  71817. // FIXME
  71818. // Should we remove this but leave this to user?
  71819. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  71820. var lastCoordSys = this._lastDataByCoordSys;
  71821. var contentNotChanged = !!lastCoordSys
  71822. && lastCoordSys.length === dataByCoordSys.length;
  71823. contentNotChanged && each$21(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  71824. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  71825. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  71826. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  71827. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  71828. contentNotChanged && each$21(lastDataByAxis, function (lastItem, indexAxis) {
  71829. var thisItem = thisDataByAxis[indexAxis] || {};
  71830. var lastIndices = lastItem.seriesDataIndices || [];
  71831. var newIndices = thisItem.seriesDataIndices || [];
  71832. contentNotChanged
  71833. &= lastItem.value === thisItem.value
  71834. && lastItem.axisType === thisItem.axisType
  71835. && lastItem.axisId === thisItem.axisId
  71836. && lastIndices.length === newIndices.length;
  71837. contentNotChanged && each$21(lastIndices, function (lastIdxItem, j) {
  71838. var newIdxItem = newIndices[j];
  71839. contentNotChanged
  71840. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  71841. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  71842. });
  71843. });
  71844. });
  71845. this._lastDataByCoordSys = dataByCoordSys;
  71846. return !!contentNotChanged;
  71847. },
  71848. _hide: function (dispatchAction) {
  71849. // Do not directly hideLater here, because this behavior may be prevented
  71850. // in dispatchAction when showTip is dispatched.
  71851. // FIXME
  71852. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  71853. this._lastDataByCoordSys = null;
  71854. dispatchAction({
  71855. type: 'hideTip',
  71856. from: this.uid
  71857. });
  71858. },
  71859. dispose: function (ecModel, api) {
  71860. if (env$1.node) {
  71861. return;
  71862. }
  71863. this._tooltipContent.hide();
  71864. unregister('itemTooltip', api);
  71865. }
  71866. });
  71867. /**
  71868. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  71869. * From top to bottom. (the last one should be globalTooltipModel);
  71870. */
  71871. function buildTooltipModel(modelCascade) {
  71872. var resultModel = modelCascade.pop();
  71873. while (modelCascade.length) {
  71874. var tooltipOpt = modelCascade.pop();
  71875. if (tooltipOpt) {
  71876. if (Model.isInstance(tooltipOpt)) {
  71877. tooltipOpt = tooltipOpt.get('tooltip', true);
  71878. }
  71879. // In each data item tooltip can be simply write:
  71880. // {
  71881. // value: 10,
  71882. // tooltip: 'Something you need to know'
  71883. // }
  71884. if (typeof tooltipOpt === 'string') {
  71885. tooltipOpt = {formatter: tooltipOpt};
  71886. }
  71887. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  71888. }
  71889. }
  71890. return resultModel;
  71891. }
  71892. function makeDispatchAction$1(payload, api) {
  71893. return payload.dispatchAction || bind(api.dispatchAction, api);
  71894. }
  71895. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  71896. var size = content.getOuterSize();
  71897. var width = size.width;
  71898. var height = size.height;
  71899. if (gapH != null) {
  71900. if (x + width + gapH > viewWidth) {
  71901. x -= width + gapH;
  71902. }
  71903. else {
  71904. x += gapH;
  71905. }
  71906. }
  71907. if (gapV != null) {
  71908. if (y + height + gapV > viewHeight) {
  71909. y -= height + gapV;
  71910. }
  71911. else {
  71912. y += gapV;
  71913. }
  71914. }
  71915. return [x, y];
  71916. }
  71917. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  71918. var size = content.getOuterSize();
  71919. var width = size.width;
  71920. var height = size.height;
  71921. x = Math.min(x + width, viewWidth) - width;
  71922. y = Math.min(y + height, viewHeight) - height;
  71923. x = Math.max(x, 0);
  71924. y = Math.max(y, 0);
  71925. return [x, y];
  71926. }
  71927. function calcTooltipPosition(position, rect, contentSize) {
  71928. var domWidth = contentSize[0];
  71929. var domHeight = contentSize[1];
  71930. var gap = 5;
  71931. var x = 0;
  71932. var y = 0;
  71933. var rectWidth = rect.width;
  71934. var rectHeight = rect.height;
  71935. switch (position) {
  71936. case 'inside':
  71937. x = rect.x + rectWidth / 2 - domWidth / 2;
  71938. y = rect.y + rectHeight / 2 - domHeight / 2;
  71939. break;
  71940. case 'top':
  71941. x = rect.x + rectWidth / 2 - domWidth / 2;
  71942. y = rect.y - domHeight - gap;
  71943. break;
  71944. case 'bottom':
  71945. x = rect.x + rectWidth / 2 - domWidth / 2;
  71946. y = rect.y + rectHeight + gap;
  71947. break;
  71948. case 'left':
  71949. x = rect.x - domWidth - gap;
  71950. y = rect.y + rectHeight / 2 - domHeight / 2;
  71951. break;
  71952. case 'right':
  71953. x = rect.x + rectWidth + gap;
  71954. y = rect.y + rectHeight / 2 - domHeight / 2;
  71955. }
  71956. return [x, y];
  71957. }
  71958. function isCenterAlign(align) {
  71959. return align === 'center' || align === 'middle';
  71960. }
  71961. /*
  71962. * Licensed to the Apache Software Foundation (ASF) under one
  71963. * or more contributor license agreements. See the NOTICE file
  71964. * distributed with this work for additional information
  71965. * regarding copyright ownership. The ASF licenses this file
  71966. * to you under the Apache License, Version 2.0 (the
  71967. * "License"); you may not use this file except in compliance
  71968. * with the License. You may obtain a copy of the License at
  71969. *
  71970. * http://www.apache.org/licenses/LICENSE-2.0
  71971. *
  71972. * Unless required by applicable law or agreed to in writing,
  71973. * software distributed under the License is distributed on an
  71974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71975. * KIND, either express or implied. See the License for the
  71976. * specific language governing permissions and limitations
  71977. * under the License.
  71978. */
  71979. // FIXME Better way to pack data in graphic element
  71980. /**
  71981. * @action
  71982. * @property {string} type
  71983. * @property {number} seriesIndex
  71984. * @property {number} dataIndex
  71985. * @property {number} [x]
  71986. * @property {number} [y]
  71987. */
  71988. registerAction(
  71989. {
  71990. type: 'showTip',
  71991. event: 'showTip',
  71992. update: 'tooltip:manuallyShowTip'
  71993. },
  71994. // noop
  71995. function () {}
  71996. );
  71997. registerAction(
  71998. {
  71999. type: 'hideTip',
  72000. event: 'hideTip',
  72001. update: 'tooltip:manuallyHideTip'
  72002. },
  72003. // noop
  72004. function () {}
  72005. );
  72006. /*
  72007. * Licensed to the Apache Software Foundation (ASF) under one
  72008. * or more contributor license agreements. See the NOTICE file
  72009. * distributed with this work for additional information
  72010. * regarding copyright ownership. The ASF licenses this file
  72011. * to you under the Apache License, Version 2.0 (the
  72012. * "License"); you may not use this file except in compliance
  72013. * with the License. You may obtain a copy of the License at
  72014. *
  72015. * http://www.apache.org/licenses/LICENSE-2.0
  72016. *
  72017. * Unless required by applicable law or agreed to in writing,
  72018. * software distributed under the License is distributed on an
  72019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72020. * KIND, either express or implied. See the License for the
  72021. * specific language governing permissions and limitations
  72022. * under the License.
  72023. */
  72024. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  72025. var preprocessor$1 = function (option, isNew) {
  72026. var brushComponents = option && option.brush;
  72027. if (!isArray(brushComponents)) {
  72028. brushComponents = brushComponents ? [brushComponents] : [];
  72029. }
  72030. if (!brushComponents.length) {
  72031. return;
  72032. }
  72033. var brushComponentSpecifiedBtns = [];
  72034. each$1(brushComponents, function (brushOpt) {
  72035. var tbs = brushOpt.hasOwnProperty('toolbox')
  72036. ? brushOpt.toolbox : [];
  72037. if (tbs instanceof Array) {
  72038. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72039. }
  72040. });
  72041. var toolbox = option && option.toolbox;
  72042. if (isArray(toolbox)) {
  72043. toolbox = toolbox[0];
  72044. }
  72045. if (!toolbox) {
  72046. toolbox = {feature: {}};
  72047. option.toolbox = [toolbox];
  72048. }
  72049. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  72050. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72051. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72052. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72053. removeDuplicate(brushTypes);
  72054. if (isNew && !brushTypes.length) {
  72055. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72056. }
  72057. };
  72058. function removeDuplicate(arr) {
  72059. var map$$1 = {};
  72060. each$1(arr, function (val) {
  72061. map$$1[val] = 1;
  72062. });
  72063. arr.length = 0;
  72064. each$1(map$$1, function (flag, val) {
  72065. arr.push(val);
  72066. });
  72067. }
  72068. /*
  72069. * Licensed to the Apache Software Foundation (ASF) under one
  72070. * or more contributor license agreements. See the NOTICE file
  72071. * distributed with this work for additional information
  72072. * regarding copyright ownership. The ASF licenses this file
  72073. * to you under the Apache License, Version 2.0 (the
  72074. * "License"); you may not use this file except in compliance
  72075. * with the License. You may obtain a copy of the License at
  72076. *
  72077. * http://www.apache.org/licenses/LICENSE-2.0
  72078. *
  72079. * Unless required by applicable law or agreed to in writing,
  72080. * software distributed under the License is distributed on an
  72081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72082. * KIND, either express or implied. See the License for the
  72083. * specific language governing permissions and limitations
  72084. * under the License.
  72085. */
  72086. /**
  72087. * @file Visual solution, for consistent option specification.
  72088. */
  72089. var each$23 = each$1;
  72090. function hasKeys(obj) {
  72091. if (obj) {
  72092. for (var name in obj) {
  72093. if (obj.hasOwnProperty(name)) {
  72094. return true;
  72095. }
  72096. }
  72097. }
  72098. }
  72099. /**
  72100. * @param {Object} option
  72101. * @param {Array.<string>} stateList
  72102. * @param {Function} [supplementVisualOption]
  72103. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  72104. */
  72105. function createVisualMappings(option, stateList, supplementVisualOption) {
  72106. var visualMappings = {};
  72107. each$23(stateList, function (state) {
  72108. var mappings = visualMappings[state] = createMappings();
  72109. each$23(option[state], function (visualData, visualType) {
  72110. if (!VisualMapping.isValidType(visualType)) {
  72111. return;
  72112. }
  72113. var mappingOption = {
  72114. type: visualType,
  72115. visual: visualData
  72116. };
  72117. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72118. mappings[visualType] = new VisualMapping(mappingOption);
  72119. // Prepare a alpha for opacity, for some case that opacity
  72120. // is not supported, such as rendering using gradient color.
  72121. if (visualType === 'opacity') {
  72122. mappingOption = clone(mappingOption);
  72123. mappingOption.type = 'colorAlpha';
  72124. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72125. }
  72126. });
  72127. });
  72128. return visualMappings;
  72129. function createMappings() {
  72130. var Creater = function () {};
  72131. // Make sure hidden fields will not be visited by
  72132. // object iteration (with hasOwnProperty checking).
  72133. Creater.prototype.__hidden = Creater.prototype;
  72134. var obj = new Creater();
  72135. return obj;
  72136. }
  72137. }
  72138. /**
  72139. * @param {Object} thisOption
  72140. * @param {Object} newOption
  72141. * @param {Array.<string>} keys
  72142. */
  72143. function replaceVisualOption(thisOption, newOption, keys) {
  72144. // Visual attributes merge is not supported, otherwise it
  72145. // brings overcomplicated merge logic. See #2853. So if
  72146. // newOption has anyone of these keys, all of these keys
  72147. // will be reset. Otherwise, all keys remain.
  72148. var has;
  72149. each$1(keys, function (key) {
  72150. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72151. has = true;
  72152. }
  72153. });
  72154. has && each$1(keys, function (key) {
  72155. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72156. thisOption[key] = clone(newOption[key]);
  72157. }
  72158. else {
  72159. delete thisOption[key];
  72160. }
  72161. });
  72162. }
  72163. /**
  72164. * @param {Array.<string>} stateList
  72165. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72166. * @param {module:echarts/data/List} list
  72167. * @param {Function} getValueState param: valueOrIndex, return: state.
  72168. * @param {object} [scope] Scope for getValueState
  72169. * @param {string} [dimension] Concrete dimension, if used.
  72170. */
  72171. // ???! handle brush?
  72172. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72173. var visualTypesMap = {};
  72174. each$1(stateList, function (state) {
  72175. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72176. visualTypesMap[state] = visualTypes;
  72177. });
  72178. var dataIndex;
  72179. function getVisual(key) {
  72180. return data.getItemVisual(dataIndex, key);
  72181. }
  72182. function setVisual(key, value) {
  72183. data.setItemVisual(dataIndex, key, value);
  72184. }
  72185. if (dimension == null) {
  72186. data.each(eachItem);
  72187. }
  72188. else {
  72189. data.each([dimension], eachItem);
  72190. }
  72191. function eachItem(valueOrIndex, index) {
  72192. dataIndex = dimension == null ? valueOrIndex : index;
  72193. var rawDataItem = data.getRawDataItem(dataIndex);
  72194. // Consider performance
  72195. if (rawDataItem && rawDataItem.visualMap === false) {
  72196. return;
  72197. }
  72198. var valueState = getValueState.call(scope, valueOrIndex);
  72199. var mappings = visualMappings[valueState];
  72200. var visualTypes = visualTypesMap[valueState];
  72201. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72202. var type = visualTypes[i];
  72203. mappings[type] && mappings[type].applyVisual(
  72204. valueOrIndex, getVisual, setVisual
  72205. );
  72206. }
  72207. }
  72208. }
  72209. /**
  72210. * @param {module:echarts/data/List} data
  72211. * @param {Array.<string>} stateList
  72212. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72213. * @param {Function} getValueState param: valueOrIndex, return: state.
  72214. * @param {number} [dim] dimension or dimension index.
  72215. */
  72216. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72217. var visualTypesMap = {};
  72218. each$1(stateList, function (state) {
  72219. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72220. visualTypesMap[state] = visualTypes;
  72221. });
  72222. function progress(params, data) {
  72223. if (dim != null) {
  72224. dim = data.getDimension(dim);
  72225. }
  72226. function getVisual(key) {
  72227. return data.getItemVisual(dataIndex, key);
  72228. }
  72229. function setVisual(key, value) {
  72230. data.setItemVisual(dataIndex, key, value);
  72231. }
  72232. var dataIndex;
  72233. while ((dataIndex = params.next()) != null) {
  72234. var rawDataItem = data.getRawDataItem(dataIndex);
  72235. // Consider performance
  72236. if (rawDataItem && rawDataItem.visualMap === false) {
  72237. continue;
  72238. }
  72239. var value = dim != null
  72240. ? data.get(dim, dataIndex, true)
  72241. : dataIndex;
  72242. var valueState = getValueState(value);
  72243. var mappings = visualMappings[valueState];
  72244. var visualTypes = visualTypesMap[valueState];
  72245. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72246. var type = visualTypes[i];
  72247. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  72248. }
  72249. }
  72250. }
  72251. return {progress: progress};
  72252. }
  72253. /*
  72254. * Licensed to the Apache Software Foundation (ASF) under one
  72255. * or more contributor license agreements. See the NOTICE file
  72256. * distributed with this work for additional information
  72257. * regarding copyright ownership. The ASF licenses this file
  72258. * to you under the Apache License, Version 2.0 (the
  72259. * "License"); you may not use this file except in compliance
  72260. * with the License. You may obtain a copy of the License at
  72261. *
  72262. * http://www.apache.org/licenses/LICENSE-2.0
  72263. *
  72264. * Unless required by applicable law or agreed to in writing,
  72265. * software distributed under the License is distributed on an
  72266. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72267. * KIND, either express or implied. See the License for the
  72268. * specific language governing permissions and limitations
  72269. * under the License.
  72270. */
  72271. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  72272. // Key of the second level is chart element type: `point`, `rect`.
  72273. // See moudule:echarts/component/helper/BrushController
  72274. // function param:
  72275. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  72276. // {Object} selectors {point: selector, rect: selector, ...}
  72277. // {Object} area {range: [[], [], ..], boudingRect}
  72278. // function return:
  72279. // {boolean} Whether in the given brush.
  72280. var selector = {
  72281. lineX: getLineSelectors(0),
  72282. lineY: getLineSelectors(1),
  72283. rect: {
  72284. point: function (itemLayout, selectors, area) {
  72285. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  72286. },
  72287. rect: function (itemLayout, selectors, area) {
  72288. return itemLayout && area.boundingRect.intersect(itemLayout);
  72289. }
  72290. },
  72291. polygon: {
  72292. point: function (itemLayout, selectors, area) {
  72293. return itemLayout
  72294. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  72295. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  72296. },
  72297. rect: function (itemLayout, selectors, area) {
  72298. var points = area.range;
  72299. if (!itemLayout || points.length <= 1) {
  72300. return false;
  72301. }
  72302. var x = itemLayout.x;
  72303. var y = itemLayout.y;
  72304. var width = itemLayout.width;
  72305. var height = itemLayout.height;
  72306. var p = points[0];
  72307. if (contain$1(points, x, y)
  72308. || contain$1(points, x + width, y)
  72309. || contain$1(points, x, y + height)
  72310. || contain$1(points, x + width, y + height)
  72311. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  72312. || linePolygonIntersect(x, y, x + width, y, points)
  72313. || linePolygonIntersect(x, y, x, y + height, points)
  72314. || linePolygonIntersect(x + width, y, x + width, y + height, points)
  72315. || linePolygonIntersect(x, y + height, x + width, y + height, points)
  72316. ) {
  72317. return true;
  72318. }
  72319. }
  72320. }
  72321. };
  72322. function getLineSelectors(xyIndex) {
  72323. var xy = ['x', 'y'];
  72324. var wh = ['width', 'height'];
  72325. return {
  72326. point: function (itemLayout, selectors, area) {
  72327. if (itemLayout) {
  72328. var range = area.range;
  72329. var p = itemLayout[xyIndex];
  72330. return inLineRange(p, range);
  72331. }
  72332. },
  72333. rect: function (itemLayout, selectors, area) {
  72334. if (itemLayout) {
  72335. var range = area.range;
  72336. var layoutRange = [
  72337. itemLayout[xy[xyIndex]],
  72338. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  72339. ];
  72340. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  72341. return inLineRange(layoutRange[0], range)
  72342. || inLineRange(layoutRange[1], range)
  72343. || inLineRange(range[0], layoutRange)
  72344. || inLineRange(range[1], layoutRange);
  72345. }
  72346. }
  72347. };
  72348. }
  72349. function inLineRange(p, range) {
  72350. return range[0] <= p && p <= range[1];
  72351. }
  72352. /*
  72353. * Licensed to the Apache Software Foundation (ASF) under one
  72354. * or more contributor license agreements. See the NOTICE file
  72355. * distributed with this work for additional information
  72356. * regarding copyright ownership. The ASF licenses this file
  72357. * to you under the Apache License, Version 2.0 (the
  72358. * "License"); you may not use this file except in compliance
  72359. * with the License. You may obtain a copy of the License at
  72360. *
  72361. * http://www.apache.org/licenses/LICENSE-2.0
  72362. *
  72363. * Unless required by applicable law or agreed to in writing,
  72364. * software distributed under the License is distributed on an
  72365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72366. * KIND, either express or implied. See the License for the
  72367. * specific language governing permissions and limitations
  72368. * under the License.
  72369. */
  72370. var STATE_LIST = ['inBrush', 'outOfBrush'];
  72371. var DISPATCH_METHOD = '__ecBrushSelect';
  72372. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  72373. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  72374. /**
  72375. * Layout for visual, the priority higher than other layout, and before brush visual.
  72376. */
  72377. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  72378. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  72379. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  72380. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  72381. );
  72382. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  72383. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  72384. });
  72385. });
  72386. /**
  72387. * Register the visual encoding if this modules required.
  72388. */
  72389. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  72390. var brushSelected = [];
  72391. var throttleType;
  72392. var throttleDelay;
  72393. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  72394. var thisBrushSelected = {
  72395. brushId: brushModel.id,
  72396. brushIndex: brushIndex,
  72397. brushName: brushModel.name,
  72398. areas: clone(brushModel.areas),
  72399. selected: []
  72400. };
  72401. // Every brush component exists in event params, convenient
  72402. // for user to find by index.
  72403. brushSelected.push(thisBrushSelected);
  72404. var brushOption = brushModel.option;
  72405. var brushLink = brushOption.brushLink;
  72406. var linkedSeriesMap = [];
  72407. var selectedDataIndexForLink = [];
  72408. var rangeInfoBySeries = [];
  72409. var hasBrushExists = 0;
  72410. if (!brushIndex) { // Only the first throttle setting works.
  72411. throttleType = brushOption.throttleType;
  72412. throttleDelay = brushOption.throttleDelay;
  72413. }
  72414. // Add boundingRect and selectors to range.
  72415. var areas = map(brushModel.areas, function (area) {
  72416. return bindSelector(
  72417. defaults(
  72418. {boundingRect: boundingRectBuilders[area.brushType](area)},
  72419. area
  72420. )
  72421. );
  72422. });
  72423. var visualMappings = createVisualMappings(
  72424. brushModel.option, STATE_LIST, function (mappingOption) {
  72425. mappingOption.mappingMethod = 'fixed';
  72426. }
  72427. );
  72428. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  72429. linkedSeriesMap[seriesIndex] = 1;
  72430. });
  72431. function linkOthers(seriesIndex) {
  72432. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  72433. }
  72434. // If no supported brush or no brush on the series,
  72435. // all visuals should be in original state.
  72436. function brushed(rangeInfoList) {
  72437. return !!rangeInfoList.length;
  72438. }
  72439. /**
  72440. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  72441. *
  72442. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  72443. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  72444. * └!hasBrushExist┘ └nothing.
  72445. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  72446. * └!hasBrushExist┘ └nothing.
  72447. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  72448. * !brushed┘ └nothing.
  72449. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  72450. */
  72451. // Step A
  72452. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72453. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  72454. seriesModel.subType === 'parallel'
  72455. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  72456. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  72457. });
  72458. function stepAParallel(seriesModel, seriesIndex) {
  72459. var coordSys = seriesModel.coordinateSystem;
  72460. hasBrushExists |= coordSys.hasAxisBrushed();
  72461. linkOthers(seriesIndex) && coordSys.eachActiveState(
  72462. seriesModel.getData(),
  72463. function (activeState, dataIndex) {
  72464. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  72465. }
  72466. );
  72467. }
  72468. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  72469. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  72470. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  72471. return;
  72472. }
  72473. each$1(areas, function (area) {
  72474. selectorsByBrushType[area.brushType]
  72475. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  72476. && rangeInfoList.push(area);
  72477. hasBrushExists |= brushed(rangeInfoList);
  72478. });
  72479. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  72480. var data = seriesModel.getData();
  72481. data.each(function (dataIndex) {
  72482. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  72483. selectedDataIndexForLink[dataIndex] = 1;
  72484. }
  72485. });
  72486. }
  72487. }
  72488. // Step B
  72489. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72490. var seriesBrushSelected = {
  72491. seriesId: seriesModel.id,
  72492. seriesIndex: seriesIndex,
  72493. seriesName: seriesModel.name,
  72494. dataIndex: []
  72495. };
  72496. // Every series exists in event params, convenient
  72497. // for user to find series by seriesIndex.
  72498. thisBrushSelected.selected.push(seriesBrushSelected);
  72499. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  72500. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  72501. var data = seriesModel.getData();
  72502. var getValueState = linkOthers(seriesIndex)
  72503. ? function (dataIndex) {
  72504. return selectedDataIndexForLink[dataIndex]
  72505. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  72506. : 'outOfBrush';
  72507. }
  72508. : function (dataIndex) {
  72509. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  72510. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  72511. : 'outOfBrush';
  72512. };
  72513. // If no supported brush or no brush, all visuals are in original state.
  72514. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  72515. && applyVisual(
  72516. STATE_LIST, visualMappings, data, getValueState
  72517. );
  72518. });
  72519. });
  72520. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  72521. });
  72522. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  72523. // This event will not be triggered when `setOpion`, otherwise dead lock may
  72524. // triggered when do `setOption` in event listener, which we do not find
  72525. // satisfactory way to solve yet. Some considered resolutions:
  72526. // (a) Diff with prevoius selected data ant only trigger event when changed.
  72527. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  72528. // also detect value changes in selected data) might bring complexity or fragility.
  72529. // (b) Use spectial param like `silent` to suppress event triggering.
  72530. // But such kind of volatile param may be weird in `setOption`.
  72531. if (!payload) {
  72532. return;
  72533. }
  72534. var zr = api.getZr();
  72535. if (zr[DISPATCH_FLAG]) {
  72536. return;
  72537. }
  72538. if (!zr[DISPATCH_METHOD]) {
  72539. zr[DISPATCH_METHOD] = doDispatch;
  72540. }
  72541. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  72542. fn(api, brushSelected);
  72543. }
  72544. function doDispatch(api, brushSelected) {
  72545. if (!api.isDisposed()) {
  72546. var zr = api.getZr();
  72547. zr[DISPATCH_FLAG] = true;
  72548. api.dispatchAction({
  72549. type: 'brushSelect',
  72550. batch: brushSelected
  72551. });
  72552. zr[DISPATCH_FLAG] = false;
  72553. }
  72554. }
  72555. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  72556. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  72557. var area = rangeInfoList[i];
  72558. if (selectorsByBrushType[area.brushType](
  72559. dataIndex, data, area.selectors, area
  72560. )) {
  72561. return true;
  72562. }
  72563. }
  72564. }
  72565. function getSelectorsByBrushType(seriesModel) {
  72566. var brushSelector = seriesModel.brushSelector;
  72567. if (isString(brushSelector)) {
  72568. var sels = [];
  72569. each$1(selector, function (selectorsByElementType, brushType) {
  72570. sels[brushType] = function (dataIndex, data, selectors, area) {
  72571. var itemLayout = data.getItemLayout(dataIndex);
  72572. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  72573. };
  72574. });
  72575. return sels;
  72576. }
  72577. else if (isFunction$1(brushSelector)) {
  72578. var bSelector = {};
  72579. each$1(selector, function (sel, brushType) {
  72580. bSelector[brushType] = brushSelector;
  72581. });
  72582. return bSelector;
  72583. }
  72584. return brushSelector;
  72585. }
  72586. function brushModelNotControll(brushModel, seriesIndex) {
  72587. var seriesIndices = brushModel.option.seriesIndex;
  72588. return seriesIndices != null
  72589. && seriesIndices !== 'all'
  72590. && (
  72591. isArray(seriesIndices)
  72592. ? indexOf(seriesIndices, seriesIndex) < 0
  72593. : seriesIndex !== seriesIndices
  72594. );
  72595. }
  72596. function bindSelector(area) {
  72597. var selectors = area.selectors = {};
  72598. each$1(selector[area.brushType], function (selFn, elType) {
  72599. // Do not use function binding or curry for performance.
  72600. selectors[elType] = function (itemLayout) {
  72601. return selFn(itemLayout, selectors, area);
  72602. };
  72603. });
  72604. return area;
  72605. }
  72606. var boundingRectBuilders = {
  72607. lineX: noop,
  72608. lineY: noop,
  72609. rect: function (area) {
  72610. return getBoundingRectFromMinMax(area.range);
  72611. },
  72612. polygon: function (area) {
  72613. var minMax;
  72614. var range = area.range;
  72615. for (var i = 0, len = range.length; i < len; i++) {
  72616. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  72617. var rg = range[i];
  72618. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  72619. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  72620. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  72621. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  72622. }
  72623. return minMax && getBoundingRectFromMinMax(minMax);
  72624. }
  72625. };
  72626. function getBoundingRectFromMinMax(minMax) {
  72627. return new BoundingRect(
  72628. minMax[0][0],
  72629. minMax[1][0],
  72630. minMax[0][1] - minMax[0][0],
  72631. minMax[1][1] - minMax[1][0]
  72632. );
  72633. }
  72634. /*
  72635. * Licensed to the Apache Software Foundation (ASF) under one
  72636. * or more contributor license agreements. See the NOTICE file
  72637. * distributed with this work for additional information
  72638. * regarding copyright ownership. The ASF licenses this file
  72639. * to you under the Apache License, Version 2.0 (the
  72640. * "License"); you may not use this file except in compliance
  72641. * with the License. You may obtain a copy of the License at
  72642. *
  72643. * http://www.apache.org/licenses/LICENSE-2.0
  72644. *
  72645. * Unless required by applicable law or agreed to in writing,
  72646. * software distributed under the License is distributed on an
  72647. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72648. * KIND, either express or implied. See the License for the
  72649. * specific language governing permissions and limitations
  72650. * under the License.
  72651. */
  72652. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  72653. var BrushModel = extendComponentModel({
  72654. type: 'brush',
  72655. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  72656. /**
  72657. * @protected
  72658. */
  72659. defaultOption: {
  72660. // inBrush: null,
  72661. // outOfBrush: null,
  72662. toolbox: null, // Default value see preprocessor.
  72663. brushLink: null, // Series indices array, broadcast using dataIndex.
  72664. // or 'all', which means all series. 'none' or null means no series.
  72665. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  72666. geoIndex: null, //
  72667. xAxisIndex: null,
  72668. yAxisIndex: null,
  72669. brushType: 'rect', // Default brushType, see BrushController.
  72670. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  72671. transformable: true, // Default transformable.
  72672. brushStyle: { // Default brushStyle
  72673. borderWidth: 1,
  72674. color: 'rgba(120,140,180,0.3)',
  72675. borderColor: 'rgba(120,140,180,0.8)'
  72676. },
  72677. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  72678. // If null, no throttle. Valid only in the first brush component
  72679. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  72680. // FIXME
  72681. // 试验效果
  72682. removeOnClick: true,
  72683. z: 10000
  72684. },
  72685. /**
  72686. * @readOnly
  72687. * @type {Array.<Object>}
  72688. */
  72689. areas: [],
  72690. /**
  72691. * Current activated brush type.
  72692. * If null, brush is inactived.
  72693. * see module:echarts/component/helper/BrushController
  72694. * @readOnly
  72695. * @type {string}
  72696. */
  72697. brushType: null,
  72698. /**
  72699. * Current brush opt.
  72700. * see module:echarts/component/helper/BrushController
  72701. * @readOnly
  72702. * @type {Object}
  72703. */
  72704. brushOption: {},
  72705. /**
  72706. * @readOnly
  72707. * @type {Array.<Object>}
  72708. */
  72709. coordInfoList: [],
  72710. optionUpdated: function (newOption, isInit) {
  72711. var thisOption = this.option;
  72712. !isInit && replaceVisualOption(
  72713. thisOption, newOption, ['inBrush', 'outOfBrush']
  72714. );
  72715. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  72716. // Always give default visual, consider setOption at the second time.
  72717. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  72718. if (!inBrush.hasOwnProperty('liftZ')) {
  72719. // Bigger than the highlight z lift, otherwise it will
  72720. // be effected by the highlight z when brush.
  72721. inBrush.liftZ = 5;
  72722. }
  72723. },
  72724. /**
  72725. * If ranges is null/undefined, range state remain.
  72726. *
  72727. * @param {Array.<Object>} [ranges]
  72728. */
  72729. setAreas: function (areas) {
  72730. if (__DEV__) {
  72731. assert$1(isArray(areas));
  72732. each$1(areas, function (area) {
  72733. assert$1(area.brushType, 'Illegal areas');
  72734. });
  72735. }
  72736. // If ranges is null/undefined, range state remain.
  72737. // This helps user to dispatchAction({type: 'brush'}) with no areas
  72738. // set but just want to get the current brush select info from a `brush` event.
  72739. if (!areas) {
  72740. return;
  72741. }
  72742. this.areas = map(areas, function (area) {
  72743. return generateBrushOption(this.option, area);
  72744. }, this);
  72745. },
  72746. /**
  72747. * see module:echarts/component/helper/BrushController
  72748. * @param {Object} brushOption
  72749. */
  72750. setBrushOption: function (brushOption) {
  72751. this.brushOption = generateBrushOption(this.option, brushOption);
  72752. this.brushType = this.brushOption.brushType;
  72753. }
  72754. });
  72755. function generateBrushOption(option, brushOption) {
  72756. return merge(
  72757. {
  72758. brushType: option.brushType,
  72759. brushMode: option.brushMode,
  72760. transformable: option.transformable,
  72761. brushStyle: new Model(option.brushStyle).getItemStyle(),
  72762. removeOnClick: option.removeOnClick,
  72763. z: option.z
  72764. },
  72765. brushOption,
  72766. true
  72767. );
  72768. }
  72769. /*
  72770. * Licensed to the Apache Software Foundation (ASF) under one
  72771. * or more contributor license agreements. See the NOTICE file
  72772. * distributed with this work for additional information
  72773. * regarding copyright ownership. The ASF licenses this file
  72774. * to you under the Apache License, Version 2.0 (the
  72775. * "License"); you may not use this file except in compliance
  72776. * with the License. You may obtain a copy of the License at
  72777. *
  72778. * http://www.apache.org/licenses/LICENSE-2.0
  72779. *
  72780. * Unless required by applicable law or agreed to in writing,
  72781. * software distributed under the License is distributed on an
  72782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72783. * KIND, either express or implied. See the License for the
  72784. * specific language governing permissions and limitations
  72785. * under the License.
  72786. */
  72787. extendComponentView({
  72788. type: 'brush',
  72789. init: function (ecModel, api) {
  72790. /**
  72791. * @readOnly
  72792. * @type {module:echarts/model/Global}
  72793. */
  72794. this.ecModel = ecModel;
  72795. /**
  72796. * @readOnly
  72797. * @type {module:echarts/ExtensionAPI}
  72798. */
  72799. this.api = api;
  72800. /**
  72801. * @readOnly
  72802. * @type {module:echarts/component/brush/BrushModel}
  72803. */
  72804. this.model;
  72805. /**
  72806. * @private
  72807. * @type {module:echarts/component/helper/BrushController}
  72808. */
  72809. (this._brushController = new BrushController(api.getZr()))
  72810. .on('brush', bind(this._onBrush, this))
  72811. .mount();
  72812. },
  72813. /**
  72814. * @override
  72815. */
  72816. render: function (brushModel) {
  72817. this.model = brushModel;
  72818. return updateController.apply(this, arguments);
  72819. },
  72820. /**
  72821. * @override
  72822. */
  72823. updateTransform: updateController,
  72824. /**
  72825. * @override
  72826. */
  72827. updateView: updateController,
  72828. // /**
  72829. // * @override
  72830. // */
  72831. // updateLayout: updateController,
  72832. // /**
  72833. // * @override
  72834. // */
  72835. // updateVisual: updateController,
  72836. /**
  72837. * @override
  72838. */
  72839. dispose: function () {
  72840. this._brushController.dispose();
  72841. },
  72842. /**
  72843. * @private
  72844. */
  72845. _onBrush: function (areas, opt) {
  72846. var modelId = this.model.id;
  72847. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  72848. // Action is not dispatched on drag end, because the drag end
  72849. // emits the same params with the last drag move event, and
  72850. // may have some delay when using touch pad, which makes
  72851. // animation not smooth (when using debounce).
  72852. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  72853. type: 'brush',
  72854. brushId: modelId,
  72855. areas: clone(areas),
  72856. $from: modelId
  72857. });
  72858. opt.isEnd && this.api.dispatchAction({
  72859. type: 'brushEnd',
  72860. brushId: modelId,
  72861. areas: clone(areas),
  72862. $from: modelId
  72863. });
  72864. }
  72865. });
  72866. function updateController(brushModel, ecModel, api, payload) {
  72867. // Do not update controller when drawing.
  72868. (!payload || payload.$from !== brushModel.id) && this._brushController
  72869. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  72870. .enableBrush(brushModel.brushOption)
  72871. .updateCovers(brushModel.areas.slice());
  72872. }
  72873. /*
  72874. * Licensed to the Apache Software Foundation (ASF) under one
  72875. * or more contributor license agreements. See the NOTICE file
  72876. * distributed with this work for additional information
  72877. * regarding copyright ownership. The ASF licenses this file
  72878. * to you under the Apache License, Version 2.0 (the
  72879. * "License"); you may not use this file except in compliance
  72880. * with the License. You may obtain a copy of the License at
  72881. *
  72882. * http://www.apache.org/licenses/LICENSE-2.0
  72883. *
  72884. * Unless required by applicable law or agreed to in writing,
  72885. * software distributed under the License is distributed on an
  72886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72887. * KIND, either express or implied. See the License for the
  72888. * specific language governing permissions and limitations
  72889. * under the License.
  72890. */
  72891. /**
  72892. * payload: {
  72893. * brushIndex: number, or,
  72894. * brushId: string, or,
  72895. * brushName: string,
  72896. * globalRanges: Array
  72897. * }
  72898. */
  72899. registerAction(
  72900. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  72901. function (payload, ecModel) {
  72902. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  72903. brushModel.setAreas(payload.areas);
  72904. });
  72905. }
  72906. );
  72907. /**
  72908. * payload: {
  72909. * brushComponents: [
  72910. * {
  72911. * brushId,
  72912. * brushIndex,
  72913. * brushName,
  72914. * series: [
  72915. * {
  72916. * seriesId,
  72917. * seriesIndex,
  72918. * seriesName,
  72919. * rawIndices: [21, 34, ...]
  72920. * },
  72921. * ...
  72922. * ]
  72923. * },
  72924. * ...
  72925. * ]
  72926. * }
  72927. */
  72928. registerAction(
  72929. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  72930. function () {}
  72931. );
  72932. registerAction(
  72933. {type: 'brushEnd', event: 'brushEnd', update: 'none'},
  72934. function () {}
  72935. );
  72936. /*
  72937. * Licensed to the Apache Software Foundation (ASF) under one
  72938. * or more contributor license agreements. See the NOTICE file
  72939. * distributed with this work for additional information
  72940. * regarding copyright ownership. The ASF licenses this file
  72941. * to you under the Apache License, Version 2.0 (the
  72942. * "License"); you may not use this file except in compliance
  72943. * with the License. You may obtain a copy of the License at
  72944. *
  72945. * http://www.apache.org/licenses/LICENSE-2.0
  72946. *
  72947. * Unless required by applicable law or agreed to in writing,
  72948. * software distributed under the License is distributed on an
  72949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72950. * KIND, either express or implied. See the License for the
  72951. * specific language governing permissions and limitations
  72952. * under the License.
  72953. */
  72954. var brushLang = lang.toolbox.brush;
  72955. function Brush(model, ecModel, api) {
  72956. this.model = model;
  72957. this.ecModel = ecModel;
  72958. this.api = api;
  72959. /**
  72960. * @private
  72961. * @type {string}
  72962. */
  72963. this._brushType;
  72964. /**
  72965. * @private
  72966. * @type {string}
  72967. */
  72968. this._brushMode;
  72969. }
  72970. Brush.defaultOption = {
  72971. show: true,
  72972. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  72973. icon: {
  72974. /* eslint-disable */
  72975. 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
  72976. 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
  72977. 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
  72978. 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
  72979. 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
  72980. 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
  72981. /* eslint-enable */
  72982. },
  72983. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  72984. title: clone(brushLang.title)
  72985. };
  72986. var proto$7 = Brush.prototype;
  72987. // proto.updateLayout = function (featureModel, ecModel, api) {
  72988. /* eslint-disable */
  72989. proto$7.render =
  72990. /* eslint-enable */
  72991. proto$7.updateView = function (featureModel, ecModel, api) {
  72992. var brushType;
  72993. var brushMode;
  72994. var isBrushed;
  72995. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  72996. brushType = brushModel.brushType;
  72997. brushMode = brushModel.brushOption.brushMode || 'single';
  72998. isBrushed |= brushModel.areas.length;
  72999. });
  73000. this._brushType = brushType;
  73001. this._brushMode = brushMode;
  73002. each$1(featureModel.get('type', true), function (type) {
  73003. featureModel.setIconStatus(
  73004. type,
  73005. (
  73006. type === 'keep'
  73007. ? brushMode === 'multiple'
  73008. : type === 'clear'
  73009. ? isBrushed
  73010. : type === brushType
  73011. ) ? 'emphasis' : 'normal'
  73012. );
  73013. });
  73014. };
  73015. proto$7.getIcons = function () {
  73016. var model = this.model;
  73017. var availableIcons = model.get('icon', true);
  73018. var icons = {};
  73019. each$1(model.get('type', true), function (type) {
  73020. if (availableIcons[type]) {
  73021. icons[type] = availableIcons[type];
  73022. }
  73023. });
  73024. return icons;
  73025. };
  73026. proto$7.onclick = function (ecModel, api, type) {
  73027. var brushType = this._brushType;
  73028. var brushMode = this._brushMode;
  73029. if (type === 'clear') {
  73030. // Trigger parallel action firstly
  73031. api.dispatchAction({
  73032. type: 'axisAreaSelect',
  73033. intervals: []
  73034. });
  73035. api.dispatchAction({
  73036. type: 'brush',
  73037. command: 'clear',
  73038. // Clear all areas of all brush components.
  73039. areas: []
  73040. });
  73041. }
  73042. else {
  73043. api.dispatchAction({
  73044. type: 'takeGlobalCursor',
  73045. key: 'brush',
  73046. brushOption: {
  73047. brushType: type === 'keep'
  73048. ? brushType
  73049. : (brushType === type ? false : type),
  73050. brushMode: type === 'keep'
  73051. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  73052. : brushMode
  73053. }
  73054. });
  73055. }
  73056. };
  73057. register$1('brush', Brush);
  73058. /*
  73059. * Licensed to the Apache Software Foundation (ASF) under one
  73060. * or more contributor license agreements. See the NOTICE file
  73061. * distributed with this work for additional information
  73062. * regarding copyright ownership. The ASF licenses this file
  73063. * to you under the Apache License, Version 2.0 (the
  73064. * "License"); you may not use this file except in compliance
  73065. * with the License. You may obtain a copy of the License at
  73066. *
  73067. * http://www.apache.org/licenses/LICENSE-2.0
  73068. *
  73069. * Unless required by applicable law or agreed to in writing,
  73070. * software distributed under the License is distributed on an
  73071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73072. * KIND, either express or implied. See the License for the
  73073. * specific language governing permissions and limitations
  73074. * under the License.
  73075. */
  73076. /**
  73077. * Brush component entry
  73078. */
  73079. registerPreprocessor(preprocessor$1);
  73080. /*
  73081. * Licensed to the Apache Software Foundation (ASF) under one
  73082. * or more contributor license agreements. See the NOTICE file
  73083. * distributed with this work for additional information
  73084. * regarding copyright ownership. The ASF licenses this file
  73085. * to you under the Apache License, Version 2.0 (the
  73086. * "License"); you may not use this file except in compliance
  73087. * with the License. You may obtain a copy of the License at
  73088. *
  73089. * http://www.apache.org/licenses/LICENSE-2.0
  73090. *
  73091. * Unless required by applicable law or agreed to in writing,
  73092. * software distributed under the License is distributed on an
  73093. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73094. * KIND, either express or implied. See the License for the
  73095. * specific language governing permissions and limitations
  73096. * under the License.
  73097. */
  73098. // Model
  73099. extendComponentModel({
  73100. type: 'title',
  73101. layoutMode: {type: 'box', ignoreSize: true},
  73102. defaultOption: {
  73103. // 一级层叠
  73104. zlevel: 0,
  73105. // 二级层叠
  73106. z: 6,
  73107. show: true,
  73108. text: '',
  73109. // 超链接跳转
  73110. // link: null,
  73111. // 仅支持self | blank
  73112. target: 'blank',
  73113. subtext: '',
  73114. // 超链接跳转
  73115. // sublink: null,
  73116. // 仅支持self | blank
  73117. subtarget: 'blank',
  73118. // 'center' ¦ 'left' ¦ 'right'
  73119. // ¦ {number}(x坐标,单位px)
  73120. left: 0,
  73121. // 'top' ¦ 'bottom' ¦ 'center'
  73122. // ¦ {number}(y坐标,单位px)
  73123. top: 0,
  73124. // 水平对齐
  73125. // 'auto' | 'left' | 'right' | 'center'
  73126. // 默认根据 left 的位置判断是左对齐还是右对齐
  73127. // textAlign: null
  73128. //
  73129. // 垂直对齐
  73130. // 'auto' | 'top' | 'bottom' | 'middle'
  73131. // 默认根据 top 位置判断是上对齐还是下对齐
  73132. // textVerticalAlign: null
  73133. // textBaseline: null // The same as textVerticalAlign.
  73134. backgroundColor: 'rgba(0,0,0,0)',
  73135. // 标题边框颜色
  73136. borderColor: '#ccc',
  73137. // 标题边框线宽,单位px,默认为0(无边框)
  73138. borderWidth: 0,
  73139. // 标题内边距,单位px,默认各方向内边距为5,
  73140. // 接受数组分别设定上右下左边距,同css
  73141. padding: 5,
  73142. // 主副标题纵向间隔,单位px,默认为10,
  73143. itemGap: 10,
  73144. textStyle: {
  73145. fontSize: 18,
  73146. fontWeight: 'bolder',
  73147. color: '#333'
  73148. },
  73149. subtextStyle: {
  73150. color: '#aaa'
  73151. }
  73152. }
  73153. });
  73154. // View
  73155. extendComponentView({
  73156. type: 'title',
  73157. render: function (titleModel, ecModel, api) {
  73158. this.group.removeAll();
  73159. if (!titleModel.get('show')) {
  73160. return;
  73161. }
  73162. var group = this.group;
  73163. var textStyleModel = titleModel.getModel('textStyle');
  73164. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73165. var textAlign = titleModel.get('textAlign');
  73166. var textVerticalAlign = retrieve2(
  73167. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  73168. );
  73169. var textEl = new Text({
  73170. style: setTextStyle({}, textStyleModel, {
  73171. text: titleModel.get('text'),
  73172. textFill: textStyleModel.getTextColor()
  73173. }, {disableBox: true}),
  73174. z2: 10
  73175. });
  73176. var textRect = textEl.getBoundingRect();
  73177. var subText = titleModel.get('subtext');
  73178. var subTextEl = new Text({
  73179. style: setTextStyle({}, subtextStyleModel, {
  73180. text: subText,
  73181. textFill: subtextStyleModel.getTextColor(),
  73182. y: textRect.height + titleModel.get('itemGap'),
  73183. textVerticalAlign: 'top'
  73184. }, {disableBox: true}),
  73185. z2: 10
  73186. });
  73187. var link = titleModel.get('link');
  73188. var sublink = titleModel.get('sublink');
  73189. var triggerEvent = titleModel.get('triggerEvent', true);
  73190. textEl.silent = !link && !triggerEvent;
  73191. subTextEl.silent = !sublink && !triggerEvent;
  73192. if (link) {
  73193. textEl.on('click', function () {
  73194. window.open(link, '_' + titleModel.get('target'));
  73195. });
  73196. }
  73197. if (sublink) {
  73198. subTextEl.on('click', function () {
  73199. window.open(sublink, '_' + titleModel.get('subtarget'));
  73200. });
  73201. }
  73202. textEl.eventData = subTextEl.eventData = triggerEvent
  73203. ? {
  73204. componentType: 'title',
  73205. componentIndex: titleModel.componentIndex
  73206. }
  73207. : null;
  73208. group.add(textEl);
  73209. subText && group.add(subTextEl);
  73210. // If no subText, but add subTextEl, there will be an empty line.
  73211. var groupRect = group.getBoundingRect();
  73212. var layoutOption = titleModel.getBoxLayoutParams();
  73213. layoutOption.width = groupRect.width;
  73214. layoutOption.height = groupRect.height;
  73215. var layoutRect = getLayoutRect(
  73216. layoutOption, {
  73217. width: api.getWidth(),
  73218. height: api.getHeight()
  73219. }, titleModel.get('padding')
  73220. );
  73221. // Adjust text align based on position
  73222. if (!textAlign) {
  73223. // Align left if title is on the left. center and right is same
  73224. textAlign = titleModel.get('left') || titleModel.get('right');
  73225. if (textAlign === 'middle') {
  73226. textAlign = 'center';
  73227. }
  73228. // Adjust layout by text align
  73229. if (textAlign === 'right') {
  73230. layoutRect.x += layoutRect.width;
  73231. }
  73232. else if (textAlign === 'center') {
  73233. layoutRect.x += layoutRect.width / 2;
  73234. }
  73235. }
  73236. if (!textVerticalAlign) {
  73237. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  73238. if (textVerticalAlign === 'center') {
  73239. textVerticalAlign = 'middle';
  73240. }
  73241. if (textVerticalAlign === 'bottom') {
  73242. layoutRect.y += layoutRect.height;
  73243. }
  73244. else if (textVerticalAlign === 'middle') {
  73245. layoutRect.y += layoutRect.height / 2;
  73246. }
  73247. textVerticalAlign = textVerticalAlign || 'top';
  73248. }
  73249. group.attr('position', [layoutRect.x, layoutRect.y]);
  73250. var alignStyle = {
  73251. textAlign: textAlign,
  73252. textVerticalAlign: textVerticalAlign
  73253. };
  73254. textEl.setStyle(alignStyle);
  73255. subTextEl.setStyle(alignStyle);
  73256. // Render background
  73257. // Get groupRect again because textAlign has been changed
  73258. groupRect = group.getBoundingRect();
  73259. var padding = layoutRect.margin;
  73260. var style = titleModel.getItemStyle(['color', 'opacity']);
  73261. style.fill = titleModel.get('backgroundColor');
  73262. var rect = new Rect({
  73263. shape: {
  73264. x: groupRect.x - padding[3],
  73265. y: groupRect.y - padding[0],
  73266. width: groupRect.width + padding[1] + padding[3],
  73267. height: groupRect.height + padding[0] + padding[2],
  73268. r: titleModel.get('borderRadius')
  73269. },
  73270. style: style,
  73271. subPixelOptimize: true,
  73272. silent: true
  73273. });
  73274. group.add(rect);
  73275. }
  73276. });
  73277. /*
  73278. * Licensed to the Apache Software Foundation (ASF) under one
  73279. * or more contributor license agreements. See the NOTICE file
  73280. * distributed with this work for additional information
  73281. * regarding copyright ownership. The ASF licenses this file
  73282. * to you under the Apache License, Version 2.0 (the
  73283. * "License"); you may not use this file except in compliance
  73284. * with the License. You may obtain a copy of the License at
  73285. *
  73286. * http://www.apache.org/licenses/LICENSE-2.0
  73287. *
  73288. * Unless required by applicable law or agreed to in writing,
  73289. * software distributed under the License is distributed on an
  73290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73291. * KIND, either express or implied. See the License for the
  73292. * specific language governing permissions and limitations
  73293. * under the License.
  73294. */
  73295. var preprocessor$2 = function (option) {
  73296. var timelineOpt = option && option.timeline;
  73297. if (!isArray(timelineOpt)) {
  73298. timelineOpt = timelineOpt ? [timelineOpt] : [];
  73299. }
  73300. each$1(timelineOpt, function (opt) {
  73301. if (!opt) {
  73302. return;
  73303. }
  73304. compatibleEC2(opt);
  73305. });
  73306. };
  73307. function compatibleEC2(opt) {
  73308. var type = opt.type;
  73309. var ec2Types = {'number': 'value', 'time': 'time'};
  73310. // Compatible with ec2
  73311. if (ec2Types[type]) {
  73312. opt.axisType = ec2Types[type];
  73313. delete opt.type;
  73314. }
  73315. transferItem(opt);
  73316. if (has$1(opt, 'controlPosition')) {
  73317. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  73318. if (!has$1(controlStyle, 'position')) {
  73319. controlStyle.position = opt.controlPosition;
  73320. }
  73321. if (controlStyle.position === 'none' && !has$1(controlStyle, 'show')) {
  73322. controlStyle.show = false;
  73323. delete controlStyle.position;
  73324. }
  73325. delete opt.controlPosition;
  73326. }
  73327. each$1(opt.data || [], function (dataItem) {
  73328. if (isObject$1(dataItem) && !isArray(dataItem)) {
  73329. if (!has$1(dataItem, 'value') && has$1(dataItem, 'name')) {
  73330. // In ec2, using name as value.
  73331. dataItem.value = dataItem.name;
  73332. }
  73333. transferItem(dataItem);
  73334. }
  73335. });
  73336. }
  73337. function transferItem(opt) {
  73338. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  73339. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  73340. // Transfer label out
  73341. var label = opt.label || (opt.label || {});
  73342. var labelNormal = label.normal || (label.normal = {});
  73343. var excludeLabelAttr = {normal: 1, emphasis: 1};
  73344. each$1(label, function (value, name) {
  73345. if (!excludeLabelAttr[name] && !has$1(labelNormal, name)) {
  73346. labelNormal[name] = value;
  73347. }
  73348. });
  73349. if (itemStyleEmphasis.label && !has$1(label, 'emphasis')) {
  73350. label.emphasis = itemStyleEmphasis.label;
  73351. delete itemStyleEmphasis.label;
  73352. }
  73353. }
  73354. function has$1(obj, attr) {
  73355. return obj.hasOwnProperty(attr);
  73356. }
  73357. /*
  73358. * Licensed to the Apache Software Foundation (ASF) under one
  73359. * or more contributor license agreements. See the NOTICE file
  73360. * distributed with this work for additional information
  73361. * regarding copyright ownership. The ASF licenses this file
  73362. * to you under the Apache License, Version 2.0 (the
  73363. * "License"); you may not use this file except in compliance
  73364. * with the License. You may obtain a copy of the License at
  73365. *
  73366. * http://www.apache.org/licenses/LICENSE-2.0
  73367. *
  73368. * Unless required by applicable law or agreed to in writing,
  73369. * software distributed under the License is distributed on an
  73370. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73371. * KIND, either express or implied. See the License for the
  73372. * specific language governing permissions and limitations
  73373. * under the License.
  73374. */
  73375. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  73376. // Only slider now.
  73377. return 'slider';
  73378. });
  73379. /*
  73380. * Licensed to the Apache Software Foundation (ASF) under one
  73381. * or more contributor license agreements. See the NOTICE file
  73382. * distributed with this work for additional information
  73383. * regarding copyright ownership. The ASF licenses this file
  73384. * to you under the Apache License, Version 2.0 (the
  73385. * "License"); you may not use this file except in compliance
  73386. * with the License. You may obtain a copy of the License at
  73387. *
  73388. * http://www.apache.org/licenses/LICENSE-2.0
  73389. *
  73390. * Unless required by applicable law or agreed to in writing,
  73391. * software distributed under the License is distributed on an
  73392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73393. * KIND, either express or implied. See the License for the
  73394. * specific language governing permissions and limitations
  73395. * under the License.
  73396. */
  73397. registerAction(
  73398. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  73399. function (payload, ecModel) {
  73400. var timelineModel = ecModel.getComponent('timeline');
  73401. if (timelineModel && payload.currentIndex != null) {
  73402. timelineModel.setCurrentIndex(payload.currentIndex);
  73403. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  73404. timelineModel.setPlayState(false);
  73405. }
  73406. }
  73407. // Set normalized currentIndex to payload.
  73408. ecModel.resetOption('timeline');
  73409. return defaults({
  73410. currentIndex: timelineModel.option.currentIndex
  73411. }, payload);
  73412. }
  73413. );
  73414. registerAction(
  73415. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  73416. function (payload, ecModel) {
  73417. var timelineModel = ecModel.getComponent('timeline');
  73418. if (timelineModel && payload.playState != null) {
  73419. timelineModel.setPlayState(payload.playState);
  73420. }
  73421. }
  73422. );
  73423. /*
  73424. * Licensed to the Apache Software Foundation (ASF) under one
  73425. * or more contributor license agreements. See the NOTICE file
  73426. * distributed with this work for additional information
  73427. * regarding copyright ownership. The ASF licenses this file
  73428. * to you under the Apache License, Version 2.0 (the
  73429. * "License"); you may not use this file except in compliance
  73430. * with the License. You may obtain a copy of the License at
  73431. *
  73432. * http://www.apache.org/licenses/LICENSE-2.0
  73433. *
  73434. * Unless required by applicable law or agreed to in writing,
  73435. * software distributed under the License is distributed on an
  73436. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73437. * KIND, either express or implied. See the License for the
  73438. * specific language governing permissions and limitations
  73439. * under the License.
  73440. */
  73441. var TimelineModel = ComponentModel.extend({
  73442. type: 'timeline',
  73443. layoutMode: 'box',
  73444. /**
  73445. * @protected
  73446. */
  73447. defaultOption: {
  73448. zlevel: 0, // 一级层叠
  73449. z: 4, // 二级层叠
  73450. show: true,
  73451. axisType: 'time', // 模式是时间类型,支持 value, category
  73452. realtime: true,
  73453. left: '20%',
  73454. top: null,
  73455. right: '20%',
  73456. bottom: 0,
  73457. width: null,
  73458. height: 40,
  73459. padding: 5,
  73460. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  73461. autoPlay: false,
  73462. rewind: false, // 反向播放
  73463. loop: true,
  73464. playInterval: 2000, // 播放时间间隔,单位ms
  73465. currentIndex: 0,
  73466. itemStyle: {},
  73467. label: {
  73468. color: '#000'
  73469. },
  73470. data: []
  73471. },
  73472. /**
  73473. * @override
  73474. */
  73475. init: function (option, parentModel, ecModel) {
  73476. /**
  73477. * @private
  73478. * @type {module:echarts/data/List}
  73479. */
  73480. this._data;
  73481. /**
  73482. * @private
  73483. * @type {Array.<string>}
  73484. */
  73485. this._names;
  73486. this.mergeDefaultAndTheme(option, ecModel);
  73487. this._initData();
  73488. },
  73489. /**
  73490. * @override
  73491. */
  73492. mergeOption: function (option) {
  73493. TimelineModel.superApply(this, 'mergeOption', arguments);
  73494. this._initData();
  73495. },
  73496. /**
  73497. * @param {number} [currentIndex]
  73498. */
  73499. setCurrentIndex: function (currentIndex) {
  73500. if (currentIndex == null) {
  73501. currentIndex = this.option.currentIndex;
  73502. }
  73503. var count = this._data.count();
  73504. if (this.option.loop) {
  73505. currentIndex = (currentIndex % count + count) % count;
  73506. }
  73507. else {
  73508. currentIndex >= count && (currentIndex = count - 1);
  73509. currentIndex < 0 && (currentIndex = 0);
  73510. }
  73511. this.option.currentIndex = currentIndex;
  73512. },
  73513. /**
  73514. * @return {number} currentIndex
  73515. */
  73516. getCurrentIndex: function () {
  73517. return this.option.currentIndex;
  73518. },
  73519. /**
  73520. * @return {boolean}
  73521. */
  73522. isIndexMax: function () {
  73523. return this.getCurrentIndex() >= this._data.count() - 1;
  73524. },
  73525. /**
  73526. * @param {boolean} state true: play, false: stop
  73527. */
  73528. setPlayState: function (state) {
  73529. this.option.autoPlay = !!state;
  73530. },
  73531. /**
  73532. * @return {boolean} true: play, false: stop
  73533. */
  73534. getPlayState: function () {
  73535. return !!this.option.autoPlay;
  73536. },
  73537. /**
  73538. * @private
  73539. */
  73540. _initData: function () {
  73541. var thisOption = this.option;
  73542. var dataArr = thisOption.data || [];
  73543. var axisType = thisOption.axisType;
  73544. var names = this._names = [];
  73545. if (axisType === 'category') {
  73546. var idxArr = [];
  73547. each$1(dataArr, function (item, index) {
  73548. var value = getDataItemValue(item);
  73549. var newItem;
  73550. if (isObject$1(item)) {
  73551. newItem = clone(item);
  73552. newItem.value = index;
  73553. }
  73554. else {
  73555. newItem = index;
  73556. }
  73557. idxArr.push(newItem);
  73558. if (!isString(value) && (value == null || isNaN(value))) {
  73559. value = '';
  73560. }
  73561. names.push(value + '');
  73562. });
  73563. dataArr = idxArr;
  73564. }
  73565. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  73566. var data = this._data = new List([{name: 'value', type: dimType}], this);
  73567. data.initData(dataArr, names);
  73568. },
  73569. getData: function () {
  73570. return this._data;
  73571. },
  73572. /**
  73573. * @public
  73574. * @return {Array.<string>} categoreis
  73575. */
  73576. getCategories: function () {
  73577. if (this.get('axisType') === 'category') {
  73578. return this._names.slice();
  73579. }
  73580. }
  73581. });
  73582. /*
  73583. * Licensed to the Apache Software Foundation (ASF) under one
  73584. * or more contributor license agreements. See the NOTICE file
  73585. * distributed with this work for additional information
  73586. * regarding copyright ownership. The ASF licenses this file
  73587. * to you under the Apache License, Version 2.0 (the
  73588. * "License"); you may not use this file except in compliance
  73589. * with the License. You may obtain a copy of the License at
  73590. *
  73591. * http://www.apache.org/licenses/LICENSE-2.0
  73592. *
  73593. * Unless required by applicable law or agreed to in writing,
  73594. * software distributed under the License is distributed on an
  73595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73596. * KIND, either express or implied. See the License for the
  73597. * specific language governing permissions and limitations
  73598. * under the License.
  73599. */
  73600. var SliderTimelineModel = TimelineModel.extend({
  73601. type: 'timeline.slider',
  73602. /**
  73603. * @protected
  73604. */
  73605. defaultOption: {
  73606. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  73607. borderColor: '#ccc', // 时间轴边框颜色
  73608. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  73609. orient: 'horizontal', // 'vertical'
  73610. inverse: false,
  73611. tooltip: { // boolean or Object
  73612. trigger: 'item' // data item may also have tootip attr.
  73613. },
  73614. symbol: 'emptyCircle',
  73615. symbolSize: 10,
  73616. lineStyle: {
  73617. show: true,
  73618. width: 2,
  73619. color: '#304654'
  73620. },
  73621. label: { // 文本标签
  73622. position: 'auto', // auto left right top bottom
  73623. // When using number, label position is not
  73624. // restricted by viewRect.
  73625. // positive: right/bottom, negative: left/top
  73626. show: true,
  73627. interval: 'auto',
  73628. rotate: 0,
  73629. // formatter: null,
  73630. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73631. color: '#304654'
  73632. },
  73633. itemStyle: {
  73634. color: '#304654',
  73635. borderWidth: 1
  73636. },
  73637. checkpointStyle: {
  73638. symbol: 'circle',
  73639. symbolSize: 13,
  73640. color: '#c23531',
  73641. borderWidth: 5,
  73642. borderColor: 'rgba(194,53,49, 0.5)',
  73643. animation: true,
  73644. animationDuration: 300,
  73645. animationEasing: 'quinticInOut'
  73646. },
  73647. controlStyle: {
  73648. show: true,
  73649. showPlayBtn: true,
  73650. showPrevBtn: true,
  73651. showNextBtn: true,
  73652. itemSize: 22,
  73653. itemGap: 12,
  73654. position: 'left', // 'left' 'right' 'top' 'bottom'
  73655. 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
  73656. 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
  73657. 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
  73658. 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
  73659. color: '#304654',
  73660. borderColor: '#304654',
  73661. borderWidth: 1
  73662. },
  73663. emphasis: {
  73664. label: {
  73665. show: true,
  73666. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73667. color: '#c23531'
  73668. },
  73669. itemStyle: {
  73670. color: '#c23531'
  73671. },
  73672. controlStyle: {
  73673. color: '#c23531',
  73674. borderColor: '#c23531',
  73675. borderWidth: 2
  73676. }
  73677. },
  73678. data: []
  73679. }
  73680. });
  73681. mixin(SliderTimelineModel, dataFormatMixin);
  73682. /*
  73683. * Licensed to the Apache Software Foundation (ASF) under one
  73684. * or more contributor license agreements. See the NOTICE file
  73685. * distributed with this work for additional information
  73686. * regarding copyright ownership. The ASF licenses this file
  73687. * to you under the Apache License, Version 2.0 (the
  73688. * "License"); you may not use this file except in compliance
  73689. * with the License. You may obtain a copy of the License at
  73690. *
  73691. * http://www.apache.org/licenses/LICENSE-2.0
  73692. *
  73693. * Unless required by applicable law or agreed to in writing,
  73694. * software distributed under the License is distributed on an
  73695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73696. * KIND, either express or implied. See the License for the
  73697. * specific language governing permissions and limitations
  73698. * under the License.
  73699. */
  73700. var TimelineView = Component$1.extend({
  73701. type: 'timeline'
  73702. });
  73703. /*
  73704. * Licensed to the Apache Software Foundation (ASF) under one
  73705. * or more contributor license agreements. See the NOTICE file
  73706. * distributed with this work for additional information
  73707. * regarding copyright ownership. The ASF licenses this file
  73708. * to you under the Apache License, Version 2.0 (the
  73709. * "License"); you may not use this file except in compliance
  73710. * with the License. You may obtain a copy of the License at
  73711. *
  73712. * http://www.apache.org/licenses/LICENSE-2.0
  73713. *
  73714. * Unless required by applicable law or agreed to in writing,
  73715. * software distributed under the License is distributed on an
  73716. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73717. * KIND, either express or implied. See the License for the
  73718. * specific language governing permissions and limitations
  73719. * under the License.
  73720. */
  73721. /**
  73722. * Extend axis 2d
  73723. * @constructor module:echarts/coord/cartesian/Axis2D
  73724. * @extends {module:echarts/coord/cartesian/Axis}
  73725. * @param {string} dim
  73726. * @param {*} scale
  73727. * @param {Array.<number>} coordExtent
  73728. * @param {string} axisType
  73729. * @param {string} position
  73730. */
  73731. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  73732. Axis.call(this, dim, scale, coordExtent);
  73733. /**
  73734. * Axis type
  73735. * - 'category'
  73736. * - 'value'
  73737. * - 'time'
  73738. * - 'log'
  73739. * @type {string}
  73740. */
  73741. this.type = axisType || 'value';
  73742. /**
  73743. * Axis model
  73744. * @param {module:echarts/component/TimelineModel}
  73745. */
  73746. this.model = null;
  73747. };
  73748. TimelineAxis.prototype = {
  73749. constructor: TimelineAxis,
  73750. /**
  73751. * @override
  73752. */
  73753. getLabelModel: function () {
  73754. return this.model.getModel('label');
  73755. },
  73756. /**
  73757. * @override
  73758. */
  73759. isHorizontal: function () {
  73760. return this.model.get('orient') === 'horizontal';
  73761. }
  73762. };
  73763. inherits(TimelineAxis, Axis);
  73764. /*
  73765. * Licensed to the Apache Software Foundation (ASF) under one
  73766. * or more contributor license agreements. See the NOTICE file
  73767. * distributed with this work for additional information
  73768. * regarding copyright ownership. The ASF licenses this file
  73769. * to you under the Apache License, Version 2.0 (the
  73770. * "License"); you may not use this file except in compliance
  73771. * with the License. You may obtain a copy of the License at
  73772. *
  73773. * http://www.apache.org/licenses/LICENSE-2.0
  73774. *
  73775. * Unless required by applicable law or agreed to in writing,
  73776. * software distributed under the License is distributed on an
  73777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73778. * KIND, either express or implied. See the License for the
  73779. * specific language governing permissions and limitations
  73780. * under the License.
  73781. */
  73782. var bind$4 = bind;
  73783. var each$24 = each$1;
  73784. var PI$5 = Math.PI;
  73785. TimelineView.extend({
  73786. type: 'timeline.slider',
  73787. init: function (ecModel, api) {
  73788. this.api = api;
  73789. /**
  73790. * @private
  73791. * @type {module:echarts/component/timeline/TimelineAxis}
  73792. */
  73793. this._axis;
  73794. /**
  73795. * @private
  73796. * @type {module:zrender/core/BoundingRect}
  73797. */
  73798. this._viewRect;
  73799. /**
  73800. * @type {number}
  73801. */
  73802. this._timer;
  73803. /**
  73804. * @type {module:zrender/Element}
  73805. */
  73806. this._currentPointer;
  73807. /**
  73808. * @type {module:zrender/container/Group}
  73809. */
  73810. this._mainGroup;
  73811. /**
  73812. * @type {module:zrender/container/Group}
  73813. */
  73814. this._labelGroup;
  73815. },
  73816. /**
  73817. * @override
  73818. */
  73819. render: function (timelineModel, ecModel, api, payload) {
  73820. this.model = timelineModel;
  73821. this.api = api;
  73822. this.ecModel = ecModel;
  73823. this.group.removeAll();
  73824. if (timelineModel.get('show', true)) {
  73825. var layoutInfo = this._layout(timelineModel, api);
  73826. var mainGroup = this._createGroup('mainGroup');
  73827. var labelGroup = this._createGroup('labelGroup');
  73828. /**
  73829. * @private
  73830. * @type {module:echarts/component/timeline/TimelineAxis}
  73831. */
  73832. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  73833. timelineModel.formatTooltip = function (dataIndex) {
  73834. return encodeHTML(axis.scale.getLabel(dataIndex));
  73835. };
  73836. each$24(
  73837. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  73838. function (name) {
  73839. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  73840. },
  73841. this
  73842. );
  73843. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  73844. this._position(layoutInfo, timelineModel);
  73845. }
  73846. this._doPlayStop();
  73847. },
  73848. /**
  73849. * @override
  73850. */
  73851. remove: function () {
  73852. this._clearTimer();
  73853. this.group.removeAll();
  73854. },
  73855. /**
  73856. * @override
  73857. */
  73858. dispose: function () {
  73859. this._clearTimer();
  73860. },
  73861. _layout: function (timelineModel, api) {
  73862. var labelPosOpt = timelineModel.get('label.position');
  73863. var orient = timelineModel.get('orient');
  73864. var viewRect = getViewRect$5(timelineModel, api);
  73865. // Auto label offset.
  73866. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73867. labelPosOpt = orient === 'horizontal'
  73868. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  73869. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  73870. }
  73871. else if (isNaN(labelPosOpt)) {
  73872. labelPosOpt = ({
  73873. horizontal: {top: '-', bottom: '+'},
  73874. vertical: {left: '-', right: '+'}
  73875. })[orient][labelPosOpt];
  73876. }
  73877. var labelAlignMap = {
  73878. horizontal: 'center',
  73879. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  73880. };
  73881. var labelBaselineMap = {
  73882. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  73883. vertical: 'middle'
  73884. };
  73885. var rotationMap = {
  73886. horizontal: 0,
  73887. vertical: PI$5 / 2
  73888. };
  73889. // Position
  73890. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73891. var controlModel = timelineModel.getModel('controlStyle');
  73892. var showControl = controlModel.get('show', true);
  73893. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73894. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73895. var sizePlusGap = controlSize + controlGap;
  73896. // Special label rotate.
  73897. var labelRotation = timelineModel.get('label.rotate') || 0;
  73898. labelRotation = labelRotation * PI$5 / 180; // To radian.
  73899. var playPosition;
  73900. var prevBtnPosition;
  73901. var nextBtnPosition;
  73902. var axisExtent;
  73903. var controlPosition = controlModel.get('position', true);
  73904. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73905. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73906. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73907. var xLeft = 0;
  73908. var xRight = mainLength;
  73909. // position[0] means left, position[1] means middle.
  73910. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73911. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73912. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73913. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73914. }
  73915. else { // 'top' 'right'
  73916. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73917. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73918. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73919. }
  73920. axisExtent = [xLeft, xRight];
  73921. if (timelineModel.get('inverse')) {
  73922. axisExtent.reverse();
  73923. }
  73924. return {
  73925. viewRect: viewRect,
  73926. mainLength: mainLength,
  73927. orient: orient,
  73928. rotation: rotationMap[orient],
  73929. labelRotation: labelRotation,
  73930. labelPosOpt: labelPosOpt,
  73931. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  73932. labelBaseline: timelineModel.get('label.verticalAlign')
  73933. || timelineModel.get('label.baseline')
  73934. || labelBaselineMap[orient],
  73935. // Based on mainGroup.
  73936. playPosition: playPosition,
  73937. prevBtnPosition: prevBtnPosition,
  73938. nextBtnPosition: nextBtnPosition,
  73939. axisExtent: axisExtent,
  73940. controlSize: controlSize,
  73941. controlGap: controlGap
  73942. };
  73943. },
  73944. _position: function (layoutInfo, timelineModel) {
  73945. // Position is be called finally, because bounding rect is needed for
  73946. // adapt content to fill viewRect (auto adapt offset).
  73947. // Timeline may be not all in the viewRect when 'offset' is specified
  73948. // as a number, because it is more appropriate that label aligns at
  73949. // 'offset' but not the other edge defined by viewRect.
  73950. var mainGroup = this._mainGroup;
  73951. var labelGroup = this._labelGroup;
  73952. var viewRect = layoutInfo.viewRect;
  73953. if (layoutInfo.orient === 'vertical') {
  73954. // transform to horizontal, inverse rotate by left-top point.
  73955. var m = create$1();
  73956. var rotateOriginX = viewRect.x;
  73957. var rotateOriginY = viewRect.y + viewRect.height;
  73958. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73959. rotate(m, m, -PI$5 / 2);
  73960. translate(m, m, [rotateOriginX, rotateOriginY]);
  73961. viewRect = viewRect.clone();
  73962. viewRect.applyTransform(m);
  73963. }
  73964. var viewBound = getBound(viewRect);
  73965. var mainBound = getBound(mainGroup.getBoundingRect());
  73966. var labelBound = getBound(labelGroup.getBoundingRect());
  73967. var mainPosition = mainGroup.position;
  73968. var labelsPosition = labelGroup.position;
  73969. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73970. var labelPosOpt = layoutInfo.labelPosOpt;
  73971. if (isNaN(labelPosOpt)) { // '+' or '-'
  73972. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73973. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73974. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73975. }
  73976. else {
  73977. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73978. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73979. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73980. }
  73981. mainGroup.attr('position', mainPosition);
  73982. labelGroup.attr('position', labelsPosition);
  73983. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73984. setOrigin(mainGroup);
  73985. setOrigin(labelGroup);
  73986. function setOrigin(targetGroup) {
  73987. var pos = targetGroup.position;
  73988. targetGroup.origin = [
  73989. viewBound[0][0] - pos[0],
  73990. viewBound[1][0] - pos[1]
  73991. ];
  73992. }
  73993. function getBound(rect) {
  73994. // [[xmin, xmax], [ymin, ymax]]
  73995. return [
  73996. [rect.x, rect.x + rect.width],
  73997. [rect.y, rect.y + rect.height]
  73998. ];
  73999. }
  74000. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  74001. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  74002. }
  74003. },
  74004. _createAxis: function (layoutInfo, timelineModel) {
  74005. var data = timelineModel.getData();
  74006. var axisType = timelineModel.get('axisType');
  74007. var scale = createScaleByModel(timelineModel, axisType);
  74008. // Customize scale. The `tickValue` is `dataIndex`.
  74009. scale.getTicks = function () {
  74010. return data.mapArray(['value'], function (value) {
  74011. return value;
  74012. });
  74013. };
  74014. var dataExtent = data.getDataExtent('value');
  74015. scale.setExtent(dataExtent[0], dataExtent[1]);
  74016. scale.niceTicks();
  74017. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  74018. axis.model = timelineModel;
  74019. return axis;
  74020. },
  74021. _createGroup: function (name) {
  74022. var newGroup = this['_' + name] = new Group();
  74023. this.group.add(newGroup);
  74024. return newGroup;
  74025. },
  74026. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  74027. var axisExtent = axis.getExtent();
  74028. if (!timelineModel.get('lineStyle.show')) {
  74029. return;
  74030. }
  74031. group.add(new Line({
  74032. shape: {
  74033. x1: axisExtent[0], y1: 0,
  74034. x2: axisExtent[1], y2: 0
  74035. },
  74036. style: extend(
  74037. {lineCap: 'round'},
  74038. timelineModel.getModel('lineStyle').getLineStyle()
  74039. ),
  74040. silent: true,
  74041. z2: 1
  74042. }));
  74043. },
  74044. /**
  74045. * @private
  74046. */
  74047. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  74048. var data = timelineModel.getData();
  74049. // Show all ticks, despite ignoring strategy.
  74050. var ticks = axis.scale.getTicks();
  74051. // The value is dataIndex, see the costomized scale.
  74052. each$24(ticks, function (value) {
  74053. var tickCoord = axis.dataToCoord(value);
  74054. var itemModel = data.getItemModel(value);
  74055. var itemStyleModel = itemModel.getModel('itemStyle');
  74056. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  74057. var symbolOpt = {
  74058. position: [tickCoord, 0],
  74059. onclick: bind$4(this._changeTimeline, this, value)
  74060. };
  74061. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74062. setHoverStyle(el, hoverStyleModel.getItemStyle());
  74063. if (itemModel.get('tooltip')) {
  74064. el.dataIndex = value;
  74065. el.dataModel = timelineModel;
  74066. }
  74067. else {
  74068. el.dataIndex = el.dataModel = null;
  74069. }
  74070. }, this);
  74071. },
  74072. /**
  74073. * @private
  74074. */
  74075. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  74076. var labelModel = axis.getLabelModel();
  74077. if (!labelModel.get('show')) {
  74078. return;
  74079. }
  74080. var data = timelineModel.getData();
  74081. var labels = axis.getViewLabels();
  74082. each$24(labels, function (labelItem) {
  74083. // The tickValue is dataIndex, see the costomized scale.
  74084. var dataIndex = labelItem.tickValue;
  74085. var itemModel = data.getItemModel(dataIndex);
  74086. var normalLabelModel = itemModel.getModel('label');
  74087. var hoverLabelModel = itemModel.getModel('emphasis.label');
  74088. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74089. var textEl = new Text({
  74090. position: [tickCoord, 0],
  74091. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74092. onclick: bind$4(this._changeTimeline, this, dataIndex),
  74093. silent: false
  74094. });
  74095. setTextStyle(textEl.style, normalLabelModel, {
  74096. text: labelItem.formattedLabel,
  74097. textAlign: layoutInfo.labelAlign,
  74098. textVerticalAlign: layoutInfo.labelBaseline
  74099. });
  74100. group.add(textEl);
  74101. setHoverStyle(
  74102. textEl, setTextStyle({}, hoverLabelModel)
  74103. );
  74104. }, this);
  74105. },
  74106. /**
  74107. * @private
  74108. */
  74109. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  74110. var controlSize = layoutInfo.controlSize;
  74111. var rotation = layoutInfo.rotation;
  74112. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74113. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  74114. var rect = [0, -controlSize / 2, controlSize, controlSize];
  74115. var playState = timelineModel.getPlayState();
  74116. var inverse = timelineModel.get('inverse', true);
  74117. makeBtn(
  74118. layoutInfo.nextBtnPosition,
  74119. 'controlStyle.nextIcon',
  74120. bind$4(this._changeTimeline, this, inverse ? '-' : '+')
  74121. );
  74122. makeBtn(
  74123. layoutInfo.prevBtnPosition,
  74124. 'controlStyle.prevIcon',
  74125. bind$4(this._changeTimeline, this, inverse ? '+' : '-')
  74126. );
  74127. makeBtn(
  74128. layoutInfo.playPosition,
  74129. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  74130. bind$4(this._handlePlayClick, this, !playState),
  74131. true
  74132. );
  74133. function makeBtn(position, iconPath, onclick, willRotate) {
  74134. if (!position) {
  74135. return;
  74136. }
  74137. var opt = {
  74138. position: position,
  74139. origin: [controlSize / 2, 0],
  74140. rotation: willRotate ? -rotation : 0,
  74141. rectHover: true,
  74142. style: itemStyle,
  74143. onclick: onclick
  74144. };
  74145. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  74146. group.add(btn);
  74147. setHoverStyle(btn, hoverStyle);
  74148. }
  74149. },
  74150. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  74151. var data = timelineModel.getData();
  74152. var currentIndex = timelineModel.getCurrentIndex();
  74153. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74154. var me = this;
  74155. var callback = {
  74156. onCreate: function (pointer) {
  74157. pointer.draggable = true;
  74158. pointer.drift = bind$4(me._handlePointerDrag, me);
  74159. pointer.ondragend = bind$4(me._handlePointerDragend, me);
  74160. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  74161. },
  74162. onUpdate: function (pointer) {
  74163. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  74164. }
  74165. };
  74166. // Reuse when exists, for animation and drag.
  74167. this._currentPointer = giveSymbol(
  74168. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  74169. );
  74170. },
  74171. _handlePlayClick: function (nextState) {
  74172. this._clearTimer();
  74173. this.api.dispatchAction({
  74174. type: 'timelinePlayChange',
  74175. playState: nextState,
  74176. from: this.uid
  74177. });
  74178. },
  74179. _handlePointerDrag: function (dx, dy, e) {
  74180. this._clearTimer();
  74181. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74182. },
  74183. _handlePointerDragend: function (e) {
  74184. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74185. },
  74186. _pointerChangeTimeline: function (mousePos, trigger) {
  74187. var toCoord = this._toAxisCoord(mousePos)[0];
  74188. var axis = this._axis;
  74189. var axisExtent = asc(axis.getExtent().slice());
  74190. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74191. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74192. this._currentPointer.position[0] = toCoord;
  74193. this._currentPointer.dirty();
  74194. var targetDataIndex = this._findNearestTick(toCoord);
  74195. var timelineModel = this.model;
  74196. if (trigger || (
  74197. targetDataIndex !== timelineModel.getCurrentIndex()
  74198. && timelineModel.get('realtime')
  74199. )) {
  74200. this._changeTimeline(targetDataIndex);
  74201. }
  74202. },
  74203. _doPlayStop: function () {
  74204. this._clearTimer();
  74205. if (this.model.getPlayState()) {
  74206. this._timer = setTimeout(
  74207. bind$4(handleFrame, this),
  74208. this.model.get('playInterval')
  74209. );
  74210. }
  74211. function handleFrame() {
  74212. // Do not cache
  74213. var timelineModel = this.model;
  74214. this._changeTimeline(
  74215. timelineModel.getCurrentIndex()
  74216. + (timelineModel.get('rewind', true) ? -1 : 1)
  74217. );
  74218. }
  74219. },
  74220. _toAxisCoord: function (vertex) {
  74221. var trans = this._mainGroup.getLocalTransform();
  74222. return applyTransform$1(vertex, trans, true);
  74223. },
  74224. _findNearestTick: function (axisCoord) {
  74225. var data = this.model.getData();
  74226. var dist = Infinity;
  74227. var targetDataIndex;
  74228. var axis = this._axis;
  74229. data.each(['value'], function (value, dataIndex) {
  74230. var coord = axis.dataToCoord(value);
  74231. var d = Math.abs(coord - axisCoord);
  74232. if (d < dist) {
  74233. dist = d;
  74234. targetDataIndex = dataIndex;
  74235. }
  74236. });
  74237. return targetDataIndex;
  74238. },
  74239. _clearTimer: function () {
  74240. if (this._timer) {
  74241. clearTimeout(this._timer);
  74242. this._timer = null;
  74243. }
  74244. },
  74245. _changeTimeline: function (nextIndex) {
  74246. var currentIndex = this.model.getCurrentIndex();
  74247. if (nextIndex === '+') {
  74248. nextIndex = currentIndex + 1;
  74249. }
  74250. else if (nextIndex === '-') {
  74251. nextIndex = currentIndex - 1;
  74252. }
  74253. this.api.dispatchAction({
  74254. type: 'timelineChange',
  74255. currentIndex: nextIndex,
  74256. from: this.uid
  74257. });
  74258. }
  74259. });
  74260. function getViewRect$5(model, api) {
  74261. return getLayoutRect(
  74262. model.getBoxLayoutParams(),
  74263. {
  74264. width: api.getWidth(),
  74265. height: api.getHeight()
  74266. },
  74267. model.get('padding')
  74268. );
  74269. }
  74270. function makeIcon(timelineModel, objPath, rect, opts) {
  74271. var icon = makePath(
  74272. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  74273. clone(opts || {}),
  74274. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  74275. 'center'
  74276. );
  74277. return icon;
  74278. }
  74279. /**
  74280. * Create symbol or update symbol
  74281. * opt: basic position and event handlers
  74282. */
  74283. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  74284. var color = itemStyleModel.get('color');
  74285. if (!symbol) {
  74286. var symbolType = hostModel.get('symbol');
  74287. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  74288. symbol.setStyle('strokeNoScale', true);
  74289. group.add(symbol);
  74290. callback && callback.onCreate(symbol);
  74291. }
  74292. else {
  74293. symbol.setColor(color);
  74294. group.add(symbol); // Group may be new, also need to add.
  74295. callback && callback.onUpdate(symbol);
  74296. }
  74297. // Style
  74298. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  74299. symbol.setStyle(itemStyle);
  74300. // Transform and events.
  74301. opt = merge({
  74302. rectHover: true,
  74303. z2: 100
  74304. }, opt, true);
  74305. var symbolSize = hostModel.get('symbolSize');
  74306. symbolSize = symbolSize instanceof Array
  74307. ? symbolSize.slice()
  74308. : [+symbolSize, +symbolSize];
  74309. symbolSize[0] /= 2;
  74310. symbolSize[1] /= 2;
  74311. opt.scale = symbolSize;
  74312. var symbolOffset = hostModel.get('symbolOffset');
  74313. if (symbolOffset) {
  74314. var pos = opt.position = opt.position || [0, 0];
  74315. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  74316. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  74317. }
  74318. var symbolRotate = hostModel.get('symbolRotate');
  74319. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  74320. symbol.attr(opt);
  74321. // FIXME
  74322. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  74323. // getBoundingRect will return wrong result.
  74324. // (This is supposed to be resolved in zrender, but it is a little difficult to
  74325. // leverage performance and auto updateTransform)
  74326. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  74327. symbol.updateTransform();
  74328. return symbol;
  74329. }
  74330. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  74331. if (pointer.dragging) {
  74332. return;
  74333. }
  74334. var pointerModel = timelineModel.getModel('checkpointStyle');
  74335. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  74336. if (noAnimation || !pointerModel.get('animation', true)) {
  74337. pointer.attr({position: [toCoord, 0]});
  74338. }
  74339. else {
  74340. pointer.stopAnimation(true);
  74341. pointer.animateTo(
  74342. {position: [toCoord, 0]},
  74343. pointerModel.get('animationDuration', true),
  74344. pointerModel.get('animationEasing', true)
  74345. );
  74346. }
  74347. }
  74348. /*
  74349. * Licensed to the Apache Software Foundation (ASF) under one
  74350. * or more contributor license agreements. See the NOTICE file
  74351. * distributed with this work for additional information
  74352. * regarding copyright ownership. The ASF licenses this file
  74353. * to you under the Apache License, Version 2.0 (the
  74354. * "License"); you may not use this file except in compliance
  74355. * with the License. You may obtain a copy of the License at
  74356. *
  74357. * http://www.apache.org/licenses/LICENSE-2.0
  74358. *
  74359. * Unless required by applicable law or agreed to in writing,
  74360. * software distributed under the License is distributed on an
  74361. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74362. * KIND, either express or implied. See the License for the
  74363. * specific language governing permissions and limitations
  74364. * under the License.
  74365. */
  74366. /**
  74367. * DataZoom component entry
  74368. */
  74369. registerPreprocessor(preprocessor$2);
  74370. /*
  74371. * Licensed to the Apache Software Foundation (ASF) under one
  74372. * or more contributor license agreements. See the NOTICE file
  74373. * distributed with this work for additional information
  74374. * regarding copyright ownership. The ASF licenses this file
  74375. * to you under the Apache License, Version 2.0 (the
  74376. * "License"); you may not use this file except in compliance
  74377. * with the License. You may obtain a copy of the License at
  74378. *
  74379. * http://www.apache.org/licenses/LICENSE-2.0
  74380. *
  74381. * Unless required by applicable law or agreed to in writing,
  74382. * software distributed under the License is distributed on an
  74383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74384. * KIND, either express or implied. See the License for the
  74385. * specific language governing permissions and limitations
  74386. * under the License.
  74387. */
  74388. var addCommas$1 = addCommas;
  74389. var encodeHTML$1 = encodeHTML;
  74390. function fillLabel(opt) {
  74391. defaultEmphasis(opt, 'label', ['show']);
  74392. }
  74393. var MarkerModel = extendComponentModel({
  74394. type: 'marker',
  74395. dependencies: ['series', 'grid', 'polar', 'geo'],
  74396. /**
  74397. * @overrite
  74398. */
  74399. init: function (option, parentModel, ecModel) {
  74400. if (__DEV__) {
  74401. if (this.type === 'marker') {
  74402. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74403. }
  74404. }
  74405. this.mergeDefaultAndTheme(option, ecModel);
  74406. this._mergeOption(option, ecModel, false, true);
  74407. },
  74408. /**
  74409. * @return {boolean}
  74410. */
  74411. isAnimationEnabled: function () {
  74412. if (env$1.node) {
  74413. return false;
  74414. }
  74415. var hostSeries = this.__hostSeries;
  74416. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74417. },
  74418. /**
  74419. * @overrite
  74420. */
  74421. mergeOption: function (newOpt, ecModel) {
  74422. this._mergeOption(newOpt, ecModel, false, false);
  74423. },
  74424. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  74425. var MarkerModel = this.constructor;
  74426. var modelPropName = this.mainType + 'Model';
  74427. if (!createdBySelf) {
  74428. ecModel.eachSeries(function (seriesModel) {
  74429. var markerOpt = seriesModel.get(this.mainType, true);
  74430. var markerModel = seriesModel[modelPropName];
  74431. if (!markerOpt || !markerOpt.data) {
  74432. seriesModel[modelPropName] = null;
  74433. return;
  74434. }
  74435. if (!markerModel) {
  74436. if (isInit) {
  74437. // Default label emphasis `position` and `show`
  74438. fillLabel(markerOpt);
  74439. }
  74440. each$1(markerOpt.data, function (item) {
  74441. // FIXME Overwrite fillLabel method ?
  74442. if (item instanceof Array) {
  74443. fillLabel(item[0]);
  74444. fillLabel(item[1]);
  74445. }
  74446. else {
  74447. fillLabel(item);
  74448. }
  74449. });
  74450. markerModel = new MarkerModel(
  74451. markerOpt, this, ecModel
  74452. );
  74453. extend(markerModel, {
  74454. mainType: this.mainType,
  74455. // Use the same series index and name
  74456. seriesIndex: seriesModel.seriesIndex,
  74457. name: seriesModel.name,
  74458. createdBySelf: true
  74459. });
  74460. markerModel.__hostSeries = seriesModel;
  74461. }
  74462. else {
  74463. markerModel._mergeOption(markerOpt, ecModel, true);
  74464. }
  74465. seriesModel[modelPropName] = markerModel;
  74466. }, this);
  74467. }
  74468. },
  74469. formatTooltip: function (dataIndex) {
  74470. var data = this.getData();
  74471. var value = this.getRawValue(dataIndex);
  74472. var formattedValue = isArray(value)
  74473. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  74474. var name = data.getName(dataIndex);
  74475. var html = encodeHTML$1(this.name);
  74476. if (value != null || name) {
  74477. html += '<br />';
  74478. }
  74479. if (name) {
  74480. html += encodeHTML$1(name);
  74481. if (value != null) {
  74482. html += ' : ';
  74483. }
  74484. }
  74485. if (value != null) {
  74486. html += encodeHTML$1(formattedValue);
  74487. }
  74488. return html;
  74489. },
  74490. getData: function () {
  74491. return this._data;
  74492. },
  74493. setData: function (data) {
  74494. this._data = data;
  74495. }
  74496. });
  74497. mixin(MarkerModel, dataFormatMixin);
  74498. /*
  74499. * Licensed to the Apache Software Foundation (ASF) under one
  74500. * or more contributor license agreements. See the NOTICE file
  74501. * distributed with this work for additional information
  74502. * regarding copyright ownership. The ASF licenses this file
  74503. * to you under the Apache License, Version 2.0 (the
  74504. * "License"); you may not use this file except in compliance
  74505. * with the License. You may obtain a copy of the License at
  74506. *
  74507. * http://www.apache.org/licenses/LICENSE-2.0
  74508. *
  74509. * Unless required by applicable law or agreed to in writing,
  74510. * software distributed under the License is distributed on an
  74511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74512. * KIND, either express or implied. See the License for the
  74513. * specific language governing permissions and limitations
  74514. * under the License.
  74515. */
  74516. MarkerModel.extend({
  74517. type: 'markPoint',
  74518. defaultOption: {
  74519. zlevel: 0,
  74520. z: 5,
  74521. symbol: 'pin',
  74522. symbolSize: 50,
  74523. //symbolRotate: 0,
  74524. //symbolOffset: [0, 0]
  74525. tooltip: {
  74526. trigger: 'item'
  74527. },
  74528. label: {
  74529. show: true,
  74530. position: 'inside'
  74531. },
  74532. itemStyle: {
  74533. borderWidth: 2
  74534. },
  74535. emphasis: {
  74536. label: {
  74537. show: true
  74538. }
  74539. }
  74540. }
  74541. });
  74542. /*
  74543. * Licensed to the Apache Software Foundation (ASF) under one
  74544. * or more contributor license agreements. See the NOTICE file
  74545. * distributed with this work for additional information
  74546. * regarding copyright ownership. The ASF licenses this file
  74547. * to you under the Apache License, Version 2.0 (the
  74548. * "License"); you may not use this file except in compliance
  74549. * with the License. You may obtain a copy of the License at
  74550. *
  74551. * http://www.apache.org/licenses/LICENSE-2.0
  74552. *
  74553. * Unless required by applicable law or agreed to in writing,
  74554. * software distributed under the License is distributed on an
  74555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74556. * KIND, either express or implied. See the License for the
  74557. * specific language governing permissions and limitations
  74558. * under the License.
  74559. */
  74560. var indexOf$2 = indexOf;
  74561. function hasXOrY(item) {
  74562. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74563. }
  74564. function hasXAndY(item) {
  74565. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74566. }
  74567. // Make it simple, do not visit all stacked value to count precision.
  74568. // function getPrecision(data, valueAxisDim, dataIndex) {
  74569. // var precision = -1;
  74570. // var stackedDim = data.mapDimension(valueAxisDim);
  74571. // do {
  74572. // precision = Math.max(
  74573. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  74574. // precision
  74575. // );
  74576. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  74577. // if (stackedOnSeries) {
  74578. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  74579. // data = stackedOnSeries.getData();
  74580. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  74581. // stackedDim = data.getCalculationInfo('stackedDimension');
  74582. // }
  74583. // else {
  74584. // data = null;
  74585. // }
  74586. // } while (data);
  74587. // return precision;
  74588. // }
  74589. function markerTypeCalculatorWithExtent(
  74590. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  74591. ) {
  74592. var coordArr = [];
  74593. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  74594. var calcDataDim = stacked
  74595. ? data.getCalculationInfo('stackResultDimension')
  74596. : targetDataDim;
  74597. var value = numCalculate(data, calcDataDim, mlType);
  74598. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74599. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74600. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  74601. // Make it simple, do not visit all stacked value to count precision.
  74602. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74603. precision = Math.min(precision, 20);
  74604. if (precision >= 0) {
  74605. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74606. }
  74607. return coordArr;
  74608. }
  74609. var curry$5 = curry;
  74610. // TODO Specified percent
  74611. var markerTypeCalculator = {
  74612. /**
  74613. * @method
  74614. * @param {module:echarts/data/List} data
  74615. * @param {string} baseAxisDim
  74616. * @param {string} valueAxisDim
  74617. */
  74618. min: curry$5(markerTypeCalculatorWithExtent, 'min'),
  74619. /**
  74620. * @method
  74621. * @param {module:echarts/data/List} data
  74622. * @param {string} baseAxisDim
  74623. * @param {string} valueAxisDim
  74624. */
  74625. max: curry$5(markerTypeCalculatorWithExtent, 'max'),
  74626. /**
  74627. * @method
  74628. * @param {module:echarts/data/List} data
  74629. * @param {string} baseAxisDim
  74630. * @param {string} valueAxisDim
  74631. */
  74632. average: curry$5(markerTypeCalculatorWithExtent, 'average')
  74633. };
  74634. /**
  74635. * Transform markPoint data item to format used in List by do the following
  74636. * 1. Calculate statistic like `max`, `min`, `average`
  74637. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74638. * @param {module:echarts/model/Series} seriesModel
  74639. * @param {module:echarts/coord/*} [coordSys]
  74640. * @param {Object} item
  74641. * @return {Object}
  74642. */
  74643. function dataTransform(seriesModel, item) {
  74644. var data = seriesModel.getData();
  74645. var coordSys = seriesModel.coordinateSystem;
  74646. // 1. If not specify the position with pixel directly
  74647. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74648. // `yAxis` to specify the coord on each dimension
  74649. // parseFloat first because item.x and item.y can be percent string like '20%'
  74650. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  74651. var dims = coordSys.dimensions;
  74652. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74653. // Clone the option
  74654. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74655. item = clone(item);
  74656. if (item.type
  74657. && markerTypeCalculator[item.type]
  74658. && axisInfo.baseAxis && axisInfo.valueAxis
  74659. ) {
  74660. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  74661. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  74662. item.coord = markerTypeCalculator[item.type](
  74663. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  74664. otherCoordIndex, targetCoordIndex
  74665. );
  74666. // Force to use the value of calculated value.
  74667. item.value = item.coord[targetCoordIndex];
  74668. }
  74669. else {
  74670. // FIXME Only has one of xAxis and yAxis.
  74671. var coord = [
  74672. item.xAxis != null ? item.xAxis : item.radiusAxis,
  74673. item.yAxis != null ? item.yAxis : item.angleAxis
  74674. ];
  74675. // Each coord support max, min, average
  74676. for (var i = 0; i < 2; i++) {
  74677. if (markerTypeCalculator[coord[i]]) {
  74678. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74679. }
  74680. }
  74681. item.coord = coord;
  74682. }
  74683. }
  74684. return item;
  74685. }
  74686. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74687. var ret = {};
  74688. if (item.valueIndex != null || item.valueDim != null) {
  74689. ret.valueDataDim = item.valueIndex != null
  74690. ? data.getDimension(item.valueIndex) : item.valueDim;
  74691. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74692. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74693. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74694. }
  74695. else {
  74696. ret.baseAxis = seriesModel.getBaseAxis();
  74697. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74698. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74699. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74700. }
  74701. return ret;
  74702. }
  74703. function dataDimToCoordDim(seriesModel, dataDim) {
  74704. var data = seriesModel.getData();
  74705. var dimensions = data.dimensions;
  74706. dataDim = data.getDimension(dataDim);
  74707. for (var i = 0; i < dimensions.length; i++) {
  74708. var dimItem = data.getDimensionInfo(dimensions[i]);
  74709. if (dimItem.name === dataDim) {
  74710. return dimItem.coordDim;
  74711. }
  74712. }
  74713. }
  74714. /**
  74715. * Filter data which is out of coordinateSystem range
  74716. * [dataFilter description]
  74717. * @param {module:echarts/coord/*} [coordSys]
  74718. * @param {Object} item
  74719. * @return {boolean}
  74720. */
  74721. function dataFilter$1(coordSys, item) {
  74722. // Alwalys return true if there is no coordSys
  74723. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  74724. ? coordSys.containData(item.coord) : true;
  74725. }
  74726. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  74727. // x, y, radius, angle
  74728. if (dimIndex < 2) {
  74729. return item.coord && item.coord[dimIndex];
  74730. }
  74731. return item.value;
  74732. }
  74733. function numCalculate(data, valueDataDim, type) {
  74734. if (type === 'average') {
  74735. var sum = 0;
  74736. var count = 0;
  74737. data.each(valueDataDim, function (val, idx) {
  74738. if (!isNaN(val)) {
  74739. sum += val;
  74740. count++;
  74741. }
  74742. });
  74743. return sum / count;
  74744. }
  74745. else if (type === 'median') {
  74746. return data.getMedian(valueDataDim);
  74747. }
  74748. else {
  74749. // max & min
  74750. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  74751. }
  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. var MarkerView = extendComponentView({
  74772. type: 'marker',
  74773. init: function () {
  74774. /**
  74775. * Markline grouped by series
  74776. * @private
  74777. * @type {module:zrender/core/util.HashMap}
  74778. */
  74779. this.markerGroupMap = createHashMap();
  74780. },
  74781. render: function (markerModel, ecModel, api) {
  74782. var markerGroupMap = this.markerGroupMap;
  74783. markerGroupMap.each(function (item) {
  74784. item.__keep = false;
  74785. });
  74786. var markerModelKey = this.type + 'Model';
  74787. ecModel.eachSeries(function (seriesModel) {
  74788. var markerModel = seriesModel[markerModelKey];
  74789. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  74790. }, this);
  74791. markerGroupMap.each(function (item) {
  74792. !item.__keep && this.group.remove(item.group);
  74793. }, this);
  74794. },
  74795. renderSeries: function () {}
  74796. });
  74797. /*
  74798. * Licensed to the Apache Software Foundation (ASF) under one
  74799. * or more contributor license agreements. See the NOTICE file
  74800. * distributed with this work for additional information
  74801. * regarding copyright ownership. The ASF licenses this file
  74802. * to you under the Apache License, Version 2.0 (the
  74803. * "License"); you may not use this file except in compliance
  74804. * with the License. You may obtain a copy of the License at
  74805. *
  74806. * http://www.apache.org/licenses/LICENSE-2.0
  74807. *
  74808. * Unless required by applicable law or agreed to in writing,
  74809. * software distributed under the License is distributed on an
  74810. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74811. * KIND, either express or implied. See the License for the
  74812. * specific language governing permissions and limitations
  74813. * under the License.
  74814. */
  74815. function updateMarkerLayout(mpData, seriesModel, api) {
  74816. var coordSys = seriesModel.coordinateSystem;
  74817. mpData.each(function (idx) {
  74818. var itemModel = mpData.getItemModel(idx);
  74819. var point;
  74820. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74821. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74822. if (!isNaN(xPx) && !isNaN(yPx)) {
  74823. point = [xPx, yPx];
  74824. }
  74825. // Chart like bar may have there own marker positioning logic
  74826. else if (seriesModel.getMarkerPosition) {
  74827. // Use the getMarkerPoisition
  74828. point = seriesModel.getMarkerPosition(
  74829. mpData.getValues(mpData.dimensions, idx)
  74830. );
  74831. }
  74832. else if (coordSys) {
  74833. var x = mpData.get(coordSys.dimensions[0], idx);
  74834. var y = mpData.get(coordSys.dimensions[1], idx);
  74835. point = coordSys.dataToPoint([x, y]);
  74836. }
  74837. // Use x, y if has any
  74838. if (!isNaN(xPx)) {
  74839. point[0] = xPx;
  74840. }
  74841. if (!isNaN(yPx)) {
  74842. point[1] = yPx;
  74843. }
  74844. mpData.setItemLayout(idx, point);
  74845. });
  74846. }
  74847. MarkerView.extend({
  74848. type: 'markPoint',
  74849. // updateLayout: function (markPointModel, ecModel, api) {
  74850. // ecModel.eachSeries(function (seriesModel) {
  74851. // var mpModel = seriesModel.markPointModel;
  74852. // if (mpModel) {
  74853. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74854. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74855. // }
  74856. // }, this);
  74857. // },
  74858. updateTransform: function (markPointModel, ecModel, api) {
  74859. ecModel.eachSeries(function (seriesModel) {
  74860. var mpModel = seriesModel.markPointModel;
  74861. if (mpModel) {
  74862. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74863. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74864. }
  74865. }, this);
  74866. },
  74867. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  74868. var coordSys = seriesModel.coordinateSystem;
  74869. var seriesId = seriesModel.id;
  74870. var seriesData = seriesModel.getData();
  74871. var symbolDrawMap = this.markerGroupMap;
  74872. var symbolDraw = symbolDrawMap.get(seriesId)
  74873. || symbolDrawMap.set(seriesId, new SymbolDraw());
  74874. var mpData = createList$1(coordSys, seriesModel, mpModel);
  74875. // FIXME
  74876. mpModel.setData(mpData);
  74877. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74878. mpData.each(function (idx) {
  74879. var itemModel = mpData.getItemModel(idx);
  74880. var symbol = itemModel.getShallow('symbol');
  74881. var symbolSize = itemModel.getShallow('symbolSize');
  74882. var isFnSymbol = isFunction$1(symbol);
  74883. var isFnSymbolSize = isFunction$1(symbolSize);
  74884. if (isFnSymbol || isFnSymbolSize) {
  74885. var rawIdx = mpModel.getRawValue(idx);
  74886. var dataParams = mpModel.getDataParams(idx);
  74887. if (isFnSymbol) {
  74888. symbol = symbol(rawIdx, dataParams);
  74889. }
  74890. if (isFnSymbolSize) {
  74891. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74892. symbolSize = symbolSize(rawIdx, dataParams);
  74893. }
  74894. }
  74895. mpData.setItemVisual(idx, {
  74896. symbol: symbol,
  74897. symbolSize: symbolSize,
  74898. color: itemModel.get('itemStyle.color')
  74899. || seriesData.getVisual('color')
  74900. });
  74901. });
  74902. // TODO Text are wrong
  74903. symbolDraw.updateData(mpData);
  74904. this.group.add(symbolDraw.group);
  74905. // Set host model for tooltip
  74906. // FIXME
  74907. mpData.eachItemGraphicEl(function (el) {
  74908. el.traverse(function (child) {
  74909. child.dataModel = mpModel;
  74910. });
  74911. });
  74912. symbolDraw.__keep = true;
  74913. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74914. }
  74915. });
  74916. /**
  74917. * @inner
  74918. * @param {module:echarts/coord/*} [coordSys]
  74919. * @param {module:echarts/model/Series} seriesModel
  74920. * @param {module:echarts/model/Model} mpModel
  74921. */
  74922. function createList$1(coordSys, seriesModel, mpModel) {
  74923. var coordDimsInfos;
  74924. if (coordSys) {
  74925. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74926. var info = seriesModel.getData().getDimensionInfo(
  74927. seriesModel.getData().mapDimension(coordDim)
  74928. ) || {};
  74929. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74930. return defaults({name: coordDim}, info);
  74931. });
  74932. }
  74933. else {
  74934. coordDimsInfos = [{
  74935. name: 'value',
  74936. type: 'float'
  74937. }];
  74938. }
  74939. var mpData = new List(coordDimsInfos, mpModel);
  74940. var dataOpt = map(mpModel.get('data'), curry(
  74941. dataTransform, seriesModel
  74942. ));
  74943. if (coordSys) {
  74944. dataOpt = filter(
  74945. dataOpt, curry(dataFilter$1, coordSys)
  74946. );
  74947. }
  74948. mpData.initData(dataOpt, null,
  74949. coordSys ? dimValueGetter : function (item) {
  74950. return item.value;
  74951. }
  74952. );
  74953. return mpData;
  74954. }
  74955. /*
  74956. * Licensed to the Apache Software Foundation (ASF) under one
  74957. * or more contributor license agreements. See the NOTICE file
  74958. * distributed with this work for additional information
  74959. * regarding copyright ownership. The ASF licenses this file
  74960. * to you under the Apache License, Version 2.0 (the
  74961. * "License"); you may not use this file except in compliance
  74962. * with the License. You may obtain a copy of the License at
  74963. *
  74964. * http://www.apache.org/licenses/LICENSE-2.0
  74965. *
  74966. * Unless required by applicable law or agreed to in writing,
  74967. * software distributed under the License is distributed on an
  74968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74969. * KIND, either express or implied. See the License for the
  74970. * specific language governing permissions and limitations
  74971. * under the License.
  74972. */
  74973. // HINT Markpoint can't be used too much
  74974. registerPreprocessor(function (opt) {
  74975. // Make sure markPoint component is enabled
  74976. opt.markPoint = opt.markPoint || {};
  74977. });
  74978. /*
  74979. * Licensed to the Apache Software Foundation (ASF) under one
  74980. * or more contributor license agreements. See the NOTICE file
  74981. * distributed with this work for additional information
  74982. * regarding copyright ownership. The ASF licenses this file
  74983. * to you under the Apache License, Version 2.0 (the
  74984. * "License"); you may not use this file except in compliance
  74985. * with the License. You may obtain a copy of the License at
  74986. *
  74987. * http://www.apache.org/licenses/LICENSE-2.0
  74988. *
  74989. * Unless required by applicable law or agreed to in writing,
  74990. * software distributed under the License is distributed on an
  74991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74992. * KIND, either express or implied. See the License for the
  74993. * specific language governing permissions and limitations
  74994. * under the License.
  74995. */
  74996. MarkerModel.extend({
  74997. type: 'markLine',
  74998. defaultOption: {
  74999. zlevel: 0,
  75000. z: 5,
  75001. symbol: ['circle', 'arrow'],
  75002. symbolSize: [8, 16],
  75003. //symbolRotate: 0,
  75004. precision: 2,
  75005. tooltip: {
  75006. trigger: 'item'
  75007. },
  75008. label: {
  75009. show: true,
  75010. position: 'end'
  75011. },
  75012. lineStyle: {
  75013. type: 'dashed'
  75014. },
  75015. emphasis: {
  75016. label: {
  75017. show: true
  75018. },
  75019. lineStyle: {
  75020. width: 3
  75021. }
  75022. },
  75023. animationEasing: 'linear'
  75024. }
  75025. });
  75026. /*
  75027. * Licensed to the Apache Software Foundation (ASF) under one
  75028. * or more contributor license agreements. See the NOTICE file
  75029. * distributed with this work for additional information
  75030. * regarding copyright ownership. The ASF licenses this file
  75031. * to you under the Apache License, Version 2.0 (the
  75032. * "License"); you may not use this file except in compliance
  75033. * with the License. You may obtain a copy of the License at
  75034. *
  75035. * http://www.apache.org/licenses/LICENSE-2.0
  75036. *
  75037. * Unless required by applicable law or agreed to in writing,
  75038. * software distributed under the License is distributed on an
  75039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75040. * KIND, either express or implied. See the License for the
  75041. * specific language governing permissions and limitations
  75042. * under the License.
  75043. */
  75044. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75045. var data = seriesModel.getData();
  75046. // Special type markLine like 'min', 'max', 'average', 'median'
  75047. var mlType = item.type;
  75048. if (!isArray(item)
  75049. && (
  75050. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  75051. // In case
  75052. // data: [{
  75053. // yAxis: 10
  75054. // }]
  75055. || (item.xAxis != null || item.yAxis != null)
  75056. )
  75057. ) {
  75058. var valueAxis;
  75059. var value;
  75060. if (item.yAxis != null || item.xAxis != null) {
  75061. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75062. value = retrieve(item.yAxis, item.xAxis);
  75063. }
  75064. else {
  75065. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75066. valueAxis = axisInfo.valueAxis;
  75067. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75068. value = numCalculate(data, valueDataDim, mlType);
  75069. }
  75070. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75071. var baseIndex = 1 - valueIndex;
  75072. var mlFrom = clone(item);
  75073. var mlTo = {};
  75074. mlFrom.type = null;
  75075. mlFrom.coord = [];
  75076. mlTo.coord = [];
  75077. mlFrom.coord[baseIndex] = -Infinity;
  75078. mlTo.coord[baseIndex] = Infinity;
  75079. var precision = mlModel.get('precision');
  75080. if (precision >= 0 && typeof value === 'number') {
  75081. value = +value.toFixed(Math.min(precision, 20));
  75082. }
  75083. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75084. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  75085. type: mlType,
  75086. valueIndex: item.valueIndex,
  75087. // Force to use the value of calculated value.
  75088. value: value
  75089. }];
  75090. }
  75091. item = [
  75092. dataTransform(seriesModel, item[0]),
  75093. dataTransform(seriesModel, item[1]),
  75094. extend({}, item[2])
  75095. ];
  75096. // Avoid line data type is extended by from(to) data type
  75097. item[2].type = item[2].type || '';
  75098. // Merge from option and to option into line option
  75099. merge(item[2], item[0]);
  75100. merge(item[2], item[1]);
  75101. return item;
  75102. };
  75103. function isInifinity(val) {
  75104. return !isNaN(val) && !isFinite(val);
  75105. }
  75106. // If a markLine has one dim
  75107. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75108. var otherDimIndex = 1 - dimIndex;
  75109. var dimName = coordSys.dimensions[dimIndex];
  75110. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  75111. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75112. }
  75113. function markLineFilter(coordSys, item) {
  75114. if (coordSys.type === 'cartesian2d') {
  75115. var fromCoord = item[0].coord;
  75116. var toCoord = item[1].coord;
  75117. // In case
  75118. // {
  75119. // markLine: {
  75120. // data: [{ yAxis: 2 }]
  75121. // }
  75122. // }
  75123. if (
  75124. fromCoord && toCoord
  75125. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  75126. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  75127. ) {
  75128. return true;
  75129. }
  75130. }
  75131. return dataFilter$1(coordSys, item[0])
  75132. && dataFilter$1(coordSys, item[1]);
  75133. }
  75134. function updateSingleMarkerEndLayout(
  75135. data, idx, isFrom, seriesModel, api
  75136. ) {
  75137. var coordSys = seriesModel.coordinateSystem;
  75138. var itemModel = data.getItemModel(idx);
  75139. var point;
  75140. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75141. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75142. if (!isNaN(xPx) && !isNaN(yPx)) {
  75143. point = [xPx, yPx];
  75144. }
  75145. else {
  75146. // Chart like bar may have there own marker positioning logic
  75147. if (seriesModel.getMarkerPosition) {
  75148. // Use the getMarkerPoisition
  75149. point = seriesModel.getMarkerPosition(
  75150. data.getValues(data.dimensions, idx)
  75151. );
  75152. }
  75153. else {
  75154. var dims = coordSys.dimensions;
  75155. var x = data.get(dims[0], idx);
  75156. var y = data.get(dims[1], idx);
  75157. point = coordSys.dataToPoint([x, y]);
  75158. }
  75159. // Expand line to the edge of grid if value on one axis is Inifnity
  75160. // In case
  75161. // markLine: {
  75162. // data: [{
  75163. // yAxis: 2
  75164. // // or
  75165. // type: 'average'
  75166. // }]
  75167. // }
  75168. if (coordSys.type === 'cartesian2d') {
  75169. var xAxis = coordSys.getAxis('x');
  75170. var yAxis = coordSys.getAxis('y');
  75171. var dims = coordSys.dimensions;
  75172. if (isInifinity(data.get(dims[0], idx))) {
  75173. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75174. }
  75175. else if (isInifinity(data.get(dims[1], idx))) {
  75176. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75177. }
  75178. }
  75179. // Use x, y if has any
  75180. if (!isNaN(xPx)) {
  75181. point[0] = xPx;
  75182. }
  75183. if (!isNaN(yPx)) {
  75184. point[1] = yPx;
  75185. }
  75186. }
  75187. data.setItemLayout(idx, point);
  75188. }
  75189. MarkerView.extend({
  75190. type: 'markLine',
  75191. // updateLayout: function (markLineModel, ecModel, api) {
  75192. // ecModel.eachSeries(function (seriesModel) {
  75193. // var mlModel = seriesModel.markLineModel;
  75194. // if (mlModel) {
  75195. // var mlData = mlModel.getData();
  75196. // var fromData = mlModel.__from;
  75197. // var toData = mlModel.__to;
  75198. // // Update visual and layout of from symbol and to symbol
  75199. // fromData.each(function (idx) {
  75200. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75201. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75202. // });
  75203. // // Update layout of line
  75204. // mlData.each(function (idx) {
  75205. // mlData.setItemLayout(idx, [
  75206. // fromData.getItemLayout(idx),
  75207. // toData.getItemLayout(idx)
  75208. // ]);
  75209. // });
  75210. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  75211. // }
  75212. // }, this);
  75213. // },
  75214. updateTransform: function (markLineModel, ecModel, api) {
  75215. ecModel.eachSeries(function (seriesModel) {
  75216. var mlModel = seriesModel.markLineModel;
  75217. if (mlModel) {
  75218. var mlData = mlModel.getData();
  75219. var fromData = mlModel.__from;
  75220. var toData = mlModel.__to;
  75221. // Update visual and layout of from symbol and to symbol
  75222. fromData.each(function (idx) {
  75223. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75224. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75225. });
  75226. // Update layout of line
  75227. mlData.each(function (idx) {
  75228. mlData.setItemLayout(idx, [
  75229. fromData.getItemLayout(idx),
  75230. toData.getItemLayout(idx)
  75231. ]);
  75232. });
  75233. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75234. }
  75235. }, this);
  75236. },
  75237. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  75238. var coordSys = seriesModel.coordinateSystem;
  75239. var seriesId = seriesModel.id;
  75240. var seriesData = seriesModel.getData();
  75241. var lineDrawMap = this.markerGroupMap;
  75242. var lineDraw = lineDrawMap.get(seriesId)
  75243. || lineDrawMap.set(seriesId, new LineDraw());
  75244. this.group.add(lineDraw.group);
  75245. var mlData = createList$2(coordSys, seriesModel, mlModel);
  75246. var fromData = mlData.from;
  75247. var toData = mlData.to;
  75248. var lineData = mlData.line;
  75249. mlModel.__from = fromData;
  75250. mlModel.__to = toData;
  75251. // Line data for tooltip and formatter
  75252. mlModel.setData(lineData);
  75253. var symbolType = mlModel.get('symbol');
  75254. var symbolSize = mlModel.get('symbolSize');
  75255. if (!isArray(symbolType)) {
  75256. symbolType = [symbolType, symbolType];
  75257. }
  75258. if (typeof symbolSize === 'number') {
  75259. symbolSize = [symbolSize, symbolSize];
  75260. }
  75261. // Update visual and layout of from symbol and to symbol
  75262. mlData.from.each(function (idx) {
  75263. updateDataVisualAndLayout(fromData, idx, true);
  75264. updateDataVisualAndLayout(toData, idx, false);
  75265. });
  75266. // Update visual and layout of line
  75267. lineData.each(function (idx) {
  75268. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  75269. lineData.setItemVisual(idx, {
  75270. color: lineColor || fromData.getItemVisual(idx, 'color')
  75271. });
  75272. lineData.setItemLayout(idx, [
  75273. fromData.getItemLayout(idx),
  75274. toData.getItemLayout(idx)
  75275. ]);
  75276. lineData.setItemVisual(idx, {
  75277. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  75278. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  75279. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  75280. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  75281. });
  75282. });
  75283. lineDraw.updateData(lineData);
  75284. // Set host model for tooltip
  75285. // FIXME
  75286. mlData.line.eachItemGraphicEl(function (el, idx) {
  75287. el.traverse(function (child) {
  75288. child.dataModel = mlModel;
  75289. });
  75290. });
  75291. function updateDataVisualAndLayout(data, idx, isFrom) {
  75292. var itemModel = data.getItemModel(idx);
  75293. updateSingleMarkerEndLayout(
  75294. data, idx, isFrom, seriesModel, api
  75295. );
  75296. data.setItemVisual(idx, {
  75297. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  75298. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  75299. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  75300. });
  75301. }
  75302. lineDraw.__keep = true;
  75303. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75304. }
  75305. });
  75306. /**
  75307. * @inner
  75308. * @param {module:echarts/coord/*} coordSys
  75309. * @param {module:echarts/model/Series} seriesModel
  75310. * @param {module:echarts/model/Model} mpModel
  75311. */
  75312. function createList$2(coordSys, seriesModel, mlModel) {
  75313. var coordDimsInfos;
  75314. if (coordSys) {
  75315. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75316. var info = seriesModel.getData().getDimensionInfo(
  75317. seriesModel.getData().mapDimension(coordDim)
  75318. ) || {};
  75319. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75320. return defaults({name: coordDim}, info);
  75321. });
  75322. }
  75323. else {
  75324. coordDimsInfos = [{
  75325. name: 'value',
  75326. type: 'float'
  75327. }];
  75328. }
  75329. var fromData = new List(coordDimsInfos, mlModel);
  75330. var toData = new List(coordDimsInfos, mlModel);
  75331. // No dimensions
  75332. var lineData = new List([], mlModel);
  75333. var optData = map(mlModel.get('data'), curry(
  75334. markLineTransform, seriesModel, coordSys, mlModel
  75335. ));
  75336. if (coordSys) {
  75337. optData = filter(
  75338. optData, curry(markLineFilter, coordSys)
  75339. );
  75340. }
  75341. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  75342. return item.value;
  75343. };
  75344. fromData.initData(
  75345. map(optData, function (item) {
  75346. return item[0];
  75347. }),
  75348. null,
  75349. dimValueGetter$$1
  75350. );
  75351. toData.initData(
  75352. map(optData, function (item) {
  75353. return item[1];
  75354. }),
  75355. null,
  75356. dimValueGetter$$1
  75357. );
  75358. lineData.initData(
  75359. map(optData, function (item) {
  75360. return item[2];
  75361. })
  75362. );
  75363. lineData.hasItemOption = true;
  75364. return {
  75365. from: fromData,
  75366. to: toData,
  75367. line: lineData
  75368. };
  75369. }
  75370. /*
  75371. * Licensed to the Apache Software Foundation (ASF) under one
  75372. * or more contributor license agreements. See the NOTICE file
  75373. * distributed with this work for additional information
  75374. * regarding copyright ownership. The ASF licenses this file
  75375. * to you under the Apache License, Version 2.0 (the
  75376. * "License"); you may not use this file except in compliance
  75377. * with the License. You may obtain a copy of the License at
  75378. *
  75379. * http://www.apache.org/licenses/LICENSE-2.0
  75380. *
  75381. * Unless required by applicable law or agreed to in writing,
  75382. * software distributed under the License is distributed on an
  75383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75384. * KIND, either express or implied. See the License for the
  75385. * specific language governing permissions and limitations
  75386. * under the License.
  75387. */
  75388. registerPreprocessor(function (opt) {
  75389. // Make sure markLine component is enabled
  75390. opt.markLine = opt.markLine || {};
  75391. });
  75392. /*
  75393. * Licensed to the Apache Software Foundation (ASF) under one
  75394. * or more contributor license agreements. See the NOTICE file
  75395. * distributed with this work for additional information
  75396. * regarding copyright ownership. The ASF licenses this file
  75397. * to you under the Apache License, Version 2.0 (the
  75398. * "License"); you may not use this file except in compliance
  75399. * with the License. You may obtain a copy of the License at
  75400. *
  75401. * http://www.apache.org/licenses/LICENSE-2.0
  75402. *
  75403. * Unless required by applicable law or agreed to in writing,
  75404. * software distributed under the License is distributed on an
  75405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75406. * KIND, either express or implied. See the License for the
  75407. * specific language governing permissions and limitations
  75408. * under the License.
  75409. */
  75410. MarkerModel.extend({
  75411. type: 'markArea',
  75412. defaultOption: {
  75413. zlevel: 0,
  75414. // PENDING
  75415. z: 1,
  75416. tooltip: {
  75417. trigger: 'item'
  75418. },
  75419. // markArea should fixed on the coordinate system
  75420. animation: false,
  75421. label: {
  75422. show: true,
  75423. position: 'top'
  75424. },
  75425. itemStyle: {
  75426. // color and borderColor default to use color from series
  75427. // color: 'auto'
  75428. // borderColor: 'auto'
  75429. borderWidth: 0
  75430. },
  75431. emphasis: {
  75432. label: {
  75433. show: true,
  75434. position: 'top'
  75435. }
  75436. }
  75437. }
  75438. });
  75439. /*
  75440. * Licensed to the Apache Software Foundation (ASF) under one
  75441. * or more contributor license agreements. See the NOTICE file
  75442. * distributed with this work for additional information
  75443. * regarding copyright ownership. The ASF licenses this file
  75444. * to you under the Apache License, Version 2.0 (the
  75445. * "License"); you may not use this file except in compliance
  75446. * with the License. You may obtain a copy of the License at
  75447. *
  75448. * http://www.apache.org/licenses/LICENSE-2.0
  75449. *
  75450. * Unless required by applicable law or agreed to in writing,
  75451. * software distributed under the License is distributed on an
  75452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75453. * KIND, either express or implied. See the License for the
  75454. * specific language governing permissions and limitations
  75455. * under the License.
  75456. */
  75457. // TODO Better on polar
  75458. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75459. var lt = dataTransform(seriesModel, item[0]);
  75460. var rb = dataTransform(seriesModel, item[1]);
  75461. var retrieve$$1 = retrieve;
  75462. // FIXME make sure lt is less than rb
  75463. var ltCoord = lt.coord;
  75464. var rbCoord = rb.coord;
  75465. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  75466. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  75467. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  75468. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  75469. // Merge option into one
  75470. var result = mergeAll([{}, lt, rb]);
  75471. result.coord = [
  75472. lt.coord, rb.coord
  75473. ];
  75474. result.x0 = lt.x;
  75475. result.y0 = lt.y;
  75476. result.x1 = rb.x;
  75477. result.y1 = rb.y;
  75478. return result;
  75479. };
  75480. function isInifinity$1(val) {
  75481. return !isNaN(val) && !isFinite(val);
  75482. }
  75483. // If a markArea has one dim
  75484. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  75485. var otherDimIndex = 1 - dimIndex;
  75486. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  75487. }
  75488. function markAreaFilter(coordSys, item) {
  75489. var fromCoord = item.coord[0];
  75490. var toCoord = item.coord[1];
  75491. if (coordSys.type === 'cartesian2d') {
  75492. // In case
  75493. // {
  75494. // markArea: {
  75495. // data: [{ yAxis: 2 }]
  75496. // }
  75497. // }
  75498. if (
  75499. fromCoord && toCoord
  75500. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  75501. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  75502. ) {
  75503. return true;
  75504. }
  75505. }
  75506. return dataFilter$1(coordSys, {
  75507. coord: fromCoord,
  75508. x: item.x0,
  75509. y: item.y0
  75510. })
  75511. || dataFilter$1(coordSys, {
  75512. coord: toCoord,
  75513. x: item.x1,
  75514. y: item.y1
  75515. });
  75516. }
  75517. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75518. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75519. var coordSys = seriesModel.coordinateSystem;
  75520. var itemModel = data.getItemModel(idx);
  75521. var point;
  75522. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75523. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75524. if (!isNaN(xPx) && !isNaN(yPx)) {
  75525. point = [xPx, yPx];
  75526. }
  75527. else {
  75528. // Chart like bar may have there own marker positioning logic
  75529. if (seriesModel.getMarkerPosition) {
  75530. // Use the getMarkerPoisition
  75531. point = seriesModel.getMarkerPosition(
  75532. data.getValues(dims, idx)
  75533. );
  75534. }
  75535. else {
  75536. var x = data.get(dims[0], idx);
  75537. var y = data.get(dims[1], idx);
  75538. var pt = [x, y];
  75539. coordSys.clampData && coordSys.clampData(pt, pt);
  75540. point = coordSys.dataToPoint(pt, true);
  75541. }
  75542. if (coordSys.type === 'cartesian2d') {
  75543. var xAxis = coordSys.getAxis('x');
  75544. var yAxis = coordSys.getAxis('y');
  75545. var x = data.get(dims[0], idx);
  75546. var y = data.get(dims[1], idx);
  75547. if (isInifinity$1(x)) {
  75548. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75549. }
  75550. else if (isInifinity$1(y)) {
  75551. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75552. }
  75553. }
  75554. // Use x, y if has any
  75555. if (!isNaN(xPx)) {
  75556. point[0] = xPx;
  75557. }
  75558. if (!isNaN(yPx)) {
  75559. point[1] = yPx;
  75560. }
  75561. }
  75562. return point;
  75563. }
  75564. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75565. MarkerView.extend({
  75566. type: 'markArea',
  75567. // updateLayout: function (markAreaModel, ecModel, api) {
  75568. // ecModel.eachSeries(function (seriesModel) {
  75569. // var maModel = seriesModel.markAreaModel;
  75570. // if (maModel) {
  75571. // var areaData = maModel.getData();
  75572. // areaData.each(function (idx) {
  75573. // var points = zrUtil.map(dimPermutations, function (dim) {
  75574. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75575. // });
  75576. // // Layout
  75577. // areaData.setItemLayout(idx, points);
  75578. // var el = areaData.getItemGraphicEl(idx);
  75579. // el.setShape('points', points);
  75580. // });
  75581. // }
  75582. // }, this);
  75583. // },
  75584. updateTransform: function (markAreaModel, ecModel, api) {
  75585. ecModel.eachSeries(function (seriesModel) {
  75586. var maModel = seriesModel.markAreaModel;
  75587. if (maModel) {
  75588. var areaData = maModel.getData();
  75589. areaData.each(function (idx) {
  75590. var points = map(dimPermutations, function (dim) {
  75591. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75592. });
  75593. // Layout
  75594. areaData.setItemLayout(idx, points);
  75595. var el = areaData.getItemGraphicEl(idx);
  75596. el.setShape('points', points);
  75597. });
  75598. }
  75599. }, this);
  75600. },
  75601. renderSeries: function (seriesModel, maModel, ecModel, api) {
  75602. var coordSys = seriesModel.coordinateSystem;
  75603. var seriesId = seriesModel.id;
  75604. var seriesData = seriesModel.getData();
  75605. var areaGroupMap = this.markerGroupMap;
  75606. var polygonGroup = areaGroupMap.get(seriesId)
  75607. || areaGroupMap.set(seriesId, {group: new Group()});
  75608. this.group.add(polygonGroup.group);
  75609. polygonGroup.__keep = true;
  75610. var areaData = createList$3(coordSys, seriesModel, maModel);
  75611. // Line data for tooltip and formatter
  75612. maModel.setData(areaData);
  75613. // Update visual and layout of line
  75614. areaData.each(function (idx) {
  75615. // Layout
  75616. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  75617. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75618. }));
  75619. // Visual
  75620. areaData.setItemVisual(idx, {
  75621. color: seriesData.getVisual('color')
  75622. });
  75623. });
  75624. areaData.diff(polygonGroup.__data)
  75625. .add(function (idx) {
  75626. var polygon = new Polygon({
  75627. shape: {
  75628. points: areaData.getItemLayout(idx)
  75629. }
  75630. });
  75631. areaData.setItemGraphicEl(idx, polygon);
  75632. polygonGroup.group.add(polygon);
  75633. })
  75634. .update(function (newIdx, oldIdx) {
  75635. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  75636. updateProps(polygon, {
  75637. shape: {
  75638. points: areaData.getItemLayout(newIdx)
  75639. }
  75640. }, maModel, newIdx);
  75641. polygonGroup.group.add(polygon);
  75642. areaData.setItemGraphicEl(newIdx, polygon);
  75643. })
  75644. .remove(function (idx) {
  75645. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  75646. polygonGroup.group.remove(polygon);
  75647. })
  75648. .execute();
  75649. areaData.eachItemGraphicEl(function (polygon, idx) {
  75650. var itemModel = areaData.getItemModel(idx);
  75651. var labelModel = itemModel.getModel('label');
  75652. var labelHoverModel = itemModel.getModel('emphasis.label');
  75653. var color = areaData.getItemVisual(idx, 'color');
  75654. polygon.useStyle(
  75655. defaults(
  75656. itemModel.getModel('itemStyle').getItemStyle(),
  75657. {
  75658. fill: modifyAlpha(color, 0.4),
  75659. stroke: color
  75660. }
  75661. )
  75662. );
  75663. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  75664. setLabelStyle(
  75665. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  75666. {
  75667. labelFetcher: maModel,
  75668. labelDataIndex: idx,
  75669. defaultText: areaData.getName(idx) || '',
  75670. isRectText: true,
  75671. autoColor: color
  75672. }
  75673. );
  75674. setHoverStyle(polygon, {});
  75675. polygon.dataModel = maModel;
  75676. });
  75677. polygonGroup.__data = areaData;
  75678. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75679. }
  75680. });
  75681. /**
  75682. * @inner
  75683. * @param {module:echarts/coord/*} coordSys
  75684. * @param {module:echarts/model/Series} seriesModel
  75685. * @param {module:echarts/model/Model} mpModel
  75686. */
  75687. function createList$3(coordSys, seriesModel, maModel) {
  75688. var coordDimsInfos;
  75689. var areaData;
  75690. var dims = ['x0', 'y0', 'x1', 'y1'];
  75691. if (coordSys) {
  75692. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75693. var data = seriesModel.getData();
  75694. var info = data.getDimensionInfo(
  75695. data.mapDimension(coordDim)
  75696. ) || {};
  75697. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75698. return defaults({name: coordDim}, info);
  75699. });
  75700. areaData = new List(map(dims, function (dim, idx) {
  75701. return {
  75702. name: dim,
  75703. type: coordDimsInfos[idx % 2].type
  75704. };
  75705. }), maModel);
  75706. }
  75707. else {
  75708. coordDimsInfos = [{
  75709. name: 'value',
  75710. type: 'float'
  75711. }];
  75712. areaData = new List(coordDimsInfos, maModel);
  75713. }
  75714. var optData = map(maModel.get('data'), curry(
  75715. markAreaTransform, seriesModel, coordSys, maModel
  75716. ));
  75717. if (coordSys) {
  75718. optData = filter(
  75719. optData, curry(markAreaFilter, coordSys)
  75720. );
  75721. }
  75722. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75723. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75724. } : function (item) {
  75725. return item.value;
  75726. };
  75727. areaData.initData(optData, null, dimValueGetter$$1);
  75728. areaData.hasItemOption = true;
  75729. return areaData;
  75730. }
  75731. /*
  75732. * Licensed to the Apache Software Foundation (ASF) under one
  75733. * or more contributor license agreements. See the NOTICE file
  75734. * distributed with this work for additional information
  75735. * regarding copyright ownership. The ASF licenses this file
  75736. * to you under the Apache License, Version 2.0 (the
  75737. * "License"); you may not use this file except in compliance
  75738. * with the License. You may obtain a copy of the License at
  75739. *
  75740. * http://www.apache.org/licenses/LICENSE-2.0
  75741. *
  75742. * Unless required by applicable law or agreed to in writing,
  75743. * software distributed under the License is distributed on an
  75744. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75745. * KIND, either express or implied. See the License for the
  75746. * specific language governing permissions and limitations
  75747. * under the License.
  75748. */
  75749. registerPreprocessor(function (opt) {
  75750. // Make sure markArea component is enabled
  75751. opt.markArea = opt.markArea || {};
  75752. });
  75753. /*
  75754. * Licensed to the Apache Software Foundation (ASF) under one
  75755. * or more contributor license agreements. See the NOTICE file
  75756. * distributed with this work for additional information
  75757. * regarding copyright ownership. The ASF licenses this file
  75758. * to you under the Apache License, Version 2.0 (the
  75759. * "License"); you may not use this file except in compliance
  75760. * with the License. You may obtain a copy of the License at
  75761. *
  75762. * http://www.apache.org/licenses/LICENSE-2.0
  75763. *
  75764. * Unless required by applicable law or agreed to in writing,
  75765. * software distributed under the License is distributed on an
  75766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75767. * KIND, either express or implied. See the License for the
  75768. * specific language governing permissions and limitations
  75769. * under the License.
  75770. */
  75771. var langSelector = lang.legend.selector;
  75772. var defaultSelectorOption = {
  75773. all: {
  75774. type: 'all',
  75775. title: clone(langSelector.all)
  75776. },
  75777. inverse: {
  75778. type: 'inverse',
  75779. title: clone(langSelector.inverse)
  75780. }
  75781. };
  75782. var LegendModel = extendComponentModel({
  75783. type: 'legend.plain',
  75784. dependencies: ['series'],
  75785. layoutMode: {
  75786. type: 'box',
  75787. // legend.width/height are maxWidth/maxHeight actually,
  75788. // whereas realy width/height is calculated by its content.
  75789. // (Setting {left: 10, right: 10} does not make sense).
  75790. // So consider the case:
  75791. // `setOption({legend: {left: 10});`
  75792. // then `setOption({legend: {right: 10});`
  75793. // The previous `left` should be cleared by setting `ignoreSize`.
  75794. ignoreSize: true
  75795. },
  75796. init: function (option, parentModel, ecModel) {
  75797. this.mergeDefaultAndTheme(option, ecModel);
  75798. option.selected = option.selected || {};
  75799. this._updateSelector(option);
  75800. },
  75801. mergeOption: function (option) {
  75802. LegendModel.superCall(this, 'mergeOption', option);
  75803. this._updateSelector(option);
  75804. },
  75805. _updateSelector: function (option) {
  75806. var selector = option.selector;
  75807. if (selector === true) {
  75808. selector = option.selector = ['all', 'inverse'];
  75809. }
  75810. if (isArray(selector)) {
  75811. each$1(selector, function (item, index) {
  75812. isString(item) && (item = {type: item});
  75813. selector[index] = merge(item, defaultSelectorOption[item.type]);
  75814. });
  75815. }
  75816. },
  75817. optionUpdated: function () {
  75818. this._updateData(this.ecModel);
  75819. var legendData = this._data;
  75820. // If selectedMode is single, try to select one
  75821. if (legendData[0] && this.get('selectedMode') === 'single') {
  75822. var hasSelected = false;
  75823. // If has any selected in option.selected
  75824. for (var i = 0; i < legendData.length; i++) {
  75825. var name = legendData[i].get('name');
  75826. if (this.isSelected(name)) {
  75827. // Force to unselect others
  75828. this.select(name);
  75829. hasSelected = true;
  75830. break;
  75831. }
  75832. }
  75833. // Try select the first if selectedMode is single
  75834. !hasSelected && this.select(legendData[0].get('name'));
  75835. }
  75836. },
  75837. _updateData: function (ecModel) {
  75838. var potentialData = [];
  75839. var availableNames = [];
  75840. ecModel.eachRawSeries(function (seriesModel) {
  75841. var seriesName = seriesModel.name;
  75842. availableNames.push(seriesName);
  75843. var isPotential;
  75844. if (seriesModel.legendVisualProvider) {
  75845. var provider = seriesModel.legendVisualProvider;
  75846. var names = provider.getAllNames();
  75847. if (!ecModel.isSeriesFiltered(seriesModel)) {
  75848. availableNames = availableNames.concat(names);
  75849. }
  75850. if (names.length) {
  75851. potentialData = potentialData.concat(names);
  75852. }
  75853. else {
  75854. isPotential = true;
  75855. }
  75856. }
  75857. else {
  75858. isPotential = true;
  75859. }
  75860. if (isPotential && isNameSpecified(seriesModel)) {
  75861. potentialData.push(seriesModel.name);
  75862. }
  75863. });
  75864. /**
  75865. * @type {Array.<string>}
  75866. * @private
  75867. */
  75868. this._availableNames = availableNames;
  75869. // If legend.data not specified in option, use availableNames as data,
  75870. // which is convinient for user preparing option.
  75871. var rawData = this.get('data') || potentialData;
  75872. var legendData = map(rawData, function (dataItem) {
  75873. // Can be string or number
  75874. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  75875. dataItem = {
  75876. name: dataItem
  75877. };
  75878. }
  75879. return new Model(dataItem, this, this.ecModel);
  75880. }, this);
  75881. /**
  75882. * @type {Array.<module:echarts/model/Model>}
  75883. * @private
  75884. */
  75885. this._data = legendData;
  75886. },
  75887. /**
  75888. * @return {Array.<module:echarts/model/Model>}
  75889. */
  75890. getData: function () {
  75891. return this._data;
  75892. },
  75893. /**
  75894. * @param {string} name
  75895. */
  75896. select: function (name) {
  75897. var selected = this.option.selected;
  75898. var selectedMode = this.get('selectedMode');
  75899. if (selectedMode === 'single') {
  75900. var data = this._data;
  75901. each$1(data, function (dataItem) {
  75902. selected[dataItem.get('name')] = false;
  75903. });
  75904. }
  75905. selected[name] = true;
  75906. },
  75907. /**
  75908. * @param {string} name
  75909. */
  75910. unSelect: function (name) {
  75911. if (this.get('selectedMode') !== 'single') {
  75912. this.option.selected[name] = false;
  75913. }
  75914. },
  75915. /**
  75916. * @param {string} name
  75917. */
  75918. toggleSelected: function (name) {
  75919. var selected = this.option.selected;
  75920. // Default is true
  75921. if (!selected.hasOwnProperty(name)) {
  75922. selected[name] = true;
  75923. }
  75924. this[selected[name] ? 'unSelect' : 'select'](name);
  75925. },
  75926. allSelect: function () {
  75927. var data = this._data;
  75928. var selected = this.option.selected;
  75929. each$1(data, function (dataItem) {
  75930. selected[dataItem.get('name', true)] = true;
  75931. });
  75932. },
  75933. inverseSelect: function () {
  75934. var data = this._data;
  75935. var selected = this.option.selected;
  75936. each$1(data, function (dataItem) {
  75937. var name = dataItem.get('name', true);
  75938. // Initially, default value is true
  75939. if (!selected.hasOwnProperty(name)) {
  75940. selected[name] = true;
  75941. }
  75942. selected[name] = !selected[name];
  75943. });
  75944. },
  75945. /**
  75946. * @param {string} name
  75947. */
  75948. isSelected: function (name) {
  75949. var selected = this.option.selected;
  75950. return !(selected.hasOwnProperty(name) && !selected[name])
  75951. && indexOf(this._availableNames, name) >= 0;
  75952. },
  75953. getOrient: function () {
  75954. return this.get('orient') === 'vertical'
  75955. ? {index: 1, name: 'vertical'}
  75956. : {index: 0, name: 'horizontal'};
  75957. },
  75958. defaultOption: {
  75959. // 一级层叠
  75960. zlevel: 0,
  75961. // 二级层叠
  75962. z: 4,
  75963. show: true,
  75964. // 布局方式,默认为水平布局,可选为:
  75965. // 'horizontal' | 'vertical'
  75966. orient: 'horizontal',
  75967. left: 'center',
  75968. // right: 'center',
  75969. top: 0,
  75970. // bottom: null,
  75971. // 水平对齐
  75972. // 'auto' | 'left' | 'right'
  75973. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  75974. align: 'auto',
  75975. backgroundColor: 'rgba(0,0,0,0)',
  75976. // 图例边框颜色
  75977. borderColor: '#ccc',
  75978. borderRadius: 0,
  75979. // 图例边框线宽,单位px,默认为0(无边框)
  75980. borderWidth: 0,
  75981. // 图例内边距,单位px,默认各方向内边距为5,
  75982. // 接受数组分别设定上右下左边距,同css
  75983. padding: 5,
  75984. // 各个item之间的间隔,单位px,默认为10,
  75985. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  75986. itemGap: 10,
  75987. // the width of legend symbol
  75988. itemWidth: 25,
  75989. // the height of legend symbol
  75990. itemHeight: 14,
  75991. // the color of unselected legend symbol
  75992. inactiveColor: '#ccc',
  75993. // the borderColor of unselected legend symbol
  75994. inactiveBorderColor: '#ccc',
  75995. itemStyle: {
  75996. // the default borderWidth of legend symbol
  75997. borderWidth: 0
  75998. },
  75999. textStyle: {
  76000. // 图例文字颜色
  76001. color: '#333'
  76002. },
  76003. // formatter: '',
  76004. // 选择模式,默认开启图例开关
  76005. selectedMode: true,
  76006. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  76007. // selected: null,
  76008. // 图例内容(详见legend.data,数组中每一项代表一个item
  76009. // data: [],
  76010. // Usage:
  76011. // selector: [{type: 'all or inverse', title: xxx}]
  76012. // or
  76013. // selector: true
  76014. // or
  76015. // selector: ['all', 'inverse']
  76016. selector: false,
  76017. selectorLabel: {
  76018. show: true,
  76019. borderRadius: 10,
  76020. padding: [3, 5, 3, 5],
  76021. fontSize: 12,
  76022. fontFamily: ' sans-serif',
  76023. color: '#666',
  76024. borderWidth: 1,
  76025. borderColor: '#666'
  76026. },
  76027. emphasis: {
  76028. selectorLabel: {
  76029. show: true,
  76030. color: '#eee',
  76031. backgroundColor: '#666'
  76032. }
  76033. },
  76034. // Value can be 'start' or 'end'
  76035. selectorPosition: 'auto',
  76036. selectorItemGap: 7,
  76037. selectorButtonGap: 10,
  76038. // Tooltip 相关配置
  76039. tooltip: {
  76040. show: false
  76041. }
  76042. }
  76043. });
  76044. /*
  76045. * Licensed to the Apache Software Foundation (ASF) under one
  76046. * or more contributor license agreements. See the NOTICE file
  76047. * distributed with this work for additional information
  76048. * regarding copyright ownership. The ASF licenses this file
  76049. * to you under the Apache License, Version 2.0 (the
  76050. * "License"); you may not use this file except in compliance
  76051. * with the License. You may obtain a copy of the License at
  76052. *
  76053. * http://www.apache.org/licenses/LICENSE-2.0
  76054. *
  76055. * Unless required by applicable law or agreed to in writing,
  76056. * software distributed under the License is distributed on an
  76057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76058. * KIND, either express or implied. See the License for the
  76059. * specific language governing permissions and limitations
  76060. * under the License.
  76061. */
  76062. function legendSelectActionHandler(methodName, payload, ecModel) {
  76063. var selectedMap = {};
  76064. var isToggleSelect = methodName === 'toggleSelected';
  76065. var isSelected;
  76066. // Update all legend components
  76067. ecModel.eachComponent('legend', function (legendModel) {
  76068. if (isToggleSelect && isSelected != null) {
  76069. // Force other legend has same selected status
  76070. // Or the first is toggled to true and other are toggled to false
  76071. // In the case one legend has some item unSelected in option. And if other legend
  76072. // doesn't has the item, they will assume it is selected.
  76073. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76074. }
  76075. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76076. legendModel[methodName]();
  76077. }
  76078. else {
  76079. legendModel[methodName](payload.name);
  76080. isSelected = legendModel.isSelected(payload.name);
  76081. }
  76082. var legendData = legendModel.getData();
  76083. each$1(legendData, function (model) {
  76084. var name = model.get('name');
  76085. // Wrap element
  76086. if (name === '\n' || name === '') {
  76087. return;
  76088. }
  76089. var isItemSelected = legendModel.isSelected(name);
  76090. if (selectedMap.hasOwnProperty(name)) {
  76091. // Unselected if any legend is unselected
  76092. selectedMap[name] = selectedMap[name] && isItemSelected;
  76093. }
  76094. else {
  76095. selectedMap[name] = isItemSelected;
  76096. }
  76097. });
  76098. });
  76099. // Return the event explicitly
  76100. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  76101. ? {
  76102. selected: selectedMap
  76103. }
  76104. : {
  76105. name: payload.name,
  76106. selected: selectedMap
  76107. };
  76108. }
  76109. /**
  76110. * @event legendToggleSelect
  76111. * @type {Object}
  76112. * @property {string} type 'legendToggleSelect'
  76113. * @property {string} [from]
  76114. * @property {string} name Series name or data item name
  76115. */
  76116. registerAction(
  76117. 'legendToggleSelect', 'legendselectchanged',
  76118. curry(legendSelectActionHandler, 'toggleSelected')
  76119. );
  76120. registerAction(
  76121. 'legendAllSelect', 'legendselectall',
  76122. curry(legendSelectActionHandler, 'allSelect')
  76123. );
  76124. registerAction(
  76125. 'legendInverseSelect', 'legendinverseselect',
  76126. curry(legendSelectActionHandler, 'inverseSelect')
  76127. );
  76128. /**
  76129. * @event legendSelect
  76130. * @type {Object}
  76131. * @property {string} type 'legendSelect'
  76132. * @property {string} name Series name or data item name
  76133. */
  76134. registerAction(
  76135. 'legendSelect', 'legendselected',
  76136. curry(legendSelectActionHandler, 'select')
  76137. );
  76138. /**
  76139. * @event legendUnSelect
  76140. * @type {Object}
  76141. * @property {string} type 'legendUnSelect'
  76142. * @property {string} name Series name or data item name
  76143. */
  76144. registerAction(
  76145. 'legendUnSelect', 'legendunselected',
  76146. curry(legendSelectActionHandler, 'unSelect')
  76147. );
  76148. /*
  76149. * Licensed to the Apache Software Foundation (ASF) under one
  76150. * or more contributor license agreements. See the NOTICE file
  76151. * distributed with this work for additional information
  76152. * regarding copyright ownership. The ASF licenses this file
  76153. * to you under the Apache License, Version 2.0 (the
  76154. * "License"); you may not use this file except in compliance
  76155. * with the License. You may obtain a copy of the License at
  76156. *
  76157. * http://www.apache.org/licenses/LICENSE-2.0
  76158. *
  76159. * Unless required by applicable law or agreed to in writing,
  76160. * software distributed under the License is distributed on an
  76161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76162. * KIND, either express or implied. See the License for the
  76163. * specific language governing permissions and limitations
  76164. * under the License.
  76165. */
  76166. var curry$6 = curry;
  76167. var each$25 = each$1;
  76168. var Group$3 = Group;
  76169. var LegendView = extendComponentView({
  76170. type: 'legend.plain',
  76171. newlineDisabled: false,
  76172. /**
  76173. * @override
  76174. */
  76175. init: function () {
  76176. /**
  76177. * @private
  76178. * @type {module:zrender/container/Group}
  76179. */
  76180. this.group.add(this._contentGroup = new Group$3());
  76181. /**
  76182. * @private
  76183. * @type {module:zrender/Element}
  76184. */
  76185. this._backgroundEl;
  76186. /**
  76187. * @private
  76188. * @type {module:zrender/container/Group}
  76189. */
  76190. this.group.add(this._selectorGroup = new Group$3());
  76191. /**
  76192. * If first rendering, `contentGroup.position` is [0, 0], which
  76193. * does not make sense and may cause unexepcted animation if adopted.
  76194. * @private
  76195. * @type {boolean}
  76196. */
  76197. this._isFirstRender = true;
  76198. },
  76199. /**
  76200. * @protected
  76201. */
  76202. getContentGroup: function () {
  76203. return this._contentGroup;
  76204. },
  76205. /**
  76206. * @protected
  76207. */
  76208. getSelectorGroup: function () {
  76209. return this._selectorGroup;
  76210. },
  76211. /**
  76212. * @override
  76213. */
  76214. render: function (legendModel, ecModel, api) {
  76215. var isFirstRender = this._isFirstRender;
  76216. this._isFirstRender = false;
  76217. this.resetInner();
  76218. if (!legendModel.get('show', true)) {
  76219. return;
  76220. }
  76221. var itemAlign = legendModel.get('align');
  76222. var orient = legendModel.get('orient');
  76223. if (!itemAlign || itemAlign === 'auto') {
  76224. itemAlign = (
  76225. legendModel.get('left') === 'right'
  76226. && orient === 'vertical'
  76227. ) ? 'right' : 'left';
  76228. }
  76229. var selector = legendModel.get('selector', true);
  76230. var selectorPosition = legendModel.get('selectorPosition', true);
  76231. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  76232. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  76233. }
  76234. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  76235. // Perform layout.
  76236. var positionInfo = legendModel.getBoxLayoutParams();
  76237. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  76238. var padding = legendModel.get('padding');
  76239. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  76240. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  76241. // Place mainGroup, based on the calculated `mainRect`.
  76242. var layoutRect = getLayoutRect(
  76243. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  76244. viewportSize,
  76245. padding
  76246. );
  76247. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  76248. // Render background after group is layout.
  76249. this.group.add(
  76250. this._backgroundEl = makeBackground(mainRect, legendModel)
  76251. );
  76252. },
  76253. /**
  76254. * @protected
  76255. */
  76256. resetInner: function () {
  76257. this.getContentGroup().removeAll();
  76258. this._backgroundEl && this.group.remove(this._backgroundEl);
  76259. this.getSelectorGroup().removeAll();
  76260. },
  76261. /**
  76262. * @protected
  76263. */
  76264. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76265. var contentGroup = this.getContentGroup();
  76266. var legendDrawnMap = createHashMap();
  76267. var selectMode = legendModel.get('selectedMode');
  76268. var excludeSeriesId = [];
  76269. ecModel.eachRawSeries(function (seriesModel) {
  76270. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  76271. });
  76272. each$25(legendModel.getData(), function (itemModel, dataIndex) {
  76273. var name = itemModel.get('name');
  76274. // Use empty string or \n as a newline string
  76275. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  76276. contentGroup.add(new Group$3({
  76277. newline: true
  76278. }));
  76279. return;
  76280. }
  76281. // Representitive series.
  76282. var seriesModel = ecModel.getSeriesByName(name)[0];
  76283. if (legendDrawnMap.get(name)) {
  76284. // Have been drawed
  76285. return;
  76286. }
  76287. // Legend to control series.
  76288. if (seriesModel) {
  76289. var data = seriesModel.getData();
  76290. var color = data.getVisual('color');
  76291. var borderColor = data.getVisual('borderColor');
  76292. // If color is a callback function
  76293. if (typeof color === 'function') {
  76294. // Use the first data
  76295. color = color(seriesModel.getDataParams(0));
  76296. }
  76297. // If borderColor is a callback function
  76298. if (typeof borderColor === 'function') {
  76299. // Use the first data
  76300. borderColor = borderColor(seriesModel.getDataParams(0));
  76301. }
  76302. // Using rect symbol defaultly
  76303. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  76304. var symbolType = data.getVisual('symbol');
  76305. var itemGroup = this._createItem(
  76306. name, dataIndex, itemModel, legendModel,
  76307. legendSymbolType, symbolType,
  76308. itemAlign, color, borderColor,
  76309. selectMode
  76310. );
  76311. itemGroup.on('click', curry$6(dispatchSelectAction, name, null, api, excludeSeriesId))
  76312. .on('mouseover', curry$6(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  76313. .on('mouseout', curry$6(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  76314. legendDrawnMap.set(name, true);
  76315. }
  76316. else {
  76317. // Legend to control data. In pie and funnel.
  76318. ecModel.eachRawSeries(function (seriesModel) {
  76319. // In case multiple series has same data name
  76320. if (legendDrawnMap.get(name)) {
  76321. return;
  76322. }
  76323. if (seriesModel.legendVisualProvider) {
  76324. var provider = seriesModel.legendVisualProvider;
  76325. if (!provider.containName(name)) {
  76326. return;
  76327. }
  76328. var idx = provider.indexOfName(name);
  76329. var color = provider.getItemVisual(idx, 'color');
  76330. var borderColor = provider.getItemVisual(idx, 'borderColor');
  76331. var legendSymbolType = 'roundRect';
  76332. var itemGroup = this._createItem(
  76333. name, dataIndex, itemModel, legendModel,
  76334. legendSymbolType, null,
  76335. itemAlign, color, borderColor,
  76336. selectMode
  76337. );
  76338. // FIXME: consider different series has items with the same name.
  76339. itemGroup.on('click', curry$6(dispatchSelectAction, null, name, api, excludeSeriesId))
  76340. // Should not specify the series name, consider legend controls
  76341. // more than one pie series.
  76342. .on('mouseover', curry$6(dispatchHighlightAction, null, name, api, excludeSeriesId))
  76343. .on('mouseout', curry$6(dispatchDownplayAction, null, name, api, excludeSeriesId));
  76344. legendDrawnMap.set(name, true);
  76345. }
  76346. }, this);
  76347. }
  76348. if (__DEV__) {
  76349. if (!legendDrawnMap.get(name)) {
  76350. console.warn(
  76351. name + ' series not exists. Legend data should be same with series name or data name.'
  76352. );
  76353. }
  76354. }
  76355. }, this);
  76356. if (selector) {
  76357. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  76358. }
  76359. },
  76360. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  76361. var selectorGroup = this.getSelectorGroup();
  76362. each$25(selector, function (selectorItem) {
  76363. createSelectorButton(selectorItem);
  76364. });
  76365. function createSelectorButton(selectorItem) {
  76366. var type = selectorItem.type;
  76367. var labelText = new Text({
  76368. style: {
  76369. x: 0,
  76370. y: 0,
  76371. align: 'center',
  76372. verticalAlign: 'middle'
  76373. },
  76374. onclick: function () {
  76375. api.dispatchAction({
  76376. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  76377. });
  76378. }
  76379. });
  76380. selectorGroup.add(labelText);
  76381. var labelModel = legendModel.getModel('selectorLabel');
  76382. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  76383. setLabelStyle(
  76384. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  76385. {
  76386. defaultText: selectorItem.title,
  76387. isRectText: false
  76388. }
  76389. );
  76390. setHoverStyle(labelText);
  76391. }
  76392. },
  76393. _createItem: function (
  76394. name, dataIndex, itemModel, legendModel,
  76395. legendSymbolType, symbolType,
  76396. itemAlign, color, borderColor, selectMode
  76397. ) {
  76398. var itemWidth = legendModel.get('itemWidth');
  76399. var itemHeight = legendModel.get('itemHeight');
  76400. var inactiveColor = legendModel.get('inactiveColor');
  76401. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  76402. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  76403. var legendModelItemStyle = legendModel.getModel('itemStyle');
  76404. var isSelected = legendModel.isSelected(name);
  76405. var itemGroup = new Group$3();
  76406. var textStyleModel = itemModel.getModel('textStyle');
  76407. var itemIcon = itemModel.get('icon');
  76408. var tooltipModel = itemModel.getModel('tooltip');
  76409. var legendGlobalTooltipModel = tooltipModel.parentModel;
  76410. // Use user given icon first
  76411. legendSymbolType = itemIcon || legendSymbolType;
  76412. var legendSymbol = createSymbol(
  76413. legendSymbolType,
  76414. 0,
  76415. 0,
  76416. itemWidth,
  76417. itemHeight,
  76418. isSelected ? color : inactiveColor,
  76419. // symbolKeepAspect default true for legend
  76420. symbolKeepAspect == null ? true : symbolKeepAspect
  76421. );
  76422. itemGroup.add(
  76423. setSymbolStyle(
  76424. legendSymbol, legendSymbolType, legendModelItemStyle,
  76425. borderColor, inactiveBorderColor, isSelected
  76426. )
  76427. );
  76428. // Compose symbols
  76429. // PENDING
  76430. if (!itemIcon && symbolType
  76431. // At least show one symbol, can't be all none
  76432. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  76433. ) {
  76434. var size = itemHeight * 0.8;
  76435. if (symbolType === 'none') {
  76436. symbolType = 'circle';
  76437. }
  76438. var legendSymbolCenter = createSymbol(
  76439. symbolType,
  76440. (itemWidth - size) / 2,
  76441. (itemHeight - size) / 2,
  76442. size,
  76443. size,
  76444. isSelected ? color : inactiveColor,
  76445. // symbolKeepAspect default true for legend
  76446. symbolKeepAspect == null ? true : symbolKeepAspect
  76447. );
  76448. // Put symbol in the center
  76449. itemGroup.add(
  76450. setSymbolStyle(
  76451. legendSymbolCenter, symbolType, legendModelItemStyle,
  76452. borderColor, inactiveBorderColor, isSelected
  76453. )
  76454. );
  76455. }
  76456. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  76457. var textAlign = itemAlign;
  76458. var formatter = legendModel.get('formatter');
  76459. var content = name;
  76460. if (typeof formatter === 'string' && formatter) {
  76461. content = formatter.replace('{name}', name != null ? name : '');
  76462. }
  76463. else if (typeof formatter === 'function') {
  76464. content = formatter(name);
  76465. }
  76466. itemGroup.add(new Text({
  76467. style: setTextStyle({}, textStyleModel, {
  76468. text: content,
  76469. x: textX,
  76470. y: itemHeight / 2,
  76471. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  76472. textAlign: textAlign,
  76473. textVerticalAlign: 'middle'
  76474. })
  76475. }));
  76476. // Add a invisible rect to increase the area of mouse hover
  76477. var hitRect = new Rect({
  76478. shape: itemGroup.getBoundingRect(),
  76479. invisible: true,
  76480. tooltip: tooltipModel.get('show') ? extend({
  76481. content: name,
  76482. // Defaul formatter
  76483. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  76484. return name;
  76485. },
  76486. formatterParams: {
  76487. componentType: 'legend',
  76488. legendIndex: legendModel.componentIndex,
  76489. name: name,
  76490. $vars: ['name']
  76491. }
  76492. }, tooltipModel.option) : null
  76493. });
  76494. itemGroup.add(hitRect);
  76495. itemGroup.eachChild(function (child) {
  76496. child.silent = true;
  76497. });
  76498. hitRect.silent = !selectMode;
  76499. this.getContentGroup().add(itemGroup);
  76500. setHoverStyle(itemGroup);
  76501. itemGroup.__legendDataIndex = dataIndex;
  76502. return itemGroup;
  76503. },
  76504. /**
  76505. * @protected
  76506. */
  76507. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76508. var contentGroup = this.getContentGroup();
  76509. var selectorGroup = this.getSelectorGroup();
  76510. // Place items in contentGroup.
  76511. box(
  76512. legendModel.get('orient'),
  76513. contentGroup,
  76514. legendModel.get('itemGap'),
  76515. maxSize.width,
  76516. maxSize.height
  76517. );
  76518. var contentRect = contentGroup.getBoundingRect();
  76519. var contentPos = [-contentRect.x, -contentRect.y];
  76520. if (selector) {
  76521. // Place buttons in selectorGroup
  76522. box(
  76523. // Buttons in selectorGroup always layout horizontally
  76524. 'horizontal',
  76525. selectorGroup,
  76526. legendModel.get('selectorItemGap', true)
  76527. );
  76528. var selectorRect = selectorGroup.getBoundingRect();
  76529. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76530. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76531. var orientIdx = legendModel.getOrient().index;
  76532. var wh = orientIdx === 0 ? 'width' : 'height';
  76533. var hw = orientIdx === 0 ? 'height' : 'width';
  76534. var yx = orientIdx === 0 ? 'y' : 'x';
  76535. if (selectorPosition === 'end') {
  76536. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  76537. }
  76538. else {
  76539. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  76540. }
  76541. //Always align selector to content as 'middle'
  76542. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  76543. selectorGroup.attr('position', selectorPos);
  76544. contentGroup.attr('position', contentPos);
  76545. var mainRect = {x: 0, y: 0};
  76546. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  76547. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  76548. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  76549. return mainRect;
  76550. }
  76551. else {
  76552. contentGroup.attr('position', contentPos);
  76553. return this.group.getBoundingRect();
  76554. }
  76555. },
  76556. /**
  76557. * @protected
  76558. */
  76559. remove: function () {
  76560. this.getContentGroup().removeAll();
  76561. this._isFirstRender = true;
  76562. }
  76563. });
  76564. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  76565. var itemStyle;
  76566. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  76567. itemStyle = legendModelItemStyle.getItemStyle();
  76568. symbol.style.stroke = borderColor;
  76569. if (!isSelected) {
  76570. itemStyle.stroke = inactiveBorderColor;
  76571. }
  76572. }
  76573. else {
  76574. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  76575. }
  76576. return symbol.setStyle(itemStyle);
  76577. }
  76578. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  76579. // downplay before unselect
  76580. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  76581. api.dispatchAction({
  76582. type: 'legendToggleSelect',
  76583. name: seriesName != null ? seriesName : dataName
  76584. });
  76585. // highlight after select
  76586. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  76587. }
  76588. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  76589. // If element hover will move to a hoverLayer.
  76590. var el = api.getZr().storage.getDisplayList()[0];
  76591. if (!(el && el.useHoverLayer)) {
  76592. api.dispatchAction({
  76593. type: 'highlight',
  76594. seriesName: seriesName,
  76595. name: dataName,
  76596. excludeSeriesId: excludeSeriesId
  76597. });
  76598. }
  76599. }
  76600. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  76601. // If element hover will move to a hoverLayer.
  76602. var el = api.getZr().storage.getDisplayList()[0];
  76603. if (!(el && el.useHoverLayer)) {
  76604. api.dispatchAction({
  76605. type: 'downplay',
  76606. seriesName: seriesName,
  76607. name: dataName,
  76608. excludeSeriesId: excludeSeriesId
  76609. });
  76610. }
  76611. }
  76612. /*
  76613. * Licensed to the Apache Software Foundation (ASF) under one
  76614. * or more contributor license agreements. See the NOTICE file
  76615. * distributed with this work for additional information
  76616. * regarding copyright ownership. The ASF licenses this file
  76617. * to you under the Apache License, Version 2.0 (the
  76618. * "License"); you may not use this file except in compliance
  76619. * with the License. You may obtain a copy of the License at
  76620. *
  76621. * http://www.apache.org/licenses/LICENSE-2.0
  76622. *
  76623. * Unless required by applicable law or agreed to in writing,
  76624. * software distributed under the License is distributed on an
  76625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76626. * KIND, either express or implied. See the License for the
  76627. * specific language governing permissions and limitations
  76628. * under the License.
  76629. */
  76630. var legendFilter = function (ecModel) {
  76631. var legendModels = ecModel.findComponents({
  76632. mainType: 'legend'
  76633. });
  76634. if (legendModels && legendModels.length) {
  76635. ecModel.filterSeries(function (series) {
  76636. // If in any legend component the status is not selected.
  76637. // Because in legend series is assumed selected when it is not in the legend data.
  76638. for (var i = 0; i < legendModels.length; i++) {
  76639. if (!legendModels[i].isSelected(series.name)) {
  76640. return false;
  76641. }
  76642. }
  76643. return true;
  76644. });
  76645. }
  76646. };
  76647. /*
  76648. * Licensed to the Apache Software Foundation (ASF) under one
  76649. * or more contributor license agreements. See the NOTICE file
  76650. * distributed with this work for additional information
  76651. * regarding copyright ownership. The ASF licenses this file
  76652. * to you under the Apache License, Version 2.0 (the
  76653. * "License"); you may not use this file except in compliance
  76654. * with the License. You may obtain a copy of the License at
  76655. *
  76656. * http://www.apache.org/licenses/LICENSE-2.0
  76657. *
  76658. * Unless required by applicable law or agreed to in writing,
  76659. * software distributed under the License is distributed on an
  76660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76661. * KIND, either express or implied. See the License for the
  76662. * specific language governing permissions and limitations
  76663. * under the License.
  76664. */
  76665. // Do not contain scrollable legend, for sake of file size.
  76666. // Series Filter
  76667. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  76668. ComponentModel.registerSubTypeDefaulter('legend', function () {
  76669. // Default 'plain' when no type specified.
  76670. return 'plain';
  76671. });
  76672. /*
  76673. * Licensed to the Apache Software Foundation (ASF) under one
  76674. * or more contributor license agreements. See the NOTICE file
  76675. * distributed with this work for additional information
  76676. * regarding copyright ownership. The ASF licenses this file
  76677. * to you under the Apache License, Version 2.0 (the
  76678. * "License"); you may not use this file except in compliance
  76679. * with the License. You may obtain a copy of the License at
  76680. *
  76681. * http://www.apache.org/licenses/LICENSE-2.0
  76682. *
  76683. * Unless required by applicable law or agreed to in writing,
  76684. * software distributed under the License is distributed on an
  76685. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76686. * KIND, either express or implied. See the License for the
  76687. * specific language governing permissions and limitations
  76688. * under the License.
  76689. */
  76690. var ScrollableLegendModel = LegendModel.extend({
  76691. type: 'legend.scroll',
  76692. /**
  76693. * @param {number} scrollDataIndex
  76694. */
  76695. setScrollDataIndex: function (scrollDataIndex) {
  76696. this.option.scrollDataIndex = scrollDataIndex;
  76697. },
  76698. defaultOption: {
  76699. scrollDataIndex: 0,
  76700. pageButtonItemGap: 5,
  76701. pageButtonGap: null,
  76702. pageButtonPosition: 'end', // 'start' or 'end'
  76703. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  76704. pageIcons: {
  76705. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  76706. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  76707. },
  76708. pageIconColor: '#2f4554',
  76709. pageIconInactiveColor: '#aaa',
  76710. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  76711. pageTextStyle: {
  76712. color: '#333'
  76713. },
  76714. animationDurationUpdate: 800
  76715. },
  76716. /**
  76717. * @override
  76718. */
  76719. init: function (option, parentModel, ecModel, extraOpt) {
  76720. var inputPositionParams = getLayoutParams(option);
  76721. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  76722. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  76723. },
  76724. /**
  76725. * @override
  76726. */
  76727. mergeOption: function (option, extraOpt) {
  76728. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  76729. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  76730. }
  76731. });
  76732. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  76733. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  76734. var orient = legendModel.getOrient();
  76735. var ignoreSize = [1, 1];
  76736. ignoreSize[orient.index] = 0;
  76737. mergeLayoutParam(target, raw, {
  76738. type: 'box', ignoreSize: ignoreSize
  76739. });
  76740. }
  76741. /*
  76742. * Licensed to the Apache Software Foundation (ASF) under one
  76743. * or more contributor license agreements. See the NOTICE file
  76744. * distributed with this work for additional information
  76745. * regarding copyright ownership. The ASF licenses this file
  76746. * to you under the Apache License, Version 2.0 (the
  76747. * "License"); you may not use this file except in compliance
  76748. * with the License. You may obtain a copy of the License at
  76749. *
  76750. * http://www.apache.org/licenses/LICENSE-2.0
  76751. *
  76752. * Unless required by applicable law or agreed to in writing,
  76753. * software distributed under the License is distributed on an
  76754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76755. * KIND, either express or implied. See the License for the
  76756. * specific language governing permissions and limitations
  76757. * under the License.
  76758. */
  76759. /**
  76760. * Separate legend and scrollable legend to reduce package size.
  76761. */
  76762. var Group$4 = Group;
  76763. var WH$1 = ['width', 'height'];
  76764. var XY$1 = ['x', 'y'];
  76765. var ScrollableLegendView = LegendView.extend({
  76766. type: 'legend.scroll',
  76767. newlineDisabled: true,
  76768. init: function () {
  76769. ScrollableLegendView.superCall(this, 'init');
  76770. /**
  76771. * @private
  76772. * @type {number} For `scroll`.
  76773. */
  76774. this._currentIndex = 0;
  76775. /**
  76776. * @private
  76777. * @type {module:zrender/container/Group}
  76778. */
  76779. this.group.add(this._containerGroup = new Group$4());
  76780. this._containerGroup.add(this.getContentGroup());
  76781. /**
  76782. * @private
  76783. * @type {module:zrender/container/Group}
  76784. */
  76785. this.group.add(this._controllerGroup = new Group$4());
  76786. /**
  76787. *
  76788. * @private
  76789. */
  76790. this._showController;
  76791. },
  76792. /**
  76793. * @override
  76794. */
  76795. resetInner: function () {
  76796. ScrollableLegendView.superCall(this, 'resetInner');
  76797. this._controllerGroup.removeAll();
  76798. this._containerGroup.removeClipPath();
  76799. this._containerGroup.__rectSize = null;
  76800. },
  76801. /**
  76802. * @override
  76803. */
  76804. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76805. var me = this;
  76806. // Render content items.
  76807. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  76808. legendModel, ecModel, api, selector, orient, selectorPosition);
  76809. var controllerGroup = this._controllerGroup;
  76810. // FIXME: support be 'auto' adapt to size number text length,
  76811. // e.g., '3/12345' should not overlap with the control arrow button.
  76812. var pageIconSize = legendModel.get('pageIconSize', true);
  76813. if (!isArray(pageIconSize)) {
  76814. pageIconSize = [pageIconSize, pageIconSize];
  76815. }
  76816. createPageButton('pagePrev', 0);
  76817. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  76818. controllerGroup.add(new Text({
  76819. name: 'pageText',
  76820. style: {
  76821. textFill: pageTextStyleModel.getTextColor(),
  76822. font: pageTextStyleModel.getFont(),
  76823. textVerticalAlign: 'middle',
  76824. textAlign: 'center'
  76825. },
  76826. silent: true
  76827. }));
  76828. createPageButton('pageNext', 1);
  76829. function createPageButton(name, iconIdx) {
  76830. var pageDataIndexName = name + 'DataIndex';
  76831. var icon = createIcon(
  76832. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  76833. {
  76834. // Buttons will be created in each render, so we do not need
  76835. // to worry about avoiding using legendModel kept in scope.
  76836. onclick: bind(
  76837. me._pageGo, me, pageDataIndexName, legendModel, api
  76838. )
  76839. },
  76840. {
  76841. x: -pageIconSize[0] / 2,
  76842. y: -pageIconSize[1] / 2,
  76843. width: pageIconSize[0],
  76844. height: pageIconSize[1]
  76845. }
  76846. );
  76847. icon.name = name;
  76848. controllerGroup.add(icon);
  76849. }
  76850. },
  76851. /**
  76852. * @override
  76853. */
  76854. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76855. var selectorGroup = this.getSelectorGroup();
  76856. var orientIdx = legendModel.getOrient().index;
  76857. var wh = WH$1[orientIdx];
  76858. var xy = XY$1[orientIdx];
  76859. var hw = WH$1[1 - orientIdx];
  76860. var yx = XY$1[1 - orientIdx];
  76861. selector && box(
  76862. // Buttons in selectorGroup always layout horizontally
  76863. 'horizontal',
  76864. selectorGroup,
  76865. legendModel.get('selectorItemGap', true)
  76866. );
  76867. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76868. var selectorRect = selectorGroup.getBoundingRect();
  76869. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76870. var processMaxSize = clone(maxSize);
  76871. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  76872. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  76873. processMaxSize, orientIdx, wh, hw, yx
  76874. );
  76875. if (selector) {
  76876. if (selectorPosition === 'end') {
  76877. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  76878. }
  76879. else {
  76880. var offset = selectorRect[wh] + selectorButtonGap;
  76881. selectorPos[orientIdx] -= offset;
  76882. mainRect[xy] -= offset;
  76883. }
  76884. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  76885. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  76886. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  76887. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  76888. selectorGroup.attr('position', selectorPos);
  76889. }
  76890. return mainRect;
  76891. },
  76892. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  76893. var contentGroup = this.getContentGroup();
  76894. var containerGroup = this._containerGroup;
  76895. var controllerGroup = this._controllerGroup;
  76896. // Place items in contentGroup.
  76897. box(
  76898. legendModel.get('orient'),
  76899. contentGroup,
  76900. legendModel.get('itemGap'),
  76901. !orientIdx ? null : maxSize.width,
  76902. orientIdx ? null : maxSize.height
  76903. );
  76904. box(
  76905. // Buttons in controller are layout always horizontally.
  76906. 'horizontal',
  76907. controllerGroup,
  76908. legendModel.get('pageButtonItemGap', true)
  76909. );
  76910. var contentRect = contentGroup.getBoundingRect();
  76911. var controllerRect = controllerGroup.getBoundingRect();
  76912. var showController = this._showController = contentRect[wh] > maxSize[wh];
  76913. var contentPos = [-contentRect.x, -contentRect.y];
  76914. // Remain contentPos when scroll animation perfroming.
  76915. // If first rendering, `contentGroup.position` is [0, 0], which
  76916. // does not make sense and may cause unexepcted animation if adopted.
  76917. if (!isFirstRender) {
  76918. contentPos[orientIdx] = contentGroup.position[orientIdx];
  76919. }
  76920. // Layout container group based on 0.
  76921. var containerPos = [0, 0];
  76922. var controllerPos = [-controllerRect.x, -controllerRect.y];
  76923. var pageButtonGap = retrieve2(
  76924. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  76925. );
  76926. // Place containerGroup and controllerGroup and contentGroup.
  76927. if (showController) {
  76928. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  76929. // controller is on the right / bottom.
  76930. if (pageButtonPosition === 'end') {
  76931. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  76932. }
  76933. // controller is on the left / top.
  76934. else {
  76935. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  76936. }
  76937. }
  76938. // Always align controller to content as 'middle'.
  76939. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  76940. contentGroup.attr('position', contentPos);
  76941. containerGroup.attr('position', containerPos);
  76942. controllerGroup.attr('position', controllerPos);
  76943. // Calculate `mainRect` and set `clipPath`.
  76944. // mainRect should not be calculated by `this.group.getBoundingRect()`
  76945. // for sake of the overflow.
  76946. var mainRect = {x: 0, y: 0};
  76947. // Consider content may be overflow (should be clipped).
  76948. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  76949. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  76950. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  76951. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  76952. containerGroup.__rectSize = maxSize[wh];
  76953. if (showController) {
  76954. var clipShape = {x: 0, y: 0};
  76955. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  76956. clipShape[hw] = mainRect[hw];
  76957. containerGroup.setClipPath(new Rect({shape: clipShape}));
  76958. // Consider content may be larger than container, container rect
  76959. // can not be obtained from `containerGroup.getBoundingRect()`.
  76960. containerGroup.__rectSize = clipShape[wh];
  76961. }
  76962. else {
  76963. // Do not remove or ignore controller. Keep them set as placeholders.
  76964. controllerGroup.eachChild(function (child) {
  76965. child.attr({invisible: true, silent: true});
  76966. });
  76967. }
  76968. // Content translate animation.
  76969. var pageInfo = this._getPageInfo(legendModel);
  76970. pageInfo.pageIndex != null && updateProps(
  76971. contentGroup,
  76972. {position: pageInfo.contentPosition},
  76973. // When switch from "show controller" to "not show controller", view should be
  76974. // updated immediately without animation, otherwise causes weird effect.
  76975. showController ? legendModel : false
  76976. );
  76977. this._updatePageInfoView(legendModel, pageInfo);
  76978. return mainRect;
  76979. },
  76980. _pageGo: function (to, legendModel, api) {
  76981. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  76982. scrollDataIndex != null && api.dispatchAction({
  76983. type: 'legendScroll',
  76984. scrollDataIndex: scrollDataIndex,
  76985. legendId: legendModel.id
  76986. });
  76987. },
  76988. _updatePageInfoView: function (legendModel, pageInfo) {
  76989. var controllerGroup = this._controllerGroup;
  76990. each$1(['pagePrev', 'pageNext'], function (name) {
  76991. var canJump = pageInfo[name + 'DataIndex'] != null;
  76992. var icon = controllerGroup.childOfName(name);
  76993. if (icon) {
  76994. icon.setStyle(
  76995. 'fill',
  76996. canJump
  76997. ? legendModel.get('pageIconColor', true)
  76998. : legendModel.get('pageIconInactiveColor', true)
  76999. );
  77000. icon.cursor = canJump ? 'pointer' : 'default';
  77001. }
  77002. });
  77003. var pageText = controllerGroup.childOfName('pageText');
  77004. var pageFormatter = legendModel.get('pageFormatter');
  77005. var pageIndex = pageInfo.pageIndex;
  77006. var current = pageIndex != null ? pageIndex + 1 : 0;
  77007. var total = pageInfo.pageCount;
  77008. pageText && pageFormatter && pageText.setStyle(
  77009. 'text',
  77010. isString(pageFormatter)
  77011. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  77012. : pageFormatter({current: current, total: total})
  77013. );
  77014. },
  77015. /**
  77016. * @param {module:echarts/model/Model} legendModel
  77017. * @return {Object} {
  77018. * contentPosition: Array.<number>, null when data item not found.
  77019. * pageIndex: number, null when data item not found.
  77020. * pageCount: number, always be a number, can be 0.
  77021. * pagePrevDataIndex: number, null when no previous page.
  77022. * pageNextDataIndex: number, null when no next page.
  77023. * }
  77024. */
  77025. _getPageInfo: function (legendModel) {
  77026. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  77027. var contentGroup = this.getContentGroup();
  77028. var containerRectSize = this._containerGroup.__rectSize;
  77029. var orientIdx = legendModel.getOrient().index;
  77030. var wh = WH$1[orientIdx];
  77031. var xy = XY$1[orientIdx];
  77032. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  77033. var children = contentGroup.children();
  77034. var targetItem = children[targetItemIndex];
  77035. var itemCount = children.length;
  77036. var pCount = !itemCount ? 0 : 1;
  77037. var result = {
  77038. contentPosition: contentGroup.position.slice(),
  77039. pageCount: pCount,
  77040. pageIndex: pCount - 1,
  77041. pagePrevDataIndex: null,
  77042. pageNextDataIndex: null
  77043. };
  77044. if (!targetItem) {
  77045. return result;
  77046. }
  77047. var targetItemInfo = getItemInfo(targetItem);
  77048. result.contentPosition[orientIdx] = -targetItemInfo.s;
  77049. // Strategy:
  77050. // (1) Always align based on the left/top most item.
  77051. // (2) It is user-friendly that the last item shown in the
  77052. // current window is shown at the begining of next window.
  77053. // Otherwise if half of the last item is cut by the window,
  77054. // it will have no chance to display entirely.
  77055. // (3) Consider that item size probably be different, we
  77056. // have calculate pageIndex by size rather than item index,
  77057. // and we can not get page index directly by division.
  77058. // (4) The window is to narrow to contain more than
  77059. // one item, we should make sure that the page can be fliped.
  77060. for (var i = targetItemIndex + 1,
  77061. winStartItemInfo = targetItemInfo,
  77062. winEndItemInfo = targetItemInfo,
  77063. currItemInfo = null;
  77064. i <= itemCount;
  77065. ++i
  77066. ) {
  77067. currItemInfo = getItemInfo(children[i]);
  77068. if (
  77069. // Half of the last item is out of the window.
  77070. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  77071. // If the current item does not intersect with the window, the new page
  77072. // can be started at the current item or the last item.
  77073. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  77074. ) {
  77075. if (winEndItemInfo.i > winStartItemInfo.i) {
  77076. winStartItemInfo = winEndItemInfo;
  77077. }
  77078. else { // e.g., when page size is smaller than item size.
  77079. winStartItemInfo = currItemInfo;
  77080. }
  77081. if (winStartItemInfo) {
  77082. if (result.pageNextDataIndex == null) {
  77083. result.pageNextDataIndex = winStartItemInfo.i;
  77084. }
  77085. ++result.pageCount;
  77086. }
  77087. }
  77088. winEndItemInfo = currItemInfo;
  77089. }
  77090. for (var i = targetItemIndex - 1,
  77091. winStartItemInfo = targetItemInfo,
  77092. winEndItemInfo = targetItemInfo,
  77093. currItemInfo = null;
  77094. i >= -1;
  77095. --i
  77096. ) {
  77097. currItemInfo = getItemInfo(children[i]);
  77098. if (
  77099. // If the the end item does not intersect with the window started
  77100. // from the current item, a page can be settled.
  77101. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  77102. // e.g., when page size is smaller than item size.
  77103. && winStartItemInfo.i < winEndItemInfo.i
  77104. ) {
  77105. winEndItemInfo = winStartItemInfo;
  77106. if (result.pagePrevDataIndex == null) {
  77107. result.pagePrevDataIndex = winStartItemInfo.i;
  77108. }
  77109. ++result.pageCount;
  77110. ++result.pageIndex;
  77111. }
  77112. winStartItemInfo = currItemInfo;
  77113. }
  77114. return result;
  77115. function getItemInfo(el) {
  77116. if (el) {
  77117. var itemRect = el.getBoundingRect();
  77118. var start = itemRect[xy] + el.position[orientIdx];
  77119. return {
  77120. s: start,
  77121. e: start + itemRect[wh],
  77122. i: el.__legendDataIndex
  77123. };
  77124. }
  77125. }
  77126. function intersect(itemInfo, winStart) {
  77127. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  77128. }
  77129. },
  77130. _findTargetItemIndex: function (targetDataIndex) {
  77131. var index;
  77132. var contentGroup = this.getContentGroup();
  77133. var defaultIndex;
  77134. if (this._showController) {
  77135. contentGroup.eachChild(function (child, idx) {
  77136. var legendDataIdx = child.__legendDataIndex;
  77137. // FIXME
  77138. // If the given targetDataIndex (from model) is illegal,
  77139. // we use defualtIndex. But the index on the legend model and
  77140. // action payload is still illegal. That case will not be
  77141. // changed until some scenario requires.
  77142. if (defaultIndex == null && legendDataIdx != null) {
  77143. defaultIndex = idx;
  77144. }
  77145. if (legendDataIdx === targetDataIndex) {
  77146. index = idx;
  77147. }
  77148. });
  77149. }
  77150. return index != null ? index : defaultIndex;
  77151. }
  77152. });
  77153. /*
  77154. * Licensed to the Apache Software Foundation (ASF) under one
  77155. * or more contributor license agreements. See the NOTICE file
  77156. * distributed with this work for additional information
  77157. * regarding copyright ownership. The ASF licenses this file
  77158. * to you under the Apache License, Version 2.0 (the
  77159. * "License"); you may not use this file except in compliance
  77160. * with the License. You may obtain a copy of the License at
  77161. *
  77162. * http://www.apache.org/licenses/LICENSE-2.0
  77163. *
  77164. * Unless required by applicable law or agreed to in writing,
  77165. * software distributed under the License is distributed on an
  77166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77167. * KIND, either express or implied. See the License for the
  77168. * specific language governing permissions and limitations
  77169. * under the License.
  77170. */
  77171. /**
  77172. * @event legendScroll
  77173. * @type {Object}
  77174. * @property {string} type 'legendScroll'
  77175. * @property {string} scrollDataIndex
  77176. */
  77177. registerAction(
  77178. 'legendScroll', 'legendscroll',
  77179. function (payload, ecModel) {
  77180. var scrollDataIndex = payload.scrollDataIndex;
  77181. scrollDataIndex != null && ecModel.eachComponent(
  77182. {mainType: 'legend', subType: 'scroll', query: payload},
  77183. function (legendModel) {
  77184. legendModel.setScrollDataIndex(scrollDataIndex);
  77185. }
  77186. );
  77187. }
  77188. );
  77189. /*
  77190. * Licensed to the Apache Software Foundation (ASF) under one
  77191. * or more contributor license agreements. See the NOTICE file
  77192. * distributed with this work for additional information
  77193. * regarding copyright ownership. The ASF licenses this file
  77194. * to you under the Apache License, Version 2.0 (the
  77195. * "License"); you may not use this file except in compliance
  77196. * with the License. You may obtain a copy of the License at
  77197. *
  77198. * http://www.apache.org/licenses/LICENSE-2.0
  77199. *
  77200. * Unless required by applicable law or agreed to in writing,
  77201. * software distributed under the License is distributed on an
  77202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77203. * KIND, either express or implied. See the License for the
  77204. * specific language governing permissions and limitations
  77205. * under the License.
  77206. */
  77207. /**
  77208. * Legend component entry file8
  77209. */
  77210. /*
  77211. * Licensed to the Apache Software Foundation (ASF) under one
  77212. * or more contributor license agreements. See the NOTICE file
  77213. * distributed with this work for additional information
  77214. * regarding copyright ownership. The ASF licenses this file
  77215. * to you under the Apache License, Version 2.0 (the
  77216. * "License"); you may not use this file except in compliance
  77217. * with the License. You may obtain a copy of the License at
  77218. *
  77219. * http://www.apache.org/licenses/LICENSE-2.0
  77220. *
  77221. * Unless required by applicable law or agreed to in writing,
  77222. * software distributed under the License is distributed on an
  77223. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77224. * KIND, either express or implied. See the License for the
  77225. * specific language governing permissions and limitations
  77226. * under the License.
  77227. */
  77228. var SliderZoomModel = DataZoomModel.extend({
  77229. type: 'dataZoom.slider',
  77230. layoutMode: 'box',
  77231. /**
  77232. * @protected
  77233. */
  77234. defaultOption: {
  77235. show: true,
  77236. // ph => placeholder. Using placehoder here because
  77237. // deault value can only be drived in view stage.
  77238. right: 'ph', // Default align to grid rect.
  77239. top: 'ph', // Default align to grid rect.
  77240. width: 'ph', // Default align to grid rect.
  77241. height: 'ph', // Default align to grid rect.
  77242. left: null, // Default align to grid rect.
  77243. bottom: null, // Default align to grid rect.
  77244. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  77245. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  77246. // highest priority, remain for compatibility of
  77247. // previous version, but not recommended any more.
  77248. dataBackground: {
  77249. lineStyle: {
  77250. color: '#2f4554',
  77251. width: 0.5,
  77252. opacity: 0.3
  77253. },
  77254. areaStyle: {
  77255. color: 'rgba(47,69,84,0.3)',
  77256. opacity: 0.3
  77257. }
  77258. },
  77259. borderColor: '#ddd', // border color of the box. For compatibility,
  77260. // if dataBackgroundColor is set, borderColor
  77261. // is ignored.
  77262. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  77263. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  77264. // 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',
  77265. /* eslint-disable */
  77266. 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',
  77267. /* eslint-enable */
  77268. // Percent of the slider height
  77269. handleSize: '100%',
  77270. handleStyle: {
  77271. color: '#a7b7cc'
  77272. },
  77273. labelPrecision: null,
  77274. labelFormatter: null,
  77275. showDetail: true,
  77276. showDataShadow: 'auto', // Default auto decision.
  77277. realtime: true,
  77278. zoomLock: false, // Whether disable zoom.
  77279. textStyle: {
  77280. color: '#333'
  77281. }
  77282. }
  77283. });
  77284. /*
  77285. * Licensed to the Apache Software Foundation (ASF) under one
  77286. * or more contributor license agreements. See the NOTICE file
  77287. * distributed with this work for additional information
  77288. * regarding copyright ownership. The ASF licenses this file
  77289. * to you under the Apache License, Version 2.0 (the
  77290. * "License"); you may not use this file except in compliance
  77291. * with the License. You may obtain a copy of the License at
  77292. *
  77293. * http://www.apache.org/licenses/LICENSE-2.0
  77294. *
  77295. * Unless required by applicable law or agreed to in writing,
  77296. * software distributed under the License is distributed on an
  77297. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77298. * KIND, either express or implied. See the License for the
  77299. * specific language governing permissions and limitations
  77300. * under the License.
  77301. */
  77302. var Rect$2 = Rect;
  77303. var linearMap$1 = linearMap;
  77304. var asc$2 = asc;
  77305. var bind$5 = bind;
  77306. var each$26 = each$1;
  77307. // Constants
  77308. var DEFAULT_LOCATION_EDGE_GAP = 7;
  77309. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  77310. var DEFAULT_FILLER_SIZE = 30;
  77311. var HORIZONTAL = 'horizontal';
  77312. var VERTICAL = 'vertical';
  77313. var LABEL_GAP = 5;
  77314. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  77315. var SliderZoomView = DataZoomView.extend({
  77316. type: 'dataZoom.slider',
  77317. init: function (ecModel, api) {
  77318. /**
  77319. * @private
  77320. * @type {Object}
  77321. */
  77322. this._displayables = {};
  77323. /**
  77324. * @private
  77325. * @type {string}
  77326. */
  77327. this._orient;
  77328. /**
  77329. * [0, 100]
  77330. * @private
  77331. */
  77332. this._range;
  77333. /**
  77334. * [coord of the first handle, coord of the second handle]
  77335. * @private
  77336. */
  77337. this._handleEnds;
  77338. /**
  77339. * [length, thick]
  77340. * @private
  77341. * @type {Array.<number>}
  77342. */
  77343. this._size;
  77344. /**
  77345. * @private
  77346. * @type {number}
  77347. */
  77348. this._handleWidth;
  77349. /**
  77350. * @private
  77351. * @type {number}
  77352. */
  77353. this._handleHeight;
  77354. /**
  77355. * @private
  77356. */
  77357. this._location;
  77358. /**
  77359. * @private
  77360. */
  77361. this._dragging;
  77362. /**
  77363. * @private
  77364. */
  77365. this._dataShadowInfo;
  77366. this.api = api;
  77367. },
  77368. /**
  77369. * @override
  77370. */
  77371. render: function (dataZoomModel, ecModel, api, payload) {
  77372. SliderZoomView.superApply(this, 'render', arguments);
  77373. createOrUpdate(
  77374. this,
  77375. '_dispatchZoomAction',
  77376. this.dataZoomModel.get('throttle'),
  77377. 'fixRate'
  77378. );
  77379. this._orient = dataZoomModel.get('orient');
  77380. if (this.dataZoomModel.get('show') === false) {
  77381. this.group.removeAll();
  77382. return;
  77383. }
  77384. // Notice: this._resetInterval() should not be executed when payload.type
  77385. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  77386. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  77387. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  77388. this._buildView();
  77389. }
  77390. this._updateView();
  77391. },
  77392. /**
  77393. * @override
  77394. */
  77395. remove: function () {
  77396. SliderZoomView.superApply(this, 'remove', arguments);
  77397. clear(this, '_dispatchZoomAction');
  77398. },
  77399. /**
  77400. * @override
  77401. */
  77402. dispose: function () {
  77403. SliderZoomView.superApply(this, 'dispose', arguments);
  77404. clear(this, '_dispatchZoomAction');
  77405. },
  77406. _buildView: function () {
  77407. var thisGroup = this.group;
  77408. thisGroup.removeAll();
  77409. this._resetLocation();
  77410. this._resetInterval();
  77411. var barGroup = this._displayables.barGroup = new Group();
  77412. this._renderBackground();
  77413. this._renderHandle();
  77414. this._renderDataShadow();
  77415. thisGroup.add(barGroup);
  77416. this._positionGroup();
  77417. },
  77418. /**
  77419. * @private
  77420. */
  77421. _resetLocation: function () {
  77422. var dataZoomModel = this.dataZoomModel;
  77423. var api = this.api;
  77424. // If some of x/y/width/height are not specified,
  77425. // auto-adapt according to target grid.
  77426. var coordRect = this._findCoordRect();
  77427. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  77428. // Default align by coordinate system rect.
  77429. var positionInfo = this._orient === HORIZONTAL
  77430. ? {
  77431. // Why using 'right', because right should be used in vertical,
  77432. // and it is better to be consistent for dealing with position param merge.
  77433. right: ecSize.width - coordRect.x - coordRect.width,
  77434. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  77435. width: coordRect.width,
  77436. height: DEFAULT_FILLER_SIZE
  77437. }
  77438. : { // vertical
  77439. right: DEFAULT_LOCATION_EDGE_GAP,
  77440. top: coordRect.y,
  77441. width: DEFAULT_FILLER_SIZE,
  77442. height: coordRect.height
  77443. };
  77444. // Do not write back to option and replace value 'ph', because
  77445. // the 'ph' value should be recalculated when resize.
  77446. var layoutParams = getLayoutParams(dataZoomModel.option);
  77447. // Replace the placeholder value.
  77448. each$1(['right', 'top', 'width', 'height'], function (name) {
  77449. if (layoutParams[name] === 'ph') {
  77450. layoutParams[name] = positionInfo[name];
  77451. }
  77452. });
  77453. var layoutRect = getLayoutRect(
  77454. layoutParams,
  77455. ecSize,
  77456. dataZoomModel.padding
  77457. );
  77458. this._location = {x: layoutRect.x, y: layoutRect.y};
  77459. this._size = [layoutRect.width, layoutRect.height];
  77460. this._orient === VERTICAL && this._size.reverse();
  77461. },
  77462. /**
  77463. * @private
  77464. */
  77465. _positionGroup: function () {
  77466. var thisGroup = this.group;
  77467. var location = this._location;
  77468. var orient = this._orient;
  77469. // Just use the first axis to determine mapping.
  77470. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  77471. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  77472. var barGroup = this._displayables.barGroup;
  77473. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  77474. // Transform barGroup.
  77475. barGroup.attr(
  77476. (orient === HORIZONTAL && !inverse)
  77477. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  77478. : (orient === HORIZONTAL && inverse)
  77479. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  77480. : (orient === VERTICAL && !inverse)
  77481. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  77482. // Dont use Math.PI, considering shadow direction.
  77483. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  77484. );
  77485. // Position barGroup
  77486. var rect = thisGroup.getBoundingRect([barGroup]);
  77487. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  77488. },
  77489. /**
  77490. * @private
  77491. */
  77492. _getViewExtent: function () {
  77493. return [0, this._size[0]];
  77494. },
  77495. _renderBackground: function () {
  77496. var dataZoomModel = this.dataZoomModel;
  77497. var size = this._size;
  77498. var barGroup = this._displayables.barGroup;
  77499. barGroup.add(new Rect$2({
  77500. silent: true,
  77501. shape: {
  77502. x: 0, y: 0, width: size[0], height: size[1]
  77503. },
  77504. style: {
  77505. fill: dataZoomModel.get('backgroundColor')
  77506. },
  77507. z2: -40
  77508. }));
  77509. // Click panel, over shadow, below handles.
  77510. barGroup.add(new Rect$2({
  77511. shape: {
  77512. x: 0, y: 0, width: size[0], height: size[1]
  77513. },
  77514. style: {
  77515. fill: 'transparent'
  77516. },
  77517. z2: 0,
  77518. onclick: bind(this._onClickPanelClick, this)
  77519. }));
  77520. },
  77521. _renderDataShadow: function () {
  77522. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  77523. if (!info) {
  77524. return;
  77525. }
  77526. var size = this._size;
  77527. var seriesModel = info.series;
  77528. var data = seriesModel.getRawData();
  77529. var otherDim = seriesModel.getShadowDim
  77530. ? seriesModel.getShadowDim() // @see candlestick
  77531. : info.otherDim;
  77532. if (otherDim == null) {
  77533. return;
  77534. }
  77535. var otherDataExtent = data.getDataExtent(otherDim);
  77536. // Nice extent.
  77537. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  77538. otherDataExtent = [
  77539. otherDataExtent[0] - otherOffset,
  77540. otherDataExtent[1] + otherOffset
  77541. ];
  77542. var otherShadowExtent = [0, size[1]];
  77543. var thisShadowExtent = [0, size[0]];
  77544. var areaPoints = [[size[0], 0], [0, 0]];
  77545. var linePoints = [];
  77546. var step = thisShadowExtent[1] / (data.count() - 1);
  77547. var thisCoord = 0;
  77548. // Optimize for large data shadow
  77549. var stride = Math.round(data.count() / size[0]);
  77550. var lastIsEmpty;
  77551. data.each([otherDim], function (value, index) {
  77552. if (stride > 0 && (index % stride)) {
  77553. thisCoord += step;
  77554. return;
  77555. }
  77556. // FIXME
  77557. // Should consider axis.min/axis.max when drawing dataShadow.
  77558. // FIXME
  77559. // 应该使用统一的空判断?还是在list里进行空判断?
  77560. var isEmpty = value == null || isNaN(value) || value === '';
  77561. // See #4235.
  77562. var otherCoord = isEmpty
  77563. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  77564. // Attempt to draw data shadow precisely when there are empty value.
  77565. if (isEmpty && !lastIsEmpty && index) {
  77566. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  77567. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  77568. }
  77569. else if (!isEmpty && lastIsEmpty) {
  77570. areaPoints.push([thisCoord, 0]);
  77571. linePoints.push([thisCoord, 0]);
  77572. }
  77573. areaPoints.push([thisCoord, otherCoord]);
  77574. linePoints.push([thisCoord, otherCoord]);
  77575. thisCoord += step;
  77576. lastIsEmpty = isEmpty;
  77577. });
  77578. var dataZoomModel = this.dataZoomModel;
  77579. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  77580. this._displayables.barGroup.add(new Polygon({
  77581. shape: {points: areaPoints},
  77582. style: defaults(
  77583. {fill: dataZoomModel.get('dataBackgroundColor')},
  77584. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  77585. ),
  77586. silent: true,
  77587. z2: -20
  77588. }));
  77589. this._displayables.barGroup.add(new Polyline({
  77590. shape: {points: linePoints},
  77591. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  77592. silent: true,
  77593. z2: -19
  77594. }));
  77595. },
  77596. _prepareDataShadowInfo: function () {
  77597. var dataZoomModel = this.dataZoomModel;
  77598. var showDataShadow = dataZoomModel.get('showDataShadow');
  77599. if (showDataShadow === false) {
  77600. return;
  77601. }
  77602. // Find a representative series.
  77603. var result;
  77604. var ecModel = this.ecModel;
  77605. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  77606. var seriesModels = dataZoomModel
  77607. .getAxisProxy(dimNames.name, axisIndex)
  77608. .getTargetSeriesModels();
  77609. each$1(seriesModels, function (seriesModel) {
  77610. if (result) {
  77611. return;
  77612. }
  77613. if (showDataShadow !== true && indexOf(
  77614. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  77615. ) < 0
  77616. ) {
  77617. return;
  77618. }
  77619. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  77620. var otherDim = getOtherDim(dimNames.name);
  77621. var otherAxisInverse;
  77622. var coordSys = seriesModel.coordinateSystem;
  77623. if (otherDim != null && coordSys.getOtherAxis) {
  77624. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  77625. }
  77626. otherDim = seriesModel.getData().mapDimension(otherDim);
  77627. result = {
  77628. thisAxis: thisAxis,
  77629. series: seriesModel,
  77630. thisDim: dimNames.name,
  77631. otherDim: otherDim,
  77632. otherAxisInverse: otherAxisInverse
  77633. };
  77634. }, this);
  77635. }, this);
  77636. return result;
  77637. },
  77638. _renderHandle: function () {
  77639. var displaybles = this._displayables;
  77640. var handles = displaybles.handles = [];
  77641. var handleLabels = displaybles.handleLabels = [];
  77642. var barGroup = this._displayables.barGroup;
  77643. var size = this._size;
  77644. var dataZoomModel = this.dataZoomModel;
  77645. barGroup.add(displaybles.filler = new Rect$2({
  77646. draggable: true,
  77647. cursor: getCursor(this._orient),
  77648. drift: bind$5(this._onDragMove, this, 'all'),
  77649. ondragstart: bind$5(this._showDataInfo, this, true),
  77650. ondragend: bind$5(this._onDragEnd, this),
  77651. onmouseover: bind$5(this._showDataInfo, this, true),
  77652. onmouseout: bind$5(this._showDataInfo, this, false),
  77653. style: {
  77654. fill: dataZoomModel.get('fillerColor'),
  77655. textPosition: 'inside'
  77656. }
  77657. }));
  77658. // Frame border.
  77659. barGroup.add(new Rect$2({
  77660. silent: true,
  77661. subPixelOptimize: true,
  77662. shape: {
  77663. x: 0,
  77664. y: 0,
  77665. width: size[0],
  77666. height: size[1]
  77667. },
  77668. style: {
  77669. stroke: dataZoomModel.get('dataBackgroundColor')
  77670. || dataZoomModel.get('borderColor'),
  77671. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  77672. fill: 'rgba(0,0,0,0)'
  77673. }
  77674. }));
  77675. each$26([0, 1], function (handleIndex) {
  77676. var path = createIcon(
  77677. dataZoomModel.get('handleIcon'),
  77678. {
  77679. cursor: getCursor(this._orient),
  77680. draggable: true,
  77681. drift: bind$5(this._onDragMove, this, handleIndex),
  77682. ondragend: bind$5(this._onDragEnd, this),
  77683. onmouseover: bind$5(this._showDataInfo, this, true),
  77684. onmouseout: bind$5(this._showDataInfo, this, false)
  77685. },
  77686. {x: -1, y: 0, width: 2, height: 2}
  77687. );
  77688. var bRect = path.getBoundingRect();
  77689. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  77690. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  77691. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  77692. var handleColor = dataZoomModel.get('handleColor');
  77693. // Compatitable with previous version
  77694. if (handleColor != null) {
  77695. path.style.fill = handleColor;
  77696. }
  77697. barGroup.add(handles[handleIndex] = path);
  77698. var textStyleModel = dataZoomModel.textStyleModel;
  77699. this.group.add(
  77700. handleLabels[handleIndex] = new Text({
  77701. silent: true,
  77702. invisible: true,
  77703. style: {
  77704. x: 0, y: 0, text: '',
  77705. textVerticalAlign: 'middle',
  77706. textAlign: 'center',
  77707. textFill: textStyleModel.getTextColor(),
  77708. textFont: textStyleModel.getFont()
  77709. },
  77710. z2: 10
  77711. }));
  77712. }, this);
  77713. },
  77714. /**
  77715. * @private
  77716. */
  77717. _resetInterval: function () {
  77718. var range = this._range = this.dataZoomModel.getPercentRange();
  77719. var viewExtent = this._getViewExtent();
  77720. this._handleEnds = [
  77721. linearMap$1(range[0], [0, 100], viewExtent, true),
  77722. linearMap$1(range[1], [0, 100], viewExtent, true)
  77723. ];
  77724. },
  77725. /**
  77726. * @private
  77727. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  77728. * @param {number} delta
  77729. * @return {boolean} changed
  77730. */
  77731. _updateInterval: function (handleIndex, delta) {
  77732. var dataZoomModel = this.dataZoomModel;
  77733. var handleEnds = this._handleEnds;
  77734. var viewExtend = this._getViewExtent();
  77735. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77736. var percentExtent = [0, 100];
  77737. sliderMove(
  77738. delta,
  77739. handleEnds,
  77740. viewExtend,
  77741. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  77742. minMaxSpan.minSpan != null
  77743. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  77744. minMaxSpan.maxSpan != null
  77745. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  77746. );
  77747. var lastRange = this._range;
  77748. var range = this._range = asc$2([
  77749. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  77750. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  77751. ]);
  77752. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  77753. },
  77754. /**
  77755. * @private
  77756. */
  77757. _updateView: function (nonRealtime) {
  77758. var displaybles = this._displayables;
  77759. var handleEnds = this._handleEnds;
  77760. var handleInterval = asc$2(handleEnds.slice());
  77761. var size = this._size;
  77762. each$26([0, 1], function (handleIndex) {
  77763. // Handles
  77764. var handle = displaybles.handles[handleIndex];
  77765. var handleHeight = this._handleHeight;
  77766. handle.attr({
  77767. scale: [handleHeight / 2, handleHeight / 2],
  77768. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  77769. });
  77770. }, this);
  77771. // Filler
  77772. displaybles.filler.setShape({
  77773. x: handleInterval[0],
  77774. y: 0,
  77775. width: handleInterval[1] - handleInterval[0],
  77776. height: size[1]
  77777. });
  77778. this._updateDataInfo(nonRealtime);
  77779. },
  77780. /**
  77781. * @private
  77782. */
  77783. _updateDataInfo: function (nonRealtime) {
  77784. var dataZoomModel = this.dataZoomModel;
  77785. var displaybles = this._displayables;
  77786. var handleLabels = displaybles.handleLabels;
  77787. var orient = this._orient;
  77788. var labelTexts = ['', ''];
  77789. // FIXME
  77790. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  77791. if (dataZoomModel.get('showDetail')) {
  77792. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  77793. if (axisProxy) {
  77794. var axis = axisProxy.getAxisModel().axis;
  77795. var range = this._range;
  77796. var dataInterval = nonRealtime
  77797. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  77798. ? axisProxy.calculateDataWindow({
  77799. start: range[0], end: range[1]
  77800. }).valueWindow
  77801. : axisProxy.getDataValueWindow();
  77802. labelTexts = [
  77803. this._formatLabel(dataInterval[0], axis),
  77804. this._formatLabel(dataInterval[1], axis)
  77805. ];
  77806. }
  77807. }
  77808. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  77809. setLabel.call(this, 0);
  77810. setLabel.call(this, 1);
  77811. function setLabel(handleIndex) {
  77812. // Label
  77813. // Text should not transform by barGroup.
  77814. // Ignore handlers transform
  77815. var barTransform = getTransform(
  77816. displaybles.handles[handleIndex].parent, this.group
  77817. );
  77818. var direction = transformDirection(
  77819. handleIndex === 0 ? 'right' : 'left', barTransform
  77820. );
  77821. var offset = this._handleWidth / 2 + LABEL_GAP;
  77822. var textPoint = applyTransform$1(
  77823. [
  77824. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  77825. this._size[1] / 2
  77826. ],
  77827. barTransform
  77828. );
  77829. handleLabels[handleIndex].setStyle({
  77830. x: textPoint[0],
  77831. y: textPoint[1],
  77832. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  77833. textAlign: orient === HORIZONTAL ? direction : 'center',
  77834. text: labelTexts[handleIndex]
  77835. });
  77836. }
  77837. },
  77838. /**
  77839. * @private
  77840. */
  77841. _formatLabel: function (value, axis) {
  77842. var dataZoomModel = this.dataZoomModel;
  77843. var labelFormatter = dataZoomModel.get('labelFormatter');
  77844. var labelPrecision = dataZoomModel.get('labelPrecision');
  77845. if (labelPrecision == null || labelPrecision === 'auto') {
  77846. labelPrecision = axis.getPixelPrecision();
  77847. }
  77848. var valueStr = (value == null || isNaN(value))
  77849. ? ''
  77850. // FIXME Glue code
  77851. : (axis.type === 'category' || axis.type === 'time')
  77852. ? axis.scale.getLabel(Math.round(value))
  77853. // param of toFixed should less then 20.
  77854. : value.toFixed(Math.min(labelPrecision, 20));
  77855. return isFunction$1(labelFormatter)
  77856. ? labelFormatter(value, valueStr)
  77857. : isString(labelFormatter)
  77858. ? labelFormatter.replace('{value}', valueStr)
  77859. : valueStr;
  77860. },
  77861. /**
  77862. * @private
  77863. * @param {boolean} showOrHide true: show, false: hide
  77864. */
  77865. _showDataInfo: function (showOrHide) {
  77866. // Always show when drgging.
  77867. showOrHide = this._dragging || showOrHide;
  77868. var handleLabels = this._displayables.handleLabels;
  77869. handleLabels[0].attr('invisible', !showOrHide);
  77870. handleLabels[1].attr('invisible', !showOrHide);
  77871. },
  77872. _onDragMove: function (handleIndex, dx, dy, event) {
  77873. this._dragging = true;
  77874. // For mobile device, prevent screen slider on the button.
  77875. stop(event.event);
  77876. // Transform dx, dy to bar coordination.
  77877. var barTransform = this._displayables.barGroup.getLocalTransform();
  77878. var vertex = applyTransform$1([dx, dy], barTransform, true);
  77879. var changed = this._updateInterval(handleIndex, vertex[0]);
  77880. var realtime = this.dataZoomModel.get('realtime');
  77881. this._updateView(!realtime);
  77882. // Avoid dispatch dataZoom repeatly but range not changed,
  77883. // which cause bad visual effect when progressive enabled.
  77884. changed && realtime && this._dispatchZoomAction();
  77885. },
  77886. _onDragEnd: function () {
  77887. this._dragging = false;
  77888. this._showDataInfo(false);
  77889. // While in realtime mode and stream mode, dispatch action when
  77890. // drag end will cause the whole view rerender, which is unnecessary.
  77891. var realtime = this.dataZoomModel.get('realtime');
  77892. !realtime && this._dispatchZoomAction();
  77893. },
  77894. _onClickPanelClick: function (e) {
  77895. var size = this._size;
  77896. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  77897. if (localPoint[0] < 0 || localPoint[0] > size[0]
  77898. || localPoint[1] < 0 || localPoint[1] > size[1]
  77899. ) {
  77900. return;
  77901. }
  77902. var handleEnds = this._handleEnds;
  77903. var center = (handleEnds[0] + handleEnds[1]) / 2;
  77904. var changed = this._updateInterval('all', localPoint[0] - center);
  77905. this._updateView();
  77906. changed && this._dispatchZoomAction();
  77907. },
  77908. /**
  77909. * This action will be throttled.
  77910. * @private
  77911. */
  77912. _dispatchZoomAction: function () {
  77913. var range = this._range;
  77914. this.api.dispatchAction({
  77915. type: 'dataZoom',
  77916. from: this.uid,
  77917. dataZoomId: this.dataZoomModel.id,
  77918. start: range[0],
  77919. end: range[1]
  77920. });
  77921. },
  77922. /**
  77923. * @private
  77924. */
  77925. _findCoordRect: function () {
  77926. // Find the grid coresponding to the first axis referred by dataZoom.
  77927. var rect;
  77928. each$26(this.getTargetCoordInfo(), function (coordInfoList) {
  77929. if (!rect && coordInfoList.length) {
  77930. var coordSys = coordInfoList[0].model.coordinateSystem;
  77931. rect = coordSys.getRect && coordSys.getRect();
  77932. }
  77933. });
  77934. if (!rect) {
  77935. var width = this.api.getWidth();
  77936. var height = this.api.getHeight();
  77937. rect = {
  77938. x: width * 0.2,
  77939. y: height * 0.2,
  77940. width: width * 0.6,
  77941. height: height * 0.6
  77942. };
  77943. }
  77944. return rect;
  77945. }
  77946. });
  77947. function getOtherDim(thisDim) {
  77948. // FIXME
  77949. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  77950. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  77951. return map$$1[thisDim];
  77952. }
  77953. function getCursor(orient) {
  77954. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  77955. }
  77956. /*
  77957. * Licensed to the Apache Software Foundation (ASF) under one
  77958. * or more contributor license agreements. See the NOTICE file
  77959. * distributed with this work for additional information
  77960. * regarding copyright ownership. The ASF licenses this file
  77961. * to you under the Apache License, Version 2.0 (the
  77962. * "License"); you may not use this file except in compliance
  77963. * with the License. You may obtain a copy of the License at
  77964. *
  77965. * http://www.apache.org/licenses/LICENSE-2.0
  77966. *
  77967. * Unless required by applicable law or agreed to in writing,
  77968. * software distributed under the License is distributed on an
  77969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77970. * KIND, either express or implied. See the License for the
  77971. * specific language governing permissions and limitations
  77972. * under the License.
  77973. */
  77974. /*
  77975. * Licensed to the Apache Software Foundation (ASF) under one
  77976. * or more contributor license agreements. See the NOTICE file
  77977. * distributed with this work for additional information
  77978. * regarding copyright ownership. The ASF licenses this file
  77979. * to you under the Apache License, Version 2.0 (the
  77980. * "License"); you may not use this file except in compliance
  77981. * with the License. You may obtain a copy of the License at
  77982. *
  77983. * http://www.apache.org/licenses/LICENSE-2.0
  77984. *
  77985. * Unless required by applicable law or agreed to in writing,
  77986. * software distributed under the License is distributed on an
  77987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77988. * KIND, either express or implied. See the License for the
  77989. * specific language governing permissions and limitations
  77990. * under the License.
  77991. */
  77992. DataZoomModel.extend({
  77993. type: 'dataZoom.inside',
  77994. /**
  77995. * @protected
  77996. */
  77997. defaultOption: {
  77998. disabled: false, // Whether disable this inside zoom.
  77999. zoomLock: false, // Whether disable zoom but only pan.
  78000. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78001. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78002. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  78003. preventDefaultMouseMove: true
  78004. }
  78005. });
  78006. /*
  78007. * Licensed to the Apache Software Foundation (ASF) under one
  78008. * or more contributor license agreements. See the NOTICE file
  78009. * distributed with this work for additional information
  78010. * regarding copyright ownership. The ASF licenses this file
  78011. * to you under the Apache License, Version 2.0 (the
  78012. * "License"); you may not use this file except in compliance
  78013. * with the License. You may obtain a copy of the License at
  78014. *
  78015. * http://www.apache.org/licenses/LICENSE-2.0
  78016. *
  78017. * Unless required by applicable law or agreed to in writing,
  78018. * software distributed under the License is distributed on an
  78019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78020. * KIND, either express or implied. See the License for the
  78021. * specific language governing permissions and limitations
  78022. * under the License.
  78023. */
  78024. // Only create one roam controller for each coordinate system.
  78025. // one roam controller might be refered by two inside data zoom
  78026. // components (for example, one for x and one for y). When user
  78027. // pan or zoom, only dispatch one action for those data zoom
  78028. // components.
  78029. var ATTR$2 = '\0_ec_dataZoom_roams';
  78030. /**
  78031. * @public
  78032. * @param {module:echarts/ExtensionAPI} api
  78033. * @param {Object} dataZoomInfo
  78034. * @param {string} dataZoomInfo.coordId
  78035. * @param {Function} dataZoomInfo.containsPoint
  78036. * @param {Array.<string>} dataZoomInfo.allCoordIds
  78037. * @param {string} dataZoomInfo.dataZoomId
  78038. * @param {Object} dataZoomInfo.getRange
  78039. * @param {Function} dataZoomInfo.getRange.pan
  78040. * @param {Function} dataZoomInfo.getRange.zoom
  78041. * @param {Function} dataZoomInfo.getRange.scrollMove
  78042. * @param {boolean} dataZoomInfo.dataZoomModel
  78043. */
  78044. function register$2(api, dataZoomInfo) {
  78045. var store = giveStore$1(api);
  78046. var theDataZoomId = dataZoomInfo.dataZoomId;
  78047. var theCoordId = dataZoomInfo.coordId;
  78048. // Do clean when a dataZoom changes its target coordnate system.
  78049. // Avoid memory leak, dispose all not-used-registered.
  78050. each$1(store, function (record, coordId) {
  78051. var dataZoomInfos = record.dataZoomInfos;
  78052. if (dataZoomInfos[theDataZoomId]
  78053. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  78054. ) {
  78055. delete dataZoomInfos[theDataZoomId];
  78056. record.count--;
  78057. }
  78058. });
  78059. cleanStore(store);
  78060. var record = store[theCoordId];
  78061. // Create if needed.
  78062. if (!record) {
  78063. record = store[theCoordId] = {
  78064. coordId: theCoordId,
  78065. dataZoomInfos: {},
  78066. count: 0
  78067. };
  78068. record.controller = createController(api, record);
  78069. record.dispatchAction = curry(dispatchAction$1, api);
  78070. }
  78071. // Update reference of dataZoom.
  78072. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  78073. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  78074. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  78075. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  78076. // Consider resize, area should be always updated.
  78077. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  78078. // Update throttle.
  78079. createOrUpdate(
  78080. record,
  78081. 'dispatchAction',
  78082. dataZoomInfo.dataZoomModel.get('throttle', true),
  78083. 'fixRate'
  78084. );
  78085. }
  78086. /**
  78087. * @public
  78088. * @param {module:echarts/ExtensionAPI} api
  78089. * @param {string} dataZoomId
  78090. */
  78091. function unregister$1(api, dataZoomId) {
  78092. var store = giveStore$1(api);
  78093. each$1(store, function (record) {
  78094. record.controller.dispose();
  78095. var dataZoomInfos = record.dataZoomInfos;
  78096. if (dataZoomInfos[dataZoomId]) {
  78097. delete dataZoomInfos[dataZoomId];
  78098. record.count--;
  78099. }
  78100. });
  78101. cleanStore(store);
  78102. }
  78103. /**
  78104. * @public
  78105. */
  78106. function generateCoordId(coordModel) {
  78107. return coordModel.type + '\0_' + coordModel.id;
  78108. }
  78109. /**
  78110. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  78111. * @type {Array.<Object>}
  78112. */
  78113. function giveStore$1(api) {
  78114. // Mount store on zrender instance, so that we do not
  78115. // need to worry about dispose.
  78116. var zr = api.getZr();
  78117. return zr[ATTR$2] || (zr[ATTR$2] = {});
  78118. }
  78119. function createController(api, newRecord) {
  78120. var controller = new RoamController(api.getZr());
  78121. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  78122. controller.on(eventName, function (event) {
  78123. var batch = [];
  78124. each$1(newRecord.dataZoomInfos, function (info) {
  78125. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  78126. // moveOnMouseWheel, ...) enabled.
  78127. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  78128. return;
  78129. }
  78130. var method = (info.getRange || {})[eventName];
  78131. var range = method && method(newRecord.controller, event);
  78132. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  78133. dataZoomId: info.dataZoomId,
  78134. start: range[0],
  78135. end: range[1]
  78136. });
  78137. });
  78138. batch.length && newRecord.dispatchAction(batch);
  78139. });
  78140. });
  78141. return controller;
  78142. }
  78143. function cleanStore(store) {
  78144. each$1(store, function (record, coordId) {
  78145. if (!record.count) {
  78146. record.controller.dispose();
  78147. delete store[coordId];
  78148. }
  78149. });
  78150. }
  78151. /**
  78152. * This action will be throttled.
  78153. */
  78154. function dispatchAction$1(api, batch) {
  78155. api.dispatchAction({
  78156. type: 'dataZoom',
  78157. batch: batch
  78158. });
  78159. }
  78160. /**
  78161. * Merge roamController settings when multiple dataZooms share one roamController.
  78162. */
  78163. function mergeControllerParams(dataZoomInfos) {
  78164. var controlType;
  78165. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  78166. // as string, it is probably revert to reserved word by compress tool. See #7411.
  78167. var prefix = 'type_';
  78168. var typePriority = {
  78169. 'type_true': 2,
  78170. 'type_move': 1,
  78171. 'type_false': 0,
  78172. 'type_undefined': -1
  78173. };
  78174. var preventDefaultMouseMove = true;
  78175. each$1(dataZoomInfos, function (dataZoomInfo) {
  78176. var dataZoomModel = dataZoomInfo.dataZoomModel;
  78177. var oneType = dataZoomModel.get('disabled', true)
  78178. ? false
  78179. : dataZoomModel.get('zoomLock', true)
  78180. ? 'move'
  78181. : true;
  78182. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  78183. controlType = oneType;
  78184. }
  78185. // Prevent default move event by default. If one false, do not prevent. Otherwise
  78186. // users may be confused why it does not work when multiple insideZooms exist.
  78187. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  78188. });
  78189. return {
  78190. controlType: controlType,
  78191. opt: {
  78192. // RoamController will enable all of these functionalities,
  78193. // and the final behavior is determined by its event listener
  78194. // provided by each inside zoom.
  78195. zoomOnMouseWheel: true,
  78196. moveOnMouseMove: true,
  78197. moveOnMouseWheel: true,
  78198. preventDefaultMouseMove: !!preventDefaultMouseMove
  78199. }
  78200. };
  78201. }
  78202. /*
  78203. * Licensed to the Apache Software Foundation (ASF) under one
  78204. * or more contributor license agreements. See the NOTICE file
  78205. * distributed with this work for additional information
  78206. * regarding copyright ownership. The ASF licenses this file
  78207. * to you under the Apache License, Version 2.0 (the
  78208. * "License"); you may not use this file except in compliance
  78209. * with the License. You may obtain a copy of the License at
  78210. *
  78211. * http://www.apache.org/licenses/LICENSE-2.0
  78212. *
  78213. * Unless required by applicable law or agreed to in writing,
  78214. * software distributed under the License is distributed on an
  78215. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78216. * KIND, either express or implied. See the License for the
  78217. * specific language governing permissions and limitations
  78218. * under the License.
  78219. */
  78220. var bind$6 = bind;
  78221. var InsideZoomView = DataZoomView.extend({
  78222. type: 'dataZoom.inside',
  78223. /**
  78224. * @override
  78225. */
  78226. init: function (ecModel, api) {
  78227. /**
  78228. * 'throttle' is used in this.dispatchAction, so we save range
  78229. * to avoid missing some 'pan' info.
  78230. * @private
  78231. * @type {Array.<number>}
  78232. */
  78233. this._range;
  78234. },
  78235. /**
  78236. * @override
  78237. */
  78238. render: function (dataZoomModel, ecModel, api, payload) {
  78239. InsideZoomView.superApply(this, 'render', arguments);
  78240. // Hence the `throttle` util ensures to preserve command order,
  78241. // here simply updating range all the time will not cause missing
  78242. // any of the the roam change.
  78243. this._range = dataZoomModel.getPercentRange();
  78244. // Reset controllers.
  78245. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  78246. var allCoordIds = map(coordInfoList, function (coordInfo) {
  78247. return generateCoordId(coordInfo.model);
  78248. });
  78249. each$1(coordInfoList, function (coordInfo) {
  78250. var coordModel = coordInfo.model;
  78251. var getRange = {};
  78252. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  78253. getRange[eventName] = bind$6(roamHandlers[eventName], this, coordInfo, coordSysName);
  78254. }, this);
  78255. register$2(
  78256. api,
  78257. {
  78258. coordId: generateCoordId(coordModel),
  78259. allCoordIds: allCoordIds,
  78260. containsPoint: function (e, x, y) {
  78261. return coordModel.coordinateSystem.containPoint([x, y]);
  78262. },
  78263. dataZoomId: dataZoomModel.id,
  78264. dataZoomModel: dataZoomModel,
  78265. getRange: getRange
  78266. }
  78267. );
  78268. }, this);
  78269. }, this);
  78270. },
  78271. /**
  78272. * @override
  78273. */
  78274. dispose: function () {
  78275. unregister$1(this.api, this.dataZoomModel.id);
  78276. InsideZoomView.superApply(this, 'dispose', arguments);
  78277. this._range = null;
  78278. }
  78279. });
  78280. var roamHandlers = {
  78281. /**
  78282. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78283. */
  78284. zoom: function (coordInfo, coordSysName, controller, e) {
  78285. var lastRange = this._range;
  78286. var range = lastRange.slice();
  78287. // Calculate transform by the first axis.
  78288. var axisModel = coordInfo.axisModels[0];
  78289. if (!axisModel) {
  78290. return;
  78291. }
  78292. var directionInfo = getDirectionInfo[coordSysName](
  78293. null, [e.originX, e.originY], axisModel, controller, coordInfo
  78294. );
  78295. var percentPoint = (
  78296. directionInfo.signal > 0
  78297. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  78298. : (directionInfo.pixel - directionInfo.pixelStart)
  78299. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  78300. var scale = Math.max(1 / e.scale, 0);
  78301. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  78302. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  78303. // Restrict range.
  78304. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  78305. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  78306. this._range = range;
  78307. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  78308. return range;
  78309. }
  78310. },
  78311. /**
  78312. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78313. */
  78314. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  78315. var directionInfo = getDirectionInfo[coordSysName](
  78316. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  78317. );
  78318. return directionInfo.signal
  78319. * (range[1] - range[0])
  78320. * directionInfo.pixel / directionInfo.pixelLength;
  78321. }),
  78322. /**
  78323. * @this {module:echarts/component/dataZoom/InsideZoomView}
  78324. */
  78325. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  78326. var directionInfo = getDirectionInfo[coordSysName](
  78327. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  78328. );
  78329. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  78330. })
  78331. };
  78332. function makeMover(getPercentDelta) {
  78333. return function (coordInfo, coordSysName, controller, e) {
  78334. var lastRange = this._range;
  78335. var range = lastRange.slice();
  78336. // Calculate transform by the first axis.
  78337. var axisModel = coordInfo.axisModels[0];
  78338. if (!axisModel) {
  78339. return;
  78340. }
  78341. var percentDelta = getPercentDelta(
  78342. range, axisModel, coordInfo, coordSysName, controller, e
  78343. );
  78344. sliderMove(percentDelta, range, [0, 100], 'all');
  78345. this._range = range;
  78346. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  78347. return range;
  78348. }
  78349. };
  78350. }
  78351. var getDirectionInfo = {
  78352. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78353. var axis = axisModel.axis;
  78354. var ret = {};
  78355. var rect = coordInfo.model.coordinateSystem.getRect();
  78356. oldPoint = oldPoint || [0, 0];
  78357. if (axis.dim === 'x') {
  78358. ret.pixel = newPoint[0] - oldPoint[0];
  78359. ret.pixelLength = rect.width;
  78360. ret.pixelStart = rect.x;
  78361. ret.signal = axis.inverse ? 1 : -1;
  78362. }
  78363. else { // axis.dim === 'y'
  78364. ret.pixel = newPoint[1] - oldPoint[1];
  78365. ret.pixelLength = rect.height;
  78366. ret.pixelStart = rect.y;
  78367. ret.signal = axis.inverse ? -1 : 1;
  78368. }
  78369. return ret;
  78370. },
  78371. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78372. var axis = axisModel.axis;
  78373. var ret = {};
  78374. var polar = coordInfo.model.coordinateSystem;
  78375. var radiusExtent = polar.getRadiusAxis().getExtent();
  78376. var angleExtent = polar.getAngleAxis().getExtent();
  78377. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  78378. newPoint = polar.pointToCoord(newPoint);
  78379. if (axisModel.mainType === 'radiusAxis') {
  78380. ret.pixel = newPoint[0] - oldPoint[0];
  78381. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  78382. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  78383. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  78384. ret.pixelStart = radiusExtent[0];
  78385. ret.signal = axis.inverse ? 1 : -1;
  78386. }
  78387. else { // 'angleAxis'
  78388. ret.pixel = newPoint[1] - oldPoint[1];
  78389. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  78390. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  78391. ret.pixelLength = angleExtent[1] - angleExtent[0];
  78392. ret.pixelStart = angleExtent[0];
  78393. ret.signal = axis.inverse ? -1 : 1;
  78394. }
  78395. return ret;
  78396. },
  78397. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  78398. var axis = axisModel.axis;
  78399. var rect = coordInfo.model.coordinateSystem.getRect();
  78400. var ret = {};
  78401. oldPoint = oldPoint || [0, 0];
  78402. if (axis.orient === 'horizontal') {
  78403. ret.pixel = newPoint[0] - oldPoint[0];
  78404. ret.pixelLength = rect.width;
  78405. ret.pixelStart = rect.x;
  78406. ret.signal = axis.inverse ? 1 : -1;
  78407. }
  78408. else { // 'vertical'
  78409. ret.pixel = newPoint[1] - oldPoint[1];
  78410. ret.pixelLength = rect.height;
  78411. ret.pixelStart = rect.y;
  78412. ret.signal = axis.inverse ? -1 : 1;
  78413. }
  78414. return ret;
  78415. }
  78416. };
  78417. /*
  78418. * Licensed to the Apache Software Foundation (ASF) under one
  78419. * or more contributor license agreements. See the NOTICE file
  78420. * distributed with this work for additional information
  78421. * regarding copyright ownership. The ASF licenses this file
  78422. * to you under the Apache License, Version 2.0 (the
  78423. * "License"); you may not use this file except in compliance
  78424. * with the License. You may obtain a copy of the License at
  78425. *
  78426. * http://www.apache.org/licenses/LICENSE-2.0
  78427. *
  78428. * Unless required by applicable law or agreed to in writing,
  78429. * software distributed under the License is distributed on an
  78430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78431. * KIND, either express or implied. See the License for the
  78432. * specific language governing permissions and limitations
  78433. * under the License.
  78434. */
  78435. /*
  78436. * Licensed to the Apache Software Foundation (ASF) under one
  78437. * or more contributor license agreements. See the NOTICE file
  78438. * distributed with this work for additional information
  78439. * regarding copyright ownership. The ASF licenses this file
  78440. * to you under the Apache License, Version 2.0 (the
  78441. * "License"); you may not use this file except in compliance
  78442. * with the License. You may obtain a copy of the License at
  78443. *
  78444. * http://www.apache.org/licenses/LICENSE-2.0
  78445. *
  78446. * Unless required by applicable law or agreed to in writing,
  78447. * software distributed under the License is distributed on an
  78448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78449. * KIND, either express or implied. See the License for the
  78450. * specific language governing permissions and limitations
  78451. * under the License.
  78452. */
  78453. // Do not include './dataZoomSelect',
  78454. // since it only work for toolbox dataZoom.
  78455. /*
  78456. * Licensed to the Apache Software Foundation (ASF) under one
  78457. * or more contributor license agreements. See the NOTICE file
  78458. * distributed with this work for additional information
  78459. * regarding copyright ownership. The ASF licenses this file
  78460. * to you under the Apache License, Version 2.0 (the
  78461. * "License"); you may not use this file except in compliance
  78462. * with the License. You may obtain a copy of the License at
  78463. *
  78464. * http://www.apache.org/licenses/LICENSE-2.0
  78465. *
  78466. * Unless required by applicable law or agreed to in writing,
  78467. * software distributed under the License is distributed on an
  78468. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78469. * KIND, either express or implied. See the License for the
  78470. * specific language governing permissions and limitations
  78471. * under the License.
  78472. */
  78473. var each$27 = each$1;
  78474. var preprocessor$3 = function (option) {
  78475. var visualMap = option && option.visualMap;
  78476. if (!isArray(visualMap)) {
  78477. visualMap = visualMap ? [visualMap] : [];
  78478. }
  78479. each$27(visualMap, function (opt) {
  78480. if (!opt) {
  78481. return;
  78482. }
  78483. // rename splitList to pieces
  78484. if (has$2(opt, 'splitList') && !has$2(opt, 'pieces')) {
  78485. opt.pieces = opt.splitList;
  78486. delete opt.splitList;
  78487. }
  78488. var pieces = opt.pieces;
  78489. if (pieces && isArray(pieces)) {
  78490. each$27(pieces, function (piece) {
  78491. if (isObject$1(piece)) {
  78492. if (has$2(piece, 'start') && !has$2(piece, 'min')) {
  78493. piece.min = piece.start;
  78494. }
  78495. if (has$2(piece, 'end') && !has$2(piece, 'max')) {
  78496. piece.max = piece.end;
  78497. }
  78498. }
  78499. });
  78500. }
  78501. });
  78502. };
  78503. function has$2(obj, name) {
  78504. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  78505. }
  78506. /*
  78507. * Licensed to the Apache Software Foundation (ASF) under one
  78508. * or more contributor license agreements. See the NOTICE file
  78509. * distributed with this work for additional information
  78510. * regarding copyright ownership. The ASF licenses this file
  78511. * to you under the Apache License, Version 2.0 (the
  78512. * "License"); you may not use this file except in compliance
  78513. * with the License. You may obtain a copy of the License at
  78514. *
  78515. * http://www.apache.org/licenses/LICENSE-2.0
  78516. *
  78517. * Unless required by applicable law or agreed to in writing,
  78518. * software distributed under the License is distributed on an
  78519. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78520. * KIND, either express or implied. See the License for the
  78521. * specific language governing permissions and limitations
  78522. * under the License.
  78523. */
  78524. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  78525. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  78526. return (
  78527. !option.categories
  78528. && (
  78529. !(
  78530. option.pieces
  78531. ? option.pieces.length > 0
  78532. : option.splitNumber > 0
  78533. )
  78534. || option.calculable
  78535. )
  78536. )
  78537. ? 'continuous' : 'piecewise';
  78538. });
  78539. /*
  78540. * Licensed to the Apache Software Foundation (ASF) under one
  78541. * or more contributor license agreements. See the NOTICE file
  78542. * distributed with this work for additional information
  78543. * regarding copyright ownership. The ASF licenses this file
  78544. * to you under the Apache License, Version 2.0 (the
  78545. * "License"); you may not use this file except in compliance
  78546. * with the License. You may obtain a copy of the License at
  78547. *
  78548. * http://www.apache.org/licenses/LICENSE-2.0
  78549. *
  78550. * Unless required by applicable law or agreed to in writing,
  78551. * software distributed under the License is distributed on an
  78552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78553. * KIND, either express or implied. See the License for the
  78554. * specific language governing permissions and limitations
  78555. * under the License.
  78556. */
  78557. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  78558. registerVisual(VISUAL_PRIORITY, {
  78559. createOnAllSeries: true,
  78560. reset: function (seriesModel, ecModel) {
  78561. var resetDefines = [];
  78562. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78563. var pipelineContext = seriesModel.pipelineContext;
  78564. if (!visualMapModel.isTargetSeries(seriesModel)
  78565. || (pipelineContext && pipelineContext.large)
  78566. ) {
  78567. return;
  78568. }
  78569. resetDefines.push(incrementalApplyVisual(
  78570. visualMapModel.stateList,
  78571. visualMapModel.targetVisuals,
  78572. bind(visualMapModel.getValueState, visualMapModel),
  78573. visualMapModel.getDataDimension(seriesModel.getData())
  78574. ));
  78575. });
  78576. return resetDefines;
  78577. }
  78578. });
  78579. // Only support color.
  78580. registerVisual(VISUAL_PRIORITY, {
  78581. createOnAllSeries: true,
  78582. reset: function (seriesModel, ecModel) {
  78583. var data = seriesModel.getData();
  78584. var visualMetaList = [];
  78585. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78586. if (visualMapModel.isTargetSeries(seriesModel)) {
  78587. var visualMeta = visualMapModel.getVisualMeta(
  78588. bind(getColorVisual, null, seriesModel, visualMapModel)
  78589. ) || {stops: [], outerColors: []};
  78590. var concreteDim = visualMapModel.getDataDimension(data);
  78591. var dimInfo = data.getDimensionInfo(concreteDim);
  78592. if (dimInfo != null) {
  78593. // visualMeta.dimension should be dimension index, but not concrete dimension.
  78594. visualMeta.dimension = dimInfo.index;
  78595. visualMetaList.push(visualMeta);
  78596. }
  78597. }
  78598. });
  78599. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  78600. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  78601. }
  78602. });
  78603. // FIXME
  78604. // performance and export for heatmap?
  78605. // value can be Infinity or -Infinity
  78606. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  78607. var mappings = visualMapModel.targetVisuals[valueState];
  78608. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78609. var resultVisual = {
  78610. color: seriesModel.getData().getVisual('color') // default color.
  78611. };
  78612. for (var i = 0, len = visualTypes.length; i < len; i++) {
  78613. var type = visualTypes[i];
  78614. var mapping = mappings[
  78615. type === 'opacity' ? '__alphaForOpacity' : type
  78616. ];
  78617. mapping && mapping.applyVisual(value, getVisual, setVisual);
  78618. }
  78619. return resultVisual.color;
  78620. function getVisual(key) {
  78621. return resultVisual[key];
  78622. }
  78623. function setVisual(key, value) {
  78624. resultVisual[key] = value;
  78625. }
  78626. }
  78627. /*
  78628. * Licensed to the Apache Software Foundation (ASF) under one
  78629. * or more contributor license agreements. See the NOTICE file
  78630. * distributed with this work for additional information
  78631. * regarding copyright ownership. The ASF licenses this file
  78632. * to you under the Apache License, Version 2.0 (the
  78633. * "License"); you may not use this file except in compliance
  78634. * with the License. You may obtain a copy of the License at
  78635. *
  78636. * http://www.apache.org/licenses/LICENSE-2.0
  78637. *
  78638. * Unless required by applicable law or agreed to in writing,
  78639. * software distributed under the License is distributed on an
  78640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78641. * KIND, either express or implied. See the License for the
  78642. * specific language governing permissions and limitations
  78643. * under the License.
  78644. */
  78645. /**
  78646. * @file Visual mapping.
  78647. */
  78648. var visualDefault = {
  78649. /**
  78650. * @public
  78651. */
  78652. get: function (visualType, key, isCategory) {
  78653. var value = clone(
  78654. (defaultOption$3[visualType] || {})[key]
  78655. );
  78656. return isCategory
  78657. ? (isArray(value) ? value[value.length - 1] : value)
  78658. : value;
  78659. }
  78660. };
  78661. var defaultOption$3 = {
  78662. color: {
  78663. active: ['#006edd', '#e0ffff'],
  78664. inactive: ['rgba(0,0,0,0)']
  78665. },
  78666. colorHue: {
  78667. active: [0, 360],
  78668. inactive: [0, 0]
  78669. },
  78670. colorSaturation: {
  78671. active: [0.3, 1],
  78672. inactive: [0, 0]
  78673. },
  78674. colorLightness: {
  78675. active: [0.9, 0.5],
  78676. inactive: [0, 0]
  78677. },
  78678. colorAlpha: {
  78679. active: [0.3, 1],
  78680. inactive: [0, 0]
  78681. },
  78682. opacity: {
  78683. active: [0.3, 1],
  78684. inactive: [0, 0]
  78685. },
  78686. symbol: {
  78687. active: ['circle', 'roundRect', 'diamond'],
  78688. inactive: ['none']
  78689. },
  78690. symbolSize: {
  78691. active: [10, 50],
  78692. inactive: [0, 0]
  78693. }
  78694. };
  78695. /*
  78696. * Licensed to the Apache Software Foundation (ASF) under one
  78697. * or more contributor license agreements. See the NOTICE file
  78698. * distributed with this work for additional information
  78699. * regarding copyright ownership. The ASF licenses this file
  78700. * to you under the Apache License, Version 2.0 (the
  78701. * "License"); you may not use this file except in compliance
  78702. * with the License. You may obtain a copy of the License at
  78703. *
  78704. * http://www.apache.org/licenses/LICENSE-2.0
  78705. *
  78706. * Unless required by applicable law or agreed to in writing,
  78707. * software distributed under the License is distributed on an
  78708. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78709. * KIND, either express or implied. See the License for the
  78710. * specific language governing permissions and limitations
  78711. * under the License.
  78712. */
  78713. var mapVisual$2 = VisualMapping.mapVisual;
  78714. var eachVisual = VisualMapping.eachVisual;
  78715. var isArray$3 = isArray;
  78716. var each$28 = each$1;
  78717. var asc$3 = asc;
  78718. var linearMap$2 = linearMap;
  78719. var noop$2 = noop;
  78720. var VisualMapModel = extendComponentModel({
  78721. type: 'visualMap',
  78722. dependencies: ['series'],
  78723. /**
  78724. * @readOnly
  78725. * @type {Array.<string>}
  78726. */
  78727. stateList: ['inRange', 'outOfRange'],
  78728. /**
  78729. * @readOnly
  78730. * @type {Array.<string>}
  78731. */
  78732. replacableOptionKeys: [
  78733. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  78734. ],
  78735. /**
  78736. * [lowerBound, upperBound]
  78737. *
  78738. * @readOnly
  78739. * @type {Array.<number>}
  78740. */
  78741. dataBound: [-Infinity, Infinity],
  78742. /**
  78743. * @readOnly
  78744. * @type {string|Object}
  78745. */
  78746. layoutMode: {type: 'box', ignoreSize: true},
  78747. /**
  78748. * @protected
  78749. */
  78750. defaultOption: {
  78751. show: true,
  78752. zlevel: 0,
  78753. z: 4,
  78754. seriesIndex: 'all', // 'all' or null/undefined: all series.
  78755. // A number or an array of number: the specified series.
  78756. // set min: 0, max: 200, only for campatible with ec2.
  78757. // In fact min max should not have default value.
  78758. min: 0, // min value, must specified if pieces is not specified.
  78759. max: 200, // max value, must specified if pieces is not specified.
  78760. dimension: null,
  78761. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  78762. // 'symbol', 'symbolSize'
  78763. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  78764. // 'colorLightness', 'colorAlpha',
  78765. // 'symbol', 'symbolSize'
  78766. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  78767. right: null, // The same as left.
  78768. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  78769. bottom: 0, // The same as top.
  78770. itemWidth: null,
  78771. itemHeight: null,
  78772. inverse: false,
  78773. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  78774. backgroundColor: 'rgba(0,0,0,0)',
  78775. borderColor: '#ccc', // 值域边框颜色
  78776. contentColor: '#5793f3',
  78777. inactiveColor: '#aaa',
  78778. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  78779. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  78780. // 接受数组分别设定上右下左边距,同css
  78781. textGap: 10, //
  78782. precision: 0, // 小数精度,默认为0,无小数点
  78783. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  78784. formatter: null,
  78785. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  78786. textStyle: {
  78787. color: '#333' // 值域文字颜色
  78788. }
  78789. },
  78790. /**
  78791. * @protected
  78792. */
  78793. init: function (option, parentModel, ecModel) {
  78794. /**
  78795. * @private
  78796. * @type {Array.<number>}
  78797. */
  78798. this._dataExtent;
  78799. /**
  78800. * @readOnly
  78801. */
  78802. this.targetVisuals = {};
  78803. /**
  78804. * @readOnly
  78805. */
  78806. this.controllerVisuals = {};
  78807. /**
  78808. * @readOnly
  78809. */
  78810. this.textStyleModel;
  78811. /**
  78812. * [width, height]
  78813. * @readOnly
  78814. * @type {Array.<number>}
  78815. */
  78816. this.itemSize;
  78817. this.mergeDefaultAndTheme(option, ecModel);
  78818. },
  78819. /**
  78820. * @protected
  78821. */
  78822. optionUpdated: function (newOption, isInit) {
  78823. var thisOption = this.option;
  78824. // FIXME
  78825. // necessary?
  78826. // Disable realtime view update if canvas is not supported.
  78827. if (!env$1.canvasSupported) {
  78828. thisOption.realtime = false;
  78829. }
  78830. !isInit && replaceVisualOption(
  78831. thisOption, newOption, this.replacableOptionKeys
  78832. );
  78833. this.textStyleModel = this.getModel('textStyle');
  78834. this.resetItemSize();
  78835. this.completeVisualOption();
  78836. },
  78837. /**
  78838. * @protected
  78839. */
  78840. resetVisual: function (supplementVisualOption) {
  78841. var stateList = this.stateList;
  78842. supplementVisualOption = bind(supplementVisualOption, this);
  78843. this.controllerVisuals = createVisualMappings(
  78844. this.option.controller, stateList, supplementVisualOption
  78845. );
  78846. this.targetVisuals = createVisualMappings(
  78847. this.option.target, stateList, supplementVisualOption
  78848. );
  78849. },
  78850. /**
  78851. * @protected
  78852. * @return {Array.<number>} An array of series indices.
  78853. */
  78854. getTargetSeriesIndices: function () {
  78855. var optionSeriesIndex = this.option.seriesIndex;
  78856. var seriesIndices = [];
  78857. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  78858. this.ecModel.eachSeries(function (seriesModel, index) {
  78859. seriesIndices.push(index);
  78860. });
  78861. }
  78862. else {
  78863. seriesIndices = normalizeToArray(optionSeriesIndex);
  78864. }
  78865. return seriesIndices;
  78866. },
  78867. /**
  78868. * @public
  78869. */
  78870. eachTargetSeries: function (callback, context) {
  78871. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  78872. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  78873. }, this);
  78874. },
  78875. /**
  78876. * @pubilc
  78877. */
  78878. isTargetSeries: function (seriesModel) {
  78879. var is = false;
  78880. this.eachTargetSeries(function (model) {
  78881. model === seriesModel && (is = true);
  78882. });
  78883. return is;
  78884. },
  78885. /**
  78886. * @example
  78887. * this.formatValueText(someVal); // format single numeric value to text.
  78888. * this.formatValueText(someVal, true); // format single category value to text.
  78889. * this.formatValueText([min, max]); // format numeric min-max to text.
  78890. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  78891. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  78892. *
  78893. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  78894. * @param {boolean} [isCategory=false] Only available when value is number.
  78895. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  78896. * @return {string}
  78897. * @protected
  78898. */
  78899. formatValueText: function (value, isCategory, edgeSymbols) {
  78900. var option = this.option;
  78901. var precision = option.precision;
  78902. var dataBound = this.dataBound;
  78903. var formatter = option.formatter;
  78904. var isMinMax;
  78905. var textValue;
  78906. edgeSymbols = edgeSymbols || ['<', '>'];
  78907. if (isArray(value)) {
  78908. value = value.slice();
  78909. isMinMax = true;
  78910. }
  78911. textValue = isCategory
  78912. ? value
  78913. : (isMinMax
  78914. ? [toFixed(value[0]), toFixed(value[1])]
  78915. : toFixed(value)
  78916. );
  78917. if (isString(formatter)) {
  78918. return formatter
  78919. .replace('{value}', isMinMax ? textValue[0] : textValue)
  78920. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  78921. }
  78922. else if (isFunction$1(formatter)) {
  78923. return isMinMax
  78924. ? formatter(value[0], value[1])
  78925. : formatter(value);
  78926. }
  78927. if (isMinMax) {
  78928. if (value[0] === dataBound[0]) {
  78929. return edgeSymbols[0] + ' ' + textValue[1];
  78930. }
  78931. else if (value[1] === dataBound[1]) {
  78932. return edgeSymbols[1] + ' ' + textValue[0];
  78933. }
  78934. else {
  78935. return textValue[0] + ' - ' + textValue[1];
  78936. }
  78937. }
  78938. else { // Format single value (includes category case).
  78939. return textValue;
  78940. }
  78941. function toFixed(val) {
  78942. return val === dataBound[0]
  78943. ? 'min'
  78944. : val === dataBound[1]
  78945. ? 'max'
  78946. : (+val).toFixed(Math.min(precision, 20));
  78947. }
  78948. },
  78949. /**
  78950. * @protected
  78951. */
  78952. resetExtent: function () {
  78953. var thisOption = this.option;
  78954. // Can not calculate data extent by data here.
  78955. // Because series and data may be modified in processing stage.
  78956. // So we do not support the feature "auto min/max".
  78957. var extent = asc$3([thisOption.min, thisOption.max]);
  78958. this._dataExtent = extent;
  78959. },
  78960. /**
  78961. * @public
  78962. * @param {module:echarts/data/List} list
  78963. * @return {string} Concrete dimention. If return null/undefined,
  78964. * no dimension used.
  78965. */
  78966. getDataDimension: function (list) {
  78967. var optDim = this.option.dimension;
  78968. var listDimensions = list.dimensions;
  78969. if (optDim == null && !listDimensions.length) {
  78970. return;
  78971. }
  78972. if (optDim != null) {
  78973. return list.getDimension(optDim);
  78974. }
  78975. var dimNames = list.dimensions;
  78976. for (var i = dimNames.length - 1; i >= 0; i--) {
  78977. var dimName = dimNames[i];
  78978. var dimInfo = list.getDimensionInfo(dimName);
  78979. if (!dimInfo.isCalculationCoord) {
  78980. return dimName;
  78981. }
  78982. }
  78983. },
  78984. /**
  78985. * @public
  78986. * @override
  78987. */
  78988. getExtent: function () {
  78989. return this._dataExtent.slice();
  78990. },
  78991. /**
  78992. * @protected
  78993. */
  78994. completeVisualOption: function () {
  78995. var ecModel = this.ecModel;
  78996. var thisOption = this.option;
  78997. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  78998. var target = thisOption.target || (thisOption.target = {});
  78999. var controller = thisOption.controller || (thisOption.controller = {});
  79000. merge(target, base); // Do not override
  79001. merge(controller, base); // Do not override
  79002. var isCategory = this.isCategory();
  79003. completeSingle.call(this, target);
  79004. completeSingle.call(this, controller);
  79005. completeInactive.call(this, target, 'inRange', 'outOfRange');
  79006. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  79007. completeController.call(this, controller);
  79008. function completeSingle(base) {
  79009. // Compatible with ec2 dataRange.color.
  79010. // The mapping order of dataRange.color is: [high value, ..., low value]
  79011. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  79012. // Notice: ec2 has no inverse.
  79013. if (isArray$3(thisOption.color)
  79014. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  79015. // So adding color only when no inRange defined.
  79016. && !base.inRange
  79017. ) {
  79018. base.inRange = {color: thisOption.color.slice().reverse()};
  79019. }
  79020. // Compatible with previous logic, always give a defautl color, otherwise
  79021. // simple config with no inRange and outOfRange will not work.
  79022. // Originally we use visualMap.color as the default color, but setOption at
  79023. // the second time the default color will be erased. So we change to use
  79024. // constant DEFAULT_COLOR.
  79025. // If user do not want the defualt color, set inRange: {color: null}.
  79026. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  79027. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  79028. each$28(this.stateList, function (state) {
  79029. var visualType = base[state];
  79030. if (isString(visualType)) {
  79031. var defa = visualDefault.get(visualType, 'active', isCategory);
  79032. if (defa) {
  79033. base[state] = {};
  79034. base[state][visualType] = defa;
  79035. }
  79036. else {
  79037. // Mark as not specified.
  79038. delete base[state];
  79039. }
  79040. }
  79041. }, this);
  79042. }
  79043. function completeInactive(base, stateExist, stateAbsent) {
  79044. var optExist = base[stateExist];
  79045. var optAbsent = base[stateAbsent];
  79046. if (optExist && !optAbsent) {
  79047. optAbsent = base[stateAbsent] = {};
  79048. each$28(optExist, function (visualData, visualType) {
  79049. if (!VisualMapping.isValidType(visualType)) {
  79050. return;
  79051. }
  79052. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  79053. if (defa != null) {
  79054. optAbsent[visualType] = defa;
  79055. // Compatibable with ec2:
  79056. // Only inactive color to rgba(0,0,0,0) can not
  79057. // make label transparent, so use opacity also.
  79058. if (visualType === 'color'
  79059. && !optAbsent.hasOwnProperty('opacity')
  79060. && !optAbsent.hasOwnProperty('colorAlpha')
  79061. ) {
  79062. optAbsent.opacity = [0, 0];
  79063. }
  79064. }
  79065. });
  79066. }
  79067. }
  79068. function completeController(controller) {
  79069. var symbolExists = (controller.inRange || {}).symbol
  79070. || (controller.outOfRange || {}).symbol;
  79071. var symbolSizeExists = (controller.inRange || {}).symbolSize
  79072. || (controller.outOfRange || {}).symbolSize;
  79073. var inactiveColor = this.get('inactiveColor');
  79074. each$28(this.stateList, function (state) {
  79075. var itemSize = this.itemSize;
  79076. var visuals = controller[state];
  79077. // Set inactive color for controller if no other color
  79078. // attr (like colorAlpha) specified.
  79079. if (!visuals) {
  79080. visuals = controller[state] = {
  79081. color: isCategory ? inactiveColor : [inactiveColor]
  79082. };
  79083. }
  79084. // Consistent symbol and symbolSize if not specified.
  79085. if (visuals.symbol == null) {
  79086. visuals.symbol = symbolExists
  79087. && clone(symbolExists)
  79088. || (isCategory ? 'roundRect' : ['roundRect']);
  79089. }
  79090. if (visuals.symbolSize == null) {
  79091. visuals.symbolSize = symbolSizeExists
  79092. && clone(symbolSizeExists)
  79093. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  79094. }
  79095. // Filter square and none.
  79096. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  79097. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  79098. });
  79099. // Normalize symbolSize
  79100. var symbolSize = visuals.symbolSize;
  79101. if (symbolSize != null) {
  79102. var max = -Infinity;
  79103. // symbolSize can be object when categories defined.
  79104. eachVisual(symbolSize, function (value) {
  79105. value > max && (max = value);
  79106. });
  79107. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  79108. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  79109. });
  79110. }
  79111. }, this);
  79112. }
  79113. },
  79114. /**
  79115. * @protected
  79116. */
  79117. resetItemSize: function () {
  79118. this.itemSize = [
  79119. parseFloat(this.get('itemWidth')),
  79120. parseFloat(this.get('itemHeight'))
  79121. ];
  79122. },
  79123. /**
  79124. * @public
  79125. */
  79126. isCategory: function () {
  79127. return !!this.option.categories;
  79128. },
  79129. /**
  79130. * @public
  79131. * @abstract
  79132. */
  79133. setSelected: noop$2,
  79134. /**
  79135. * @public
  79136. * @abstract
  79137. * @param {*|module:echarts/data/List} valueOrData
  79138. * @param {number} dataIndex
  79139. * @return {string} state See this.stateList
  79140. */
  79141. getValueState: noop$2,
  79142. /**
  79143. * FIXME
  79144. * Do not publish to thirt-part-dev temporarily
  79145. * util the interface is stable. (Should it return
  79146. * a function but not visual meta?)
  79147. *
  79148. * @pubilc
  79149. * @abstract
  79150. * @param {Function} getColorVisual
  79151. * params: value, valueState
  79152. * return: color
  79153. * @return {Object} visualMeta
  79154. * should includes {stops, outerColors}
  79155. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  79156. */
  79157. getVisualMeta: noop$2
  79158. });
  79159. /*
  79160. * Licensed to the Apache Software Foundation (ASF) under one
  79161. * or more contributor license agreements. See the NOTICE file
  79162. * distributed with this work for additional information
  79163. * regarding copyright ownership. The ASF licenses this file
  79164. * to you under the Apache License, Version 2.0 (the
  79165. * "License"); you may not use this file except in compliance
  79166. * with the License. You may obtain a copy of the License at
  79167. *
  79168. * http://www.apache.org/licenses/LICENSE-2.0
  79169. *
  79170. * Unless required by applicable law or agreed to in writing,
  79171. * software distributed under the License is distributed on an
  79172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79173. * KIND, either express or implied. See the License for the
  79174. * specific language governing permissions and limitations
  79175. * under the License.
  79176. */
  79177. // Constant
  79178. var DEFAULT_BAR_BOUND = [20, 140];
  79179. var ContinuousModel = VisualMapModel.extend({
  79180. type: 'visualMap.continuous',
  79181. /**
  79182. * @protected
  79183. */
  79184. defaultOption: {
  79185. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  79186. calculable: false, // This prop effect default component type determine,
  79187. // See echarts/component/visualMap/typeDefaulter.
  79188. range: null, // selected range. In default case `range` is [min, max]
  79189. // and can auto change along with modification of min max,
  79190. // util use specifid a range.
  79191. realtime: true, // Whether realtime update.
  79192. itemHeight: null, // The length of the range control edge.
  79193. itemWidth: null, // The length of the other side.
  79194. hoverLink: true, // Enable hover highlight.
  79195. hoverLinkDataSize: null, // The size of hovered data.
  79196. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  79197. // If not specified, follow the value of `realtime`.
  79198. },
  79199. /**
  79200. * @override
  79201. */
  79202. optionUpdated: function (newOption, isInit) {
  79203. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  79204. this.resetExtent();
  79205. this.resetVisual(function (mappingOption) {
  79206. mappingOption.mappingMethod = 'linear';
  79207. mappingOption.dataExtent = this.getExtent();
  79208. });
  79209. this._resetRange();
  79210. },
  79211. /**
  79212. * @protected
  79213. * @override
  79214. */
  79215. resetItemSize: function () {
  79216. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  79217. var itemSize = this.itemSize;
  79218. this._orient === 'horizontal' && itemSize.reverse();
  79219. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  79220. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  79221. },
  79222. /**
  79223. * @private
  79224. */
  79225. _resetRange: function () {
  79226. var dataExtent = this.getExtent();
  79227. var range = this.option.range;
  79228. if (!range || range.auto) {
  79229. // `range` should always be array (so we dont use other
  79230. // value like 'auto') for user-friend. (consider getOption).
  79231. dataExtent.auto = 1;
  79232. this.option.range = dataExtent;
  79233. }
  79234. else if (isArray(range)) {
  79235. if (range[0] > range[1]) {
  79236. range.reverse();
  79237. }
  79238. range[0] = Math.max(range[0], dataExtent[0]);
  79239. range[1] = Math.min(range[1], dataExtent[1]);
  79240. }
  79241. },
  79242. /**
  79243. * @protected
  79244. * @override
  79245. */
  79246. completeVisualOption: function () {
  79247. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  79248. each$1(this.stateList, function (state) {
  79249. var symbolSize = this.option.controller[state].symbolSize;
  79250. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  79251. symbolSize[0] = 0; // For good looking.
  79252. }
  79253. }, this);
  79254. },
  79255. /**
  79256. * @override
  79257. */
  79258. setSelected: function (selected) {
  79259. this.option.range = selected.slice();
  79260. this._resetRange();
  79261. },
  79262. /**
  79263. * @public
  79264. */
  79265. getSelected: function () {
  79266. var dataExtent = this.getExtent();
  79267. var dataInterval = asc(
  79268. (this.get('range') || []).slice()
  79269. );
  79270. // Clamp
  79271. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  79272. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  79273. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  79274. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  79275. return dataInterval;
  79276. },
  79277. /**
  79278. * @override
  79279. */
  79280. getValueState: function (value) {
  79281. var range = this.option.range;
  79282. var dataExtent = this.getExtent();
  79283. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  79284. // range[1] is processed likewise.
  79285. return (
  79286. (range[0] <= dataExtent[0] || range[0] <= value)
  79287. && (range[1] >= dataExtent[1] || value <= range[1])
  79288. ) ? 'inRange' : 'outOfRange';
  79289. },
  79290. /**
  79291. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  79292. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  79293. */
  79294. findTargetDataIndices: function (range) {
  79295. var result = [];
  79296. this.eachTargetSeries(function (seriesModel) {
  79297. var dataIndices = [];
  79298. var data = seriesModel.getData();
  79299. data.each(this.getDataDimension(data), function (value, dataIndex) {
  79300. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  79301. }, this);
  79302. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  79303. }, this);
  79304. return result;
  79305. },
  79306. /**
  79307. * @implement
  79308. */
  79309. getVisualMeta: function (getColorVisual) {
  79310. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  79311. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  79312. var stops = [];
  79313. function setStop(value, valueState) {
  79314. stops.push({
  79315. value: value,
  79316. color: getColorVisual(value, valueState)
  79317. });
  79318. }
  79319. // Format to: outOfRange -- inRange -- outOfRange.
  79320. var iIdx = 0;
  79321. var oIdx = 0;
  79322. var iLen = iVals.length;
  79323. var oLen = oVals.length;
  79324. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  79325. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  79326. if (oVals[oIdx] < iVals[iIdx]) {
  79327. setStop(oVals[oIdx], 'outOfRange');
  79328. }
  79329. }
  79330. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  79331. // If range is full, value beyond min, max will be clamped.
  79332. // make a singularity
  79333. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  79334. setStop(iVals[iIdx], 'inRange');
  79335. }
  79336. for (var first = 1; oIdx < oLen; oIdx++) {
  79337. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  79338. // make a singularity
  79339. if (first) {
  79340. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  79341. first = 0;
  79342. }
  79343. setStop(oVals[oIdx], 'outOfRange');
  79344. }
  79345. }
  79346. var stopsLen = stops.length;
  79347. return {
  79348. stops: stops,
  79349. outerColors: [
  79350. stopsLen ? stops[0].color : 'transparent',
  79351. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  79352. ]
  79353. };
  79354. }
  79355. });
  79356. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  79357. if (dataExtent[0] === dataExtent[1]) {
  79358. return dataExtent.slice();
  79359. }
  79360. // When using colorHue mapping, it is not linear color any more.
  79361. // Moreover, canvas gradient seems not to be accurate linear.
  79362. // FIXME
  79363. // Should be arbitrary value 100? or based on pixel size?
  79364. var count = 200;
  79365. var step = (dataExtent[1] - dataExtent[0]) / count;
  79366. var value = dataExtent[0];
  79367. var stopValues = [];
  79368. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  79369. stopValues.push(value);
  79370. value += step;
  79371. }
  79372. stopValues.push(dataExtent[1]);
  79373. return stopValues;
  79374. }
  79375. /*
  79376. * Licensed to the Apache Software Foundation (ASF) under one
  79377. * or more contributor license agreements. See the NOTICE file
  79378. * distributed with this work for additional information
  79379. * regarding copyright ownership. The ASF licenses this file
  79380. * to you under the Apache License, Version 2.0 (the
  79381. * "License"); you may not use this file except in compliance
  79382. * with the License. You may obtain a copy of the License at
  79383. *
  79384. * http://www.apache.org/licenses/LICENSE-2.0
  79385. *
  79386. * Unless required by applicable law or agreed to in writing,
  79387. * software distributed under the License is distributed on an
  79388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79389. * KIND, either express or implied. See the License for the
  79390. * specific language governing permissions and limitations
  79391. * under the License.
  79392. */
  79393. var VisualMapView = extendComponentView({
  79394. type: 'visualMap',
  79395. /**
  79396. * @readOnly
  79397. * @type {Object}
  79398. */
  79399. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  79400. init: function (ecModel, api) {
  79401. /**
  79402. * @readOnly
  79403. * @type {module:echarts/model/Global}
  79404. */
  79405. this.ecModel = ecModel;
  79406. /**
  79407. * @readOnly
  79408. * @type {module:echarts/ExtensionAPI}
  79409. */
  79410. this.api = api;
  79411. /**
  79412. * @readOnly
  79413. * @type {module:echarts/component/visualMap/visualMapModel}
  79414. */
  79415. this.visualMapModel;
  79416. },
  79417. /**
  79418. * @protected
  79419. */
  79420. render: function (visualMapModel, ecModel, api, payload) {
  79421. this.visualMapModel = visualMapModel;
  79422. if (visualMapModel.get('show') === false) {
  79423. this.group.removeAll();
  79424. return;
  79425. }
  79426. this.doRender.apply(this, arguments);
  79427. },
  79428. /**
  79429. * @protected
  79430. */
  79431. renderBackground: function (group) {
  79432. var visualMapModel = this.visualMapModel;
  79433. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  79434. var rect = group.getBoundingRect();
  79435. group.add(new Rect({
  79436. z2: -1, // Lay background rect on the lowest layer.
  79437. silent: true,
  79438. shape: {
  79439. x: rect.x - padding[3],
  79440. y: rect.y - padding[0],
  79441. width: rect.width + padding[3] + padding[1],
  79442. height: rect.height + padding[0] + padding[2]
  79443. },
  79444. style: {
  79445. fill: visualMapModel.get('backgroundColor'),
  79446. stroke: visualMapModel.get('borderColor'),
  79447. lineWidth: visualMapModel.get('borderWidth')
  79448. }
  79449. }));
  79450. },
  79451. /**
  79452. * @protected
  79453. * @param {number} targetValue can be Infinity or -Infinity
  79454. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  79455. * @param {Object} [opts]
  79456. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  79457. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  79458. * @return {*} Visual value.
  79459. */
  79460. getControllerVisual: function (targetValue, visualCluster, opts) {
  79461. opts = opts || {};
  79462. var forceState = opts.forceState;
  79463. var visualMapModel = this.visualMapModel;
  79464. var visualObj = {};
  79465. // Default values.
  79466. if (visualCluster === 'symbol') {
  79467. visualObj.symbol = visualMapModel.get('itemSymbol');
  79468. }
  79469. if (visualCluster === 'color') {
  79470. var defaultColor = visualMapModel.get('contentColor');
  79471. visualObj.color = defaultColor;
  79472. }
  79473. function getter(key) {
  79474. return visualObj[key];
  79475. }
  79476. function setter(key, value) {
  79477. visualObj[key] = value;
  79478. }
  79479. var mappings = visualMapModel.controllerVisuals[
  79480. forceState || visualMapModel.getValueState(targetValue)
  79481. ];
  79482. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79483. each$1(visualTypes, function (type) {
  79484. var visualMapping = mappings[type];
  79485. if (opts.convertOpacityToAlpha && type === 'opacity') {
  79486. type = 'colorAlpha';
  79487. visualMapping = mappings.__alphaForOpacity;
  79488. }
  79489. if (VisualMapping.dependsOn(type, visualCluster)) {
  79490. visualMapping && visualMapping.applyVisual(
  79491. targetValue, getter, setter
  79492. );
  79493. }
  79494. });
  79495. return visualObj[visualCluster];
  79496. },
  79497. /**
  79498. * @protected
  79499. */
  79500. positionGroup: function (group) {
  79501. var model = this.visualMapModel;
  79502. var api = this.api;
  79503. positionElement(
  79504. group,
  79505. model.getBoxLayoutParams(),
  79506. {width: api.getWidth(), height: api.getHeight()}
  79507. );
  79508. },
  79509. /**
  79510. * @protected
  79511. * @abstract
  79512. */
  79513. doRender: noop
  79514. });
  79515. /*
  79516. * Licensed to the Apache Software Foundation (ASF) under one
  79517. * or more contributor license agreements. See the NOTICE file
  79518. * distributed with this work for additional information
  79519. * regarding copyright ownership. The ASF licenses this file
  79520. * to you under the Apache License, Version 2.0 (the
  79521. * "License"); you may not use this file except in compliance
  79522. * with the License. You may obtain a copy of the License at
  79523. *
  79524. * http://www.apache.org/licenses/LICENSE-2.0
  79525. *
  79526. * Unless required by applicable law or agreed to in writing,
  79527. * software distributed under the License is distributed on an
  79528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79529. * KIND, either express or implied. See the License for the
  79530. * specific language governing permissions and limitations
  79531. * under the License.
  79532. */
  79533. /**
  79534. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  79535. * @param {module:echarts/ExtensionAPI} api
  79536. * @param {Array.<number>} itemSize always [short, long]
  79537. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  79538. */
  79539. function getItemAlign(visualMapModel, api, itemSize) {
  79540. var modelOption = visualMapModel.option;
  79541. var itemAlign = modelOption.align;
  79542. if (itemAlign != null && itemAlign !== 'auto') {
  79543. return itemAlign;
  79544. }
  79545. // Auto decision align.
  79546. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  79547. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  79548. var paramsSet = [
  79549. ['left', 'right', 'width'],
  79550. ['top', 'bottom', 'height']
  79551. ];
  79552. var reals = paramsSet[realIndex];
  79553. var fakeValue = [0, null, 10];
  79554. var layoutInput = {};
  79555. for (var i = 0; i < 3; i++) {
  79556. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  79557. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  79558. }
  79559. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  79560. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  79561. return reals[
  79562. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  79563. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  79564. ];
  79565. }
  79566. /**
  79567. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  79568. * dataIndexInside means filtered index.
  79569. */
  79570. function makeHighDownBatch(batch, visualMapModel) {
  79571. each$1(batch || [], function (batchItem) {
  79572. if (batchItem.dataIndex != null) {
  79573. batchItem.dataIndexInside = batchItem.dataIndex;
  79574. batchItem.dataIndex = null;
  79575. }
  79576. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  79577. });
  79578. return batch;
  79579. }
  79580. /*
  79581. * Licensed to the Apache Software Foundation (ASF) under one
  79582. * or more contributor license agreements. See the NOTICE file
  79583. * distributed with this work for additional information
  79584. * regarding copyright ownership. The ASF licenses this file
  79585. * to you under the Apache License, Version 2.0 (the
  79586. * "License"); you may not use this file except in compliance
  79587. * with the License. You may obtain a copy of the License at
  79588. *
  79589. * http://www.apache.org/licenses/LICENSE-2.0
  79590. *
  79591. * Unless required by applicable law or agreed to in writing,
  79592. * software distributed under the License is distributed on an
  79593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79594. * KIND, either express or implied. See the License for the
  79595. * specific language governing permissions and limitations
  79596. * under the License.
  79597. */
  79598. var linearMap$3 = linearMap;
  79599. var each$29 = each$1;
  79600. var mathMin$8 = Math.min;
  79601. var mathMax$8 = Math.max;
  79602. // Arbitrary value
  79603. var HOVER_LINK_SIZE = 12;
  79604. var HOVER_LINK_OUT = 6;
  79605. // Notice:
  79606. // Any "interval" should be by the order of [low, high].
  79607. // "handle0" (handleIndex === 0) maps to
  79608. // low data value: this._dataInterval[0] and has low coord.
  79609. // "handle1" (handleIndex === 1) maps to
  79610. // high data value: this._dataInterval[1] and has high coord.
  79611. // The logic of transform is implemented in this._createBarGroup.
  79612. var ContinuousView = VisualMapView.extend({
  79613. type: 'visualMap.continuous',
  79614. /**
  79615. * @override
  79616. */
  79617. init: function () {
  79618. ContinuousView.superApply(this, 'init', arguments);
  79619. /**
  79620. * @private
  79621. */
  79622. this._shapes = {};
  79623. /**
  79624. * @private
  79625. */
  79626. this._dataInterval = [];
  79627. /**
  79628. * @private
  79629. */
  79630. this._handleEnds = [];
  79631. /**
  79632. * @private
  79633. */
  79634. this._orient;
  79635. /**
  79636. * @private
  79637. */
  79638. this._useHandle;
  79639. /**
  79640. * @private
  79641. */
  79642. this._hoverLinkDataIndices = [];
  79643. /**
  79644. * @private
  79645. */
  79646. this._dragging;
  79647. /**
  79648. * @private
  79649. */
  79650. this._hovering;
  79651. },
  79652. /**
  79653. * @protected
  79654. * @override
  79655. */
  79656. doRender: function (visualMapModel, ecModel, api, payload) {
  79657. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  79658. this._buildView();
  79659. }
  79660. },
  79661. /**
  79662. * @private
  79663. */
  79664. _buildView: function () {
  79665. this.group.removeAll();
  79666. var visualMapModel = this.visualMapModel;
  79667. var thisGroup = this.group;
  79668. this._orient = visualMapModel.get('orient');
  79669. this._useHandle = visualMapModel.get('calculable');
  79670. this._resetInterval();
  79671. this._renderBar(thisGroup);
  79672. var dataRangeText = visualMapModel.get('text');
  79673. this._renderEndsText(thisGroup, dataRangeText, 0);
  79674. this._renderEndsText(thisGroup, dataRangeText, 1);
  79675. // Do this for background size calculation.
  79676. this._updateView(true);
  79677. // After updating view, inner shapes is built completely,
  79678. // and then background can be rendered.
  79679. this.renderBackground(thisGroup);
  79680. // Real update view
  79681. this._updateView();
  79682. this._enableHoverLinkToSeries();
  79683. this._enableHoverLinkFromSeries();
  79684. this.positionGroup(thisGroup);
  79685. },
  79686. /**
  79687. * @private
  79688. */
  79689. _renderEndsText: function (group, dataRangeText, endsIndex) {
  79690. if (!dataRangeText) {
  79691. return;
  79692. }
  79693. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  79694. var text = dataRangeText[1 - endsIndex];
  79695. text = text != null ? text + '' : '';
  79696. var visualMapModel = this.visualMapModel;
  79697. var textGap = visualMapModel.get('textGap');
  79698. var itemSize = visualMapModel.itemSize;
  79699. var barGroup = this._shapes.barGroup;
  79700. var position = this._applyTransform(
  79701. [
  79702. itemSize[0] / 2,
  79703. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  79704. ],
  79705. barGroup
  79706. );
  79707. var align = this._applyTransform(
  79708. endsIndex === 0 ? 'bottom' : 'top',
  79709. barGroup
  79710. );
  79711. var orient = this._orient;
  79712. var textStyleModel = this.visualMapModel.textStyleModel;
  79713. this.group.add(new Text({
  79714. style: {
  79715. x: position[0],
  79716. y: position[1],
  79717. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  79718. textAlign: orient === 'horizontal' ? align : 'center',
  79719. text: text,
  79720. textFont: textStyleModel.getFont(),
  79721. textFill: textStyleModel.getTextColor()
  79722. }
  79723. }));
  79724. },
  79725. /**
  79726. * @private
  79727. */
  79728. _renderBar: function (targetGroup) {
  79729. var visualMapModel = this.visualMapModel;
  79730. var shapes = this._shapes;
  79731. var itemSize = visualMapModel.itemSize;
  79732. var orient = this._orient;
  79733. var useHandle = this._useHandle;
  79734. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  79735. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  79736. // Bar
  79737. barGroup.add(shapes.outOfRange = createPolygon());
  79738. barGroup.add(shapes.inRange = createPolygon(
  79739. null,
  79740. useHandle ? getCursor$1(this._orient) : null,
  79741. bind(this._dragHandle, this, 'all', false),
  79742. bind(this._dragHandle, this, 'all', true)
  79743. ));
  79744. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  79745. var textSize = mathMax$8(textRect.width, textRect.height);
  79746. // Handle
  79747. if (useHandle) {
  79748. shapes.handleThumbs = [];
  79749. shapes.handleLabels = [];
  79750. shapes.handleLabelPoints = [];
  79751. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  79752. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  79753. }
  79754. this._createIndicator(barGroup, itemSize, textSize, orient);
  79755. targetGroup.add(barGroup);
  79756. },
  79757. /**
  79758. * @private
  79759. */
  79760. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  79761. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  79762. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  79763. var handleThumb = createPolygon(
  79764. createHandlePoints(handleIndex, textSize),
  79765. getCursor$1(this._orient),
  79766. onDrift,
  79767. onDragEnd
  79768. );
  79769. handleThumb.position[0] = itemSize[0];
  79770. barGroup.add(handleThumb);
  79771. // Text is always horizontal layout but should not be effected by
  79772. // transform (orient/inverse). So label is built separately but not
  79773. // use zrender/graphic/helper/RectText, and is located based on view
  79774. // group (according to handleLabelPoint) but not barGroup.
  79775. var textStyleModel = this.visualMapModel.textStyleModel;
  79776. var handleLabel = new Text({
  79777. draggable: true,
  79778. drift: onDrift,
  79779. onmousemove: function (e) {
  79780. // Fot mobile devicem, prevent screen slider on the button.
  79781. stop(e.event);
  79782. },
  79783. ondragend: onDragEnd,
  79784. style: {
  79785. x: 0, y: 0, text: '',
  79786. textFont: textStyleModel.getFont(),
  79787. textFill: textStyleModel.getTextColor()
  79788. }
  79789. });
  79790. this.group.add(handleLabel);
  79791. var handleLabelPoint = [
  79792. orient === 'horizontal'
  79793. ? textSize / 2
  79794. : textSize * 1.5,
  79795. orient === 'horizontal'
  79796. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  79797. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  79798. ];
  79799. var shapes = this._shapes;
  79800. shapes.handleThumbs[handleIndex] = handleThumb;
  79801. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  79802. shapes.handleLabels[handleIndex] = handleLabel;
  79803. },
  79804. /**
  79805. * @private
  79806. */
  79807. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  79808. var indicator = createPolygon([[0, 0]], 'move');
  79809. indicator.position[0] = itemSize[0];
  79810. indicator.attr({invisible: true, silent: true});
  79811. barGroup.add(indicator);
  79812. var textStyleModel = this.visualMapModel.textStyleModel;
  79813. var indicatorLabel = new Text({
  79814. silent: true,
  79815. invisible: true,
  79816. style: {
  79817. x: 0, y: 0, text: '',
  79818. textFont: textStyleModel.getFont(),
  79819. textFill: textStyleModel.getTextColor()
  79820. }
  79821. });
  79822. this.group.add(indicatorLabel);
  79823. var indicatorLabelPoint = [
  79824. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  79825. 0
  79826. ];
  79827. var shapes = this._shapes;
  79828. shapes.indicator = indicator;
  79829. shapes.indicatorLabel = indicatorLabel;
  79830. shapes.indicatorLabelPoint = indicatorLabelPoint;
  79831. },
  79832. /**
  79833. * @private
  79834. */
  79835. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  79836. if (!this._useHandle) {
  79837. return;
  79838. }
  79839. this._dragging = !isEnd;
  79840. if (!isEnd) {
  79841. // Transform dx, dy to bar coordination.
  79842. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  79843. this._updateInterval(handleIndex, vertex[1]);
  79844. // Considering realtime, update view should be executed
  79845. // before dispatch action.
  79846. this._updateView();
  79847. }
  79848. // dragEnd do not dispatch action when realtime.
  79849. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  79850. this.api.dispatchAction({
  79851. type: 'selectDataRange',
  79852. from: this.uid,
  79853. visualMapId: this.visualMapModel.id,
  79854. selected: this._dataInterval.slice()
  79855. });
  79856. }
  79857. if (isEnd) {
  79858. !this._hovering && this._clearHoverLinkToSeries();
  79859. }
  79860. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  79861. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  79862. }
  79863. },
  79864. /**
  79865. * @private
  79866. */
  79867. _resetInterval: function () {
  79868. var visualMapModel = this.visualMapModel;
  79869. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  79870. var dataExtent = visualMapModel.getExtent();
  79871. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79872. this._handleEnds = [
  79873. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  79874. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  79875. ];
  79876. },
  79877. /**
  79878. * @private
  79879. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  79880. * @param {number} dx
  79881. * @param {number} dy
  79882. */
  79883. _updateInterval: function (handleIndex, delta) {
  79884. delta = delta || 0;
  79885. var visualMapModel = this.visualMapModel;
  79886. var handleEnds = this._handleEnds;
  79887. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79888. sliderMove(
  79889. delta,
  79890. handleEnds,
  79891. sizeExtent,
  79892. handleIndex,
  79893. // cross is forbiden
  79894. 0
  79895. );
  79896. var dataExtent = visualMapModel.getExtent();
  79897. // Update data interval.
  79898. this._dataInterval = [
  79899. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  79900. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  79901. ];
  79902. },
  79903. /**
  79904. * @private
  79905. */
  79906. _updateView: function (forSketch) {
  79907. var visualMapModel = this.visualMapModel;
  79908. var dataExtent = visualMapModel.getExtent();
  79909. var shapes = this._shapes;
  79910. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  79911. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  79912. var visualInRange = this._createBarVisual(
  79913. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  79914. );
  79915. var visualOutOfRange = this._createBarVisual(
  79916. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  79917. );
  79918. shapes.inRange
  79919. .setStyle({
  79920. fill: visualInRange.barColor,
  79921. opacity: visualInRange.opacity
  79922. })
  79923. .setShape('points', visualInRange.barPoints);
  79924. shapes.outOfRange
  79925. .setStyle({
  79926. fill: visualOutOfRange.barColor,
  79927. opacity: visualOutOfRange.opacity
  79928. })
  79929. .setShape('points', visualOutOfRange.barPoints);
  79930. this._updateHandle(inRangeHandleEnds, visualInRange);
  79931. },
  79932. /**
  79933. * @private
  79934. */
  79935. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  79936. var opts = {
  79937. forceState: forceState,
  79938. convertOpacityToAlpha: true
  79939. };
  79940. var colorStops = this._makeColorGradient(dataInterval, opts);
  79941. var symbolSizes = [
  79942. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  79943. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  79944. ];
  79945. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  79946. return {
  79947. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  79948. barPoints: barPoints,
  79949. handlesColor: [
  79950. colorStops[0].color,
  79951. colorStops[colorStops.length - 1].color
  79952. ]
  79953. };
  79954. },
  79955. /**
  79956. * @private
  79957. */
  79958. _makeColorGradient: function (dataInterval, opts) {
  79959. // Considering colorHue, which is not linear, so we have to sample
  79960. // to calculate gradient color stops, but not only caculate head
  79961. // and tail.
  79962. var sampleNumber = 100; // Arbitrary value.
  79963. var colorStops = [];
  79964. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  79965. colorStops.push({
  79966. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  79967. offset: 0
  79968. });
  79969. for (var i = 1; i < sampleNumber; i++) {
  79970. var currValue = dataInterval[0] + step * i;
  79971. if (currValue > dataInterval[1]) {
  79972. break;
  79973. }
  79974. colorStops.push({
  79975. color: this.getControllerVisual(currValue, 'color', opts),
  79976. offset: i / sampleNumber
  79977. });
  79978. }
  79979. colorStops.push({
  79980. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  79981. offset: 1
  79982. });
  79983. return colorStops;
  79984. },
  79985. /**
  79986. * @private
  79987. */
  79988. _createBarPoints: function (handleEnds, symbolSizes) {
  79989. var itemSize = this.visualMapModel.itemSize;
  79990. return [
  79991. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  79992. [itemSize[0], handleEnds[0]],
  79993. [itemSize[0], handleEnds[1]],
  79994. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  79995. ];
  79996. },
  79997. /**
  79998. * @private
  79999. */
  80000. _createBarGroup: function (itemAlign) {
  80001. var orient = this._orient;
  80002. var inverse = this.visualMapModel.get('inverse');
  80003. return new Group(
  80004. (orient === 'horizontal' && !inverse)
  80005. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  80006. : (orient === 'horizontal' && inverse)
  80007. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  80008. : (orient === 'vertical' && !inverse)
  80009. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  80010. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  80011. );
  80012. },
  80013. /**
  80014. * @private
  80015. */
  80016. _updateHandle: function (handleEnds, visualInRange) {
  80017. if (!this._useHandle) {
  80018. return;
  80019. }
  80020. var shapes = this._shapes;
  80021. var visualMapModel = this.visualMapModel;
  80022. var handleThumbs = shapes.handleThumbs;
  80023. var handleLabels = shapes.handleLabels;
  80024. each$29([0, 1], function (handleIndex) {
  80025. var handleThumb = handleThumbs[handleIndex];
  80026. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  80027. handleThumb.position[1] = handleEnds[handleIndex];
  80028. // Update handle label position.
  80029. var textPoint = applyTransform$1(
  80030. shapes.handleLabelPoints[handleIndex],
  80031. getTransform(handleThumb, this.group)
  80032. );
  80033. handleLabels[handleIndex].setStyle({
  80034. x: textPoint[0],
  80035. y: textPoint[1],
  80036. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  80037. textVerticalAlign: 'middle',
  80038. textAlign: this._applyTransform(
  80039. this._orient === 'horizontal'
  80040. ? (handleIndex === 0 ? 'bottom' : 'top')
  80041. : 'left',
  80042. shapes.barGroup
  80043. )
  80044. });
  80045. }, this);
  80046. },
  80047. /**
  80048. * @private
  80049. * @param {number} cursorValue
  80050. * @param {number} textValue
  80051. * @param {string} [rangeSymbol]
  80052. * @param {number} [halfHoverLinkSize]
  80053. */
  80054. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  80055. var visualMapModel = this.visualMapModel;
  80056. var dataExtent = visualMapModel.getExtent();
  80057. var itemSize = visualMapModel.itemSize;
  80058. var sizeExtent = [0, itemSize[1]];
  80059. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  80060. var shapes = this._shapes;
  80061. var indicator = shapes.indicator;
  80062. if (!indicator) {
  80063. return;
  80064. }
  80065. indicator.position[1] = pos;
  80066. indicator.attr('invisible', false);
  80067. indicator.setShape('points', createIndicatorPoints(
  80068. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  80069. ));
  80070. var opts = {convertOpacityToAlpha: true};
  80071. var color = this.getControllerVisual(cursorValue, 'color', opts);
  80072. indicator.setStyle('fill', color);
  80073. // Update handle label position.
  80074. var textPoint = applyTransform$1(
  80075. shapes.indicatorLabelPoint,
  80076. getTransform(indicator, this.group)
  80077. );
  80078. var indicatorLabel = shapes.indicatorLabel;
  80079. indicatorLabel.attr('invisible', false);
  80080. var align = this._applyTransform('left', shapes.barGroup);
  80081. var orient = this._orient;
  80082. indicatorLabel.setStyle({
  80083. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  80084. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  80085. textAlign: orient === 'horizontal' ? 'center' : align,
  80086. x: textPoint[0],
  80087. y: textPoint[1]
  80088. });
  80089. },
  80090. /**
  80091. * @private
  80092. */
  80093. _enableHoverLinkToSeries: function () {
  80094. var self = this;
  80095. this._shapes.barGroup
  80096. .on('mousemove', function (e) {
  80097. self._hovering = true;
  80098. if (!self._dragging) {
  80099. var itemSize = self.visualMapModel.itemSize;
  80100. var pos = self._applyTransform(
  80101. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  80102. );
  80103. // For hover link show when hover handle, which might be
  80104. // below or upper than sizeExtent.
  80105. pos[1] = mathMin$8(mathMax$8(0, pos[1]), itemSize[1]);
  80106. self._doHoverLinkToSeries(
  80107. pos[1],
  80108. 0 <= pos[0] && pos[0] <= itemSize[0]
  80109. );
  80110. }
  80111. })
  80112. .on('mouseout', function () {
  80113. // When mouse is out of handle, hoverLink still need
  80114. // to be displayed when realtime is set as false.
  80115. self._hovering = false;
  80116. !self._dragging && self._clearHoverLinkToSeries();
  80117. });
  80118. },
  80119. /**
  80120. * @private
  80121. */
  80122. _enableHoverLinkFromSeries: function () {
  80123. var zr = this.api.getZr();
  80124. if (this.visualMapModel.option.hoverLink) {
  80125. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  80126. zr.on('mouseout', this._hideIndicator, this);
  80127. }
  80128. else {
  80129. this._clearHoverLinkFromSeries();
  80130. }
  80131. },
  80132. /**
  80133. * @private
  80134. */
  80135. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  80136. var visualMapModel = this.visualMapModel;
  80137. var itemSize = visualMapModel.itemSize;
  80138. if (!visualMapModel.option.hoverLink) {
  80139. return;
  80140. }
  80141. var sizeExtent = [0, itemSize[1]];
  80142. var dataExtent = visualMapModel.getExtent();
  80143. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  80144. cursorPos = mathMin$8(mathMax$8(sizeExtent[0], cursorPos), sizeExtent[1]);
  80145. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  80146. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  80147. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  80148. var valueRange = [
  80149. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  80150. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  80151. ];
  80152. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  80153. // where china and india has very large population.
  80154. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  80155. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  80156. // Do not show indicator when mouse is over handle,
  80157. // otherwise labels overlap, especially when dragging.
  80158. if (hoverOnBar) {
  80159. if (valueRange[0] === -Infinity) {
  80160. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  80161. }
  80162. else if (valueRange[1] === Infinity) {
  80163. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  80164. }
  80165. else {
  80166. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  80167. }
  80168. }
  80169. // When realtime is set as false, handles, which are in barGroup,
  80170. // also trigger hoverLink, which help user to realize where they
  80171. // focus on when dragging. (see test/heatmap-large.html)
  80172. // When realtime is set as true, highlight will not show when hover
  80173. // handle, because the label on handle, which displays a exact value
  80174. // but not range, might mislead users.
  80175. var oldBatch = this._hoverLinkDataIndices;
  80176. var newBatch = [];
  80177. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  80178. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  80179. }
  80180. var resultBatches = compressBatches(oldBatch, newBatch);
  80181. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  80182. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  80183. },
  80184. /**
  80185. * @private
  80186. */
  80187. _hoverLinkFromSeriesMouseOver: function (e) {
  80188. var el = e.target;
  80189. var visualMapModel = this.visualMapModel;
  80190. if (!el || el.dataIndex == null) {
  80191. return;
  80192. }
  80193. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  80194. if (!visualMapModel.isTargetSeries(dataModel)) {
  80195. return;
  80196. }
  80197. var data = dataModel.getData(el.dataType);
  80198. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  80199. if (!isNaN(value)) {
  80200. this._showIndicator(value, value);
  80201. }
  80202. },
  80203. /**
  80204. * @private
  80205. */
  80206. _hideIndicator: function () {
  80207. var shapes = this._shapes;
  80208. shapes.indicator && shapes.indicator.attr('invisible', true);
  80209. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  80210. },
  80211. /**
  80212. * @private
  80213. */
  80214. _clearHoverLinkToSeries: function () {
  80215. this._hideIndicator();
  80216. var indices = this._hoverLinkDataIndices;
  80217. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  80218. indices.length = 0;
  80219. },
  80220. /**
  80221. * @private
  80222. */
  80223. _clearHoverLinkFromSeries: function () {
  80224. this._hideIndicator();
  80225. var zr = this.api.getZr();
  80226. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  80227. zr.off('mouseout', this._hideIndicator);
  80228. },
  80229. /**
  80230. * @private
  80231. */
  80232. _applyTransform: function (vertex, element, inverse, global) {
  80233. var transform = getTransform(element, global ? null : this.group);
  80234. return graphic[
  80235. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  80236. ](vertex, transform, inverse);
  80237. },
  80238. /**
  80239. * @private
  80240. */
  80241. _dispatchHighDown: function (type, batch) {
  80242. batch && batch.length && this.api.dispatchAction({
  80243. type: type,
  80244. batch: batch
  80245. });
  80246. },
  80247. /**
  80248. * @override
  80249. */
  80250. dispose: function () {
  80251. this._clearHoverLinkFromSeries();
  80252. this._clearHoverLinkToSeries();
  80253. },
  80254. /**
  80255. * @override
  80256. */
  80257. remove: function () {
  80258. this._clearHoverLinkFromSeries();
  80259. this._clearHoverLinkToSeries();
  80260. }
  80261. });
  80262. function createPolygon(points, cursor, onDrift, onDragEnd) {
  80263. return new Polygon({
  80264. shape: {points: points},
  80265. draggable: !!onDrift,
  80266. cursor: cursor,
  80267. drift: onDrift,
  80268. onmousemove: function (e) {
  80269. // Fot mobile devicem, prevent screen slider on the button.
  80270. stop(e.event);
  80271. },
  80272. ondragend: onDragEnd
  80273. });
  80274. }
  80275. function createHandlePoints(handleIndex, textSize) {
  80276. return handleIndex === 0
  80277. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  80278. : [[0, 0], [textSize, 0], [textSize, textSize]];
  80279. }
  80280. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  80281. return isRange
  80282. ? [ // indicate range
  80283. [0, -mathMin$8(halfHoverLinkSize, mathMax$8(pos, 0))],
  80284. [HOVER_LINK_OUT, 0],
  80285. [0, mathMin$8(halfHoverLinkSize, mathMax$8(extentMax - pos, 0))]
  80286. ]
  80287. : [ // indicate single value
  80288. [0, 0], [5, -5], [5, 5]
  80289. ];
  80290. }
  80291. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  80292. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  80293. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  80294. if (hoverLinkDataSize) {
  80295. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  80296. }
  80297. return halfHoverLinkSize;
  80298. }
  80299. function useHoverLinkOnHandle(visualMapModel) {
  80300. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  80301. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  80302. }
  80303. function getCursor$1(orient) {
  80304. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  80305. }
  80306. /*
  80307. * Licensed to the Apache Software Foundation (ASF) under one
  80308. * or more contributor license agreements. See the NOTICE file
  80309. * distributed with this work for additional information
  80310. * regarding copyright ownership. The ASF licenses this file
  80311. * to you under the Apache License, Version 2.0 (the
  80312. * "License"); you may not use this file except in compliance
  80313. * with the License. You may obtain a copy of the License at
  80314. *
  80315. * http://www.apache.org/licenses/LICENSE-2.0
  80316. *
  80317. * Unless required by applicable law or agreed to in writing,
  80318. * software distributed under the License is distributed on an
  80319. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80320. * KIND, either express or implied. See the License for the
  80321. * specific language governing permissions and limitations
  80322. * under the License.
  80323. */
  80324. var actionInfo$2 = {
  80325. type: 'selectDataRange',
  80326. event: 'dataRangeSelected',
  80327. // FIXME use updateView appears wrong
  80328. update: 'update'
  80329. };
  80330. registerAction(actionInfo$2, function (payload, ecModel) {
  80331. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  80332. model.setSelected(payload.selected);
  80333. });
  80334. });
  80335. /*
  80336. * Licensed to the Apache Software Foundation (ASF) under one
  80337. * or more contributor license agreements. See the NOTICE file
  80338. * distributed with this work for additional information
  80339. * regarding copyright ownership. The ASF licenses this file
  80340. * to you under the Apache License, Version 2.0 (the
  80341. * "License"); you may not use this file except in compliance
  80342. * with the License. You may obtain a copy of the License at
  80343. *
  80344. * http://www.apache.org/licenses/LICENSE-2.0
  80345. *
  80346. * Unless required by applicable law or agreed to in writing,
  80347. * software distributed under the License is distributed on an
  80348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80349. * KIND, either express or implied. See the License for the
  80350. * specific language governing permissions and limitations
  80351. * under the License.
  80352. */
  80353. /**
  80354. * DataZoom component entry
  80355. */
  80356. registerPreprocessor(preprocessor$3);
  80357. /*
  80358. * Licensed to the Apache Software Foundation (ASF) under one
  80359. * or more contributor license agreements. See the NOTICE file
  80360. * distributed with this work for additional information
  80361. * regarding copyright ownership. The ASF licenses this file
  80362. * to you under the Apache License, Version 2.0 (the
  80363. * "License"); you may not use this file except in compliance
  80364. * with the License. You may obtain a copy of the License at
  80365. *
  80366. * http://www.apache.org/licenses/LICENSE-2.0
  80367. *
  80368. * Unless required by applicable law or agreed to in writing,
  80369. * software distributed under the License is distributed on an
  80370. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80371. * KIND, either express or implied. See the License for the
  80372. * specific language governing permissions and limitations
  80373. * under the License.
  80374. */
  80375. var PiecewiseModel = VisualMapModel.extend({
  80376. type: 'visualMap.piecewise',
  80377. /**
  80378. * Order Rule:
  80379. *
  80380. * option.categories / option.pieces / option.text / option.selected:
  80381. * If !option.inverse,
  80382. * Order when vertical: ['top', ..., 'bottom'].
  80383. * Order when horizontal: ['left', ..., 'right'].
  80384. * If option.inverse, the meaning of
  80385. * the order should be reversed.
  80386. *
  80387. * this._pieceList:
  80388. * The order is always [low, ..., high].
  80389. *
  80390. * Mapping from location to low-high:
  80391. * If !option.inverse
  80392. * When vertical, top is high.
  80393. * When horizontal, right is high.
  80394. * If option.inverse, reverse.
  80395. */
  80396. /**
  80397. * @protected
  80398. */
  80399. defaultOption: {
  80400. selected: null, // Object. If not specified, means selected.
  80401. // When pieces and splitNumber: {'0': true, '5': true}
  80402. // When categories: {'cate1': false, 'cate3': true}
  80403. // When selected === false, means all unselected.
  80404. minOpen: false, // Whether include values that smaller than `min`.
  80405. maxOpen: false, // Whether include values that bigger than `max`.
  80406. align: 'auto', // 'auto', 'left', 'right'
  80407. itemWidth: 20, // When put the controller vertically, it is the length of
  80408. // horizontal side of each item. Otherwise, vertical side.
  80409. itemHeight: 14, // When put the controller vertically, it is the length of
  80410. // vertical side of each item. Otherwise, horizontal side.
  80411. itemSymbol: 'roundRect',
  80412. pieceList: null, // Each item is Object, with some of those attrs:
  80413. // {min, max, lt, gt, lte, gte, value,
  80414. // color, colorSaturation, colorAlpha, opacity,
  80415. // symbol, symbolSize}, which customize the range or visual
  80416. // coding of the certain piece. Besides, see "Order Rule".
  80417. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  80418. // Attr min/max are ignored when categories set. See "Order Rule"
  80419. splitNumber: 5, // If set to 5, auto split five pieces equally.
  80420. // If set to 0 and component type not set, component type will be
  80421. // determined as "continuous". (It is less reasonable but for ec2
  80422. // compatibility, see echarts/component/visualMap/typeDefaulter)
  80423. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  80424. itemGap: 10, // The gap between two items, in px.
  80425. hoverLink: true, // Enable hover highlight.
  80426. showLabel: null // By default, when text is used, label will hide (the logic
  80427. // is remained for compatibility reason)
  80428. },
  80429. /**
  80430. * @override
  80431. */
  80432. optionUpdated: function (newOption, isInit) {
  80433. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  80434. /**
  80435. * The order is always [low, ..., high].
  80436. * [{text: string, interval: Array.<number>}, ...]
  80437. * @private
  80438. * @type {Array.<Object>}
  80439. */
  80440. this._pieceList = [];
  80441. this.resetExtent();
  80442. /**
  80443. * 'pieces', 'categories', 'splitNumber'
  80444. * @type {string}
  80445. */
  80446. var mode = this._mode = this._determineMode();
  80447. resetMethods[this._mode].call(this);
  80448. this._resetSelected(newOption, isInit);
  80449. var categories = this.option.categories;
  80450. this.resetVisual(function (mappingOption, state) {
  80451. if (mode === 'categories') {
  80452. mappingOption.mappingMethod = 'category';
  80453. mappingOption.categories = clone(categories);
  80454. }
  80455. else {
  80456. mappingOption.dataExtent = this.getExtent();
  80457. mappingOption.mappingMethod = 'piecewise';
  80458. mappingOption.pieceList = map(this._pieceList, function (piece) {
  80459. var piece = clone(piece);
  80460. if (state !== 'inRange') {
  80461. // FIXME
  80462. // outOfRange do not support special visual in pieces.
  80463. piece.visual = null;
  80464. }
  80465. return piece;
  80466. });
  80467. }
  80468. });
  80469. },
  80470. /**
  80471. * @protected
  80472. * @override
  80473. */
  80474. completeVisualOption: function () {
  80475. // Consider this case:
  80476. // visualMap: {
  80477. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  80478. // }
  80479. // where no inRange/outOfRange set but only pieces. So we should make
  80480. // default inRange/outOfRange for this case, otherwise visuals that only
  80481. // appear in `pieces` will not be taken into account in visual encoding.
  80482. var option = this.option;
  80483. var visualTypesInPieces = {};
  80484. var visualTypes = VisualMapping.listVisualTypes();
  80485. var isCategory = this.isCategory();
  80486. each$1(option.pieces, function (piece) {
  80487. each$1(visualTypes, function (visualType) {
  80488. if (piece.hasOwnProperty(visualType)) {
  80489. visualTypesInPieces[visualType] = 1;
  80490. }
  80491. });
  80492. });
  80493. each$1(visualTypesInPieces, function (v, visualType) {
  80494. var exists = 0;
  80495. each$1(this.stateList, function (state) {
  80496. exists |= has(option, state, visualType)
  80497. || has(option.target, state, visualType);
  80498. }, this);
  80499. !exists && each$1(this.stateList, function (state) {
  80500. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  80501. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  80502. );
  80503. });
  80504. }, this);
  80505. function has(obj, state, visualType) {
  80506. return obj && obj[state] && (
  80507. isObject$1(obj[state])
  80508. ? obj[state].hasOwnProperty(visualType)
  80509. : obj[state] === visualType // e.g., inRange: 'symbol'
  80510. );
  80511. }
  80512. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  80513. },
  80514. _resetSelected: function (newOption, isInit) {
  80515. var thisOption = this.option;
  80516. var pieceList = this._pieceList;
  80517. // Selected do not merge but all override.
  80518. var selected = (isInit ? thisOption : newOption).selected || {};
  80519. thisOption.selected = selected;
  80520. // Consider 'not specified' means true.
  80521. each$1(pieceList, function (piece, index) {
  80522. var key = this.getSelectedMapKey(piece);
  80523. if (!selected.hasOwnProperty(key)) {
  80524. selected[key] = true;
  80525. }
  80526. }, this);
  80527. if (thisOption.selectedMode === 'single') {
  80528. // Ensure there is only one selected.
  80529. var hasSel = false;
  80530. each$1(pieceList, function (piece, index) {
  80531. var key = this.getSelectedMapKey(piece);
  80532. if (selected[key]) {
  80533. hasSel
  80534. ? (selected[key] = false)
  80535. : (hasSel = true);
  80536. }
  80537. }, this);
  80538. }
  80539. // thisOption.selectedMode === 'multiple', default: all selected.
  80540. },
  80541. /**
  80542. * @public
  80543. */
  80544. getSelectedMapKey: function (piece) {
  80545. return this._mode === 'categories'
  80546. ? piece.value + '' : piece.index + '';
  80547. },
  80548. /**
  80549. * @public
  80550. */
  80551. getPieceList: function () {
  80552. return this._pieceList;
  80553. },
  80554. /**
  80555. * @private
  80556. * @return {string}
  80557. */
  80558. _determineMode: function () {
  80559. var option = this.option;
  80560. return option.pieces && option.pieces.length > 0
  80561. ? 'pieces'
  80562. : this.option.categories
  80563. ? 'categories'
  80564. : 'splitNumber';
  80565. },
  80566. /**
  80567. * @public
  80568. * @override
  80569. */
  80570. setSelected: function (selected) {
  80571. this.option.selected = clone(selected);
  80572. },
  80573. /**
  80574. * @public
  80575. * @override
  80576. */
  80577. getValueState: function (value) {
  80578. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  80579. return index != null
  80580. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  80581. ? 'inRange' : 'outOfRange'
  80582. )
  80583. : 'outOfRange';
  80584. },
  80585. /**
  80586. * @public
  80587. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  80588. * @return {Array.<Object>} [{seriesId, dataIndex: <Array.<number>>}, ...]
  80589. */
  80590. findTargetDataIndices: function (pieceIndex) {
  80591. var result = [];
  80592. this.eachTargetSeries(function (seriesModel) {
  80593. var dataIndices = [];
  80594. var data = seriesModel.getData();
  80595. data.each(this.getDataDimension(data), function (value, dataIndex) {
  80596. // Should always base on model pieceList, because it is order sensitive.
  80597. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  80598. pIdx === pieceIndex && dataIndices.push(dataIndex);
  80599. }, this);
  80600. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  80601. }, this);
  80602. return result;
  80603. },
  80604. /**
  80605. * @private
  80606. * @param {Object} piece piece.value or piece.interval is required.
  80607. * @return {number} Can be Infinity or -Infinity
  80608. */
  80609. getRepresentValue: function (piece) {
  80610. var representValue;
  80611. if (this.isCategory()) {
  80612. representValue = piece.value;
  80613. }
  80614. else {
  80615. if (piece.value != null) {
  80616. representValue = piece.value;
  80617. }
  80618. else {
  80619. var pieceInterval = piece.interval || [];
  80620. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  80621. ? 0
  80622. : (pieceInterval[0] + pieceInterval[1]) / 2;
  80623. }
  80624. }
  80625. return representValue;
  80626. },
  80627. getVisualMeta: function (getColorVisual) {
  80628. // Do not support category. (category axis is ordinal, numerical)
  80629. if (this.isCategory()) {
  80630. return;
  80631. }
  80632. var stops = [];
  80633. var outerColors = [];
  80634. var visualMapModel = this;
  80635. function setStop(interval, valueState) {
  80636. var representValue = visualMapModel.getRepresentValue({interval: interval});
  80637. if (!valueState) {
  80638. valueState = visualMapModel.getValueState(representValue);
  80639. }
  80640. var color = getColorVisual(representValue, valueState);
  80641. if (interval[0] === -Infinity) {
  80642. outerColors[0] = color;
  80643. }
  80644. else if (interval[1] === Infinity) {
  80645. outerColors[1] = color;
  80646. }
  80647. else {
  80648. stops.push(
  80649. {value: interval[0], color: color},
  80650. {value: interval[1], color: color}
  80651. );
  80652. }
  80653. }
  80654. // Suplement
  80655. var pieceList = this._pieceList.slice();
  80656. if (!pieceList.length) {
  80657. pieceList.push({interval: [-Infinity, Infinity]});
  80658. }
  80659. else {
  80660. var edge = pieceList[0].interval[0];
  80661. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  80662. edge = pieceList[pieceList.length - 1].interval[1];
  80663. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  80664. }
  80665. var curr = -Infinity;
  80666. each$1(pieceList, function (piece) {
  80667. var interval = piece.interval;
  80668. if (interval) {
  80669. // Fulfill gap.
  80670. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  80671. setStop(interval.slice());
  80672. curr = interval[1];
  80673. }
  80674. }, this);
  80675. return {stops: stops, outerColors: outerColors};
  80676. }
  80677. });
  80678. /**
  80679. * Key is this._mode
  80680. * @type {Object}
  80681. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  80682. */
  80683. var resetMethods = {
  80684. splitNumber: function () {
  80685. var thisOption = this.option;
  80686. var pieceList = this._pieceList;
  80687. var precision = Math.min(thisOption.precision, 20);
  80688. var dataExtent = this.getExtent();
  80689. var splitNumber = thisOption.splitNumber;
  80690. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  80691. thisOption.splitNumber = splitNumber;
  80692. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  80693. // Precision auto-adaption
  80694. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  80695. precision++;
  80696. }
  80697. thisOption.precision = precision;
  80698. splitStep = +splitStep.toFixed(precision);
  80699. var index = 0;
  80700. if (thisOption.minOpen) {
  80701. pieceList.push({
  80702. index: index++,
  80703. interval: [-Infinity, dataExtent[0]],
  80704. close: [0, 0]
  80705. });
  80706. }
  80707. for (
  80708. var curr = dataExtent[0], len = index + splitNumber;
  80709. index < len;
  80710. curr += splitStep
  80711. ) {
  80712. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  80713. pieceList.push({
  80714. index: index++,
  80715. interval: [curr, max],
  80716. close: [1, 1]
  80717. });
  80718. }
  80719. if (thisOption.maxOpen) {
  80720. pieceList.push({
  80721. index: index++,
  80722. interval: [dataExtent[1], Infinity],
  80723. close: [0, 0]
  80724. });
  80725. }
  80726. reformIntervals(pieceList);
  80727. each$1(pieceList, function (piece) {
  80728. piece.text = this.formatValueText(piece.interval);
  80729. }, this);
  80730. },
  80731. categories: function () {
  80732. var thisOption = this.option;
  80733. each$1(thisOption.categories, function (cate) {
  80734. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  80735. // 是否改一致。
  80736. this._pieceList.push({
  80737. text: this.formatValueText(cate, true),
  80738. value: cate
  80739. });
  80740. }, this);
  80741. // See "Order Rule".
  80742. normalizeReverse(thisOption, this._pieceList);
  80743. },
  80744. pieces: function () {
  80745. var thisOption = this.option;
  80746. var pieceList = this._pieceList;
  80747. each$1(thisOption.pieces, function (pieceListItem, index) {
  80748. if (!isObject$1(pieceListItem)) {
  80749. pieceListItem = {value: pieceListItem};
  80750. }
  80751. var item = {text: '', index: index};
  80752. if (pieceListItem.label != null) {
  80753. item.text = pieceListItem.label;
  80754. }
  80755. if (pieceListItem.hasOwnProperty('value')) {
  80756. var value = item.value = pieceListItem.value;
  80757. item.interval = [value, value];
  80758. item.close = [1, 1];
  80759. }
  80760. else {
  80761. // `min` `max` is legacy option.
  80762. // `lt` `gt` `lte` `gte` is recommanded.
  80763. var interval = item.interval = [];
  80764. var close = item.close = [0, 0];
  80765. var closeList = [1, 0, 1];
  80766. var infinityList = [-Infinity, Infinity];
  80767. var useMinMax = [];
  80768. for (var lg = 0; lg < 2; lg++) {
  80769. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  80770. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  80771. interval[lg] = pieceListItem[names[i]];
  80772. close[lg] = closeList[i];
  80773. useMinMax[lg] = i === 2;
  80774. }
  80775. interval[lg] == null && (interval[lg] = infinityList[lg]);
  80776. }
  80777. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  80778. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  80779. if (__DEV__) {
  80780. if (interval[0] > interval[1]) {
  80781. console.warn(
  80782. 'Piece ' + index + 'is illegal: ' + interval
  80783. + ' lower bound should not greater then uppper bound.'
  80784. );
  80785. }
  80786. }
  80787. if (interval[0] === interval[1] && close[0] && close[1]) {
  80788. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  80789. // we use value to lift the priority when min === max
  80790. item.value = interval[0];
  80791. }
  80792. }
  80793. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  80794. pieceList.push(item);
  80795. }, this);
  80796. // See "Order Rule".
  80797. normalizeReverse(thisOption, pieceList);
  80798. // Only pieces
  80799. reformIntervals(pieceList);
  80800. each$1(pieceList, function (piece) {
  80801. var close = piece.close;
  80802. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  80803. piece.text = piece.text || this.formatValueText(
  80804. piece.value != null ? piece.value : piece.interval,
  80805. false,
  80806. edgeSymbols
  80807. );
  80808. }, this);
  80809. }
  80810. };
  80811. function normalizeReverse(thisOption, pieceList) {
  80812. var inverse = thisOption.inverse;
  80813. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  80814. pieceList.reverse();
  80815. }
  80816. }
  80817. /*
  80818. * Licensed to the Apache Software Foundation (ASF) under one
  80819. * or more contributor license agreements. See the NOTICE file
  80820. * distributed with this work for additional information
  80821. * regarding copyright ownership. The ASF licenses this file
  80822. * to you under the Apache License, Version 2.0 (the
  80823. * "License"); you may not use this file except in compliance
  80824. * with the License. You may obtain a copy of the License at
  80825. *
  80826. * http://www.apache.org/licenses/LICENSE-2.0
  80827. *
  80828. * Unless required by applicable law or agreed to in writing,
  80829. * software distributed under the License is distributed on an
  80830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80831. * KIND, either express or implied. See the License for the
  80832. * specific language governing permissions and limitations
  80833. * under the License.
  80834. */
  80835. var PiecewiseVisualMapView = VisualMapView.extend({
  80836. type: 'visualMap.piecewise',
  80837. /**
  80838. * @protected
  80839. * @override
  80840. */
  80841. doRender: function () {
  80842. var thisGroup = this.group;
  80843. thisGroup.removeAll();
  80844. var visualMapModel = this.visualMapModel;
  80845. var textGap = visualMapModel.get('textGap');
  80846. var textStyleModel = visualMapModel.textStyleModel;
  80847. var textFont = textStyleModel.getFont();
  80848. var textFill = textStyleModel.getTextColor();
  80849. var itemAlign = this._getItemAlign();
  80850. var itemSize = visualMapModel.itemSize;
  80851. var viewData = this._getViewData();
  80852. var endsText = viewData.endsText;
  80853. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  80854. endsText && this._renderEndsText(
  80855. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  80856. );
  80857. each$1(viewData.viewPieceList, renderItem, this);
  80858. endsText && this._renderEndsText(
  80859. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  80860. );
  80861. box(
  80862. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  80863. );
  80864. this.renderBackground(thisGroup);
  80865. this.positionGroup(thisGroup);
  80866. function renderItem(item) {
  80867. var piece = item.piece;
  80868. var itemGroup = new Group();
  80869. itemGroup.onclick = bind(this._onItemClick, this, piece);
  80870. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  80871. var representValue = visualMapModel.getRepresentValue(piece);
  80872. this._createItemSymbol(
  80873. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  80874. );
  80875. if (showLabel) {
  80876. var visualState = this.visualMapModel.getValueState(representValue);
  80877. itemGroup.add(new Text({
  80878. style: {
  80879. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  80880. y: itemSize[1] / 2,
  80881. text: piece.text,
  80882. textVerticalAlign: 'middle',
  80883. textAlign: itemAlign,
  80884. textFont: textFont,
  80885. textFill: textFill,
  80886. opacity: visualState === 'outOfRange' ? 0.5 : 1
  80887. }
  80888. }));
  80889. }
  80890. thisGroup.add(itemGroup);
  80891. }
  80892. },
  80893. /**
  80894. * @private
  80895. */
  80896. _enableHoverLink: function (itemGroup, pieceIndex) {
  80897. itemGroup
  80898. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  80899. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  80900. function onHoverLink(method) {
  80901. var visualMapModel = this.visualMapModel;
  80902. visualMapModel.option.hoverLink && this.api.dispatchAction({
  80903. type: method,
  80904. batch: makeHighDownBatch(
  80905. visualMapModel.findTargetDataIndices(pieceIndex),
  80906. visualMapModel
  80907. )
  80908. });
  80909. }
  80910. },
  80911. /**
  80912. * @private
  80913. */
  80914. _getItemAlign: function () {
  80915. var visualMapModel = this.visualMapModel;
  80916. var modelOption = visualMapModel.option;
  80917. if (modelOption.orient === 'vertical') {
  80918. return getItemAlign(
  80919. visualMapModel, this.api, visualMapModel.itemSize
  80920. );
  80921. }
  80922. else { // horizontal, most case left unless specifying right.
  80923. var align = modelOption.align;
  80924. if (!align || align === 'auto') {
  80925. align = 'left';
  80926. }
  80927. return align;
  80928. }
  80929. },
  80930. /**
  80931. * @private
  80932. */
  80933. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  80934. if (!text) {
  80935. return;
  80936. }
  80937. var itemGroup = new Group();
  80938. var textStyleModel = this.visualMapModel.textStyleModel;
  80939. itemGroup.add(new Text({
  80940. style: {
  80941. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  80942. y: itemSize[1] / 2,
  80943. textVerticalAlign: 'middle',
  80944. textAlign: showLabel ? itemAlign : 'center',
  80945. text: text,
  80946. textFont: textStyleModel.getFont(),
  80947. textFill: textStyleModel.getTextColor()
  80948. }
  80949. }));
  80950. group.add(itemGroup);
  80951. },
  80952. /**
  80953. * @private
  80954. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  80955. */
  80956. _getViewData: function () {
  80957. var visualMapModel = this.visualMapModel;
  80958. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  80959. return {piece: piece, indexInModelPieceList: index};
  80960. });
  80961. var endsText = visualMapModel.get('text');
  80962. // Consider orient and inverse.
  80963. var orient = visualMapModel.get('orient');
  80964. var inverse = visualMapModel.get('inverse');
  80965. // Order of model pieceList is always [low, ..., high]
  80966. if (orient === 'horizontal' ? inverse : !inverse) {
  80967. viewPieceList.reverse();
  80968. }
  80969. // Origin order of endsText is [high, low]
  80970. else if (endsText) {
  80971. endsText = endsText.slice().reverse();
  80972. }
  80973. return {viewPieceList: viewPieceList, endsText: endsText};
  80974. },
  80975. /**
  80976. * @private
  80977. */
  80978. _createItemSymbol: function (group, representValue, shapeParam) {
  80979. group.add(createSymbol(
  80980. this.getControllerVisual(representValue, 'symbol'),
  80981. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  80982. this.getControllerVisual(representValue, 'color')
  80983. ));
  80984. },
  80985. /**
  80986. * @private
  80987. */
  80988. _onItemClick: function (piece) {
  80989. var visualMapModel = this.visualMapModel;
  80990. var option = visualMapModel.option;
  80991. var selected = clone(option.selected);
  80992. var newKey = visualMapModel.getSelectedMapKey(piece);
  80993. if (option.selectedMode === 'single') {
  80994. selected[newKey] = true;
  80995. each$1(selected, function (o, key) {
  80996. selected[key] = key === newKey;
  80997. });
  80998. }
  80999. else {
  81000. selected[newKey] = !selected[newKey];
  81001. }
  81002. this.api.dispatchAction({
  81003. type: 'selectDataRange',
  81004. from: this.uid,
  81005. visualMapId: this.visualMapModel.id,
  81006. selected: selected
  81007. });
  81008. }
  81009. });
  81010. /*
  81011. * Licensed to the Apache Software Foundation (ASF) under one
  81012. * or more contributor license agreements. See the NOTICE file
  81013. * distributed with this work for additional information
  81014. * regarding copyright ownership. The ASF licenses this file
  81015. * to you under the Apache License, Version 2.0 (the
  81016. * "License"); you may not use this file except in compliance
  81017. * with the License. You may obtain a copy of the License at
  81018. *
  81019. * http://www.apache.org/licenses/LICENSE-2.0
  81020. *
  81021. * Unless required by applicable law or agreed to in writing,
  81022. * software distributed under the License is distributed on an
  81023. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81024. * KIND, either express or implied. See the License for the
  81025. * specific language governing permissions and limitations
  81026. * under the License.
  81027. */
  81028. /**
  81029. * DataZoom component entry
  81030. */
  81031. registerPreprocessor(preprocessor$3);
  81032. /*
  81033. * Licensed to the Apache Software Foundation (ASF) under one
  81034. * or more contributor license agreements. See the NOTICE file
  81035. * distributed with this work for additional information
  81036. * regarding copyright ownership. The ASF licenses this file
  81037. * to you under the Apache License, Version 2.0 (the
  81038. * "License"); you may not use this file except in compliance
  81039. * with the License. You may obtain a copy of the License at
  81040. *
  81041. * http://www.apache.org/licenses/LICENSE-2.0
  81042. *
  81043. * Unless required by applicable law or agreed to in writing,
  81044. * software distributed under the License is distributed on an
  81045. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  81046. * KIND, either express or implied. See the License for the
  81047. * specific language governing permissions and limitations
  81048. * under the License.
  81049. */
  81050. /**
  81051. * visualMap component entry
  81052. */
  81053. var urn = 'urn:schemas-microsoft-com:vml';
  81054. var win = typeof window === 'undefined' ? null : window;
  81055. var vmlInited = false;
  81056. var doc = win && win.document;
  81057. function createNode(tagName) {
  81058. return doCreateNode(tagName);
  81059. }
  81060. // Avoid assign to an exported variable, for transforming to cjs.
  81061. var doCreateNode;
  81062. if (doc && !env$1.canvasSupported) {
  81063. try {
  81064. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  81065. doCreateNode = function (tagName) {
  81066. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  81067. };
  81068. }
  81069. catch (e) {
  81070. doCreateNode = function (tagName) {
  81071. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  81072. };
  81073. }
  81074. }
  81075. // From raphael
  81076. function initVML() {
  81077. if (vmlInited || !doc) {
  81078. return;
  81079. }
  81080. vmlInited = true;
  81081. var styleSheets = doc.styleSheets;
  81082. if (styleSheets.length < 31) {
  81083. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  81084. }
  81085. else {
  81086. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  81087. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  81088. }
  81089. }
  81090. // http://www.w3.org/TR/NOTE-VML
  81091. // TODO Use proxy like svg instead of overwrite brush methods
  81092. var CMD$3 = PathProxy.CMD;
  81093. var round$3 = Math.round;
  81094. var sqrt = Math.sqrt;
  81095. var abs$1 = Math.abs;
  81096. var cos = Math.cos;
  81097. var sin = Math.sin;
  81098. var mathMax$9 = Math.max;
  81099. if (!env$1.canvasSupported) {
  81100. var comma = ',';
  81101. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  81102. var Z = 21600;
  81103. var Z2 = Z / 2;
  81104. var ZLEVEL_BASE = 100000;
  81105. var Z_BASE$1 = 1000;
  81106. var initRootElStyle = function (el) {
  81107. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  81108. el.coordsize = Z + ',' + Z;
  81109. el.coordorigin = '0,0';
  81110. };
  81111. var encodeHtmlAttribute = function (s) {
  81112. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  81113. };
  81114. var rgb2Str = function (r, g, b) {
  81115. return 'rgb(' + [r, g, b].join(',') + ')';
  81116. };
  81117. var append = function (parent, child) {
  81118. if (child && parent && child.parentNode !== parent) {
  81119. parent.appendChild(child);
  81120. }
  81121. };
  81122. var remove = function (parent, child) {
  81123. if (child && parent && child.parentNode === parent) {
  81124. parent.removeChild(child);
  81125. }
  81126. };
  81127. var getZIndex = function (zlevel, z, z2) {
  81128. // z 的取值范围为 [0, 1000]
  81129. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  81130. };
  81131. var parsePercent$3 = parsePercent;
  81132. /***************************************************
  81133. * PATH
  81134. **************************************************/
  81135. var setColorAndOpacity = function (el, color, opacity) {
  81136. var colorArr = parse(color);
  81137. opacity = +opacity;
  81138. if (isNaN(opacity)) {
  81139. opacity = 1;
  81140. }
  81141. if (colorArr) {
  81142. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  81143. el.opacity = opacity * colorArr[3];
  81144. }
  81145. };
  81146. var getColorAndAlpha = function (color) {
  81147. var colorArr = parse(color);
  81148. return [
  81149. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  81150. colorArr[3]
  81151. ];
  81152. };
  81153. var updateFillNode = function (el, style, zrEl) {
  81154. // TODO pattern
  81155. var fill = style.fill;
  81156. if (fill != null) {
  81157. // Modified from excanvas
  81158. if (fill instanceof Gradient) {
  81159. var gradientType;
  81160. var angle = 0;
  81161. var focus = [0, 0];
  81162. // additional offset
  81163. var shift = 0;
  81164. // scale factor for offset
  81165. var expansion = 1;
  81166. var rect = zrEl.getBoundingRect();
  81167. var rectWidth = rect.width;
  81168. var rectHeight = rect.height;
  81169. if (fill.type === 'linear') {
  81170. gradientType = 'gradient';
  81171. var transform = zrEl.transform;
  81172. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81173. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  81174. if (transform) {
  81175. applyTransform(p0, p0, transform);
  81176. applyTransform(p1, p1, transform);
  81177. }
  81178. var dx = p1[0] - p0[0];
  81179. var dy = p1[1] - p0[1];
  81180. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  81181. // The angle should be a non-negative number.
  81182. if (angle < 0) {
  81183. angle += 360;
  81184. }
  81185. // Very small angles produce an unexpected result because they are
  81186. // converted to a scientific notation string.
  81187. if (angle < 1e-6) {
  81188. angle = 0;
  81189. }
  81190. }
  81191. else {
  81192. gradientType = 'gradientradial';
  81193. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  81194. var transform = zrEl.transform;
  81195. var scale$$1 = zrEl.scale;
  81196. var width = rectWidth;
  81197. var height = rectHeight;
  81198. focus = [
  81199. // Percent in bounding rect
  81200. (p0[0] - rect.x) / width,
  81201. (p0[1] - rect.y) / height
  81202. ];
  81203. if (transform) {
  81204. applyTransform(p0, p0, transform);
  81205. }
  81206. width /= scale$$1[0] * Z;
  81207. height /= scale$$1[1] * Z;
  81208. var dimension = mathMax$9(width, height);
  81209. shift = 2 * 0 / dimension;
  81210. expansion = 2 * fill.r / dimension - shift;
  81211. }
  81212. // We need to sort the color stops in ascending order by offset,
  81213. // otherwise IE won't interpret it correctly.
  81214. var stops = fill.colorStops.slice();
  81215. stops.sort(function (cs1, cs2) {
  81216. return cs1.offset - cs2.offset;
  81217. });
  81218. var length$$1 = stops.length;
  81219. // Color and alpha list of first and last stop
  81220. var colorAndAlphaList = [];
  81221. var colors = [];
  81222. for (var i = 0; i < length$$1; i++) {
  81223. var stop = stops[i];
  81224. var colorAndAlpha = getColorAndAlpha(stop.color);
  81225. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  81226. if (i === 0 || i === length$$1 - 1) {
  81227. colorAndAlphaList.push(colorAndAlpha);
  81228. }
  81229. }
  81230. if (length$$1 >= 2) {
  81231. var color1 = colorAndAlphaList[0][0];
  81232. var color2 = colorAndAlphaList[1][0];
  81233. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  81234. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  81235. el.type = gradientType;
  81236. el.method = 'none';
  81237. el.focus = '100%';
  81238. el.angle = angle;
  81239. el.color = color1;
  81240. el.color2 = color2;
  81241. el.colors = colors.join(',');
  81242. // When colors attribute is used, the meanings of opacity and o:opacity2
  81243. // are reversed.
  81244. el.opacity = opacity2;
  81245. // FIXME g_o_:opacity ?
  81246. el.opacity2 = opacity1;
  81247. }
  81248. if (gradientType === 'radial') {
  81249. el.focusposition = focus.join(',');
  81250. }
  81251. }
  81252. else {
  81253. // FIXME Change from Gradient fill to color fill
  81254. setColorAndOpacity(el, fill, style.opacity);
  81255. }
  81256. }
  81257. };
  81258. var updateStrokeNode = function (el, style) {
  81259. // if (style.lineJoin != null) {
  81260. // el.joinstyle = style.lineJoin;
  81261. // }
  81262. // if (style.miterLimit != null) {
  81263. // el.miterlimit = style.miterLimit * Z;
  81264. // }
  81265. // if (style.lineCap != null) {
  81266. // el.endcap = style.lineCap;
  81267. // }
  81268. if (style.lineDash) {
  81269. el.dashstyle = style.lineDash.join(' ');
  81270. }
  81271. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  81272. setColorAndOpacity(el, style.stroke, style.opacity);
  81273. }
  81274. };
  81275. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  81276. var isFill = type === 'fill';
  81277. var el = vmlEl.getElementsByTagName(type)[0];
  81278. // Stroke must have lineWidth
  81279. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  81280. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  81281. // FIXME Remove before updating, or set `colors` will throw error
  81282. if (style[type] instanceof Gradient) {
  81283. remove(vmlEl, el);
  81284. }
  81285. if (!el) {
  81286. el = createNode(type);
  81287. }
  81288. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  81289. append(vmlEl, el);
  81290. }
  81291. else {
  81292. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  81293. remove(vmlEl, el);
  81294. }
  81295. };
  81296. var points$3 = [[], [], []];
  81297. var pathDataToString = function (path, m) {
  81298. var M = CMD$3.M;
  81299. var C = CMD$3.C;
  81300. var L = CMD$3.L;
  81301. var A = CMD$3.A;
  81302. var Q = CMD$3.Q;
  81303. var str = [];
  81304. var nPoint;
  81305. var cmdStr;
  81306. var cmd;
  81307. var i;
  81308. var xi;
  81309. var yi;
  81310. var data = path.data;
  81311. var dataLength = path.len();
  81312. for (i = 0; i < dataLength;) {
  81313. cmd = data[i++];
  81314. cmdStr = '';
  81315. nPoint = 0;
  81316. switch (cmd) {
  81317. case M:
  81318. cmdStr = ' m ';
  81319. nPoint = 1;
  81320. xi = data[i++];
  81321. yi = data[i++];
  81322. points$3[0][0] = xi;
  81323. points$3[0][1] = yi;
  81324. break;
  81325. case L:
  81326. cmdStr = ' l ';
  81327. nPoint = 1;
  81328. xi = data[i++];
  81329. yi = data[i++];
  81330. points$3[0][0] = xi;
  81331. points$3[0][1] = yi;
  81332. break;
  81333. case Q:
  81334. case C:
  81335. cmdStr = ' c ';
  81336. nPoint = 3;
  81337. var x1 = data[i++];
  81338. var y1 = data[i++];
  81339. var x2 = data[i++];
  81340. var y2 = data[i++];
  81341. var x3;
  81342. var y3;
  81343. if (cmd === Q) {
  81344. // Convert quadratic to cubic using degree elevation
  81345. x3 = x2;
  81346. y3 = y2;
  81347. x2 = (x2 + 2 * x1) / 3;
  81348. y2 = (y2 + 2 * y1) / 3;
  81349. x1 = (xi + 2 * x1) / 3;
  81350. y1 = (yi + 2 * y1) / 3;
  81351. }
  81352. else {
  81353. x3 = data[i++];
  81354. y3 = data[i++];
  81355. }
  81356. points$3[0][0] = x1;
  81357. points$3[0][1] = y1;
  81358. points$3[1][0] = x2;
  81359. points$3[1][1] = y2;
  81360. points$3[2][0] = x3;
  81361. points$3[2][1] = y3;
  81362. xi = x3;
  81363. yi = y3;
  81364. break;
  81365. case A:
  81366. var x = 0;
  81367. var y = 0;
  81368. var sx = 1;
  81369. var sy = 1;
  81370. var angle = 0;
  81371. if (m) {
  81372. // Extract SRT from matrix
  81373. x = m[4];
  81374. y = m[5];
  81375. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  81376. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  81377. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  81378. }
  81379. var cx = data[i++];
  81380. var cy = data[i++];
  81381. var rx = data[i++];
  81382. var ry = data[i++];
  81383. var startAngle = data[i++] + angle;
  81384. var endAngle = data[i++] + startAngle + angle;
  81385. // FIXME
  81386. // var psi = data[i++];
  81387. i++;
  81388. var clockwise = data[i++];
  81389. var x0 = cx + cos(startAngle) * rx;
  81390. var y0 = cy + sin(startAngle) * ry;
  81391. var x1 = cx + cos(endAngle) * rx;
  81392. var y1 = cy + sin(endAngle) * ry;
  81393. var type = clockwise ? ' wa ' : ' at ';
  81394. if (Math.abs(x0 - x1) < 1e-4) {
  81395. // IE won't render arches drawn counter clockwise if x0 == x1.
  81396. if (Math.abs(endAngle - startAngle) > 1e-2) {
  81397. // Offset x0 by 1/80 of a pixel. Use something
  81398. // that can be represented in binary
  81399. if (clockwise) {
  81400. x0 += 270 / Z;
  81401. }
  81402. }
  81403. else {
  81404. // Avoid case draw full circle
  81405. if (Math.abs(y0 - cy) < 1e-4) {
  81406. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  81407. y1 -= 270 / Z;
  81408. }
  81409. else {
  81410. y1 += 270 / Z;
  81411. }
  81412. }
  81413. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  81414. x1 += 270 / Z;
  81415. }
  81416. else {
  81417. x1 -= 270 / Z;
  81418. }
  81419. }
  81420. }
  81421. str.push(
  81422. type,
  81423. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  81424. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  81425. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  81426. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  81427. round$3((x0 * sx + x) * Z - Z2), comma,
  81428. round$3((y0 * sy + y) * Z - Z2), comma,
  81429. round$3((x1 * sx + x) * Z - Z2), comma,
  81430. round$3((y1 * sy + y) * Z - Z2)
  81431. );
  81432. xi = x1;
  81433. yi = y1;
  81434. break;
  81435. case CMD$3.R:
  81436. var p0 = points$3[0];
  81437. var p1 = points$3[1];
  81438. // x0, y0
  81439. p0[0] = data[i++];
  81440. p0[1] = data[i++];
  81441. // x1, y1
  81442. p1[0] = p0[0] + data[i++];
  81443. p1[1] = p0[1] + data[i++];
  81444. if (m) {
  81445. applyTransform(p0, p0, m);
  81446. applyTransform(p1, p1, m);
  81447. }
  81448. p0[0] = round$3(p0[0] * Z - Z2);
  81449. p1[0] = round$3(p1[0] * Z - Z2);
  81450. p0[1] = round$3(p0[1] * Z - Z2);
  81451. p1[1] = round$3(p1[1] * Z - Z2);
  81452. str.push(
  81453. // x0, y0
  81454. ' m ', p0[0], comma, p0[1],
  81455. // x1, y0
  81456. ' l ', p1[0], comma, p0[1],
  81457. // x1, y1
  81458. ' l ', p1[0], comma, p1[1],
  81459. // x0, y1
  81460. ' l ', p0[0], comma, p1[1]
  81461. );
  81462. break;
  81463. case CMD$3.Z:
  81464. // FIXME Update xi, yi
  81465. str.push(' x ');
  81466. }
  81467. if (nPoint > 0) {
  81468. str.push(cmdStr);
  81469. for (var k = 0; k < nPoint; k++) {
  81470. var p = points$3[k];
  81471. m && applyTransform(p, p, m);
  81472. // 不 round 会非常慢
  81473. str.push(
  81474. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  81475. k < nPoint - 1 ? comma : ''
  81476. );
  81477. }
  81478. }
  81479. }
  81480. return str.join('');
  81481. };
  81482. // Rewrite the original path method
  81483. Path.prototype.brushVML = function (vmlRoot) {
  81484. var style = this.style;
  81485. var vmlEl = this._vmlEl;
  81486. if (!vmlEl) {
  81487. vmlEl = createNode('shape');
  81488. initRootElStyle(vmlEl);
  81489. this._vmlEl = vmlEl;
  81490. }
  81491. updateFillAndStroke(vmlEl, 'fill', style, this);
  81492. updateFillAndStroke(vmlEl, 'stroke', style, this);
  81493. var m = this.transform;
  81494. var needTransform = m != null;
  81495. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  81496. if (strokeEl) {
  81497. var lineWidth = style.lineWidth;
  81498. // Get the line scale.
  81499. // Determinant of this.m_ means how much the area is enlarged by the
  81500. // transformation. So its square root can be used as a scale factor
  81501. // for width.
  81502. if (needTransform && !style.strokeNoScale) {
  81503. var det = m[0] * m[3] - m[1] * m[2];
  81504. lineWidth *= sqrt(abs$1(det));
  81505. }
  81506. strokeEl.weight = lineWidth + 'px';
  81507. }
  81508. var path = this.path || (this.path = new PathProxy());
  81509. if (this.__dirtyPath) {
  81510. path.beginPath();
  81511. path.subPixelOptimize = false;
  81512. this.buildPath(path, this.shape);
  81513. path.toStatic();
  81514. this.__dirtyPath = false;
  81515. }
  81516. vmlEl.path = pathDataToString(path, this.transform);
  81517. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81518. // Append to root
  81519. append(vmlRoot, vmlEl);
  81520. // Text
  81521. if (style.text != null) {
  81522. this.drawRectText(vmlRoot, this.getBoundingRect());
  81523. }
  81524. else {
  81525. this.removeRectText(vmlRoot);
  81526. }
  81527. };
  81528. Path.prototype.onRemove = function (vmlRoot) {
  81529. remove(vmlRoot, this._vmlEl);
  81530. this.removeRectText(vmlRoot);
  81531. };
  81532. Path.prototype.onAdd = function (vmlRoot) {
  81533. append(vmlRoot, this._vmlEl);
  81534. this.appendRectText(vmlRoot);
  81535. };
  81536. /***************************************************
  81537. * IMAGE
  81538. **************************************************/
  81539. var isImage = function (img) {
  81540. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  81541. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  81542. // return img instanceof Image;
  81543. };
  81544. // Rewrite the original path method
  81545. ZImage.prototype.brushVML = function (vmlRoot) {
  81546. var style = this.style;
  81547. var image = style.image;
  81548. // Image original width, height
  81549. var ow;
  81550. var oh;
  81551. if (isImage(image)) {
  81552. var src = image.src;
  81553. if (src === this._imageSrc) {
  81554. ow = this._imageWidth;
  81555. oh = this._imageHeight;
  81556. }
  81557. else {
  81558. var imageRuntimeStyle = image.runtimeStyle;
  81559. var oldRuntimeWidth = imageRuntimeStyle.width;
  81560. var oldRuntimeHeight = imageRuntimeStyle.height;
  81561. imageRuntimeStyle.width = 'auto';
  81562. imageRuntimeStyle.height = 'auto';
  81563. // get the original size
  81564. ow = image.width;
  81565. oh = image.height;
  81566. // and remove overides
  81567. imageRuntimeStyle.width = oldRuntimeWidth;
  81568. imageRuntimeStyle.height = oldRuntimeHeight;
  81569. // Caching image original width, height and src
  81570. this._imageSrc = src;
  81571. this._imageWidth = ow;
  81572. this._imageHeight = oh;
  81573. }
  81574. image = src;
  81575. }
  81576. else {
  81577. if (image === this._imageSrc) {
  81578. ow = this._imageWidth;
  81579. oh = this._imageHeight;
  81580. }
  81581. }
  81582. if (!image) {
  81583. return;
  81584. }
  81585. var x = style.x || 0;
  81586. var y = style.y || 0;
  81587. var dw = style.width;
  81588. var dh = style.height;
  81589. var sw = style.sWidth;
  81590. var sh = style.sHeight;
  81591. var sx = style.sx || 0;
  81592. var sy = style.sy || 0;
  81593. var hasCrop = sw && sh;
  81594. var vmlEl = this._vmlEl;
  81595. if (!vmlEl) {
  81596. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  81597. // vmlEl = vmlCore.createNode('group');
  81598. vmlEl = doc.createElement('div');
  81599. initRootElStyle(vmlEl);
  81600. this._vmlEl = vmlEl;
  81601. }
  81602. var vmlElStyle = vmlEl.style;
  81603. var hasRotation = false;
  81604. var m;
  81605. var scaleX = 1;
  81606. var scaleY = 1;
  81607. if (this.transform) {
  81608. m = this.transform;
  81609. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  81610. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  81611. hasRotation = m[1] || m[2];
  81612. }
  81613. if (hasRotation) {
  81614. // If filters are necessary (rotation exists), create them
  81615. // filters are bog-slow, so only create them if abbsolutely necessary
  81616. // The following check doesn't account for skews (which don't exist
  81617. // in the canvas spec (yet) anyway.
  81618. // From excanvas
  81619. var p0 = [x, y];
  81620. var p1 = [x + dw, y];
  81621. var p2 = [x, y + dh];
  81622. var p3 = [x + dw, y + dh];
  81623. applyTransform(p0, p0, m);
  81624. applyTransform(p1, p1, m);
  81625. applyTransform(p2, p2, m);
  81626. applyTransform(p3, p3, m);
  81627. var maxX = mathMax$9(p0[0], p1[0], p2[0], p3[0]);
  81628. var maxY = mathMax$9(p0[1], p1[1], p2[1], p3[1]);
  81629. var transformFilter = [];
  81630. transformFilter.push('M11=', m[0] / scaleX, comma,
  81631. 'M12=', m[2] / scaleY, comma,
  81632. 'M21=', m[1] / scaleX, comma,
  81633. 'M22=', m[3] / scaleY, comma,
  81634. 'Dx=', round$3(x * scaleX + m[4]), comma,
  81635. 'Dy=', round$3(y * scaleY + m[5]));
  81636. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  81637. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  81638. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  81639. + transformFilter.join('') + ', SizingMethod=clip)';
  81640. }
  81641. else {
  81642. if (m) {
  81643. x = x * scaleX + m[4];
  81644. y = y * scaleY + m[5];
  81645. }
  81646. vmlElStyle.filter = '';
  81647. vmlElStyle.left = round$3(x) + 'px';
  81648. vmlElStyle.top = round$3(y) + 'px';
  81649. }
  81650. var imageEl = this._imageEl;
  81651. var cropEl = this._cropEl;
  81652. if (!imageEl) {
  81653. imageEl = doc.createElement('div');
  81654. this._imageEl = imageEl;
  81655. }
  81656. var imageELStyle = imageEl.style;
  81657. if (hasCrop) {
  81658. // Needs know image original width and height
  81659. if (!(ow && oh)) {
  81660. var tmpImage = new Image();
  81661. var self = this;
  81662. tmpImage.onload = function () {
  81663. tmpImage.onload = null;
  81664. ow = tmpImage.width;
  81665. oh = tmpImage.height;
  81666. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  81667. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  81668. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  81669. // Caching image original width, height and src
  81670. self._imageWidth = ow;
  81671. self._imageHeight = oh;
  81672. self._imageSrc = image;
  81673. };
  81674. tmpImage.src = image;
  81675. }
  81676. else {
  81677. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  81678. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  81679. }
  81680. if (!cropEl) {
  81681. cropEl = doc.createElement('div');
  81682. cropEl.style.overflow = 'hidden';
  81683. this._cropEl = cropEl;
  81684. }
  81685. var cropElStyle = cropEl.style;
  81686. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  81687. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  81688. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  81689. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  81690. if (!cropEl.parentNode) {
  81691. vmlEl.appendChild(cropEl);
  81692. }
  81693. if (imageEl.parentNode !== cropEl) {
  81694. cropEl.appendChild(imageEl);
  81695. }
  81696. }
  81697. else {
  81698. imageELStyle.width = round$3(scaleX * dw) + 'px';
  81699. imageELStyle.height = round$3(scaleY * dh) + 'px';
  81700. vmlEl.appendChild(imageEl);
  81701. if (cropEl && cropEl.parentNode) {
  81702. vmlEl.removeChild(cropEl);
  81703. this._cropEl = null;
  81704. }
  81705. }
  81706. var filterStr = '';
  81707. var alpha = style.opacity;
  81708. if (alpha < 1) {
  81709. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  81710. }
  81711. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  81712. imageELStyle.filter = filterStr;
  81713. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81714. // Append to root
  81715. append(vmlRoot, vmlEl);
  81716. // Text
  81717. if (style.text != null) {
  81718. this.drawRectText(vmlRoot, this.getBoundingRect());
  81719. }
  81720. };
  81721. ZImage.prototype.onRemove = function (vmlRoot) {
  81722. remove(vmlRoot, this._vmlEl);
  81723. this._vmlEl = null;
  81724. this._cropEl = null;
  81725. this._imageEl = null;
  81726. this.removeRectText(vmlRoot);
  81727. };
  81728. ZImage.prototype.onAdd = function (vmlRoot) {
  81729. append(vmlRoot, this._vmlEl);
  81730. this.appendRectText(vmlRoot);
  81731. };
  81732. /***************************************************
  81733. * TEXT
  81734. **************************************************/
  81735. var DEFAULT_STYLE_NORMAL = 'normal';
  81736. var fontStyleCache = {};
  81737. var fontStyleCacheCount = 0;
  81738. var MAX_FONT_CACHE_SIZE = 100;
  81739. var fontEl = document.createElement('div');
  81740. var getFontStyle = function (fontString) {
  81741. var fontStyle = fontStyleCache[fontString];
  81742. if (!fontStyle) {
  81743. // Clear cache
  81744. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  81745. fontStyleCacheCount = 0;
  81746. fontStyleCache = {};
  81747. }
  81748. var style = fontEl.style;
  81749. var fontFamily;
  81750. try {
  81751. style.font = fontString;
  81752. fontFamily = style.fontFamily.split(',')[0];
  81753. }
  81754. catch (e) {
  81755. }
  81756. fontStyle = {
  81757. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  81758. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  81759. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  81760. size: parseFloat(style.fontSize || 12) | 0,
  81761. family: fontFamily || 'Microsoft YaHei'
  81762. };
  81763. fontStyleCache[fontString] = fontStyle;
  81764. fontStyleCacheCount++;
  81765. }
  81766. return fontStyle;
  81767. };
  81768. var textMeasureEl;
  81769. // Overwrite measure text method
  81770. $override$1('measureText', function (text, textFont) {
  81771. var doc$$1 = doc;
  81772. if (!textMeasureEl) {
  81773. textMeasureEl = doc$$1.createElement('div');
  81774. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  81775. + 'padding:0;margin:0;border:none;white-space:pre;';
  81776. doc.body.appendChild(textMeasureEl);
  81777. }
  81778. try {
  81779. textMeasureEl.style.font = textFont;
  81780. }
  81781. catch (ex) {
  81782. // Ignore failures to set to invalid font.
  81783. }
  81784. textMeasureEl.innerHTML = '';
  81785. // Don't use innerHTML or innerText because they allow markup/whitespace.
  81786. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  81787. return {
  81788. width: textMeasureEl.offsetWidth
  81789. };
  81790. });
  81791. var tmpRect$2 = new BoundingRect();
  81792. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  81793. var style = this.style;
  81794. // Optimize, avoid normalize every time.
  81795. this.__dirty && normalizeTextStyle(style, true);
  81796. var text = style.text;
  81797. // Convert to string
  81798. text != null && (text += '');
  81799. if (!text) {
  81800. return;
  81801. }
  81802. // Convert rich text to plain text. Rich text is not supported in
  81803. // IE8-, but tags in rich text template will be removed.
  81804. if (style.rich) {
  81805. var contentBlock = parseRichText(text, style);
  81806. text = [];
  81807. for (var i = 0; i < contentBlock.lines.length; i++) {
  81808. var tokens = contentBlock.lines[i].tokens;
  81809. var textLine = [];
  81810. for (var j = 0; j < tokens.length; j++) {
  81811. textLine.push(tokens[j].text);
  81812. }
  81813. text.push(textLine.join(''));
  81814. }
  81815. text = text.join('\n');
  81816. }
  81817. var x;
  81818. var y;
  81819. var align = style.textAlign;
  81820. var verticalAlign = style.textVerticalAlign;
  81821. var fontStyle = getFontStyle(style.font);
  81822. // FIXME encodeHtmlAttribute ?
  81823. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  81824. + fontStyle.size + 'px "' + fontStyle.family + '"';
  81825. textRect = textRect || getBoundingRect(
  81826. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  81827. );
  81828. // Transform rect to view space
  81829. var m = this.transform;
  81830. // Ignore transform for text in other element
  81831. if (m && !fromTextEl) {
  81832. tmpRect$2.copy(rect);
  81833. tmpRect$2.applyTransform(m);
  81834. rect = tmpRect$2;
  81835. }
  81836. if (!fromTextEl) {
  81837. var textPosition = style.textPosition;
  81838. // Text position represented by coord
  81839. if (textPosition instanceof Array) {
  81840. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  81841. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  81842. align = align || 'left';
  81843. }
  81844. else {
  81845. var res = this.calculateTextPosition
  81846. ? this.calculateTextPosition({}, style, rect)
  81847. : calculateTextPosition({}, style, rect);
  81848. x = res.x;
  81849. y = res.y;
  81850. // Default align and baseline when has textPosition
  81851. align = align || res.textAlign;
  81852. verticalAlign = verticalAlign || res.textVerticalAlign;
  81853. }
  81854. }
  81855. else {
  81856. x = rect.x;
  81857. y = rect.y;
  81858. }
  81859. x = adjustTextX(x, textRect.width, align);
  81860. y = adjustTextY(y, textRect.height, verticalAlign);
  81861. // Force baseline 'middle'
  81862. y += textRect.height / 2;
  81863. // var fontSize = fontStyle.size;
  81864. // 1.75 is an arbitrary number, as there is no info about the text baseline
  81865. // switch (baseline) {
  81866. // case 'hanging':
  81867. // case 'top':
  81868. // y += fontSize / 1.75;
  81869. // break;
  81870. // case 'middle':
  81871. // break;
  81872. // default:
  81873. // // case null:
  81874. // // case 'alphabetic':
  81875. // // case 'ideographic':
  81876. // // case 'bottom':
  81877. // y -= fontSize / 2.25;
  81878. // break;
  81879. // }
  81880. // switch (align) {
  81881. // case 'left':
  81882. // break;
  81883. // case 'center':
  81884. // x -= textRect.width / 2;
  81885. // break;
  81886. // case 'right':
  81887. // x -= textRect.width;
  81888. // break;
  81889. // case 'end':
  81890. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  81891. // break;
  81892. // case 'start':
  81893. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  81894. // break;
  81895. // default:
  81896. // align = 'left';
  81897. // }
  81898. var createNode$$1 = createNode;
  81899. var textVmlEl = this._textVmlEl;
  81900. var pathEl;
  81901. var textPathEl;
  81902. var skewEl;
  81903. if (!textVmlEl) {
  81904. textVmlEl = createNode$$1('line');
  81905. pathEl = createNode$$1('path');
  81906. textPathEl = createNode$$1('textpath');
  81907. skewEl = createNode$$1('skew');
  81908. // FIXME Why here is not cammel case
  81909. // Align 'center' seems wrong
  81910. textPathEl.style['v-text-align'] = 'left';
  81911. initRootElStyle(textVmlEl);
  81912. pathEl.textpathok = true;
  81913. textPathEl.on = true;
  81914. textVmlEl.from = '0 0';
  81915. textVmlEl.to = '1000 0.05';
  81916. append(textVmlEl, skewEl);
  81917. append(textVmlEl, pathEl);
  81918. append(textVmlEl, textPathEl);
  81919. this._textVmlEl = textVmlEl;
  81920. }
  81921. else {
  81922. // 这里是在前面 appendChild 保证顺序的前提下
  81923. skewEl = textVmlEl.firstChild;
  81924. pathEl = skewEl.nextSibling;
  81925. textPathEl = pathEl.nextSibling;
  81926. }
  81927. var coords = [x, y];
  81928. var textVmlElStyle = textVmlEl.style;
  81929. // Ignore transform for text in other element
  81930. if (m && fromTextEl) {
  81931. applyTransform(coords, coords, m);
  81932. skewEl.on = true;
  81933. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  81934. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  81935. // Text position
  81936. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  81937. // Left top point as origin
  81938. skewEl.origin = '0 0';
  81939. textVmlElStyle.left = '0px';
  81940. textVmlElStyle.top = '0px';
  81941. }
  81942. else {
  81943. skewEl.on = false;
  81944. textVmlElStyle.left = round$3(x) + 'px';
  81945. textVmlElStyle.top = round$3(y) + 'px';
  81946. }
  81947. textPathEl.string = encodeHtmlAttribute(text);
  81948. // TODO
  81949. try {
  81950. textPathEl.style.font = font;
  81951. }
  81952. // Error font format
  81953. catch (e) {}
  81954. updateFillAndStroke(textVmlEl, 'fill', {
  81955. fill: style.textFill,
  81956. opacity: style.opacity
  81957. }, this);
  81958. updateFillAndStroke(textVmlEl, 'stroke', {
  81959. stroke: style.textStroke,
  81960. opacity: style.opacity,
  81961. lineDash: style.lineDash || null // style.lineDash can be `false`.
  81962. }, this);
  81963. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  81964. // Attached to root
  81965. append(vmlRoot, textVmlEl);
  81966. };
  81967. var removeRectText = function (vmlRoot) {
  81968. remove(vmlRoot, this._textVmlEl);
  81969. this._textVmlEl = null;
  81970. };
  81971. var appendRectText = function (vmlRoot) {
  81972. append(vmlRoot, this._textVmlEl);
  81973. };
  81974. var list = [RectText, Displayable, ZImage, Path, Text];
  81975. // In case Displayable has been mixed in RectText
  81976. for (var i$3 = 0; i$3 < list.length; i$3++) {
  81977. var proto$8 = list[i$3].prototype;
  81978. proto$8.drawRectText = drawRectText;
  81979. proto$8.removeRectText = removeRectText;
  81980. proto$8.appendRectText = appendRectText;
  81981. }
  81982. Text.prototype.brushVML = function (vmlRoot) {
  81983. var style = this.style;
  81984. if (style.text != null) {
  81985. this.drawRectText(vmlRoot, {
  81986. x: style.x || 0, y: style.y || 0,
  81987. width: 0, height: 0
  81988. }, this.getBoundingRect(), true);
  81989. }
  81990. else {
  81991. this.removeRectText(vmlRoot);
  81992. }
  81993. };
  81994. Text.prototype.onRemove = function (vmlRoot) {
  81995. this.removeRectText(vmlRoot);
  81996. };
  81997. Text.prototype.onAdd = function (vmlRoot) {
  81998. this.appendRectText(vmlRoot);
  81999. };
  82000. }
  82001. /**
  82002. * VML Painter.
  82003. *
  82004. * @module zrender/vml/Painter
  82005. */
  82006. function parseInt10$1(val) {
  82007. return parseInt(val, 10);
  82008. }
  82009. /**
  82010. * @alias module:zrender/vml/Painter
  82011. */
  82012. function VMLPainter(root, storage) {
  82013. initVML();
  82014. this.root = root;
  82015. this.storage = storage;
  82016. var vmlViewport = document.createElement('div');
  82017. var vmlRoot = document.createElement('div');
  82018. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  82019. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  82020. root.appendChild(vmlViewport);
  82021. this._vmlRoot = vmlRoot;
  82022. this._vmlViewport = vmlViewport;
  82023. this.resize();
  82024. // Modify storage
  82025. var oldDelFromStorage = storage.delFromStorage;
  82026. var oldAddToStorage = storage.addToStorage;
  82027. storage.delFromStorage = function (el) {
  82028. oldDelFromStorage.call(storage, el);
  82029. if (el) {
  82030. el.onRemove && el.onRemove(vmlRoot);
  82031. }
  82032. };
  82033. storage.addToStorage = function (el) {
  82034. // Displayable already has a vml node
  82035. el.onAdd && el.onAdd(vmlRoot);
  82036. oldAddToStorage.call(storage, el);
  82037. };
  82038. this._firstPaint = true;
  82039. }
  82040. VMLPainter.prototype = {
  82041. constructor: VMLPainter,
  82042. getType: function () {
  82043. return 'vml';
  82044. },
  82045. /**
  82046. * @return {HTMLDivElement}
  82047. */
  82048. getViewportRoot: function () {
  82049. return this._vmlViewport;
  82050. },
  82051. getViewportRootOffset: function () {
  82052. var viewportRoot = this.getViewportRoot();
  82053. if (viewportRoot) {
  82054. return {
  82055. offsetLeft: viewportRoot.offsetLeft || 0,
  82056. offsetTop: viewportRoot.offsetTop || 0
  82057. };
  82058. }
  82059. },
  82060. /**
  82061. * 刷新
  82062. */
  82063. refresh: function () {
  82064. var list = this.storage.getDisplayList(true, true);
  82065. this._paintList(list);
  82066. },
  82067. _paintList: function (list) {
  82068. var vmlRoot = this._vmlRoot;
  82069. for (var i = 0; i < list.length; i++) {
  82070. var el = list[i];
  82071. if (el.invisible || el.ignore) {
  82072. if (!el.__alreadyNotVisible) {
  82073. el.onRemove(vmlRoot);
  82074. }
  82075. // Set as already invisible
  82076. el.__alreadyNotVisible = true;
  82077. }
  82078. else {
  82079. if (el.__alreadyNotVisible) {
  82080. el.onAdd(vmlRoot);
  82081. }
  82082. el.__alreadyNotVisible = false;
  82083. if (el.__dirty) {
  82084. el.beforeBrush && el.beforeBrush();
  82085. (el.brushVML || el.brush).call(el, vmlRoot);
  82086. el.afterBrush && el.afterBrush();
  82087. }
  82088. }
  82089. el.__dirty = false;
  82090. }
  82091. if (this._firstPaint) {
  82092. // Detached from document at first time
  82093. // to avoid page refreshing too many times
  82094. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  82095. this._vmlViewport.appendChild(vmlRoot);
  82096. this._firstPaint = false;
  82097. }
  82098. },
  82099. resize: function (width, height) {
  82100. var width = width == null ? this._getWidth() : width;
  82101. var height = height == null ? this._getHeight() : height;
  82102. if (this._width !== width || this._height !== height) {
  82103. this._width = width;
  82104. this._height = height;
  82105. var vmlViewportStyle = this._vmlViewport.style;
  82106. vmlViewportStyle.width = width + 'px';
  82107. vmlViewportStyle.height = height + 'px';
  82108. }
  82109. },
  82110. dispose: function () {
  82111. this.root.innerHTML = '';
  82112. this._vmlRoot =
  82113. this._vmlViewport =
  82114. this.storage = null;
  82115. },
  82116. getWidth: function () {
  82117. return this._width;
  82118. },
  82119. getHeight: function () {
  82120. return this._height;
  82121. },
  82122. clear: function () {
  82123. if (this._vmlViewport) {
  82124. this.root.removeChild(this._vmlViewport);
  82125. }
  82126. },
  82127. _getWidth: function () {
  82128. var root = this.root;
  82129. var stl = root.currentStyle;
  82130. return ((root.clientWidth || parseInt10$1(stl.width))
  82131. - parseInt10$1(stl.paddingLeft)
  82132. - parseInt10$1(stl.paddingRight)) | 0;
  82133. },
  82134. _getHeight: function () {
  82135. var root = this.root;
  82136. var stl = root.currentStyle;
  82137. return ((root.clientHeight || parseInt10$1(stl.height))
  82138. - parseInt10$1(stl.paddingTop)
  82139. - parseInt10$1(stl.paddingBottom)) | 0;
  82140. }
  82141. };
  82142. // Not supported methods
  82143. function createMethodNotSupport(method) {
  82144. return function () {
  82145. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  82146. };
  82147. }
  82148. // Unsupported methods
  82149. each$1([
  82150. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  82151. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  82152. ], function (name) {
  82153. VMLPainter.prototype[name] = createMethodNotSupport(name);
  82154. });
  82155. registerPainter('vml', VMLPainter);
  82156. var svgURI = 'http://www.w3.org/2000/svg';
  82157. function createElement(name) {
  82158. return document.createElementNS(svgURI, name);
  82159. }
  82160. // TODO
  82161. // 1. shadow
  82162. // 2. Image: sx, sy, sw, sh
  82163. var CMD$4 = PathProxy.CMD;
  82164. var arrayJoin = Array.prototype.join;
  82165. var NONE = 'none';
  82166. var mathRound = Math.round;
  82167. var mathSin$3 = Math.sin;
  82168. var mathCos$3 = Math.cos;
  82169. var PI$6 = Math.PI;
  82170. var PI2$6 = Math.PI * 2;
  82171. var degree = 180 / PI$6;
  82172. var EPSILON$4 = 1e-4;
  82173. function round4(val) {
  82174. return mathRound(val * 1e4) / 1e4;
  82175. }
  82176. function isAroundZero$1(val) {
  82177. return val < EPSILON$4 && val > -EPSILON$4;
  82178. }
  82179. function pathHasFill(style, isText) {
  82180. var fill = isText ? style.textFill : style.fill;
  82181. return fill != null && fill !== NONE;
  82182. }
  82183. function pathHasStroke(style, isText) {
  82184. var stroke = isText ? style.textStroke : style.stroke;
  82185. return stroke != null && stroke !== NONE;
  82186. }
  82187. function setTransform(svgEl, m) {
  82188. if (m) {
  82189. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  82190. }
  82191. }
  82192. function attr(el, key, val) {
  82193. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  82194. // Don't set attribute for gradient, since it need new dom nodes
  82195. el.setAttribute(key, val);
  82196. }
  82197. }
  82198. function attrXLink(el, key, val) {
  82199. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  82200. }
  82201. function bindStyle(svgEl, style, isText, el) {
  82202. if (pathHasFill(style, isText)) {
  82203. var fill = isText ? style.textFill : style.fill;
  82204. fill = fill === 'transparent' ? NONE : fill;
  82205. attr(svgEl, 'fill', fill);
  82206. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  82207. }
  82208. else {
  82209. attr(svgEl, 'fill', NONE);
  82210. }
  82211. if (pathHasStroke(style, isText)) {
  82212. var stroke = isText ? style.textStroke : style.stroke;
  82213. stroke = stroke === 'transparent' ? NONE : stroke;
  82214. attr(svgEl, 'stroke', stroke);
  82215. var strokeWidth = isText
  82216. ? style.textStrokeWidth
  82217. : style.lineWidth;
  82218. var strokeScale = !isText && style.strokeNoScale
  82219. ? el.getLineScale()
  82220. : 1;
  82221. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  82222. // stroke then fill for text; fill then stroke for others
  82223. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  82224. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  82225. var lineDash = style.lineDash;
  82226. if (lineDash) {
  82227. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  82228. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  82229. }
  82230. else {
  82231. attr(svgEl, 'stroke-dasharray', '');
  82232. }
  82233. // PENDING
  82234. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  82235. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  82236. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  82237. }
  82238. else {
  82239. attr(svgEl, 'stroke', NONE);
  82240. }
  82241. }
  82242. /***************************************************
  82243. * PATH
  82244. **************************************************/
  82245. function pathDataToString$1(path) {
  82246. var str = [];
  82247. var data = path.data;
  82248. var dataLength = path.len();
  82249. for (var i = 0; i < dataLength;) {
  82250. var cmd = data[i++];
  82251. var cmdStr = '';
  82252. var nData = 0;
  82253. switch (cmd) {
  82254. case CMD$4.M:
  82255. cmdStr = 'M';
  82256. nData = 2;
  82257. break;
  82258. case CMD$4.L:
  82259. cmdStr = 'L';
  82260. nData = 2;
  82261. break;
  82262. case CMD$4.Q:
  82263. cmdStr = 'Q';
  82264. nData = 4;
  82265. break;
  82266. case CMD$4.C:
  82267. cmdStr = 'C';
  82268. nData = 6;
  82269. break;
  82270. case CMD$4.A:
  82271. var cx = data[i++];
  82272. var cy = data[i++];
  82273. var rx = data[i++];
  82274. var ry = data[i++];
  82275. var theta = data[i++];
  82276. var dTheta = data[i++];
  82277. var psi = data[i++];
  82278. var clockwise = data[i++];
  82279. var dThetaPositive = Math.abs(dTheta);
  82280. var isCircle = isAroundZero$1(dThetaPositive - PI2$6)
  82281. || (clockwise ? dTheta >= PI2$6 : -dTheta >= PI2$6);
  82282. // Mapping to 0~2PI
  82283. var unifiedTheta = dTheta > 0 ? dTheta % PI2$6 : (dTheta % PI2$6 + PI2$6);
  82284. var large = false;
  82285. if (isCircle) {
  82286. large = true;
  82287. }
  82288. else if (isAroundZero$1(dThetaPositive)) {
  82289. large = false;
  82290. }
  82291. else {
  82292. large = (unifiedTheta >= PI$6) === !!clockwise;
  82293. }
  82294. var x0 = round4(cx + rx * mathCos$3(theta));
  82295. var y0 = round4(cy + ry * mathSin$3(theta));
  82296. // It will not draw if start point and end point are exactly the same
  82297. // We need to shift the end point with a small value
  82298. // FIXME A better way to draw circle ?
  82299. if (isCircle) {
  82300. if (clockwise) {
  82301. dTheta = PI2$6 - 1e-4;
  82302. }
  82303. else {
  82304. dTheta = -PI2$6 + 1e-4;
  82305. }
  82306. large = true;
  82307. if (i === 9) {
  82308. // Move to (x0, y0) only when CMD.A comes at the
  82309. // first position of a shape.
  82310. // For instance, when drawing a ring, CMD.A comes
  82311. // after CMD.M, so it's unnecessary to move to
  82312. // (x0, y0).
  82313. str.push('M', x0, y0);
  82314. }
  82315. }
  82316. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  82317. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  82318. // FIXME Ellipse
  82319. str.push('A', round4(rx), round4(ry),
  82320. mathRound(psi * degree), +large, +clockwise, x, y);
  82321. break;
  82322. case CMD$4.Z:
  82323. cmdStr = 'Z';
  82324. break;
  82325. case CMD$4.R:
  82326. var x = round4(data[i++]);
  82327. var y = round4(data[i++]);
  82328. var w = round4(data[i++]);
  82329. var h = round4(data[i++]);
  82330. str.push(
  82331. 'M', x, y,
  82332. 'L', x + w, y,
  82333. 'L', x + w, y + h,
  82334. 'L', x, y + h,
  82335. 'L', x, y
  82336. );
  82337. break;
  82338. }
  82339. cmdStr && str.push(cmdStr);
  82340. for (var j = 0; j < nData; j++) {
  82341. // PENDING With scale
  82342. str.push(round4(data[i++]));
  82343. }
  82344. }
  82345. return str.join(' ');
  82346. }
  82347. var svgPath = {};
  82348. svgPath.brush = function (el) {
  82349. var style = el.style;
  82350. var svgEl = el.__svgEl;
  82351. if (!svgEl) {
  82352. svgEl = createElement('path');
  82353. el.__svgEl = svgEl;
  82354. }
  82355. if (!el.path) {
  82356. el.createPathProxy();
  82357. }
  82358. var path = el.path;
  82359. if (el.__dirtyPath) {
  82360. path.beginPath();
  82361. path.subPixelOptimize = false;
  82362. el.buildPath(path, el.shape);
  82363. el.__dirtyPath = false;
  82364. var pathStr = pathDataToString$1(path);
  82365. if (pathStr.indexOf('NaN') < 0) {
  82366. // Ignore illegal path, which may happen such in out-of-range
  82367. // data in Calendar series.
  82368. attr(svgEl, 'd', pathStr);
  82369. }
  82370. }
  82371. bindStyle(svgEl, style, false, el);
  82372. setTransform(svgEl, el.transform);
  82373. if (style.text != null) {
  82374. svgTextDrawRectText(el, el.getBoundingRect());
  82375. }
  82376. else {
  82377. removeOldTextNode(el);
  82378. }
  82379. };
  82380. /***************************************************
  82381. * IMAGE
  82382. **************************************************/
  82383. var svgImage = {};
  82384. svgImage.brush = function (el) {
  82385. var style = el.style;
  82386. var image = style.image;
  82387. if (image instanceof HTMLImageElement) {
  82388. var src = image.src;
  82389. image = src;
  82390. }
  82391. if (!image) {
  82392. return;
  82393. }
  82394. var x = style.x || 0;
  82395. var y = style.y || 0;
  82396. var dw = style.width;
  82397. var dh = style.height;
  82398. var svgEl = el.__svgEl;
  82399. if (!svgEl) {
  82400. svgEl = createElement('image');
  82401. el.__svgEl = svgEl;
  82402. }
  82403. if (image !== el.__imageSrc) {
  82404. attrXLink(svgEl, 'href', image);
  82405. // Caching image src
  82406. el.__imageSrc = image;
  82407. }
  82408. attr(svgEl, 'width', dw);
  82409. attr(svgEl, 'height', dh);
  82410. attr(svgEl, 'x', x);
  82411. attr(svgEl, 'y', y);
  82412. setTransform(svgEl, el.transform);
  82413. if (style.text != null) {
  82414. svgTextDrawRectText(el, el.getBoundingRect());
  82415. }
  82416. else {
  82417. removeOldTextNode(el);
  82418. }
  82419. };
  82420. /***************************************************
  82421. * TEXT
  82422. **************************************************/
  82423. var svgText = {};
  82424. var _tmpTextHostRect = new BoundingRect();
  82425. var _tmpTextBoxPos = {};
  82426. var _tmpTextTransform = [];
  82427. var TEXT_ALIGN_TO_ANCHRO = {
  82428. left: 'start',
  82429. right: 'end',
  82430. center: 'middle',
  82431. middle: 'middle'
  82432. };
  82433. /**
  82434. * @param {module:zrender/Element} el
  82435. * @param {Object|boolean} [hostRect] {x, y, width, height}
  82436. * If set false, rect text is not used.
  82437. */
  82438. var svgTextDrawRectText = function (el, hostRect) {
  82439. var style = el.style;
  82440. var elTransform = el.transform;
  82441. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  82442. el.__dirty && normalizeTextStyle(style, true);
  82443. var text = style.text;
  82444. // Convert to string
  82445. text != null && (text += '');
  82446. if (!needDrawText(text, style)) {
  82447. return;
  82448. }
  82449. // render empty text for svg if no text but need draw text.
  82450. text == null && (text = '');
  82451. // Follow the setting in the canvas renderer, if not transform the
  82452. // text, transform the hostRect, by which the text is located.
  82453. if (!needTransformTextByHostEl && elTransform) {
  82454. _tmpTextHostRect.copy(hostRect);
  82455. _tmpTextHostRect.applyTransform(elTransform);
  82456. hostRect = _tmpTextHostRect;
  82457. }
  82458. var textSvgEl = el.__textSvgEl;
  82459. if (!textSvgEl) {
  82460. textSvgEl = createElement('text');
  82461. el.__textSvgEl = textSvgEl;
  82462. }
  82463. // style.font has been normalized by `normalizeTextStyle`.
  82464. var textSvgElStyle = textSvgEl.style;
  82465. var font = style.font || DEFAULT_FONT$1;
  82466. var computedFont = textSvgEl.__computedFont;
  82467. if (font !== textSvgEl.__styleFont) {
  82468. textSvgElStyle.font = textSvgEl.__styleFont = font;
  82469. // The computedFont might not be the orginal font if it is illegal font.
  82470. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  82471. }
  82472. var textPadding = style.textPadding;
  82473. var textLineHeight = style.textLineHeight;
  82474. var contentBlock = el.__textCotentBlock;
  82475. if (!contentBlock || el.__dirtyText) {
  82476. contentBlock = el.__textCotentBlock = parsePlainText(
  82477. text, computedFont, textPadding, textLineHeight, style.truncate
  82478. );
  82479. }
  82480. var outerHeight = contentBlock.outerHeight;
  82481. var lineHeight = contentBlock.lineHeight;
  82482. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  82483. var baseX = _tmpTextBoxPos.baseX;
  82484. var baseY = _tmpTextBoxPos.baseY;
  82485. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  82486. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  82487. setTextTransform(
  82488. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  82489. );
  82490. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  82491. var textX = baseX;
  82492. var textY = boxY;
  82493. // TODO needDrawBg
  82494. if (textPadding) {
  82495. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  82496. textY += textPadding[0];
  82497. }
  82498. // `textBaseline` is set as 'middle'.
  82499. textY += lineHeight / 2;
  82500. bindStyle(textSvgEl, style, true, el);
  82501. // FIXME
  82502. // Add a <style> to reset all of the text font as inherit?
  82503. // otherwise the outer <style> may set the unexpected style.
  82504. // Font may affect position of each tspan elements
  82505. var canCacheByTextString = contentBlock.canCacheByTextString;
  82506. var tspanList = el.__tspanList || (el.__tspanList = []);
  82507. var tspanOriginLen = tspanList.length;
  82508. // Optimize for most cases, just compare text string to determine change.
  82509. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  82510. if (el.__dirtyText && tspanOriginLen) {
  82511. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  82512. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  82513. }
  82514. }
  82515. }
  82516. else {
  82517. el.__text = text;
  82518. el.__canCacheByTextString = canCacheByTextString;
  82519. var textLines = contentBlock.lines;
  82520. var nTextLines = textLines.length;
  82521. var idx = 0;
  82522. for (; idx < nTextLines; idx++) {
  82523. // Using cached tspan elements
  82524. var tspan = tspanList[idx];
  82525. var singleLineText = textLines[idx];
  82526. if (!tspan) {
  82527. tspan = tspanList[idx] = createElement('tspan');
  82528. textSvgEl.appendChild(tspan);
  82529. tspan.appendChild(document.createTextNode(singleLineText));
  82530. }
  82531. else if (tspan.__zrText !== singleLineText) {
  82532. tspan.innerHTML = '';
  82533. tspan.appendChild(document.createTextNode(singleLineText));
  82534. }
  82535. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  82536. }
  82537. // Remove unused tspan elements
  82538. if (tspanOriginLen > nTextLines) {
  82539. for (; idx < tspanOriginLen; idx++) {
  82540. textSvgEl.removeChild(tspanList[idx]);
  82541. }
  82542. tspanList.length = nTextLines;
  82543. }
  82544. }
  82545. };
  82546. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  82547. identity(_tmpTextTransform);
  82548. if (needTransformTextByHostEl && elTransform) {
  82549. copy$1(_tmpTextTransform, elTransform);
  82550. }
  82551. // textRotation only apply in RectText.
  82552. var textRotation = style.textRotation;
  82553. if (hostRect && textRotation) {
  82554. var origin = style.textOrigin;
  82555. if (origin === 'center') {
  82556. baseX = hostRect.width / 2 + hostRect.x;
  82557. baseY = hostRect.height / 2 + hostRect.y;
  82558. }
  82559. else if (origin) {
  82560. baseX = origin[0] + hostRect.x;
  82561. baseY = origin[1] + hostRect.y;
  82562. }
  82563. _tmpTextTransform[4] -= baseX;
  82564. _tmpTextTransform[5] -= baseY;
  82565. // Positive: anticlockwise
  82566. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  82567. _tmpTextTransform[4] += baseX;
  82568. _tmpTextTransform[5] += baseY;
  82569. }
  82570. // See the definition in `Style.js#textOrigin`, the default
  82571. // origin is from the result of `getBoxPosition`.
  82572. setTransform(textSvgEl, _tmpTextTransform);
  82573. }
  82574. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  82575. function getTextXForPadding$1(x, textAlign, textPadding) {
  82576. return textAlign === 'right'
  82577. ? (x - textPadding[1])
  82578. : textAlign === 'center'
  82579. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  82580. : (x + textPadding[3]);
  82581. }
  82582. function updateTextLocation(tspan, textAlign, x, y) {
  82583. // Consider different font display differently in vertial align, we always
  82584. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  82585. attr(tspan, 'dominant-baseline', 'middle');
  82586. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  82587. attr(tspan, 'x', x);
  82588. attr(tspan, 'y', y);
  82589. }
  82590. function removeOldTextNode(el) {
  82591. if (el && el.__textSvgEl) {
  82592. // textSvgEl may has no parentNode if el has been removed temporary.
  82593. if (el.__textSvgEl.parentNode) {
  82594. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  82595. }
  82596. el.__textSvgEl = null;
  82597. el.__tspanList = [];
  82598. el.__text = null;
  82599. }
  82600. }
  82601. svgText.drawRectText = svgTextDrawRectText;
  82602. svgText.brush = function (el) {
  82603. var style = el.style;
  82604. if (style.text != null) {
  82605. svgTextDrawRectText(el, false);
  82606. }
  82607. else {
  82608. removeOldTextNode(el);
  82609. }
  82610. };
  82611. // Myers' Diff Algorithm
  82612. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  82613. function Diff() {}
  82614. Diff.prototype = {
  82615. diff: function (oldArr, newArr, equals) {
  82616. if (!equals) {
  82617. equals = function (a, b) {
  82618. return a === b;
  82619. };
  82620. }
  82621. this.equals = equals;
  82622. var self = this;
  82623. oldArr = oldArr.slice();
  82624. newArr = newArr.slice();
  82625. // Allow subclasses to massage the input prior to running
  82626. var newLen = newArr.length;
  82627. var oldLen = oldArr.length;
  82628. var editLength = 1;
  82629. var maxEditLength = newLen + oldLen;
  82630. var bestPath = [{ newPos: -1, components: [] }];
  82631. // Seed editLength = 0, i.e. the content starts with the same values
  82632. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  82633. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  82634. var indices = [];
  82635. for (var i = 0; i < newArr.length; i++) {
  82636. indices.push(i);
  82637. }
  82638. // Identity per the equality and tokenizer
  82639. return [{
  82640. indices: indices, count: newArr.length
  82641. }];
  82642. }
  82643. // Main worker method. checks all permutations of a given edit length for acceptance.
  82644. function execEditLength() {
  82645. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  82646. var basePath;
  82647. var addPath = bestPath[diagonalPath - 1];
  82648. var removePath = bestPath[diagonalPath + 1];
  82649. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  82650. if (addPath) {
  82651. // No one else is going to attempt to use this value, clear it
  82652. bestPath[diagonalPath - 1] = undefined;
  82653. }
  82654. var canAdd = addPath && addPath.newPos + 1 < newLen;
  82655. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  82656. if (!canAdd && !canRemove) {
  82657. // If this path is a terminal then prune
  82658. bestPath[diagonalPath] = undefined;
  82659. continue;
  82660. }
  82661. // Select the diagonal that we want to branch from. We select the prior
  82662. // path whose position in the new string is the farthest from the origin
  82663. // and does not pass the bounds of the diff graph
  82664. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  82665. basePath = clonePath(removePath);
  82666. self.pushComponent(basePath.components, undefined, true);
  82667. }
  82668. else {
  82669. basePath = addPath; // No need to clone, we've pulled it from the list
  82670. basePath.newPos++;
  82671. self.pushComponent(basePath.components, true, undefined);
  82672. }
  82673. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  82674. // If we have hit the end of both strings, then we are done
  82675. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  82676. return buildValues(self, basePath.components, newArr, oldArr);
  82677. }
  82678. else {
  82679. // Otherwise track this path as a potential candidate and continue.
  82680. bestPath[diagonalPath] = basePath;
  82681. }
  82682. }
  82683. editLength++;
  82684. }
  82685. while (editLength <= maxEditLength) {
  82686. var ret = execEditLength();
  82687. if (ret) {
  82688. return ret;
  82689. }
  82690. }
  82691. },
  82692. pushComponent: function (components, added, removed) {
  82693. var last = components[components.length - 1];
  82694. if (last && last.added === added && last.removed === removed) {
  82695. // We need to clone here as the component clone operation is just
  82696. // as shallow array clone
  82697. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  82698. }
  82699. else {
  82700. components.push({count: 1, added: added, removed: removed });
  82701. }
  82702. },
  82703. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  82704. var newLen = newArr.length;
  82705. var oldLen = oldArr.length;
  82706. var newPos = basePath.newPos;
  82707. var oldPos = newPos - diagonalPath;
  82708. var commonCount = 0;
  82709. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  82710. newPos++;
  82711. oldPos++;
  82712. commonCount++;
  82713. }
  82714. if (commonCount) {
  82715. basePath.components.push({count: commonCount});
  82716. }
  82717. basePath.newPos = newPos;
  82718. return oldPos;
  82719. },
  82720. tokenize: function (value) {
  82721. return value.slice();
  82722. },
  82723. join: function (value) {
  82724. return value.slice();
  82725. }
  82726. };
  82727. function buildValues(diff, components, newArr, oldArr) {
  82728. var componentPos = 0;
  82729. var componentLen = components.length;
  82730. var newPos = 0;
  82731. var oldPos = 0;
  82732. for (; componentPos < componentLen; componentPos++) {
  82733. var component = components[componentPos];
  82734. if (!component.removed) {
  82735. var indices = [];
  82736. for (var i = newPos; i < newPos + component.count; i++) {
  82737. indices.push(i);
  82738. }
  82739. component.indices = indices;
  82740. newPos += component.count;
  82741. // Common case
  82742. if (!component.added) {
  82743. oldPos += component.count;
  82744. }
  82745. }
  82746. else {
  82747. var indices = [];
  82748. for (var i = oldPos; i < oldPos + component.count; i++) {
  82749. indices.push(i);
  82750. }
  82751. component.indices = indices;
  82752. oldPos += component.count;
  82753. }
  82754. }
  82755. return components;
  82756. }
  82757. function clonePath(path) {
  82758. return { newPos: path.newPos, components: path.components.slice(0) };
  82759. }
  82760. var arrayDiff = new Diff();
  82761. var arrayDiff$1 = function (oldArr, newArr, callback) {
  82762. return arrayDiff.diff(oldArr, newArr, callback);
  82763. };
  82764. /**
  82765. * @file Manages elements that can be defined in <defs> in SVG,
  82766. * e.g., gradients, clip path, etc.
  82767. * @author Zhang Wenli
  82768. */
  82769. var MARK_UNUSED = '0';
  82770. var MARK_USED = '1';
  82771. /**
  82772. * Manages elements that can be defined in <defs> in SVG,
  82773. * e.g., gradients, clip path, etc.
  82774. *
  82775. * @class
  82776. * @param {number} zrId zrender instance id
  82777. * @param {SVGElement} svgRoot root of SVG document
  82778. * @param {string|string[]} tagNames possible tag names
  82779. * @param {string} markLabel label name to make if the element
  82780. * is used
  82781. */
  82782. function Definable(
  82783. zrId,
  82784. svgRoot,
  82785. tagNames,
  82786. markLabel,
  82787. domName
  82788. ) {
  82789. this._zrId = zrId;
  82790. this._svgRoot = svgRoot;
  82791. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  82792. this._markLabel = markLabel;
  82793. this._domName = domName || '_dom';
  82794. this.nextId = 0;
  82795. }
  82796. Definable.prototype.createElement = createElement;
  82797. /**
  82798. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  82799. *
  82800. * @param {boolean} isForceCreating if need to create when not exists
  82801. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  82802. * exist and isForceCreating is false
  82803. */
  82804. Definable.prototype.getDefs = function (isForceCreating) {
  82805. var svgRoot = this._svgRoot;
  82806. var defs = this._svgRoot.getElementsByTagName('defs');
  82807. if (defs.length === 0) {
  82808. // Not exist
  82809. if (isForceCreating) {
  82810. defs = svgRoot.insertBefore(
  82811. this.createElement('defs'), // Create new tag
  82812. svgRoot.firstChild // Insert in the front of svg
  82813. );
  82814. if (!defs.contains) {
  82815. // IE doesn't support contains method
  82816. defs.contains = function (el) {
  82817. var children = defs.children;
  82818. if (!children) {
  82819. return false;
  82820. }
  82821. for (var i = children.length - 1; i >= 0; --i) {
  82822. if (children[i] === el) {
  82823. return true;
  82824. }
  82825. }
  82826. return false;
  82827. };
  82828. }
  82829. return defs;
  82830. }
  82831. else {
  82832. return null;
  82833. }
  82834. }
  82835. else {
  82836. return defs[0];
  82837. }
  82838. };
  82839. /**
  82840. * Update DOM element if necessary.
  82841. *
  82842. * @param {Object|string} element style element. e.g., for gradient,
  82843. * it may be '#ccc' or {type: 'linear', ...}
  82844. * @param {Function|undefined} onUpdate update callback
  82845. */
  82846. Definable.prototype.update = function (element, onUpdate) {
  82847. if (!element) {
  82848. return;
  82849. }
  82850. var defs = this.getDefs(false);
  82851. if (element[this._domName] && defs.contains(element[this._domName])) {
  82852. // Update DOM
  82853. if (typeof onUpdate === 'function') {
  82854. onUpdate(element);
  82855. }
  82856. }
  82857. else {
  82858. // No previous dom, create new
  82859. var dom = this.add(element);
  82860. if (dom) {
  82861. element[this._domName] = dom;
  82862. }
  82863. }
  82864. };
  82865. /**
  82866. * Add gradient dom to defs
  82867. *
  82868. * @param {SVGElement} dom DOM to be added to <defs>
  82869. */
  82870. Definable.prototype.addDom = function (dom) {
  82871. var defs = this.getDefs(true);
  82872. defs.appendChild(dom);
  82873. };
  82874. /**
  82875. * Remove DOM of a given element.
  82876. *
  82877. * @param {SVGElement} element element to remove dom
  82878. */
  82879. Definable.prototype.removeDom = function (element) {
  82880. var defs = this.getDefs(false);
  82881. if (defs && element[this._domName]) {
  82882. defs.removeChild(element[this._domName]);
  82883. element[this._domName] = null;
  82884. }
  82885. };
  82886. /**
  82887. * Get DOMs of this element.
  82888. *
  82889. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  82890. */
  82891. Definable.prototype.getDoms = function () {
  82892. var defs = this.getDefs(false);
  82893. if (!defs) {
  82894. // No dom when defs is not defined
  82895. return [];
  82896. }
  82897. var doms = [];
  82898. each$1(this._tagNames, function (tagName) {
  82899. var tags = defs.getElementsByTagName(tagName);
  82900. // Note that tags is HTMLCollection, which is array-like
  82901. // rather than real array.
  82902. // So `doms.concat(tags)` add tags as one object.
  82903. doms = doms.concat([].slice.call(tags));
  82904. });
  82905. return doms;
  82906. };
  82907. /**
  82908. * Mark DOMs to be unused before painting, and clear unused ones at the end
  82909. * of the painting.
  82910. */
  82911. Definable.prototype.markAllUnused = function () {
  82912. var doms = this.getDoms();
  82913. var that = this;
  82914. each$1(doms, function (dom) {
  82915. dom[that._markLabel] = MARK_UNUSED;
  82916. });
  82917. };
  82918. /**
  82919. * Mark a single DOM to be used.
  82920. *
  82921. * @param {SVGElement} dom DOM to mark
  82922. */
  82923. Definable.prototype.markUsed = function (dom) {
  82924. if (dom) {
  82925. dom[this._markLabel] = MARK_USED;
  82926. }
  82927. };
  82928. /**
  82929. * Remove unused DOMs defined in <defs>
  82930. */
  82931. Definable.prototype.removeUnused = function () {
  82932. var defs = this.getDefs(false);
  82933. if (!defs) {
  82934. // Nothing to remove
  82935. return;
  82936. }
  82937. var doms = this.getDoms();
  82938. var that = this;
  82939. each$1(doms, function (dom) {
  82940. if (dom[that._markLabel] !== MARK_USED) {
  82941. // Remove gradient
  82942. defs.removeChild(dom);
  82943. }
  82944. });
  82945. };
  82946. /**
  82947. * Get SVG proxy.
  82948. *
  82949. * @param {Displayable} displayable displayable element
  82950. * @return {Path|Image|Text} svg proxy of given element
  82951. */
  82952. Definable.prototype.getSvgProxy = function (displayable) {
  82953. if (displayable instanceof Path) {
  82954. return svgPath;
  82955. }
  82956. else if (displayable instanceof ZImage) {
  82957. return svgImage;
  82958. }
  82959. else if (displayable instanceof Text) {
  82960. return svgText;
  82961. }
  82962. else {
  82963. return svgPath;
  82964. }
  82965. };
  82966. /**
  82967. * Get text SVG element.
  82968. *
  82969. * @param {Displayable} displayable displayable element
  82970. * @return {SVGElement} SVG element of text
  82971. */
  82972. Definable.prototype.getTextSvgElement = function (displayable) {
  82973. return displayable.__textSvgEl;
  82974. };
  82975. /**
  82976. * Get SVG element.
  82977. *
  82978. * @param {Displayable} displayable displayable element
  82979. * @return {SVGElement} SVG element
  82980. */
  82981. Definable.prototype.getSvgElement = function (displayable) {
  82982. return displayable.__svgEl;
  82983. };
  82984. /**
  82985. * @file Manages SVG gradient elements.
  82986. * @author Zhang Wenli
  82987. */
  82988. /**
  82989. * Manages SVG gradient elements.
  82990. *
  82991. * @class
  82992. * @extends Definable
  82993. * @param {number} zrId zrender instance id
  82994. * @param {SVGElement} svgRoot root of SVG document
  82995. */
  82996. function GradientManager(zrId, svgRoot) {
  82997. Definable.call(
  82998. this,
  82999. zrId,
  83000. svgRoot,
  83001. ['linearGradient', 'radialGradient'],
  83002. '__gradient_in_use__'
  83003. );
  83004. }
  83005. inherits(GradientManager, Definable);
  83006. /**
  83007. * Create new gradient DOM for fill or stroke if not exist,
  83008. * but will not update gradient if exists.
  83009. *
  83010. * @param {SvgElement} svgElement SVG element to paint
  83011. * @param {Displayable} displayable zrender displayable element
  83012. */
  83013. GradientManager.prototype.addWithoutUpdate = function (
  83014. svgElement,
  83015. displayable
  83016. ) {
  83017. if (displayable && displayable.style) {
  83018. var that = this;
  83019. each$1(['fill', 'stroke'], function (fillOrStroke) {
  83020. if (displayable.style[fillOrStroke]
  83021. && (displayable.style[fillOrStroke].type === 'linear'
  83022. || displayable.style[fillOrStroke].type === 'radial')
  83023. ) {
  83024. var gradient = displayable.style[fillOrStroke];
  83025. var defs = that.getDefs(true);
  83026. // Create dom in <defs> if not exists
  83027. var dom;
  83028. if (gradient._dom) {
  83029. // Gradient exists
  83030. dom = gradient._dom;
  83031. if (!defs.contains(gradient._dom)) {
  83032. // _dom is no longer in defs, recreate
  83033. that.addDom(dom);
  83034. }
  83035. }
  83036. else {
  83037. // New dom
  83038. dom = that.add(gradient);
  83039. }
  83040. that.markUsed(displayable);
  83041. var id = dom.getAttribute('id');
  83042. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  83043. }
  83044. });
  83045. }
  83046. };
  83047. /**
  83048. * Add a new gradient tag in <defs>
  83049. *
  83050. * @param {Gradient} gradient zr gradient instance
  83051. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  83052. * created DOM
  83053. */
  83054. GradientManager.prototype.add = function (gradient) {
  83055. var dom;
  83056. if (gradient.type === 'linear') {
  83057. dom = this.createElement('linearGradient');
  83058. }
  83059. else if (gradient.type === 'radial') {
  83060. dom = this.createElement('radialGradient');
  83061. }
  83062. else {
  83063. logError$1('Illegal gradient type.');
  83064. return null;
  83065. }
  83066. // Set dom id with gradient id, since each gradient instance
  83067. // will have no more than one dom element.
  83068. // id may exists before for those dirty elements, in which case
  83069. // id should remain the same, and other attributes should be
  83070. // updated.
  83071. gradient.id = gradient.id || this.nextId++;
  83072. dom.setAttribute('id', 'zr' + this._zrId
  83073. + '-gradient-' + gradient.id);
  83074. this.updateDom(gradient, dom);
  83075. this.addDom(dom);
  83076. return dom;
  83077. };
  83078. /**
  83079. * Update gradient.
  83080. *
  83081. * @param {Gradient} gradient zr gradient instance
  83082. */
  83083. GradientManager.prototype.update = function (gradient) {
  83084. var that = this;
  83085. Definable.prototype.update.call(this, gradient, function () {
  83086. var type = gradient.type;
  83087. var tagName = gradient._dom.tagName;
  83088. if (type === 'linear' && tagName === 'linearGradient'
  83089. || type === 'radial' && tagName === 'radialGradient'
  83090. ) {
  83091. // Gradient type is not changed, update gradient
  83092. that.updateDom(gradient, gradient._dom);
  83093. }
  83094. else {
  83095. // Remove and re-create if type is changed
  83096. that.removeDom(gradient);
  83097. that.add(gradient);
  83098. }
  83099. });
  83100. };
  83101. /**
  83102. * Update gradient dom
  83103. *
  83104. * @param {Gradient} gradient zr gradient instance
  83105. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  83106. * DOM to update
  83107. */
  83108. GradientManager.prototype.updateDom = function (gradient, dom) {
  83109. if (gradient.type === 'linear') {
  83110. dom.setAttribute('x1', gradient.x);
  83111. dom.setAttribute('y1', gradient.y);
  83112. dom.setAttribute('x2', gradient.x2);
  83113. dom.setAttribute('y2', gradient.y2);
  83114. }
  83115. else if (gradient.type === 'radial') {
  83116. dom.setAttribute('cx', gradient.x);
  83117. dom.setAttribute('cy', gradient.y);
  83118. dom.setAttribute('r', gradient.r);
  83119. }
  83120. else {
  83121. logError$1('Illegal gradient type.');
  83122. return;
  83123. }
  83124. if (gradient.global) {
  83125. // x1, x2, y1, y2 in range of 0 to canvas width or height
  83126. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  83127. }
  83128. else {
  83129. // x1, x2, y1, y2 in range of 0 to 1
  83130. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  83131. }
  83132. // Remove color stops if exists
  83133. dom.innerHTML = '';
  83134. // Add color stops
  83135. var colors = gradient.colorStops;
  83136. for (var i = 0, len = colors.length; i < len; ++i) {
  83137. var stop = this.createElement('stop');
  83138. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  83139. var color = colors[i].color;
  83140. if (color.indexOf('rgba' > -1)) {
  83141. // Fix Safari bug that stop-color not recognizing alpha #9014
  83142. var opacity = parse(color)[3];
  83143. var hex = toHex(color);
  83144. // stop-color cannot be color, since:
  83145. // The opacity value used for the gradient calculation is the
  83146. // *product* of the value of stop-opacity and the opacity of the
  83147. // value of stop-color.
  83148. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  83149. stop.setAttribute('stop-color', '#' + hex);
  83150. stop.setAttribute('stop-opacity', opacity);
  83151. }
  83152. else {
  83153. stop.setAttribute('stop-color', colors[i].color);
  83154. }
  83155. dom.appendChild(stop);
  83156. }
  83157. // Store dom element in gradient, to avoid creating multiple
  83158. // dom instances for the same gradient element
  83159. gradient._dom = dom;
  83160. };
  83161. /**
  83162. * Mark a single gradient to be used
  83163. *
  83164. * @param {Displayable} displayable displayable element
  83165. */
  83166. GradientManager.prototype.markUsed = function (displayable) {
  83167. if (displayable.style) {
  83168. var gradient = displayable.style.fill;
  83169. if (gradient && gradient._dom) {
  83170. Definable.prototype.markUsed.call(this, gradient._dom);
  83171. }
  83172. gradient = displayable.style.stroke;
  83173. if (gradient && gradient._dom) {
  83174. Definable.prototype.markUsed.call(this, gradient._dom);
  83175. }
  83176. }
  83177. };
  83178. /**
  83179. * @file Manages SVG clipPath elements.
  83180. * @author Zhang Wenli
  83181. */
  83182. /**
  83183. * Manages SVG clipPath elements.
  83184. *
  83185. * @class
  83186. * @extends Definable
  83187. * @param {number} zrId zrender instance id
  83188. * @param {SVGElement} svgRoot root of SVG document
  83189. */
  83190. function ClippathManager(zrId, svgRoot) {
  83191. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  83192. }
  83193. inherits(ClippathManager, Definable);
  83194. /**
  83195. * Update clipPath.
  83196. *
  83197. * @param {Displayable} displayable displayable element
  83198. */
  83199. ClippathManager.prototype.update = function (displayable) {
  83200. var svgEl = this.getSvgElement(displayable);
  83201. if (svgEl) {
  83202. this.updateDom(svgEl, displayable.__clipPaths, false);
  83203. }
  83204. var textEl = this.getTextSvgElement(displayable);
  83205. if (textEl) {
  83206. // Make another clipPath for text, since it's transform
  83207. // matrix is not the same with svgElement
  83208. this.updateDom(textEl, displayable.__clipPaths, true);
  83209. }
  83210. this.markUsed(displayable);
  83211. };
  83212. /**
  83213. * Create an SVGElement of displayable and create a <clipPath> of its
  83214. * clipPath
  83215. *
  83216. * @param {Displayable} parentEl parent element
  83217. * @param {ClipPath[]} clipPaths clipPaths of parent element
  83218. * @param {boolean} isText if parent element is Text
  83219. */
  83220. ClippathManager.prototype.updateDom = function (
  83221. parentEl,
  83222. clipPaths,
  83223. isText
  83224. ) {
  83225. if (clipPaths && clipPaths.length > 0) {
  83226. // Has clipPath, create <clipPath> with the first clipPath
  83227. var defs = this.getDefs(true);
  83228. var clipPath = clipPaths[0];
  83229. var clipPathEl;
  83230. var id;
  83231. var dom = isText ? '_textDom' : '_dom';
  83232. if (clipPath[dom]) {
  83233. // Use a dom that is already in <defs>
  83234. id = clipPath[dom].getAttribute('id');
  83235. clipPathEl = clipPath[dom];
  83236. // Use a dom that is already in <defs>
  83237. if (!defs.contains(clipPathEl)) {
  83238. // This happens when set old clipPath that has
  83239. // been previously removed
  83240. defs.appendChild(clipPathEl);
  83241. }
  83242. }
  83243. else {
  83244. // New <clipPath>
  83245. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  83246. ++this.nextId;
  83247. clipPathEl = this.createElement('clipPath');
  83248. clipPathEl.setAttribute('id', id);
  83249. defs.appendChild(clipPathEl);
  83250. clipPath[dom] = clipPathEl;
  83251. }
  83252. // Build path and add to <clipPath>
  83253. var svgProxy = this.getSvgProxy(clipPath);
  83254. if (clipPath.transform
  83255. && clipPath.parent.invTransform
  83256. && !isText
  83257. ) {
  83258. /**
  83259. * If a clipPath has a parent with transform, the transform
  83260. * of parent should not be considered when setting transform
  83261. * of clipPath. So we need to transform back from parent's
  83262. * transform, which is done by multiplying parent's inverse
  83263. * transform.
  83264. */
  83265. // Store old transform
  83266. var transform = Array.prototype.slice.call(
  83267. clipPath.transform
  83268. );
  83269. // Transform back from parent, and brush path
  83270. mul$1(
  83271. clipPath.transform,
  83272. clipPath.parent.invTransform,
  83273. clipPath.transform
  83274. );
  83275. svgProxy.brush(clipPath);
  83276. // Set back transform of clipPath
  83277. clipPath.transform = transform;
  83278. }
  83279. else {
  83280. svgProxy.brush(clipPath);
  83281. }
  83282. var pathEl = this.getSvgElement(clipPath);
  83283. clipPathEl.innerHTML = '';
  83284. /**
  83285. * Use `cloneNode()` here to appendChild to multiple parents,
  83286. * which may happend when Text and other shapes are using the same
  83287. * clipPath. Since Text will create an extra clipPath DOM due to
  83288. * different transform rules.
  83289. */
  83290. clipPathEl.appendChild(pathEl.cloneNode());
  83291. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  83292. if (clipPaths.length > 1) {
  83293. // Make the other clipPaths recursively
  83294. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  83295. }
  83296. }
  83297. else {
  83298. // No clipPath
  83299. if (parentEl) {
  83300. parentEl.setAttribute('clip-path', 'none');
  83301. }
  83302. }
  83303. };
  83304. /**
  83305. * Mark a single clipPath to be used
  83306. *
  83307. * @param {Displayable} displayable displayable element
  83308. */
  83309. ClippathManager.prototype.markUsed = function (displayable) {
  83310. var that = this;
  83311. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  83312. if (displayable.__clipPaths) {
  83313. each$1(displayable.__clipPaths, function (clipPath) {
  83314. if (clipPath._dom) {
  83315. Definable.prototype.markUsed.call(that, clipPath._dom);
  83316. }
  83317. if (clipPath._textDom) {
  83318. Definable.prototype.markUsed.call(that, clipPath._textDom);
  83319. }
  83320. });
  83321. }
  83322. };
  83323. /**
  83324. * @file Manages SVG shadow elements.
  83325. * @author Zhang Wenli
  83326. */
  83327. /**
  83328. * Manages SVG shadow elements.
  83329. *
  83330. * @class
  83331. * @extends Definable
  83332. * @param {number} zrId zrender instance id
  83333. * @param {SVGElement} svgRoot root of SVG document
  83334. */
  83335. function ShadowManager(zrId, svgRoot) {
  83336. Definable.call(
  83337. this,
  83338. zrId,
  83339. svgRoot,
  83340. ['filter'],
  83341. '__filter_in_use__',
  83342. '_shadowDom'
  83343. );
  83344. }
  83345. inherits(ShadowManager, Definable);
  83346. /**
  83347. * Create new shadow DOM for fill or stroke if not exist,
  83348. * but will not update shadow if exists.
  83349. *
  83350. * @param {SvgElement} svgElement SVG element to paint
  83351. * @param {Displayable} displayable zrender displayable element
  83352. */
  83353. ShadowManager.prototype.addWithoutUpdate = function (
  83354. svgElement,
  83355. displayable
  83356. ) {
  83357. if (displayable && hasShadow(displayable.style)) {
  83358. // Create dom in <defs> if not exists
  83359. var dom;
  83360. if (displayable._shadowDom) {
  83361. // Gradient exists
  83362. dom = displayable._shadowDom;
  83363. var defs = this.getDefs(true);
  83364. if (!defs.contains(displayable._shadowDom)) {
  83365. // _shadowDom is no longer in defs, recreate
  83366. this.addDom(dom);
  83367. }
  83368. }
  83369. else {
  83370. // New dom
  83371. dom = this.add(displayable);
  83372. }
  83373. this.markUsed(displayable);
  83374. var id = dom.getAttribute('id');
  83375. svgElement.style.filter = 'url(#' + id + ')';
  83376. }
  83377. };
  83378. /**
  83379. * Add a new shadow tag in <defs>
  83380. *
  83381. * @param {Displayable} displayable zrender displayable element
  83382. * @return {SVGFilterElement} created DOM
  83383. */
  83384. ShadowManager.prototype.add = function (displayable) {
  83385. var dom = this.createElement('filter');
  83386. // Set dom id with shadow id, since each shadow instance
  83387. // will have no more than one dom element.
  83388. // id may exists before for those dirty elements, in which case
  83389. // id should remain the same, and other attributes should be
  83390. // updated.
  83391. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  83392. dom.setAttribute('id', 'zr' + this._zrId
  83393. + '-shadow-' + displayable._shadowDomId);
  83394. this.updateDom(displayable, dom);
  83395. this.addDom(dom);
  83396. return dom;
  83397. };
  83398. /**
  83399. * Update shadow.
  83400. *
  83401. * @param {Displayable} displayable zrender displayable element
  83402. */
  83403. ShadowManager.prototype.update = function (svgElement, displayable) {
  83404. var style = displayable.style;
  83405. if (hasShadow(style)) {
  83406. var that = this;
  83407. Definable.prototype.update.call(this, displayable, function () {
  83408. that.updateDom(displayable, displayable._shadowDom);
  83409. });
  83410. }
  83411. else {
  83412. // Remove shadow
  83413. this.remove(svgElement, displayable);
  83414. }
  83415. };
  83416. /**
  83417. * Remove DOM and clear parent filter
  83418. */
  83419. ShadowManager.prototype.remove = function (svgElement, displayable) {
  83420. if (displayable._shadowDomId != null) {
  83421. this.removeDom(svgElement);
  83422. svgElement.style.filter = '';
  83423. }
  83424. };
  83425. /**
  83426. * Update shadow dom
  83427. *
  83428. * @param {Displayable} displayable zrender displayable element
  83429. * @param {SVGFilterElement} dom DOM to update
  83430. */
  83431. ShadowManager.prototype.updateDom = function (displayable, dom) {
  83432. var domChild = dom.getElementsByTagName('feDropShadow');
  83433. if (domChild.length === 0) {
  83434. domChild = this.createElement('feDropShadow');
  83435. }
  83436. else {
  83437. domChild = domChild[0];
  83438. }
  83439. var style = displayable.style;
  83440. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  83441. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  83442. // TODO: textBoxShadowBlur is not supported yet
  83443. var offsetX;
  83444. var offsetY;
  83445. var blur;
  83446. var color;
  83447. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  83448. offsetX = style.shadowOffsetX || 0;
  83449. offsetY = style.shadowOffsetY || 0;
  83450. blur = style.shadowBlur;
  83451. color = style.shadowColor;
  83452. }
  83453. else if (style.textShadowBlur) {
  83454. offsetX = style.textShadowOffsetX || 0;
  83455. offsetY = style.textShadowOffsetY || 0;
  83456. blur = style.textShadowBlur;
  83457. color = style.textShadowColor;
  83458. }
  83459. else {
  83460. // Remove shadow
  83461. this.removeDom(dom, style);
  83462. return;
  83463. }
  83464. domChild.setAttribute('dx', offsetX / scaleX);
  83465. domChild.setAttribute('dy', offsetY / scaleY);
  83466. domChild.setAttribute('flood-color', color);
  83467. // Divide by two here so that it looks the same as in canvas
  83468. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  83469. var stdDx = blur / 2 / scaleX;
  83470. var stdDy = blur / 2 / scaleY;
  83471. var stdDeviation = stdDx + ' ' + stdDy;
  83472. domChild.setAttribute('stdDeviation', stdDeviation);
  83473. // Fix filter clipping problem
  83474. dom.setAttribute('x', '-100%');
  83475. dom.setAttribute('y', '-100%');
  83476. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  83477. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  83478. dom.appendChild(domChild);
  83479. // Store dom element in shadow, to avoid creating multiple
  83480. // dom instances for the same shadow element
  83481. displayable._shadowDom = dom;
  83482. };
  83483. /**
  83484. * Mark a single shadow to be used
  83485. *
  83486. * @param {Displayable} displayable displayable element
  83487. */
  83488. ShadowManager.prototype.markUsed = function (displayable) {
  83489. if (displayable._shadowDom) {
  83490. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  83491. }
  83492. };
  83493. function hasShadow(style) {
  83494. // TODO: textBoxShadowBlur is not supported yet
  83495. return style
  83496. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  83497. || style.textShadowBlur || style.textShadowOffsetX
  83498. || style.textShadowOffsetY);
  83499. }
  83500. /**
  83501. * SVG Painter
  83502. * @module zrender/svg/Painter
  83503. */
  83504. function parseInt10$2(val) {
  83505. return parseInt(val, 10);
  83506. }
  83507. function getSvgProxy(el) {
  83508. if (el instanceof Path) {
  83509. return svgPath;
  83510. }
  83511. else if (el instanceof ZImage) {
  83512. return svgImage;
  83513. }
  83514. else if (el instanceof Text) {
  83515. return svgText;
  83516. }
  83517. else {
  83518. return svgPath;
  83519. }
  83520. }
  83521. function checkParentAvailable(parent, child) {
  83522. return child && parent && child.parentNode !== parent;
  83523. }
  83524. function insertAfter(parent, child, prevSibling) {
  83525. if (checkParentAvailable(parent, child) && prevSibling) {
  83526. var nextSibling = prevSibling.nextSibling;
  83527. nextSibling ? parent.insertBefore(child, nextSibling)
  83528. : parent.appendChild(child);
  83529. }
  83530. }
  83531. function prepend(parent, child) {
  83532. if (checkParentAvailable(parent, child)) {
  83533. var firstChild = parent.firstChild;
  83534. firstChild ? parent.insertBefore(child, firstChild)
  83535. : parent.appendChild(child);
  83536. }
  83537. }
  83538. // function append(parent, child) {
  83539. // if (checkParentAvailable(parent, child)) {
  83540. // parent.appendChild(child);
  83541. // }
  83542. // }
  83543. function remove$1(parent, child) {
  83544. if (child && parent && child.parentNode === parent) {
  83545. parent.removeChild(child);
  83546. }
  83547. }
  83548. function getTextSvgElement(displayable) {
  83549. return displayable.__textSvgEl;
  83550. }
  83551. function getSvgElement(displayable) {
  83552. return displayable.__svgEl;
  83553. }
  83554. /**
  83555. * @alias module:zrender/svg/Painter
  83556. * @constructor
  83557. * @param {HTMLElement} root 绘图容器
  83558. * @param {module:zrender/Storage} storage
  83559. * @param {Object} opts
  83560. */
  83561. var SVGPainter = function (root, storage, opts, zrId) {
  83562. this.root = root;
  83563. this.storage = storage;
  83564. this._opts = opts = extend({}, opts || {});
  83565. var svgRoot = createElement('svg');
  83566. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  83567. svgRoot.setAttribute('version', '1.1');
  83568. svgRoot.setAttribute('baseProfile', 'full');
  83569. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  83570. this.gradientManager = new GradientManager(zrId, svgRoot);
  83571. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  83572. this.shadowManager = new ShadowManager(zrId, svgRoot);
  83573. var viewport = document.createElement('div');
  83574. viewport.style.cssText = 'overflow:hidden;position:relative';
  83575. this._svgRoot = svgRoot;
  83576. this._viewport = viewport;
  83577. root.appendChild(viewport);
  83578. viewport.appendChild(svgRoot);
  83579. this.resize(opts.width, opts.height);
  83580. this._visibleList = [];
  83581. };
  83582. SVGPainter.prototype = {
  83583. constructor: SVGPainter,
  83584. getType: function () {
  83585. return 'svg';
  83586. },
  83587. getViewportRoot: function () {
  83588. return this._viewport;
  83589. },
  83590. getViewportRootOffset: function () {
  83591. var viewportRoot = this.getViewportRoot();
  83592. if (viewportRoot) {
  83593. return {
  83594. offsetLeft: viewportRoot.offsetLeft || 0,
  83595. offsetTop: viewportRoot.offsetTop || 0
  83596. };
  83597. }
  83598. },
  83599. refresh: function () {
  83600. var list = this.storage.getDisplayList(true);
  83601. this._paintList(list);
  83602. },
  83603. setBackgroundColor: function (backgroundColor) {
  83604. // TODO gradient
  83605. this._viewport.style.background = backgroundColor;
  83606. },
  83607. _paintList: function (list) {
  83608. this.gradientManager.markAllUnused();
  83609. this.clipPathManager.markAllUnused();
  83610. this.shadowManager.markAllUnused();
  83611. var svgRoot = this._svgRoot;
  83612. var visibleList = this._visibleList;
  83613. var listLen = list.length;
  83614. var newVisibleList = [];
  83615. var i;
  83616. for (i = 0; i < listLen; i++) {
  83617. var displayable = list[i];
  83618. var svgProxy = getSvgProxy(displayable);
  83619. var svgElement = getSvgElement(displayable)
  83620. || getTextSvgElement(displayable);
  83621. if (!displayable.invisible) {
  83622. if (displayable.__dirty) {
  83623. svgProxy && svgProxy.brush(displayable);
  83624. // Update clipPath
  83625. this.clipPathManager.update(displayable);
  83626. // Update gradient and shadow
  83627. if (displayable.style) {
  83628. this.gradientManager
  83629. .update(displayable.style.fill);
  83630. this.gradientManager
  83631. .update(displayable.style.stroke);
  83632. this.shadowManager
  83633. .update(svgElement, displayable);
  83634. }
  83635. displayable.__dirty = false;
  83636. }
  83637. newVisibleList.push(displayable);
  83638. }
  83639. }
  83640. var diff = arrayDiff$1(visibleList, newVisibleList);
  83641. var prevSvgElement;
  83642. // First do remove, in case element moved to the head and do remove
  83643. // after add
  83644. for (i = 0; i < diff.length; i++) {
  83645. var item = diff[i];
  83646. if (item.removed) {
  83647. for (var k = 0; k < item.count; k++) {
  83648. var displayable = visibleList[item.indices[k]];
  83649. var svgElement = getSvgElement(displayable);
  83650. var textSvgElement = getTextSvgElement(displayable);
  83651. remove$1(svgRoot, svgElement);
  83652. remove$1(svgRoot, textSvgElement);
  83653. }
  83654. }
  83655. }
  83656. for (i = 0; i < diff.length; i++) {
  83657. var item = diff[i];
  83658. if (item.added) {
  83659. for (var k = 0; k < item.count; k++) {
  83660. var displayable = newVisibleList[item.indices[k]];
  83661. var svgElement = getSvgElement(displayable);
  83662. var textSvgElement = getTextSvgElement(displayable);
  83663. prevSvgElement
  83664. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  83665. : prepend(svgRoot, svgElement);
  83666. if (svgElement) {
  83667. insertAfter(svgRoot, textSvgElement, svgElement);
  83668. }
  83669. else if (prevSvgElement) {
  83670. insertAfter(
  83671. svgRoot, textSvgElement, prevSvgElement
  83672. );
  83673. }
  83674. else {
  83675. prepend(svgRoot, textSvgElement);
  83676. }
  83677. // Insert text
  83678. insertAfter(svgRoot, textSvgElement, svgElement);
  83679. prevSvgElement = textSvgElement || svgElement
  83680. || prevSvgElement;
  83681. // zrender.Text only create textSvgElement.
  83682. this.gradientManager
  83683. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83684. this.shadowManager
  83685. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83686. this.clipPathManager.markUsed(displayable);
  83687. }
  83688. }
  83689. else if (!item.removed) {
  83690. for (var k = 0; k < item.count; k++) {
  83691. var displayable = newVisibleList[item.indices[k]];
  83692. var svgElement = getSvgElement(displayable);
  83693. var textSvgElement = getTextSvgElement(displayable);
  83694. var svgElement = getSvgElement(displayable);
  83695. var textSvgElement = getTextSvgElement(displayable);
  83696. this.gradientManager.markUsed(displayable);
  83697. this.gradientManager
  83698. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83699. this.shadowManager.markUsed(displayable);
  83700. this.shadowManager
  83701. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  83702. this.clipPathManager.markUsed(displayable);
  83703. if (textSvgElement) { // Insert text.
  83704. insertAfter(svgRoot, textSvgElement, svgElement);
  83705. }
  83706. prevSvgElement = svgElement
  83707. || textSvgElement || prevSvgElement;
  83708. }
  83709. }
  83710. }
  83711. this.gradientManager.removeUnused();
  83712. this.clipPathManager.removeUnused();
  83713. this.shadowManager.removeUnused();
  83714. this._visibleList = newVisibleList;
  83715. },
  83716. _getDefs: function (isForceCreating) {
  83717. var svgRoot = this._svgRoot;
  83718. var defs = this._svgRoot.getElementsByTagName('defs');
  83719. if (defs.length === 0) {
  83720. // Not exist
  83721. if (isForceCreating) {
  83722. var defs = svgRoot.insertBefore(
  83723. createElement('defs'), // Create new tag
  83724. svgRoot.firstChild // Insert in the front of svg
  83725. );
  83726. if (!defs.contains) {
  83727. // IE doesn't support contains method
  83728. defs.contains = function (el) {
  83729. var children = defs.children;
  83730. if (!children) {
  83731. return false;
  83732. }
  83733. for (var i = children.length - 1; i >= 0; --i) {
  83734. if (children[i] === el) {
  83735. return true;
  83736. }
  83737. }
  83738. return false;
  83739. };
  83740. }
  83741. return defs;
  83742. }
  83743. else {
  83744. return null;
  83745. }
  83746. }
  83747. else {
  83748. return defs[0];
  83749. }
  83750. },
  83751. resize: function (width, height) {
  83752. var viewport = this._viewport;
  83753. // FIXME Why ?
  83754. viewport.style.display = 'none';
  83755. // Save input w/h
  83756. var opts = this._opts;
  83757. width != null && (opts.width = width);
  83758. height != null && (opts.height = height);
  83759. width = this._getSize(0);
  83760. height = this._getSize(1);
  83761. viewport.style.display = '';
  83762. if (this._width !== width || this._height !== height) {
  83763. this._width = width;
  83764. this._height = height;
  83765. var viewportStyle = viewport.style;
  83766. viewportStyle.width = width + 'px';
  83767. viewportStyle.height = height + 'px';
  83768. var svgRoot = this._svgRoot;
  83769. // Set width by 'svgRoot.width = width' is invalid
  83770. svgRoot.setAttribute('width', width);
  83771. svgRoot.setAttribute('height', height);
  83772. }
  83773. },
  83774. /**
  83775. * 获取绘图区域宽度
  83776. */
  83777. getWidth: function () {
  83778. return this._width;
  83779. },
  83780. /**
  83781. * 获取绘图区域高度
  83782. */
  83783. getHeight: function () {
  83784. return this._height;
  83785. },
  83786. _getSize: function (whIdx) {
  83787. var opts = this._opts;
  83788. var wh = ['width', 'height'][whIdx];
  83789. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  83790. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  83791. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  83792. if (opts[wh] != null && opts[wh] !== 'auto') {
  83793. return parseFloat(opts[wh]);
  83794. }
  83795. var root = this.root;
  83796. // IE8 does not support getComputedStyle, but it use VML.
  83797. var stl = document.defaultView.getComputedStyle(root);
  83798. return (
  83799. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  83800. - (parseInt10$2(stl[plt]) || 0)
  83801. - (parseInt10$2(stl[prb]) || 0)
  83802. ) | 0;
  83803. },
  83804. dispose: function () {
  83805. this.root.innerHTML = '';
  83806. this._svgRoot =
  83807. this._viewport =
  83808. this.storage =
  83809. null;
  83810. },
  83811. clear: function () {
  83812. if (this._viewport) {
  83813. this.root.removeChild(this._viewport);
  83814. }
  83815. },
  83816. pathToDataUrl: function () {
  83817. this.refresh();
  83818. var html = this._svgRoot.outerHTML;
  83819. return 'data:image/svg+xml;charset=UTF-8,' + html;
  83820. }
  83821. };
  83822. // Not supported methods
  83823. function createMethodNotSupport$1(method) {
  83824. return function () {
  83825. logError$1('In SVG mode painter not support method "' + method + '"');
  83826. };
  83827. }
  83828. // Unsuppoted methods
  83829. each$1([
  83830. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  83831. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  83832. 'toDataURL', 'pathToImage'
  83833. ], function (name) {
  83834. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  83835. });
  83836. registerPainter('svg', SVGPainter);
  83837. /*
  83838. * Licensed to the Apache Software Foundation (ASF) under one
  83839. * or more contributor license agreements. See the NOTICE file
  83840. * distributed with this work for additional information
  83841. * regarding copyright ownership. The ASF licenses this file
  83842. * to you under the Apache License, Version 2.0 (the
  83843. * "License"); you may not use this file except in compliance
  83844. * with the License. You may obtain a copy of the License at
  83845. *
  83846. * http://www.apache.org/licenses/LICENSE-2.0
  83847. *
  83848. * Unless required by applicable law or agreed to in writing,
  83849. * software distributed under the License is distributed on an
  83850. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  83851. * KIND, either express or implied. See the License for the
  83852. * specific language governing permissions and limitations
  83853. * under the License.
  83854. */
  83855. // ----------------------------------------------
  83856. // All of the modules that are allowed to be
  83857. // imported are listed below.
  83858. //
  83859. // Users MUST NOT import other modules that are
  83860. // not included in this list.
  83861. // ----------------------------------------------
  83862. // ----------------
  83863. // Charts (series)
  83864. // ----------------
  83865. // All of the series types, for example:
  83866. // chart.setOption({
  83867. // series: [{
  83868. // type: 'line' // or 'bar', 'pie', ...
  83869. // }]
  83870. // });
  83871. // -------------------
  83872. // Coordinate systems
  83873. // -------------------
  83874. // All of the axis modules have been included in the
  83875. // coordinate system module below, do not need to
  83876. // make extra import.
  83877. // `cartesian` coordinate system. For some historical
  83878. // reasons, it is named as grid, for example:
  83879. // chart.setOption({
  83880. // grid: {...},
  83881. // xAxis: {...},
  83882. // yAxis: {...},
  83883. // series: [{...}]
  83884. // });
  83885. // `polar` coordinate system, for example:
  83886. // chart.setOption({
  83887. // polar: {...},
  83888. // radiusAxis: {...},
  83889. // angleAxis: {...},
  83890. // series: [{
  83891. // coordinateSystem: 'polar'
  83892. // }]
  83893. // });
  83894. // `geo` coordinate system, for example:
  83895. // chart.setOption({
  83896. // geo: {...},
  83897. // series: [{
  83898. // coordinateSystem: 'geo'
  83899. // }]
  83900. // });
  83901. // `singleAxis` coordinate system (notice, it is a coordinate system
  83902. // with only one axis, work for chart like theme river), for example:
  83903. // chart.setOption({
  83904. // singleAxis: {...}
  83905. // series: [{type: 'themeRiver', ...}]
  83906. // });
  83907. // `parallel` coordinate system, only work for parallel series, for example:
  83908. // chart.setOption({
  83909. // parallel: {...},
  83910. // parallelAxis: [{...}, ...],
  83911. // series: [{
  83912. // type: 'parallel'
  83913. // }]
  83914. // });
  83915. // `calendar` coordinate system. for example,
  83916. // chart.setOptionp({
  83917. // calendar: {...},
  83918. // series: [{
  83919. // coordinateSystem: 'calendar'
  83920. // }]
  83921. // );
  83922. // ------------------
  83923. // Other components
  83924. // ------------------
  83925. // `graphic` component, for example:
  83926. // chart.setOption({
  83927. // graphic: {...}
  83928. // });
  83929. // `toolbox` component, for example:
  83930. // chart.setOption({
  83931. // toolbox: {...}
  83932. // });
  83933. // `tooltip` component, for example:
  83934. // chart.setOption({
  83935. // tooltip: {...}
  83936. // });
  83937. // `axisPointer` component, for example:
  83938. // chart.setOption({
  83939. // tooltip: {axisPointer: {...}, ...}
  83940. // });
  83941. // Or
  83942. // chart.setOption({
  83943. // axisPointer: {...}
  83944. // });
  83945. // `brush` component, for example:
  83946. // chart.setOption({
  83947. // brush: {...}
  83948. // });
  83949. // Or
  83950. // chart.setOption({
  83951. // tooltip: {feature: {brush: {...}}
  83952. // })
  83953. // `title` component, for example:
  83954. // chart.setOption({
  83955. // title: {...}
  83956. // });
  83957. // `timeline` component, for example:
  83958. // chart.setOption({
  83959. // timeline: {...}
  83960. // });
  83961. // `markPoint` component, for example:
  83962. // chart.setOption({
  83963. // series: [{markPoint: {...}}]
  83964. // });
  83965. // `markLine` component, for example:
  83966. // chart.setOption({
  83967. // series: [{markLine: {...}}]
  83968. // });
  83969. // `markArea` component, for example:
  83970. // chart.setOption({
  83971. // series: [{markArea: {...}}]
  83972. // });
  83973. // `legend` component scrollable, for example:
  83974. // chart.setOption({
  83975. // legend: {type: 'scroll'}
  83976. // });
  83977. // `legend` component not scrollable. for example:
  83978. // chart.setOption({
  83979. // legend: {...}
  83980. // });
  83981. // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  83982. // `dataZoom` component providing drag, pinch, wheel behaviors
  83983. // inside coodinate system, for example:
  83984. // chart.setOption({
  83985. // dataZoom: {type: 'inside'}
  83986. // });
  83987. // `dataZoom` component providing a slider bar, for example:
  83988. // chart.setOption({
  83989. // dataZoom: {type: 'slider'}
  83990. // });
  83991. // `dataZoom` component including both `visualMapContinuous` and `visualMapPiecewise`.
  83992. // `visualMap` component providing continuous bar, for example:
  83993. // chart.setOption({
  83994. // visualMap: {type: 'continuous'}
  83995. // });
  83996. // `visualMap` component providing pieces bar, for example:
  83997. // chart.setOption({
  83998. // visualMap: {type: 'piecewise'}
  83999. // });
  84000. // -----------------
  84001. // Render engines
  84002. // -----------------
  84003. // Provide IE 6,7,8 compatibility.
  84004. // Render via SVG rather than canvas.
  84005. exports.version = version;
  84006. exports.dependencies = dependencies;
  84007. exports.PRIORITY = PRIORITY;
  84008. exports.init = init;
  84009. exports.connect = connect;
  84010. exports.disConnect = disConnect;
  84011. exports.disconnect = disconnect;
  84012. exports.dispose = dispose;
  84013. exports.getInstanceByDom = getInstanceByDom;
  84014. exports.getInstanceById = getInstanceById;
  84015. exports.registerTheme = registerTheme;
  84016. exports.registerPreprocessor = registerPreprocessor;
  84017. exports.registerProcessor = registerProcessor;
  84018. exports.registerPostUpdate = registerPostUpdate;
  84019. exports.registerAction = registerAction;
  84020. exports.registerCoordinateSystem = registerCoordinateSystem;
  84021. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  84022. exports.registerLayout = registerLayout;
  84023. exports.registerVisual = registerVisual;
  84024. exports.registerLoading = registerLoading;
  84025. exports.extendComponentModel = extendComponentModel;
  84026. exports.extendComponentView = extendComponentView;
  84027. exports.extendSeriesModel = extendSeriesModel;
  84028. exports.extendChartView = extendChartView;
  84029. exports.setCanvasCreator = setCanvasCreator;
  84030. exports.registerMap = registerMap;
  84031. exports.getMap = getMap;
  84032. exports.dataTool = dataTool;
  84033. exports.zrender = zrender;
  84034. exports.number = number;
  84035. exports.format = format;
  84036. exports.throttle = throttle;
  84037. exports.helper = helper;
  84038. exports.matrix = matrix;
  84039. exports.vector = vector;
  84040. exports.color = color;
  84041. exports.parseGeoJSON = parseGeoJson$1;
  84042. exports.parseGeoJson = parseGeoJson;
  84043. exports.util = ecUtil;
  84044. exports.graphic = graphic$1;
  84045. exports.List = List;
  84046. exports.Model = Model;
  84047. exports.Axis = Axis;
  84048. exports.env = env$1;
  84049. })));
  84050. //# sourceMappingURL=echarts.js.map