echarts-en.common.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. function find(obj, cb, context) {
  575. if (!(obj && cb)) {
  576. return;
  577. }
  578. for (var i = 0, len = obj.length; i < len; i++) {
  579. if (cb.call(context, obj[i], i, obj)) {
  580. return obj[i];
  581. }
  582. }
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @param {*} context
  588. * @return {Function}
  589. */
  590. function bind(func, context) {
  591. var args = nativeSlice.call(arguments, 2);
  592. return function () {
  593. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  594. };
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {Function} func
  599. * @return {Function}
  600. */
  601. function curry(func) {
  602. var args = nativeSlice.call(arguments, 1);
  603. return function () {
  604. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  605. };
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isArray(value) {
  613. return objToString.call(value) === '[object Array]';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isFunction$1(value) {
  621. return typeof value === 'function';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isString(value) {
  629. return objToString.call(value) === '[object String]';
  630. }
  631. /**
  632. * @memberOf module:zrender/core/util
  633. * @param {*} value
  634. * @return {boolean}
  635. */
  636. function isObject$1(value) {
  637. // Avoid a V8 JIT bug in Chrome 19-20.
  638. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  639. var type = typeof value;
  640. return type === 'function' || (!!value && type === 'object');
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isBuiltInObject(value) {
  648. return !!BUILTIN_OBJECT[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isTypedArray(value) {
  656. return !!TYPED_ARRAY[objToString.call(value)];
  657. }
  658. /**
  659. * @memberOf module:zrender/core/util
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function isDom(value) {
  664. return typeof value === 'object'
  665. && typeof value.nodeType === 'number'
  666. && typeof value.ownerDocument === 'object';
  667. }
  668. /**
  669. * Whether is exactly NaN. Notice isNaN('a') returns true.
  670. * @param {*} value
  671. * @return {boolean}
  672. */
  673. function eqNaN(value) {
  674. /* eslint-disable-next-line no-self-compare */
  675. return value !== value;
  676. }
  677. /**
  678. * If value1 is not null, then return value1, otherwise judget rest of values.
  679. * Low performance.
  680. * @memberOf module:zrender/core/util
  681. * @return {*} Final value
  682. */
  683. function retrieve(values) {
  684. for (var i = 0, len = arguments.length; i < len; i++) {
  685. if (arguments[i] != null) {
  686. return arguments[i];
  687. }
  688. }
  689. }
  690. function retrieve2(value0, value1) {
  691. return value0 != null
  692. ? value0
  693. : value1;
  694. }
  695. function retrieve3(value0, value1, value2) {
  696. return value0 != null
  697. ? value0
  698. : value1 != null
  699. ? value1
  700. : value2;
  701. }
  702. /**
  703. * @memberOf module:zrender/core/util
  704. * @param {Array} arr
  705. * @param {number} startIndex
  706. * @param {number} endIndex
  707. * @return {Array}
  708. */
  709. function slice() {
  710. return Function.call.apply(nativeSlice, arguments);
  711. }
  712. /**
  713. * Normalize css liked array configuration
  714. * e.g.
  715. * 3 => [3, 3, 3, 3]
  716. * [4, 2] => [4, 2, 4, 2]
  717. * [4, 3, 2] => [4, 3, 2, 3]
  718. * @param {number|Array.<number>} val
  719. * @return {Array.<number>}
  720. */
  721. function normalizeCssArray(val) {
  722. if (typeof (val) === 'number') {
  723. return [val, val, val, val];
  724. }
  725. var len = val.length;
  726. if (len === 2) {
  727. // vertical | horizontal
  728. return [val[0], val[1], val[0], val[1]];
  729. }
  730. else if (len === 3) {
  731. // top | horizontal | bottom
  732. return [val[0], val[1], val[2], val[1]];
  733. }
  734. return val;
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {boolean} condition
  739. * @param {string} message
  740. */
  741. function assert$1(condition, message) {
  742. if (!condition) {
  743. throw new Error(message);
  744. }
  745. }
  746. /**
  747. * @memberOf module:zrender/core/util
  748. * @param {string} str string to be trimed
  749. * @return {string} trimed string
  750. */
  751. function trim(str) {
  752. if (str == null) {
  753. return null;
  754. }
  755. else if (typeof str.trim === 'function') {
  756. return str.trim();
  757. }
  758. else {
  759. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  760. }
  761. }
  762. var primitiveKey = '__ec_primitive__';
  763. /**
  764. * Set an object as primitive to be ignored traversing children in clone or merge
  765. */
  766. function setAsPrimitive(obj) {
  767. obj[primitiveKey] = true;
  768. }
  769. function isPrimitive(obj) {
  770. return obj[primitiveKey];
  771. }
  772. /**
  773. * @constructor
  774. * @param {Object} obj Only apply `ownProperty`.
  775. */
  776. function HashMap(obj) {
  777. var isArr = isArray(obj);
  778. // Key should not be set on this, otherwise
  779. // methods get/set/... may be overrided.
  780. this.data = {};
  781. var thisMap = this;
  782. (obj instanceof HashMap)
  783. ? obj.each(visit)
  784. : (obj && each$1(obj, visit));
  785. function visit(value, key) {
  786. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  787. }
  788. }
  789. HashMap.prototype = {
  790. constructor: HashMap,
  791. // Do not provide `has` method to avoid defining what is `has`.
  792. // (We usually treat `null` and `undefined` as the same, different
  793. // from ES6 Map).
  794. get: function (key) {
  795. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  796. },
  797. set: function (key, value) {
  798. // Comparing with invocation chaining, `return value` is more commonly
  799. // used in this case: `var someVal = map.set('a', genVal());`
  800. return (this.data[key] = value);
  801. },
  802. // Although util.each can be performed on this hashMap directly, user
  803. // should not use the exposed keys, who are prefixed.
  804. each: function (cb, context) {
  805. context !== void 0 && (cb = bind(cb, context));
  806. /* eslint-disable guard-for-in */
  807. for (var key in this.data) {
  808. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  809. }
  810. /* eslint-enable guard-for-in */
  811. },
  812. // Do not use this method if performance sensitive.
  813. removeKey: function (key) {
  814. delete this.data[key];
  815. }
  816. };
  817. function createHashMap(obj) {
  818. return new HashMap(obj);
  819. }
  820. function concatArray(a, b) {
  821. var newArray = new a.constructor(a.length + b.length);
  822. for (var i = 0; i < a.length; i++) {
  823. newArray[i] = a[i];
  824. }
  825. var offset = a.length;
  826. for (i = 0; i < b.length; i++) {
  827. newArray[i + offset] = b[i];
  828. }
  829. return newArray;
  830. }
  831. function noop() {}
  832. var zrUtil = (Object.freeze || Object)({
  833. $override: $override,
  834. clone: clone,
  835. merge: merge,
  836. mergeAll: mergeAll,
  837. extend: extend,
  838. defaults: defaults,
  839. createCanvas: createCanvas,
  840. getContext: getContext,
  841. indexOf: indexOf,
  842. inherits: inherits,
  843. mixin: mixin,
  844. isArrayLike: isArrayLike,
  845. each: each$1,
  846. map: map,
  847. reduce: reduce,
  848. filter: filter,
  849. find: find,
  850. bind: bind,
  851. curry: curry,
  852. isArray: isArray,
  853. isFunction: isFunction$1,
  854. isString: isString,
  855. isObject: isObject$1,
  856. isBuiltInObject: isBuiltInObject,
  857. isTypedArray: isTypedArray,
  858. isDom: isDom,
  859. eqNaN: eqNaN,
  860. retrieve: retrieve,
  861. retrieve2: retrieve2,
  862. retrieve3: retrieve3,
  863. slice: slice,
  864. normalizeCssArray: normalizeCssArray,
  865. assert: assert$1,
  866. trim: trim,
  867. setAsPrimitive: setAsPrimitive,
  868. isPrimitive: isPrimitive,
  869. createHashMap: createHashMap,
  870. concatArray: concatArray,
  871. noop: noop
  872. });
  873. /* global Float32Array */
  874. var ArrayCtor = typeof Float32Array === 'undefined'
  875. ? Array
  876. : Float32Array;
  877. /**
  878. * 创建一个向量
  879. * @param {number} [x=0]
  880. * @param {number} [y=0]
  881. * @return {Vector2}
  882. */
  883. function create(x, y) {
  884. var out = new ArrayCtor(2);
  885. if (x == null) {
  886. x = 0;
  887. }
  888. if (y == null) {
  889. y = 0;
  890. }
  891. out[0] = x;
  892. out[1] = y;
  893. return out;
  894. }
  895. /**
  896. * 复制向量数据
  897. * @param {Vector2} out
  898. * @param {Vector2} v
  899. * @return {Vector2}
  900. */
  901. function copy(out, v) {
  902. out[0] = v[0];
  903. out[1] = v[1];
  904. return out;
  905. }
  906. /**
  907. * 克隆一个向量
  908. * @param {Vector2} v
  909. * @return {Vector2}
  910. */
  911. function clone$1(v) {
  912. var out = new ArrayCtor(2);
  913. out[0] = v[0];
  914. out[1] = v[1];
  915. return out;
  916. }
  917. /**
  918. * 设置向量的两个项
  919. * @param {Vector2} out
  920. * @param {number} a
  921. * @param {number} b
  922. * @return {Vector2} 结果
  923. */
  924. function set(out, a, b) {
  925. out[0] = a;
  926. out[1] = b;
  927. return out;
  928. }
  929. /**
  930. * 向量相加
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function add(out, v1, v2) {
  936. out[0] = v1[0] + v2[0];
  937. out[1] = v1[1] + v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量缩放后相加
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. * @param {number} a
  946. */
  947. function scaleAndAdd(out, v1, v2, a) {
  948. out[0] = v1[0] + v2[0] * a;
  949. out[1] = v1[1] + v2[1] * a;
  950. return out;
  951. }
  952. /**
  953. * 向量相减
  954. * @param {Vector2} out
  955. * @param {Vector2} v1
  956. * @param {Vector2} v2
  957. */
  958. function sub(out, v1, v2) {
  959. out[0] = v1[0] - v2[0];
  960. out[1] = v1[1] - v2[1];
  961. return out;
  962. }
  963. /**
  964. * 向量长度
  965. * @param {Vector2} v
  966. * @return {number}
  967. */
  968. function len(v) {
  969. return Math.sqrt(lenSquare(v));
  970. }
  971. var length = len; // jshint ignore:line
  972. /**
  973. * 向量长度平方
  974. * @param {Vector2} v
  975. * @return {number}
  976. */
  977. function lenSquare(v) {
  978. return v[0] * v[0] + v[1] * v[1];
  979. }
  980. var lengthSquare = lenSquare;
  981. /**
  982. * 向量乘法
  983. * @param {Vector2} out
  984. * @param {Vector2} v1
  985. * @param {Vector2} v2
  986. */
  987. function mul(out, v1, v2) {
  988. out[0] = v1[0] * v2[0];
  989. out[1] = v1[1] * v2[1];
  990. return out;
  991. }
  992. /**
  993. * 向量除法
  994. * @param {Vector2} out
  995. * @param {Vector2} v1
  996. * @param {Vector2} v2
  997. */
  998. function div(out, v1, v2) {
  999. out[0] = v1[0] / v2[0];
  1000. out[1] = v1[1] / v2[1];
  1001. return out;
  1002. }
  1003. /**
  1004. * 向量点乘
  1005. * @param {Vector2} v1
  1006. * @param {Vector2} v2
  1007. * @return {number}
  1008. */
  1009. function dot(v1, v2) {
  1010. return v1[0] * v2[0] + v1[1] * v2[1];
  1011. }
  1012. /**
  1013. * 向量缩放
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. * @param {number} s
  1017. */
  1018. function scale(out, v, s) {
  1019. out[0] = v[0] * s;
  1020. out[1] = v[1] * s;
  1021. return out;
  1022. }
  1023. /**
  1024. * 向量归一化
  1025. * @param {Vector2} out
  1026. * @param {Vector2} v
  1027. */
  1028. function normalize(out, v) {
  1029. var d = len(v);
  1030. if (d === 0) {
  1031. out[0] = 0;
  1032. out[1] = 0;
  1033. }
  1034. else {
  1035. out[0] = v[0] / d;
  1036. out[1] = v[1] / d;
  1037. }
  1038. return out;
  1039. }
  1040. /**
  1041. * 计算向量间距离
  1042. * @param {Vector2} v1
  1043. * @param {Vector2} v2
  1044. * @return {number}
  1045. */
  1046. function distance(v1, v2) {
  1047. return Math.sqrt(
  1048. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1050. );
  1051. }
  1052. var dist = distance;
  1053. /**
  1054. * 向量距离平方
  1055. * @param {Vector2} v1
  1056. * @param {Vector2} v2
  1057. * @return {number}
  1058. */
  1059. function distanceSquare(v1, v2) {
  1060. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1061. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1062. }
  1063. var distSquare = distanceSquare;
  1064. /**
  1065. * 求负向量
  1066. * @param {Vector2} out
  1067. * @param {Vector2} v
  1068. */
  1069. function negate(out, v) {
  1070. out[0] = -v[0];
  1071. out[1] = -v[1];
  1072. return out;
  1073. }
  1074. /**
  1075. * 插值两个点
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. * @param {number} t
  1080. */
  1081. function lerp(out, v1, v2, t) {
  1082. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1083. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1084. return out;
  1085. }
  1086. /**
  1087. * 矩阵左乘向量
  1088. * @param {Vector2} out
  1089. * @param {Vector2} v
  1090. * @param {Vector2} m
  1091. */
  1092. function applyTransform(out, v, m) {
  1093. var x = v[0];
  1094. var y = v[1];
  1095. out[0] = m[0] * x + m[2] * y + m[4];
  1096. out[1] = m[1] * x + m[3] * y + m[5];
  1097. return out;
  1098. }
  1099. /**
  1100. * 求两个向量最小值
  1101. * @param {Vector2} out
  1102. * @param {Vector2} v1
  1103. * @param {Vector2} v2
  1104. */
  1105. function min(out, v1, v2) {
  1106. out[0] = Math.min(v1[0], v2[0]);
  1107. out[1] = Math.min(v1[1], v2[1]);
  1108. return out;
  1109. }
  1110. /**
  1111. * 求两个向量最大值
  1112. * @param {Vector2} out
  1113. * @param {Vector2} v1
  1114. * @param {Vector2} v2
  1115. */
  1116. function max(out, v1, v2) {
  1117. out[0] = Math.max(v1[0], v2[0]);
  1118. out[1] = Math.max(v1[1], v2[1]);
  1119. return out;
  1120. }
  1121. var vector = (Object.freeze || Object)({
  1122. create: create,
  1123. copy: copy,
  1124. clone: clone$1,
  1125. set: set,
  1126. add: add,
  1127. scaleAndAdd: scaleAndAdd,
  1128. sub: sub,
  1129. len: len,
  1130. length: length,
  1131. lenSquare: lenSquare,
  1132. lengthSquare: lengthSquare,
  1133. mul: mul,
  1134. div: div,
  1135. dot: dot,
  1136. scale: scale,
  1137. normalize: normalize,
  1138. distance: distance,
  1139. dist: dist,
  1140. distanceSquare: distanceSquare,
  1141. distSquare: distSquare,
  1142. negate: negate,
  1143. lerp: lerp,
  1144. applyTransform: applyTransform,
  1145. min: min,
  1146. max: max
  1147. });
  1148. // TODO Draggable for group
  1149. // FIXME Draggable on element which has parent rotation or scale
  1150. function Draggable() {
  1151. this.on('mousedown', this._dragStart, this);
  1152. this.on('mousemove', this._drag, this);
  1153. this.on('mouseup', this._dragEnd, this);
  1154. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1155. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1156. // `_dragEnd` when globalout. That would brings better user experience.
  1157. // this.on('globalout', this._dragEnd, this);
  1158. // this._dropTarget = null;
  1159. // this._draggingTarget = null;
  1160. // this._x = 0;
  1161. // this._y = 0;
  1162. }
  1163. Draggable.prototype = {
  1164. constructor: Draggable,
  1165. _dragStart: function (e) {
  1166. var draggingTarget = e.target;
  1167. // Find if there is draggable in the ancestor
  1168. while (draggingTarget && !draggingTarget.draggable) {
  1169. draggingTarget = draggingTarget.parent;
  1170. }
  1171. if (draggingTarget) {
  1172. this._draggingTarget = draggingTarget;
  1173. draggingTarget.dragging = true;
  1174. this._x = e.offsetX;
  1175. this._y = e.offsetY;
  1176. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1177. }
  1178. },
  1179. _drag: function (e) {
  1180. var draggingTarget = this._draggingTarget;
  1181. if (draggingTarget) {
  1182. var x = e.offsetX;
  1183. var y = e.offsetY;
  1184. var dx = x - this._x;
  1185. var dy = y - this._y;
  1186. this._x = x;
  1187. this._y = y;
  1188. draggingTarget.drift(dx, dy, e);
  1189. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1190. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1191. var lastDropTarget = this._dropTarget;
  1192. this._dropTarget = dropTarget;
  1193. if (draggingTarget !== dropTarget) {
  1194. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1195. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1196. }
  1197. if (dropTarget && dropTarget !== lastDropTarget) {
  1198. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1199. }
  1200. }
  1201. }
  1202. },
  1203. _dragEnd: function (e) {
  1204. var draggingTarget = this._draggingTarget;
  1205. if (draggingTarget) {
  1206. draggingTarget.dragging = false;
  1207. }
  1208. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1209. if (this._dropTarget) {
  1210. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1211. }
  1212. this._draggingTarget = null;
  1213. this._dropTarget = null;
  1214. }
  1215. };
  1216. function param(target, e) {
  1217. return {target: target, topTarget: e && e.topTarget};
  1218. }
  1219. /**
  1220. * Event Mixin
  1221. * @module zrender/mixin/Eventful
  1222. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1223. * pissang (https://www.github.com/pissang)
  1224. */
  1225. var arrySlice = Array.prototype.slice;
  1226. /**
  1227. * Event dispatcher.
  1228. *
  1229. * @alias module:zrender/mixin/Eventful
  1230. * @constructor
  1231. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1232. * `eventProcessor.xxx` called.
  1233. * @param {Function} [eventProcessor.normalizeQuery]
  1234. * param: {string|Object} Raw query.
  1235. * return: {string|Object} Normalized query.
  1236. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1237. * if it returns `true`.
  1238. * param: {string} eventType
  1239. * param: {string|Object} query
  1240. * return: {boolean}
  1241. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1242. * param: {string} eventType
  1243. */
  1244. var Eventful = function (eventProcessor) {
  1245. this._$handlers = {};
  1246. this._$eventProcessor = eventProcessor;
  1247. };
  1248. Eventful.prototype = {
  1249. constructor: Eventful,
  1250. /**
  1251. * The handler can only be triggered once, then removed.
  1252. *
  1253. * @param {string} event The event name.
  1254. * @param {string|Object} [query] Condition used on event filter.
  1255. * @param {Function} handler The event handler.
  1256. * @param {Object} context
  1257. */
  1258. one: function (event, query, handler, context) {
  1259. return on(this, event, query, handler, context, true);
  1260. },
  1261. /**
  1262. * Bind a handler.
  1263. *
  1264. * @param {string} event The event name.
  1265. * @param {string|Object} [query] Condition used on event filter.
  1266. * @param {Function} handler The event handler.
  1267. * @param {Object} [context]
  1268. */
  1269. on: function (event, query, handler, context) {
  1270. return on(this, event, query, handler, context, false);
  1271. },
  1272. /**
  1273. * Whether any handler has bound.
  1274. *
  1275. * @param {string} event
  1276. * @return {boolean}
  1277. */
  1278. isSilent: function (event) {
  1279. var _h = this._$handlers;
  1280. return !_h[event] || !_h[event].length;
  1281. },
  1282. /**
  1283. * Unbind a event.
  1284. *
  1285. * @param {string} [event] The event name.
  1286. * If no `event` input, "off" all listeners.
  1287. * @param {Function} [handler] The event handler.
  1288. * If no `handler` input, "off" all listeners of the `event`.
  1289. */
  1290. off: function (event, handler) {
  1291. var _h = this._$handlers;
  1292. if (!event) {
  1293. this._$handlers = {};
  1294. return this;
  1295. }
  1296. if (handler) {
  1297. if (_h[event]) {
  1298. var newList = [];
  1299. for (var i = 0, l = _h[event].length; i < l; i++) {
  1300. if (_h[event][i].h !== handler) {
  1301. newList.push(_h[event][i]);
  1302. }
  1303. }
  1304. _h[event] = newList;
  1305. }
  1306. if (_h[event] && _h[event].length === 0) {
  1307. delete _h[event];
  1308. }
  1309. }
  1310. else {
  1311. delete _h[event];
  1312. }
  1313. return this;
  1314. },
  1315. /**
  1316. * Dispatch a event.
  1317. *
  1318. * @param {string} type The event name.
  1319. */
  1320. trigger: function (type) {
  1321. var _h = this._$handlers[type];
  1322. var eventProcessor = this._$eventProcessor;
  1323. if (_h) {
  1324. var args = arguments;
  1325. var argLen = args.length;
  1326. if (argLen > 3) {
  1327. args = arrySlice.call(args, 1);
  1328. }
  1329. var len = _h.length;
  1330. for (var i = 0; i < len;) {
  1331. var hItem = _h[i];
  1332. if (eventProcessor
  1333. && eventProcessor.filter
  1334. && hItem.query != null
  1335. && !eventProcessor.filter(type, hItem.query)
  1336. ) {
  1337. i++;
  1338. continue;
  1339. }
  1340. // Optimize advise from backbone
  1341. switch (argLen) {
  1342. case 1:
  1343. hItem.h.call(hItem.ctx);
  1344. break;
  1345. case 2:
  1346. hItem.h.call(hItem.ctx, args[1]);
  1347. break;
  1348. case 3:
  1349. hItem.h.call(hItem.ctx, args[1], args[2]);
  1350. break;
  1351. default:
  1352. // have more than 2 given arguments
  1353. hItem.h.apply(hItem.ctx, args);
  1354. break;
  1355. }
  1356. if (hItem.one) {
  1357. _h.splice(i, 1);
  1358. len--;
  1359. }
  1360. else {
  1361. i++;
  1362. }
  1363. }
  1364. }
  1365. eventProcessor && eventProcessor.afterTrigger
  1366. && eventProcessor.afterTrigger(type);
  1367. return this;
  1368. },
  1369. /**
  1370. * Dispatch a event with context, which is specified at the last parameter.
  1371. *
  1372. * @param {string} type The event name.
  1373. */
  1374. triggerWithContext: function (type) {
  1375. var _h = this._$handlers[type];
  1376. var eventProcessor = this._$eventProcessor;
  1377. if (_h) {
  1378. var args = arguments;
  1379. var argLen = args.length;
  1380. if (argLen > 4) {
  1381. args = arrySlice.call(args, 1, args.length - 1);
  1382. }
  1383. var ctx = args[args.length - 1];
  1384. var len = _h.length;
  1385. for (var i = 0; i < len;) {
  1386. var hItem = _h[i];
  1387. if (eventProcessor
  1388. && eventProcessor.filter
  1389. && hItem.query != null
  1390. && !eventProcessor.filter(type, hItem.query)
  1391. ) {
  1392. i++;
  1393. continue;
  1394. }
  1395. // Optimize advise from backbone
  1396. switch (argLen) {
  1397. case 1:
  1398. hItem.h.call(ctx);
  1399. break;
  1400. case 2:
  1401. hItem.h.call(ctx, args[1]);
  1402. break;
  1403. case 3:
  1404. hItem.h.call(ctx, args[1], args[2]);
  1405. break;
  1406. default:
  1407. // have more than 2 given arguments
  1408. hItem.h.apply(ctx, args);
  1409. break;
  1410. }
  1411. if (hItem.one) {
  1412. _h.splice(i, 1);
  1413. len--;
  1414. }
  1415. else {
  1416. i++;
  1417. }
  1418. }
  1419. }
  1420. eventProcessor && eventProcessor.afterTrigger
  1421. && eventProcessor.afterTrigger(type);
  1422. return this;
  1423. }
  1424. };
  1425. function normalizeQuery(host, query) {
  1426. var eventProcessor = host._$eventProcessor;
  1427. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1428. query = eventProcessor.normalizeQuery(query);
  1429. }
  1430. return query;
  1431. }
  1432. function on(eventful, event, query, handler, context, isOnce) {
  1433. var _h = eventful._$handlers;
  1434. if (typeof query === 'function') {
  1435. context = handler;
  1436. handler = query;
  1437. query = null;
  1438. }
  1439. if (!handler || !event) {
  1440. return eventful;
  1441. }
  1442. query = normalizeQuery(eventful, query);
  1443. if (!_h[event]) {
  1444. _h[event] = [];
  1445. }
  1446. for (var i = 0; i < _h[event].length; i++) {
  1447. if (_h[event][i].h === handler) {
  1448. return eventful;
  1449. }
  1450. }
  1451. var wrap = {
  1452. h: handler,
  1453. one: isOnce,
  1454. query: query,
  1455. ctx: context || eventful,
  1456. // FIXME
  1457. // Do not publish this feature util it is proved that it makes sense.
  1458. callAtLast: handler.zrEventfulCallAtLast
  1459. };
  1460. var lastIndex = _h[event].length - 1;
  1461. var lastWrap = _h[event][lastIndex];
  1462. (lastWrap && lastWrap.callAtLast)
  1463. ? _h[event].splice(lastIndex, 0, wrap)
  1464. : _h[event].push(wrap);
  1465. return eventful;
  1466. }
  1467. /**
  1468. * The algoritm is learnt from
  1469. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1470. * And we made some optimization for matrix inversion.
  1471. * Other similar approaches:
  1472. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1473. */
  1474. var LN2 = Math.log(2);
  1475. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1476. var cacheKey = rowMask + '-' + colMask;
  1477. var fullRank = rows.length;
  1478. if (detCache.hasOwnProperty(cacheKey)) {
  1479. return detCache[cacheKey];
  1480. }
  1481. if (rank === 1) {
  1482. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1483. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1484. return rows[rowStart][colStart];
  1485. }
  1486. var subRowMask = rowMask | (1 << rowStart);
  1487. var subRowStart = rowStart + 1;
  1488. while (rowMask & (1 << subRowStart)) {
  1489. subRowStart++;
  1490. }
  1491. var sum = 0;
  1492. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1493. var colTag = 1 << j;
  1494. if (!(colTag & colMask)) {
  1495. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1496. // det(subMatrix(0, j))
  1497. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1498. colLocalIdx++;
  1499. }
  1500. }
  1501. detCache[cacheKey] = sum;
  1502. return sum;
  1503. }
  1504. /**
  1505. * Usage:
  1506. * ```js
  1507. * var transformer = buildTransformer(
  1508. * [10, 44, 100, 44, 100, 300, 10, 300],
  1509. * [50, 54, 130, 14, 140, 330, 14, 220]
  1510. * );
  1511. * var out = [];
  1512. * transformer && transformer([11, 33], out);
  1513. * ```
  1514. *
  1515. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1516. *
  1517. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1518. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1519. * @return {Function} transformer If fail, return null/undefined.
  1520. */
  1521. function buildTransformer(src, dest) {
  1522. var mA = [
  1523. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1524. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1525. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1526. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1527. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1528. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1529. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1530. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1531. ];
  1532. var detCache = {};
  1533. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1534. if (det === 0) {
  1535. // can not make transformer when and only when
  1536. // any three of the markers are collinear.
  1537. return;
  1538. }
  1539. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1540. var vh = [];
  1541. for (var i = 0; i < 8; i++) {
  1542. for (var j = 0; j < 8; j++) {
  1543. vh[j] == null && (vh[j] = 0);
  1544. vh[j] += ((i + j) % 2 ? -1 : 1)
  1545. // det(subMatrix(i, j))
  1546. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1547. / det * dest[i];
  1548. }
  1549. }
  1550. return function (out, srcPointX, srcPointY) {
  1551. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1552. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1553. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1554. };
  1555. }
  1556. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1557. var _calcOut$1 = [];
  1558. /**
  1559. * Transform "local coord" from `elFrom` to `elTarget`.
  1560. * "local coord": the coord based on the input `el`. The origin point is at
  1561. * the position of "left: 0; top: 0;" in the `el`.
  1562. *
  1563. * Support when CSS transform is used.
  1564. *
  1565. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1566. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1567. * to locate the element.
  1568. *
  1569. * For example, this code below positions a child of `document.body` on the event
  1570. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1571. * ```js
  1572. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1573. * if (!eqNaN(out[0])) {
  1574. * // Then locate the tip element on the event point.
  1575. * var tipEl = document.createElement('div');
  1576. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1577. * document.body.appendChild(tipEl);
  1578. * }
  1579. * ```
  1580. *
  1581. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1582. *
  1583. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1584. * If can not transform, `out` will not be modified but return `false`.
  1585. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1586. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1587. * @param {number} inX
  1588. * @param {number} inY
  1589. * @return {boolean} Whether transform successfully.
  1590. */
  1591. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1592. return transformCoordWithViewport(_calcOut$1, elFrom, inX, inY, true)
  1593. && transformCoordWithViewport(out, elTarget, _calcOut$1[0], _calcOut$1[1]);
  1594. }
  1595. /**
  1596. * Transform between a "viewport coord" and a "local coord".
  1597. * "viewport coord": the coord based on the left-top corner of the viewport
  1598. * of the browser.
  1599. * "local coord": the coord based on the input `el`. The origin point is at
  1600. * the position of "left: 0; top: 0;" in the `el`.
  1601. *
  1602. * Support the case when CSS transform is used on el.
  1603. *
  1604. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1605. * it represents "local coord", otherwise "vireport coord".
  1606. * If can not transform, `out` will not be modified but return `false`.
  1607. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1608. * @param {number} inX If `inverse: false`,
  1609. * it represents "vireport coord", otherwise "local coord".
  1610. * @param {number} inY If `inverse: false`,
  1611. * it represents "vireport coord", otherwise "local coord".
  1612. * @param {boolean} [inverse=false]
  1613. * `true`: from "viewport coord" to "local coord".
  1614. * `false`: from "local coord" to "viewport coord".
  1615. * @return {boolean} Whether transform successfully.
  1616. */
  1617. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1618. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1619. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1620. var markers = prepareCoordMarkers(el, saved);
  1621. var transformer = preparePointerTransformer(markers, saved, inverse);
  1622. if (transformer) {
  1623. transformer(out, inX, inY);
  1624. return true;
  1625. }
  1626. }
  1627. return false;
  1628. }
  1629. function prepareCoordMarkers(el, saved) {
  1630. var markers = saved.markers;
  1631. if (markers) {
  1632. return markers;
  1633. }
  1634. markers = saved.markers = [];
  1635. var propLR = ['left', 'right'];
  1636. var propTB = ['top', 'bottom'];
  1637. for (var i = 0; i < 4; i++) {
  1638. var marker = document.createElement('div');
  1639. var stl = marker.style;
  1640. var idxLR = i % 2;
  1641. var idxTB = (i >> 1) % 2;
  1642. stl.cssText = [
  1643. 'position: absolute',
  1644. 'visibility: hidden',
  1645. 'padding: 0',
  1646. 'margin: 0',
  1647. 'border-width: 0',
  1648. 'user-select: none',
  1649. 'width:0',
  1650. 'height:0',
  1651. // 'width: 5px',
  1652. // 'height: 5px',
  1653. propLR[idxLR] + ':0',
  1654. propTB[idxTB] + ':0',
  1655. propLR[1 - idxLR] + ':auto',
  1656. propTB[1 - idxTB] + ':auto',
  1657. ''
  1658. ].join('!important;');
  1659. el.appendChild(marker);
  1660. markers.push(marker);
  1661. }
  1662. return markers;
  1663. }
  1664. function preparePointerTransformer(markers, saved, inverse) {
  1665. var transformerName = inverse ? 'invTrans' : 'trans';
  1666. var transformer = saved[transformerName];
  1667. var oldSrcCoords = saved.srcCoords;
  1668. var oldCoordTheSame = true;
  1669. var srcCoords = [];
  1670. var destCoords = [];
  1671. for (var i = 0; i < 4; i++) {
  1672. var rect = markers[i].getBoundingClientRect();
  1673. var ii = 2 * i;
  1674. var x = rect.left;
  1675. var y = rect.top;
  1676. srcCoords.push(x, y);
  1677. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1678. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1679. }
  1680. // Cache to avoid time consuming of `buildTransformer`.
  1681. return (oldCoordTheSame && transformer)
  1682. ? transformer
  1683. : (
  1684. saved.srcCoords = srcCoords,
  1685. saved[transformerName] = inverse
  1686. ? buildTransformer(destCoords, srcCoords)
  1687. : buildTransformer(srcCoords, destCoords)
  1688. );
  1689. }
  1690. function isCanvasEl(el) {
  1691. return el.nodeName.toUpperCase() === 'CANVAS';
  1692. }
  1693. /**
  1694. * Utilities for mouse or touch events.
  1695. */
  1696. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1697. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1698. var _calcOut = [];
  1699. /**
  1700. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1701. * the input `el`.
  1702. * CSS transform (2D & 3D) is supported.
  1703. *
  1704. * The strategy to fetch the coords:
  1705. * + If `calculate` is not set as `true`, users of this method should
  1706. * ensure that `el` is the same or the same size & location as `e.target`.
  1707. * Otherwise the result coords are probably not expected. Because we
  1708. * firstly try to get coords from e.offsetX/e.offsetY.
  1709. * + If `calculate` is set as `true`, the input `el` can be any element
  1710. * and we force to calculate the coords based on `el`.
  1711. * + The input `el` should be positionable (not position:static).
  1712. *
  1713. * The force `calculate` can be used in case like:
  1714. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1715. *
  1716. * @param {HTMLElement} el DOM element.
  1717. * @param {Event} e Mouse event or touch event.
  1718. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1719. * @param {boolean} [calculate=false] Whether to force calculate
  1720. * the coordinates but not use ones provided by browser.
  1721. */
  1722. function clientToLocal(el, e, out, calculate) {
  1723. out = out || {};
  1724. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1725. // to the padding edge of the target element. The only browser using this convention
  1726. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1727. // not support the properties.
  1728. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1729. // In zr painter.dom, padding edge equals to border edge.
  1730. if (calculate || !env$1.canvasSupported) {
  1731. calculateZrXY(el, e, out);
  1732. }
  1733. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1734. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1735. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1736. // zoom-factor, overflow / opacity layers, transforms ...)
  1737. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1738. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1739. // BTW3, In ff, offsetX/offsetY is always 0.
  1740. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1741. out.zrX = e.layerX;
  1742. out.zrY = e.layerY;
  1743. }
  1744. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1745. else if (e.offsetX != null) {
  1746. out.zrX = e.offsetX;
  1747. out.zrY = e.offsetY;
  1748. }
  1749. // For some other device, e.g., IOS safari.
  1750. else {
  1751. calculateZrXY(el, e, out);
  1752. }
  1753. return out;
  1754. }
  1755. function calculateZrXY(el, e, out) {
  1756. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1757. if (env$1.domSupported && el.getBoundingClientRect) {
  1758. var ex = e.clientX;
  1759. var ey = e.clientY;
  1760. if (isCanvasEl(el)) {
  1761. // Original approach, which do not support CSS transform.
  1762. // marker can not be locationed in a canvas container
  1763. // (getBoundingClientRect is always 0). We do not support
  1764. // that input a pre-created canvas to zr while using css
  1765. // transform in iOS.
  1766. var box = el.getBoundingClientRect();
  1767. out.zrX = ex - box.left;
  1768. out.zrY = ey - box.top;
  1769. return;
  1770. }
  1771. else {
  1772. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1773. out.zrX = _calcOut[0];
  1774. out.zrY = _calcOut[1];
  1775. return;
  1776. }
  1777. }
  1778. }
  1779. out.zrX = out.zrY = 0;
  1780. }
  1781. /**
  1782. * Find native event compat for legency IE.
  1783. * Should be called at the begining of a native event listener.
  1784. *
  1785. * @param {Event} [e] Mouse event or touch event or pointer event.
  1786. * For lagency IE, we use `window.event` is used.
  1787. * @return {Event} The native event.
  1788. */
  1789. function getNativeEvent(e) {
  1790. return e || window.event;
  1791. }
  1792. /**
  1793. * Normalize the coordinates of the input event.
  1794. *
  1795. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1796. * the input `el`.
  1797. * Get `e.zrDelta` if using mouse wheel.
  1798. * Get `e.which`, see the comment inside this function.
  1799. *
  1800. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1801. *
  1802. * Notice: see comments in `clientToLocal`. check the relationship
  1803. * between the result coords and the parameters `el` and `calculate`.
  1804. *
  1805. * @param {HTMLElement} el DOM element.
  1806. * @param {Event} [e] See `getNativeEvent`.
  1807. * @param {boolean} [calculate=false] Whether to force calculate
  1808. * the coordinates but not use ones provided by browser.
  1809. * @return {UIEvent} The normalized native UIEvent.
  1810. */
  1811. function normalizeEvent(el, e, calculate) {
  1812. e = getNativeEvent(e);
  1813. if (e.zrX != null) {
  1814. return e;
  1815. }
  1816. var eventType = e.type;
  1817. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1818. if (!isTouch) {
  1819. clientToLocal(el, e, e, calculate);
  1820. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1821. }
  1822. else {
  1823. var touch = eventType !== 'touchend'
  1824. ? e.targetTouches[0]
  1825. : e.changedTouches[0];
  1826. touch && clientToLocal(el, touch, e, calculate);
  1827. }
  1828. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1829. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1830. // If e.which has been defined, it may be readonly,
  1831. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1832. var button = e.button;
  1833. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1834. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1835. }
  1836. // [Caution]: `e.which` from browser is not always reliable. For example,
  1837. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1838. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1839. // `mousedown (pointerdown)` is the same as Chrome does.
  1840. return e;
  1841. }
  1842. /**
  1843. * @param {HTMLElement} el
  1844. * @param {string} name
  1845. * @param {Function} handler
  1846. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1847. * @param {boolean} [opt.capture=false]
  1848. * @param {boolean} [opt.passive=false]
  1849. */
  1850. function addEventListener(el, name, handler, opt) {
  1851. if (isDomLevel2) {
  1852. // Reproduct the console warning:
  1853. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1854. // Consider marking event handler as 'passive' to make the page more responsive.
  1855. // Just set console log level: verbose in chrome dev tool.
  1856. // then the warning log will be printed when addEventListener called.
  1857. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1858. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1859. // listener delegate all of the upper events of element. Some of those events need
  1860. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1861. // Before passive can be adopted, these issues should be considered:
  1862. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1863. // passive or not.
  1864. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1865. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1866. // compatibility should be handled.
  1867. // var opts = (env.passiveSupported && name === 'mousewheel')
  1868. // ? {passive: true}
  1869. // // By default, the third param of el.addEventListener is `capture: false`.
  1870. // : void 0;
  1871. // el.addEventListener(name, handler /* , opts */);
  1872. el.addEventListener(name, handler, opt);
  1873. }
  1874. else {
  1875. // For simplicity, do not implement `setCapture` for IE9-.
  1876. el.attachEvent('on' + name, handler);
  1877. }
  1878. }
  1879. /**
  1880. * Parameter are the same as `addEventListener`.
  1881. *
  1882. * Notice that if a listener is registered twice, one with capture and one without,
  1883. * remove each one separately. Removal of a capturing listener does not affect a
  1884. * non-capturing version of the same listener, and vice versa.
  1885. */
  1886. function removeEventListener(el, name, handler, opt) {
  1887. if (isDomLevel2) {
  1888. el.removeEventListener(name, handler, opt);
  1889. }
  1890. else {
  1891. el.detachEvent('on' + name, handler);
  1892. }
  1893. }
  1894. /**
  1895. * preventDefault and stopPropagation.
  1896. * Notice: do not use this method in zrender. It can only be
  1897. * used by upper applications if necessary.
  1898. *
  1899. * @param {Event} e A mouse or touch event.
  1900. */
  1901. var stop = isDomLevel2
  1902. ? function (e) {
  1903. e.preventDefault();
  1904. e.stopPropagation();
  1905. e.cancelBubble = true;
  1906. }
  1907. : function (e) {
  1908. e.returnValue = false;
  1909. e.cancelBubble = true;
  1910. };
  1911. /**
  1912. * This method only works for mouseup and mousedown. The functionality is restricted
  1913. * for fault tolerance, See the `e.which` compatibility above.
  1914. *
  1915. * @param {MouseEvent} e
  1916. * @return {boolean}
  1917. */
  1918. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1919. return e.which === 2 || e.which === 3;
  1920. }
  1921. /**
  1922. * To be removed.
  1923. * @deprecated
  1924. */
  1925. /**
  1926. * Only implements needed gestures for mobile.
  1927. */
  1928. var GestureMgr = function () {
  1929. /**
  1930. * @private
  1931. * @type {Array.<Object>}
  1932. */
  1933. this._track = [];
  1934. };
  1935. GestureMgr.prototype = {
  1936. constructor: GestureMgr,
  1937. recognize: function (event, target, root) {
  1938. this._doTrack(event, target, root);
  1939. return this._recognize(event);
  1940. },
  1941. clear: function () {
  1942. this._track.length = 0;
  1943. return this;
  1944. },
  1945. _doTrack: function (event, target, root) {
  1946. var touches = event.touches;
  1947. if (!touches) {
  1948. return;
  1949. }
  1950. var trackItem = {
  1951. points: [],
  1952. touches: [],
  1953. target: target,
  1954. event: event
  1955. };
  1956. for (var i = 0, len = touches.length; i < len; i++) {
  1957. var touch = touches[i];
  1958. var pos = clientToLocal(root, touch, {});
  1959. trackItem.points.push([pos.zrX, pos.zrY]);
  1960. trackItem.touches.push(touch);
  1961. }
  1962. this._track.push(trackItem);
  1963. },
  1964. _recognize: function (event) {
  1965. for (var eventName in recognizers) {
  1966. if (recognizers.hasOwnProperty(eventName)) {
  1967. var gestureInfo = recognizers[eventName](this._track, event);
  1968. if (gestureInfo) {
  1969. return gestureInfo;
  1970. }
  1971. }
  1972. }
  1973. }
  1974. };
  1975. function dist$1(pointPair) {
  1976. var dx = pointPair[1][0] - pointPair[0][0];
  1977. var dy = pointPair[1][1] - pointPair[0][1];
  1978. return Math.sqrt(dx * dx + dy * dy);
  1979. }
  1980. function center(pointPair) {
  1981. return [
  1982. (pointPair[0][0] + pointPair[1][0]) / 2,
  1983. (pointPair[0][1] + pointPair[1][1]) / 2
  1984. ];
  1985. }
  1986. var recognizers = {
  1987. pinch: function (track, event) {
  1988. var trackLen = track.length;
  1989. if (!trackLen) {
  1990. return;
  1991. }
  1992. var pinchEnd = (track[trackLen - 1] || {}).points;
  1993. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1994. if (pinchPre
  1995. && pinchPre.length > 1
  1996. && pinchEnd
  1997. && pinchEnd.length > 1
  1998. ) {
  1999. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  2000. !isFinite(pinchScale) && (pinchScale = 1);
  2001. event.pinchScale = pinchScale;
  2002. var pinchCenter = center(pinchEnd);
  2003. event.pinchX = pinchCenter[0];
  2004. event.pinchY = pinchCenter[1];
  2005. return {
  2006. type: 'pinch',
  2007. target: track[0].target,
  2008. event: event
  2009. };
  2010. }
  2011. }
  2012. // Only pinch currently.
  2013. };
  2014. /**
  2015. * [The interface between `Handler` and `HandlerProxy`]:
  2016. *
  2017. * The default `HandlerProxy` only support the common standard web environment
  2018. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  2019. * But `HandlerProxy` can be replaced to support more non-standard environment
  2020. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  2021. * not provided (like echarts-gl did).
  2022. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  2023. * make break changes util inevitable. The interface include the public methods
  2024. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  2025. * drives `Handler`.
  2026. */
  2027. /**
  2028. * [Drag outside]:
  2029. *
  2030. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  2031. * zrender area when dragging. That is important for the improvement of the user experience
  2032. * when dragging something near the boundary without being terminated unexpectedly.
  2033. *
  2034. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  2035. * to resolve this issue. But some drawbacks of it is described in
  2036. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  2037. *
  2038. * Instead, we referenced the specifications:
  2039. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  2040. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  2041. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  2042. * operation and the pointer has left the boundary. (for the mouse event, browsers
  2043. * only do it on `document` and when the pointer has left the boundary of the browser.)
  2044. *
  2045. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  2046. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  2047. * to fire until release the pointer. That is implemented by listen to those event on
  2048. * `document`.
  2049. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  2050. * The touch event support this feature by default.
  2051. *
  2052. * Note:
  2053. * There might be some cases that the mouse event can not be
  2054. * received on `document`. For example,
  2055. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  2056. * of zr dom throw Error .
  2057. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  2058. * zr dom call `stopPropagation`.
  2059. * In these cases, the `mousemove` event might be keep triggered event
  2060. * if the mouse is released. We try to reduce the side-effect in those cases.
  2061. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  2062. *
  2063. * Note:
  2064. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  2065. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  2066. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  2067. * `document` capture phase to prevent the propagation to any listener of the webpage.
  2068. * But they are needed to work when the pointer inside the zrender dom.
  2069. */
  2070. var SILENT = 'silent';
  2071. function makeEventPacket(eveType, targetInfo, event) {
  2072. return {
  2073. type: eveType,
  2074. event: event,
  2075. // target can only be an element that is not silent.
  2076. target: targetInfo.target,
  2077. // topTarget can be a silent element.
  2078. topTarget: targetInfo.topTarget,
  2079. cancelBubble: false,
  2080. offsetX: event.zrX,
  2081. offsetY: event.zrY,
  2082. gestureEvent: event.gestureEvent,
  2083. pinchX: event.pinchX,
  2084. pinchY: event.pinchY,
  2085. pinchScale: event.pinchScale,
  2086. wheelDelta: event.zrDelta,
  2087. zrByTouch: event.zrByTouch,
  2088. which: event.which,
  2089. stop: stopEvent
  2090. };
  2091. }
  2092. function stopEvent() {
  2093. stop(this.event);
  2094. }
  2095. function EmptyProxy() {}
  2096. EmptyProxy.prototype.dispose = function () {};
  2097. var handlerNames = [
  2098. 'click', 'dblclick', 'mousewheel', 'mouseout',
  2099. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  2100. ];
  2101. /**
  2102. * @alias module:zrender/Handler
  2103. * @constructor
  2104. * @extends module:zrender/mixin/Eventful
  2105. * @param {module:zrender/Storage} storage Storage instance.
  2106. * @param {module:zrender/Painter} painter Painter instance.
  2107. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  2108. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  2109. */
  2110. var Handler = function (storage, painter, proxy, painterRoot) {
  2111. Eventful.call(this);
  2112. this.storage = storage;
  2113. this.painter = painter;
  2114. this.painterRoot = painterRoot;
  2115. proxy = proxy || new EmptyProxy();
  2116. /**
  2117. * Proxy of event. can be Dom, WebGLSurface, etc.
  2118. */
  2119. this.proxy = null;
  2120. /**
  2121. * {target, topTarget, x, y}
  2122. * @private
  2123. * @type {Object}
  2124. */
  2125. this._hovered = {};
  2126. /**
  2127. * @private
  2128. * @type {Date}
  2129. */
  2130. this._lastTouchMoment;
  2131. /**
  2132. * @private
  2133. * @type {number}
  2134. */
  2135. this._lastX;
  2136. /**
  2137. * @private
  2138. * @type {number}
  2139. */
  2140. this._lastY;
  2141. /**
  2142. * @private
  2143. * @type {module:zrender/core/GestureMgr}
  2144. */
  2145. this._gestureMgr;
  2146. Draggable.call(this);
  2147. this.setHandlerProxy(proxy);
  2148. };
  2149. Handler.prototype = {
  2150. constructor: Handler,
  2151. setHandlerProxy: function (proxy) {
  2152. if (this.proxy) {
  2153. this.proxy.dispose();
  2154. }
  2155. if (proxy) {
  2156. each$1(handlerNames, function (name) {
  2157. proxy.on && proxy.on(name, this[name], this);
  2158. }, this);
  2159. // Attach handler
  2160. proxy.handler = this;
  2161. }
  2162. this.proxy = proxy;
  2163. },
  2164. mousemove: function (event) {
  2165. var x = event.zrX;
  2166. var y = event.zrY;
  2167. var isOutside = isOutsideBoundary(this, x, y);
  2168. var lastHovered = this._hovered;
  2169. var lastHoveredTarget = lastHovered.target;
  2170. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2171. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2172. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2173. // See #6198.
  2174. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2175. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2176. lastHoveredTarget = lastHovered.target;
  2177. }
  2178. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2179. var hoveredTarget = hovered.target;
  2180. var proxy = this.proxy;
  2181. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2182. // Mouse out on previous hovered element
  2183. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2184. this.dispatchToElement(lastHovered, 'mouseout', event);
  2185. }
  2186. // Mouse moving on one element
  2187. this.dispatchToElement(hovered, 'mousemove', event);
  2188. // Mouse over on a new element
  2189. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2190. this.dispatchToElement(hovered, 'mouseover', event);
  2191. }
  2192. },
  2193. mouseout: function (event) {
  2194. var eventControl = event.zrEventControl;
  2195. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2196. if (eventControl !== 'only_globalout') {
  2197. this.dispatchToElement(this._hovered, 'mouseout', event);
  2198. }
  2199. if (eventControl !== 'no_globalout') {
  2200. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2201. // the `globalout` should have been triggered. But currently not.
  2202. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2203. }
  2204. },
  2205. /**
  2206. * Resize
  2207. */
  2208. resize: function (event) {
  2209. this._hovered = {};
  2210. },
  2211. /**
  2212. * Dispatch event
  2213. * @param {string} eventName
  2214. * @param {event=} eventArgs
  2215. */
  2216. dispatch: function (eventName, eventArgs) {
  2217. var handler = this[eventName];
  2218. handler && handler.call(this, eventArgs);
  2219. },
  2220. /**
  2221. * Dispose
  2222. */
  2223. dispose: function () {
  2224. this.proxy.dispose();
  2225. this.storage =
  2226. this.proxy =
  2227. this.painter = null;
  2228. },
  2229. /**
  2230. * 设置默认的cursor style
  2231. * @param {string} [cursorStyle='default'] 例如 crosshair
  2232. */
  2233. setCursorStyle: function (cursorStyle) {
  2234. var proxy = this.proxy;
  2235. proxy.setCursor && proxy.setCursor(cursorStyle);
  2236. },
  2237. /**
  2238. * 事件分发代理
  2239. *
  2240. * @private
  2241. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2242. * @param {string} eventName 事件名称
  2243. * @param {Object} event 事件对象
  2244. */
  2245. dispatchToElement: function (targetInfo, eventName, event) {
  2246. targetInfo = targetInfo || {};
  2247. var el = targetInfo.target;
  2248. if (el && el.silent) {
  2249. return;
  2250. }
  2251. var eventHandler = 'on' + eventName;
  2252. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2253. while (el) {
  2254. el[eventHandler]
  2255. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2256. el.trigger(eventName, eventPacket);
  2257. el = el.parent;
  2258. if (eventPacket.cancelBubble) {
  2259. break;
  2260. }
  2261. }
  2262. if (!eventPacket.cancelBubble) {
  2263. // 冒泡到顶级 zrender 对象
  2264. this.trigger(eventName, eventPacket);
  2265. // 分发事件到用户自定义层
  2266. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2267. this.painter && this.painter.eachOtherLayer(function (layer) {
  2268. if (typeof (layer[eventHandler]) === 'function') {
  2269. layer[eventHandler].call(layer, eventPacket);
  2270. }
  2271. if (layer.trigger) {
  2272. layer.trigger(eventName, eventPacket);
  2273. }
  2274. });
  2275. }
  2276. },
  2277. /**
  2278. * @private
  2279. * @param {number} x
  2280. * @param {number} y
  2281. * @param {module:zrender/graphic/Displayable} exclude
  2282. * @return {model:zrender/Element}
  2283. * @method
  2284. */
  2285. findHover: function (x, y, exclude) {
  2286. var list = this.storage.getDisplayList();
  2287. var out = {x: x, y: y};
  2288. for (var i = list.length - 1; i >= 0; i--) {
  2289. var hoverCheckResult;
  2290. if (list[i] !== exclude
  2291. // getDisplayList may include ignored item in VML mode
  2292. && !list[i].ignore
  2293. && (hoverCheckResult = isHover(list[i], x, y))
  2294. ) {
  2295. !out.topTarget && (out.topTarget = list[i]);
  2296. if (hoverCheckResult !== SILENT) {
  2297. out.target = list[i];
  2298. break;
  2299. }
  2300. }
  2301. }
  2302. return out;
  2303. },
  2304. processGesture: function (event, stage) {
  2305. if (!this._gestureMgr) {
  2306. this._gestureMgr = new GestureMgr();
  2307. }
  2308. var gestureMgr = this._gestureMgr;
  2309. stage === 'start' && gestureMgr.clear();
  2310. var gestureInfo = gestureMgr.recognize(
  2311. event,
  2312. this.findHover(event.zrX, event.zrY, null).target,
  2313. this.proxy.dom
  2314. );
  2315. stage === 'end' && gestureMgr.clear();
  2316. // Do not do any preventDefault here. Upper application do that if necessary.
  2317. if (gestureInfo) {
  2318. var type = gestureInfo.type;
  2319. event.gestureEvent = type;
  2320. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2321. }
  2322. }
  2323. };
  2324. // Common handlers
  2325. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2326. Handler.prototype[name] = function (event) {
  2327. var x = event.zrX;
  2328. var y = event.zrY;
  2329. var isOutside = isOutsideBoundary(this, x, y);
  2330. var hovered;
  2331. var hoveredTarget;
  2332. if (name !== 'mouseup' || !isOutside) {
  2333. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2334. hovered = this.findHover(x, y);
  2335. hoveredTarget = hovered.target;
  2336. }
  2337. if (name === 'mousedown') {
  2338. this._downEl = hoveredTarget;
  2339. this._downPoint = [event.zrX, event.zrY];
  2340. // In case click triggered before mouseup
  2341. this._upEl = hoveredTarget;
  2342. }
  2343. else if (name === 'mouseup') {
  2344. this._upEl = hoveredTarget;
  2345. }
  2346. else if (name === 'click') {
  2347. if (this._downEl !== this._upEl
  2348. // Original click event is triggered on the whole canvas element,
  2349. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2350. // which should be filtered, otherwise it will bring trouble to
  2351. // pan and zoom.
  2352. || !this._downPoint
  2353. // Arbitrary value
  2354. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2355. ) {
  2356. return;
  2357. }
  2358. this._downPoint = null;
  2359. }
  2360. this.dispatchToElement(hovered, name, event);
  2361. };
  2362. });
  2363. function isHover(displayable, x, y) {
  2364. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2365. var el = displayable;
  2366. var isSilent;
  2367. while (el) {
  2368. // If clipped by ancestor.
  2369. // FIXME: If clipPath has neither stroke nor fill,
  2370. // el.clipPath.contain(x, y) will always return false.
  2371. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2372. return false;
  2373. }
  2374. if (el.silent) {
  2375. isSilent = true;
  2376. }
  2377. el = el.parent;
  2378. }
  2379. return isSilent ? SILENT : true;
  2380. }
  2381. return false;
  2382. }
  2383. /**
  2384. * See [Drag outside].
  2385. */
  2386. function isOutsideBoundary(handlerInstance, x, y) {
  2387. var painter = handlerInstance.painter;
  2388. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2389. }
  2390. mixin(Handler, Eventful);
  2391. mixin(Handler, Draggable);
  2392. /**
  2393. * 3x2矩阵操作类
  2394. * @exports zrender/tool/matrix
  2395. */
  2396. /* global Float32Array */
  2397. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2398. ? Array
  2399. : Float32Array;
  2400. /**
  2401. * Create a identity matrix.
  2402. * @return {Float32Array|Array.<number>}
  2403. */
  2404. function create$1() {
  2405. var out = new ArrayCtor$1(6);
  2406. identity(out);
  2407. return out;
  2408. }
  2409. /**
  2410. * 设置矩阵为单位矩阵
  2411. * @param {Float32Array|Array.<number>} out
  2412. */
  2413. function identity(out) {
  2414. out[0] = 1;
  2415. out[1] = 0;
  2416. out[2] = 0;
  2417. out[3] = 1;
  2418. out[4] = 0;
  2419. out[5] = 0;
  2420. return out;
  2421. }
  2422. /**
  2423. * 复制矩阵
  2424. * @param {Float32Array|Array.<number>} out
  2425. * @param {Float32Array|Array.<number>} m
  2426. */
  2427. function copy$1(out, m) {
  2428. out[0] = m[0];
  2429. out[1] = m[1];
  2430. out[2] = m[2];
  2431. out[3] = m[3];
  2432. out[4] = m[4];
  2433. out[5] = m[5];
  2434. return out;
  2435. }
  2436. /**
  2437. * 矩阵相乘
  2438. * @param {Float32Array|Array.<number>} out
  2439. * @param {Float32Array|Array.<number>} m1
  2440. * @param {Float32Array|Array.<number>} m2
  2441. */
  2442. function mul$1(out, m1, m2) {
  2443. // Consider matrix.mul(m, m2, m);
  2444. // where out is the same as m2.
  2445. // So use temp variable to escape error.
  2446. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2447. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2448. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2449. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2450. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2451. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2452. out[0] = out0;
  2453. out[1] = out1;
  2454. out[2] = out2;
  2455. out[3] = out3;
  2456. out[4] = out4;
  2457. out[5] = out5;
  2458. return out;
  2459. }
  2460. /**
  2461. * 平移变换
  2462. * @param {Float32Array|Array.<number>} out
  2463. * @param {Float32Array|Array.<number>} a
  2464. * @param {Float32Array|Array.<number>} v
  2465. */
  2466. function translate(out, a, v) {
  2467. out[0] = a[0];
  2468. out[1] = a[1];
  2469. out[2] = a[2];
  2470. out[3] = a[3];
  2471. out[4] = a[4] + v[0];
  2472. out[5] = a[5] + v[1];
  2473. return out;
  2474. }
  2475. /**
  2476. * 旋转变换
  2477. * @param {Float32Array|Array.<number>} out
  2478. * @param {Float32Array|Array.<number>} a
  2479. * @param {number} rad
  2480. */
  2481. function rotate(out, a, rad) {
  2482. var aa = a[0];
  2483. var ac = a[2];
  2484. var atx = a[4];
  2485. var ab = a[1];
  2486. var ad = a[3];
  2487. var aty = a[5];
  2488. var st = Math.sin(rad);
  2489. var ct = Math.cos(rad);
  2490. out[0] = aa * ct + ab * st;
  2491. out[1] = -aa * st + ab * ct;
  2492. out[2] = ac * ct + ad * st;
  2493. out[3] = -ac * st + ct * ad;
  2494. out[4] = ct * atx + st * aty;
  2495. out[5] = ct * aty - st * atx;
  2496. return out;
  2497. }
  2498. /**
  2499. * 缩放变换
  2500. * @param {Float32Array|Array.<number>} out
  2501. * @param {Float32Array|Array.<number>} a
  2502. * @param {Float32Array|Array.<number>} v
  2503. */
  2504. function scale$1(out, a, v) {
  2505. var vx = v[0];
  2506. var vy = v[1];
  2507. out[0] = a[0] * vx;
  2508. out[1] = a[1] * vy;
  2509. out[2] = a[2] * vx;
  2510. out[3] = a[3] * vy;
  2511. out[4] = a[4] * vx;
  2512. out[5] = a[5] * vy;
  2513. return out;
  2514. }
  2515. /**
  2516. * 求逆矩阵
  2517. * @param {Float32Array|Array.<number>} out
  2518. * @param {Float32Array|Array.<number>} a
  2519. */
  2520. function invert(out, a) {
  2521. var aa = a[0];
  2522. var ac = a[2];
  2523. var atx = a[4];
  2524. var ab = a[1];
  2525. var ad = a[3];
  2526. var aty = a[5];
  2527. var det = aa * ad - ab * ac;
  2528. if (!det) {
  2529. return null;
  2530. }
  2531. det = 1.0 / det;
  2532. out[0] = ad * det;
  2533. out[1] = -ab * det;
  2534. out[2] = -ac * det;
  2535. out[3] = aa * det;
  2536. out[4] = (ac * aty - ad * atx) * det;
  2537. out[5] = (ab * atx - aa * aty) * det;
  2538. return out;
  2539. }
  2540. /**
  2541. * Clone a new matrix.
  2542. * @param {Float32Array|Array.<number>} a
  2543. */
  2544. function clone$2(a) {
  2545. var b = create$1();
  2546. copy$1(b, a);
  2547. return b;
  2548. }
  2549. var matrix = (Object.freeze || Object)({
  2550. create: create$1,
  2551. identity: identity,
  2552. copy: copy$1,
  2553. mul: mul$1,
  2554. translate: translate,
  2555. rotate: rotate,
  2556. scale: scale$1,
  2557. invert: invert,
  2558. clone: clone$2
  2559. });
  2560. /**
  2561. * 提供变换扩展
  2562. * @module zrender/mixin/Transformable
  2563. * @author pissang (https://www.github.com/pissang)
  2564. */
  2565. var mIdentity = identity;
  2566. var EPSILON = 5e-5;
  2567. function isNotAroundZero(val) {
  2568. return val > EPSILON || val < -EPSILON;
  2569. }
  2570. /**
  2571. * @alias module:zrender/mixin/Transformable
  2572. * @constructor
  2573. */
  2574. var Transformable = function (opts) {
  2575. opts = opts || {};
  2576. // If there are no given position, rotation, scale
  2577. if (!opts.position) {
  2578. /**
  2579. * 平移
  2580. * @type {Array.<number>}
  2581. * @default [0, 0]
  2582. */
  2583. this.position = [0, 0];
  2584. }
  2585. if (opts.rotation == null) {
  2586. /**
  2587. * 旋转
  2588. * @type {Array.<number>}
  2589. * @default 0
  2590. */
  2591. this.rotation = 0;
  2592. }
  2593. if (!opts.scale) {
  2594. /**
  2595. * 缩放
  2596. * @type {Array.<number>}
  2597. * @default [1, 1]
  2598. */
  2599. this.scale = [1, 1];
  2600. }
  2601. /**
  2602. * 旋转和缩放的原点
  2603. * @type {Array.<number>}
  2604. * @default null
  2605. */
  2606. this.origin = this.origin || null;
  2607. };
  2608. var transformableProto = Transformable.prototype;
  2609. transformableProto.transform = null;
  2610. /**
  2611. * 判断是否需要有坐标变换
  2612. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2613. */
  2614. transformableProto.needLocalTransform = function () {
  2615. return isNotAroundZero(this.rotation)
  2616. || isNotAroundZero(this.position[0])
  2617. || isNotAroundZero(this.position[1])
  2618. || isNotAroundZero(this.scale[0] - 1)
  2619. || isNotAroundZero(this.scale[1] - 1);
  2620. };
  2621. var scaleTmp = [];
  2622. transformableProto.updateTransform = function () {
  2623. var parent = this.parent;
  2624. var parentHasTransform = parent && parent.transform;
  2625. var needLocalTransform = this.needLocalTransform();
  2626. var m = this.transform;
  2627. if (!(needLocalTransform || parentHasTransform)) {
  2628. m && mIdentity(m);
  2629. return;
  2630. }
  2631. m = m || create$1();
  2632. if (needLocalTransform) {
  2633. this.getLocalTransform(m);
  2634. }
  2635. else {
  2636. mIdentity(m);
  2637. }
  2638. // 应用父节点变换
  2639. if (parentHasTransform) {
  2640. if (needLocalTransform) {
  2641. mul$1(m, parent.transform, m);
  2642. }
  2643. else {
  2644. copy$1(m, parent.transform);
  2645. }
  2646. }
  2647. // 保存这个变换矩阵
  2648. this.transform = m;
  2649. var globalScaleRatio = this.globalScaleRatio;
  2650. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2651. this.getGlobalScale(scaleTmp);
  2652. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2653. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2654. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2655. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2656. m[0] *= sx;
  2657. m[1] *= sx;
  2658. m[2] *= sy;
  2659. m[3] *= sy;
  2660. }
  2661. this.invTransform = this.invTransform || create$1();
  2662. invert(this.invTransform, m);
  2663. };
  2664. transformableProto.getLocalTransform = function (m) {
  2665. return Transformable.getLocalTransform(this, m);
  2666. };
  2667. /**
  2668. * 将自己的transform应用到context上
  2669. * @param {CanvasRenderingContext2D} ctx
  2670. */
  2671. transformableProto.setTransform = function (ctx) {
  2672. var m = this.transform;
  2673. var dpr = ctx.dpr || 1;
  2674. if (m) {
  2675. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2676. }
  2677. else {
  2678. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2679. }
  2680. };
  2681. transformableProto.restoreTransform = function (ctx) {
  2682. var dpr = ctx.dpr || 1;
  2683. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2684. };
  2685. var tmpTransform = [];
  2686. var originTransform = create$1();
  2687. transformableProto.setLocalTransform = function (m) {
  2688. if (!m) {
  2689. // TODO return or set identity?
  2690. return;
  2691. }
  2692. var sx = m[0] * m[0] + m[1] * m[1];
  2693. var sy = m[2] * m[2] + m[3] * m[3];
  2694. var position = this.position;
  2695. var scale$$1 = this.scale;
  2696. if (isNotAroundZero(sx - 1)) {
  2697. sx = Math.sqrt(sx);
  2698. }
  2699. if (isNotAroundZero(sy - 1)) {
  2700. sy = Math.sqrt(sy);
  2701. }
  2702. if (m[0] < 0) {
  2703. sx = -sx;
  2704. }
  2705. if (m[3] < 0) {
  2706. sy = -sy;
  2707. }
  2708. position[0] = m[4];
  2709. position[1] = m[5];
  2710. scale$$1[0] = sx;
  2711. scale$$1[1] = sy;
  2712. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2713. };
  2714. /**
  2715. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2716. */
  2717. transformableProto.decomposeTransform = function () {
  2718. if (!this.transform) {
  2719. return;
  2720. }
  2721. var parent = this.parent;
  2722. var m = this.transform;
  2723. if (parent && parent.transform) {
  2724. // Get local transform and decompose them to position, scale, rotation
  2725. mul$1(tmpTransform, parent.invTransform, m);
  2726. m = tmpTransform;
  2727. }
  2728. var origin = this.origin;
  2729. if (origin && (origin[0] || origin[1])) {
  2730. originTransform[4] = origin[0];
  2731. originTransform[5] = origin[1];
  2732. mul$1(tmpTransform, m, originTransform);
  2733. tmpTransform[4] -= origin[0];
  2734. tmpTransform[5] -= origin[1];
  2735. m = tmpTransform;
  2736. }
  2737. this.setLocalTransform(m);
  2738. };
  2739. /**
  2740. * Get global scale
  2741. * @return {Array.<number>}
  2742. */
  2743. transformableProto.getGlobalScale = function (out) {
  2744. var m = this.transform;
  2745. out = out || [];
  2746. if (!m) {
  2747. out[0] = 1;
  2748. out[1] = 1;
  2749. return out;
  2750. }
  2751. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2752. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2753. if (m[0] < 0) {
  2754. out[0] = -out[0];
  2755. }
  2756. if (m[3] < 0) {
  2757. out[1] = -out[1];
  2758. }
  2759. return out;
  2760. };
  2761. /**
  2762. * 变换坐标位置到 shape 的局部坐标空间
  2763. * @method
  2764. * @param {number} x
  2765. * @param {number} y
  2766. * @return {Array.<number>}
  2767. */
  2768. transformableProto.transformCoordToLocal = function (x, y) {
  2769. var v2 = [x, y];
  2770. var invTransform = this.invTransform;
  2771. if (invTransform) {
  2772. applyTransform(v2, v2, invTransform);
  2773. }
  2774. return v2;
  2775. };
  2776. /**
  2777. * 变换局部坐标位置到全局坐标空间
  2778. * @method
  2779. * @param {number} x
  2780. * @param {number} y
  2781. * @return {Array.<number>}
  2782. */
  2783. transformableProto.transformCoordToGlobal = function (x, y) {
  2784. var v2 = [x, y];
  2785. var transform = this.transform;
  2786. if (transform) {
  2787. applyTransform(v2, v2, transform);
  2788. }
  2789. return v2;
  2790. };
  2791. /**
  2792. * @static
  2793. * @param {Object} target
  2794. * @param {Array.<number>} target.origin
  2795. * @param {number} target.rotation
  2796. * @param {Array.<number>} target.position
  2797. * @param {Array.<number>} [m]
  2798. */
  2799. Transformable.getLocalTransform = function (target, m) {
  2800. m = m || [];
  2801. mIdentity(m);
  2802. var origin = target.origin;
  2803. var scale$$1 = target.scale || [1, 1];
  2804. var rotation = target.rotation || 0;
  2805. var position = target.position || [0, 0];
  2806. if (origin) {
  2807. // Translate to origin
  2808. m[4] -= origin[0];
  2809. m[5] -= origin[1];
  2810. }
  2811. scale$1(m, m, scale$$1);
  2812. if (rotation) {
  2813. rotate(m, m, rotation);
  2814. }
  2815. if (origin) {
  2816. // Translate back from origin
  2817. m[4] += origin[0];
  2818. m[5] += origin[1];
  2819. }
  2820. m[4] += position[0];
  2821. m[5] += position[1];
  2822. return m;
  2823. };
  2824. /**
  2825. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2826. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2827. * @exports zrender/animation/easing
  2828. */
  2829. var easing = {
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. linear: function (k) {
  2835. return k;
  2836. },
  2837. /**
  2838. * @param {number} k
  2839. * @return {number}
  2840. */
  2841. quadraticIn: function (k) {
  2842. return k * k;
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. quadraticOut: function (k) {
  2849. return k * (2 - k);
  2850. },
  2851. /**
  2852. * @param {number} k
  2853. * @return {number}
  2854. */
  2855. quadraticInOut: function (k) {
  2856. if ((k *= 2) < 1) {
  2857. return 0.5 * k * k;
  2858. }
  2859. return -0.5 * (--k * (k - 2) - 1);
  2860. },
  2861. // 三次方的缓动(t^3)
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. cubicIn: function (k) {
  2867. return k * k * k;
  2868. },
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. cubicOut: function (k) {
  2874. return --k * k * k + 1;
  2875. },
  2876. /**
  2877. * @param {number} k
  2878. * @return {number}
  2879. */
  2880. cubicInOut: function (k) {
  2881. if ((k *= 2) < 1) {
  2882. return 0.5 * k * k * k;
  2883. }
  2884. return 0.5 * ((k -= 2) * k * k + 2);
  2885. },
  2886. // 四次方的缓动(t^4)
  2887. /**
  2888. * @param {number} k
  2889. * @return {number}
  2890. */
  2891. quarticIn: function (k) {
  2892. return k * k * k * k;
  2893. },
  2894. /**
  2895. * @param {number} k
  2896. * @return {number}
  2897. */
  2898. quarticOut: function (k) {
  2899. return 1 - (--k * k * k * k);
  2900. },
  2901. /**
  2902. * @param {number} k
  2903. * @return {number}
  2904. */
  2905. quarticInOut: function (k) {
  2906. if ((k *= 2) < 1) {
  2907. return 0.5 * k * k * k * k;
  2908. }
  2909. return -0.5 * ((k -= 2) * k * k * k - 2);
  2910. },
  2911. // 五次方的缓动(t^5)
  2912. /**
  2913. * @param {number} k
  2914. * @return {number}
  2915. */
  2916. quinticIn: function (k) {
  2917. return k * k * k * k * k;
  2918. },
  2919. /**
  2920. * @param {number} k
  2921. * @return {number}
  2922. */
  2923. quinticOut: function (k) {
  2924. return --k * k * k * k * k + 1;
  2925. },
  2926. /**
  2927. * @param {number} k
  2928. * @return {number}
  2929. */
  2930. quinticInOut: function (k) {
  2931. if ((k *= 2) < 1) {
  2932. return 0.5 * k * k * k * k * k;
  2933. }
  2934. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2935. },
  2936. // 正弦曲线的缓动(sin(t))
  2937. /**
  2938. * @param {number} k
  2939. * @return {number}
  2940. */
  2941. sinusoidalIn: function (k) {
  2942. return 1 - Math.cos(k * Math.PI / 2);
  2943. },
  2944. /**
  2945. * @param {number} k
  2946. * @return {number}
  2947. */
  2948. sinusoidalOut: function (k) {
  2949. return Math.sin(k * Math.PI / 2);
  2950. },
  2951. /**
  2952. * @param {number} k
  2953. * @return {number}
  2954. */
  2955. sinusoidalInOut: function (k) {
  2956. return 0.5 * (1 - Math.cos(Math.PI * k));
  2957. },
  2958. // 指数曲线的缓动(2^t)
  2959. /**
  2960. * @param {number} k
  2961. * @return {number}
  2962. */
  2963. exponentialIn: function (k) {
  2964. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2965. },
  2966. /**
  2967. * @param {number} k
  2968. * @return {number}
  2969. */
  2970. exponentialOut: function (k) {
  2971. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2972. },
  2973. /**
  2974. * @param {number} k
  2975. * @return {number}
  2976. */
  2977. exponentialInOut: function (k) {
  2978. if (k === 0) {
  2979. return 0;
  2980. }
  2981. if (k === 1) {
  2982. return 1;
  2983. }
  2984. if ((k *= 2) < 1) {
  2985. return 0.5 * Math.pow(1024, k - 1);
  2986. }
  2987. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2988. },
  2989. // 圆形曲线的缓动(sqrt(1-t^2))
  2990. /**
  2991. * @param {number} k
  2992. * @return {number}
  2993. */
  2994. circularIn: function (k) {
  2995. return 1 - Math.sqrt(1 - k * k);
  2996. },
  2997. /**
  2998. * @param {number} k
  2999. * @return {number}
  3000. */
  3001. circularOut: function (k) {
  3002. return Math.sqrt(1 - (--k * k));
  3003. },
  3004. /**
  3005. * @param {number} k
  3006. * @return {number}
  3007. */
  3008. circularInOut: function (k) {
  3009. if ((k *= 2) < 1) {
  3010. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3011. }
  3012. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3013. },
  3014. // 创建类似于弹簧在停止前来回振荡的动画
  3015. /**
  3016. * @param {number} k
  3017. * @return {number}
  3018. */
  3019. elasticIn: function (k) {
  3020. var s;
  3021. var a = 0.1;
  3022. var p = 0.4;
  3023. if (k === 0) {
  3024. return 0;
  3025. }
  3026. if (k === 1) {
  3027. return 1;
  3028. }
  3029. if (!a || a < 1) {
  3030. a = 1;
  3031. s = p / 4;
  3032. }
  3033. else {
  3034. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3035. }
  3036. return -(a * Math.pow(2, 10 * (k -= 1))
  3037. * Math.sin((k - s) * (2 * Math.PI) / p));
  3038. },
  3039. /**
  3040. * @param {number} k
  3041. * @return {number}
  3042. */
  3043. elasticOut: function (k) {
  3044. var s;
  3045. var a = 0.1;
  3046. var p = 0.4;
  3047. if (k === 0) {
  3048. return 0;
  3049. }
  3050. if (k === 1) {
  3051. return 1;
  3052. }
  3053. if (!a || a < 1) {
  3054. a = 1;
  3055. s = p / 4;
  3056. }
  3057. else {
  3058. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3059. }
  3060. return (a * Math.pow(2, -10 * k)
  3061. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3062. },
  3063. /**
  3064. * @param {number} k
  3065. * @return {number}
  3066. */
  3067. elasticInOut: function (k) {
  3068. var s;
  3069. var a = 0.1;
  3070. var p = 0.4;
  3071. if (k === 0) {
  3072. return 0;
  3073. }
  3074. if (k === 1) {
  3075. return 1;
  3076. }
  3077. if (!a || a < 1) {
  3078. a = 1;
  3079. s = p / 4;
  3080. }
  3081. else {
  3082. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3083. }
  3084. if ((k *= 2) < 1) {
  3085. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3086. * Math.sin((k - s) * (2 * Math.PI) / p));
  3087. }
  3088. return a * Math.pow(2, -10 * (k -= 1))
  3089. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3090. },
  3091. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  3092. /**
  3093. * @param {number} k
  3094. * @return {number}
  3095. */
  3096. backIn: function (k) {
  3097. var s = 1.70158;
  3098. return k * k * ((s + 1) * k - s);
  3099. },
  3100. /**
  3101. * @param {number} k
  3102. * @return {number}
  3103. */
  3104. backOut: function (k) {
  3105. var s = 1.70158;
  3106. return --k * k * ((s + 1) * k + s) + 1;
  3107. },
  3108. /**
  3109. * @param {number} k
  3110. * @return {number}
  3111. */
  3112. backInOut: function (k) {
  3113. var s = 1.70158 * 1.525;
  3114. if ((k *= 2) < 1) {
  3115. return 0.5 * (k * k * ((s + 1) * k - s));
  3116. }
  3117. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3118. },
  3119. // 创建弹跳效果
  3120. /**
  3121. * @param {number} k
  3122. * @return {number}
  3123. */
  3124. bounceIn: function (k) {
  3125. return 1 - easing.bounceOut(1 - k);
  3126. },
  3127. /**
  3128. * @param {number} k
  3129. * @return {number}
  3130. */
  3131. bounceOut: function (k) {
  3132. if (k < (1 / 2.75)) {
  3133. return 7.5625 * k * k;
  3134. }
  3135. else if (k < (2 / 2.75)) {
  3136. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3137. }
  3138. else if (k < (2.5 / 2.75)) {
  3139. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3140. }
  3141. else {
  3142. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3143. }
  3144. },
  3145. /**
  3146. * @param {number} k
  3147. * @return {number}
  3148. */
  3149. bounceInOut: function (k) {
  3150. if (k < 0.5) {
  3151. return easing.bounceIn(k * 2) * 0.5;
  3152. }
  3153. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3154. }
  3155. };
  3156. /**
  3157. * 动画主控制器
  3158. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3159. * @config life(1000) 动画时长
  3160. * @config delay(0) 动画延迟时间
  3161. * @config loop(true)
  3162. * @config gap(0) 循环的间隔时间
  3163. * @config onframe
  3164. * @config easing(optional)
  3165. * @config ondestroy(optional)
  3166. * @config onrestart(optional)
  3167. *
  3168. * TODO pause
  3169. */
  3170. function Clip(options) {
  3171. this._target = options.target;
  3172. // 生命周期
  3173. this._life = options.life || 1000;
  3174. // 延时
  3175. this._delay = options.delay || 0;
  3176. // 开始时间
  3177. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3178. this._initialized = false;
  3179. // 是否循环
  3180. this.loop = options.loop == null ? false : options.loop;
  3181. this.gap = options.gap || 0;
  3182. this.easing = options.easing || 'Linear';
  3183. this.onframe = options.onframe;
  3184. this.ondestroy = options.ondestroy;
  3185. this.onrestart = options.onrestart;
  3186. this._pausedTime = 0;
  3187. this._paused = false;
  3188. }
  3189. Clip.prototype = {
  3190. constructor: Clip,
  3191. step: function (globalTime, deltaTime) {
  3192. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3193. // PENDING
  3194. if (!this._initialized) {
  3195. this._startTime = globalTime + this._delay;
  3196. this._initialized = true;
  3197. }
  3198. if (this._paused) {
  3199. this._pausedTime += deltaTime;
  3200. return;
  3201. }
  3202. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3203. // 还没开始
  3204. if (percent < 0) {
  3205. return;
  3206. }
  3207. percent = Math.min(percent, 1);
  3208. var easing$$1 = this.easing;
  3209. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3210. var schedule = typeof easingFunc === 'function'
  3211. ? easingFunc(percent)
  3212. : percent;
  3213. this.fire('frame', schedule);
  3214. // 结束
  3215. if (percent === 1) {
  3216. if (this.loop) {
  3217. this.restart(globalTime);
  3218. // 重新开始周期
  3219. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3220. return 'restart';
  3221. }
  3222. // 动画完成将这个控制器标识为待删除
  3223. // 在Animation.update中进行批量删除
  3224. this._needsRemove = true;
  3225. return 'destroy';
  3226. }
  3227. return null;
  3228. },
  3229. restart: function (globalTime) {
  3230. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3231. this._startTime = globalTime - remainder + this.gap;
  3232. this._pausedTime = 0;
  3233. this._needsRemove = false;
  3234. },
  3235. fire: function (eventType, arg) {
  3236. eventType = 'on' + eventType;
  3237. if (this[eventType]) {
  3238. this[eventType](this._target, arg);
  3239. }
  3240. },
  3241. pause: function () {
  3242. this._paused = true;
  3243. },
  3244. resume: function () {
  3245. this._paused = false;
  3246. }
  3247. };
  3248. // Simple LRU cache use doubly linked list
  3249. // @module zrender/core/LRU
  3250. /**
  3251. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3252. * @constructor
  3253. */
  3254. var LinkedList = function () {
  3255. /**
  3256. * @type {module:zrender/core/LRU~Entry}
  3257. */
  3258. this.head = null;
  3259. /**
  3260. * @type {module:zrender/core/LRU~Entry}
  3261. */
  3262. this.tail = null;
  3263. this._len = 0;
  3264. };
  3265. var linkedListProto = LinkedList.prototype;
  3266. /**
  3267. * Insert a new value at the tail
  3268. * @param {} val
  3269. * @return {module:zrender/core/LRU~Entry}
  3270. */
  3271. linkedListProto.insert = function (val) {
  3272. var entry = new Entry(val);
  3273. this.insertEntry(entry);
  3274. return entry;
  3275. };
  3276. /**
  3277. * Insert an entry at the tail
  3278. * @param {module:zrender/core/LRU~Entry} entry
  3279. */
  3280. linkedListProto.insertEntry = function (entry) {
  3281. if (!this.head) {
  3282. this.head = this.tail = entry;
  3283. }
  3284. else {
  3285. this.tail.next = entry;
  3286. entry.prev = this.tail;
  3287. entry.next = null;
  3288. this.tail = entry;
  3289. }
  3290. this._len++;
  3291. };
  3292. /**
  3293. * Remove entry.
  3294. * @param {module:zrender/core/LRU~Entry} entry
  3295. */
  3296. linkedListProto.remove = function (entry) {
  3297. var prev = entry.prev;
  3298. var next = entry.next;
  3299. if (prev) {
  3300. prev.next = next;
  3301. }
  3302. else {
  3303. // Is head
  3304. this.head = next;
  3305. }
  3306. if (next) {
  3307. next.prev = prev;
  3308. }
  3309. else {
  3310. // Is tail
  3311. this.tail = prev;
  3312. }
  3313. entry.next = entry.prev = null;
  3314. this._len--;
  3315. };
  3316. /**
  3317. * @return {number}
  3318. */
  3319. linkedListProto.len = function () {
  3320. return this._len;
  3321. };
  3322. /**
  3323. * Clear list
  3324. */
  3325. linkedListProto.clear = function () {
  3326. this.head = this.tail = null;
  3327. this._len = 0;
  3328. };
  3329. /**
  3330. * @constructor
  3331. * @param {} val
  3332. */
  3333. var Entry = function (val) {
  3334. /**
  3335. * @type {}
  3336. */
  3337. this.value = val;
  3338. /**
  3339. * @type {module:zrender/core/LRU~Entry}
  3340. */
  3341. this.next;
  3342. /**
  3343. * @type {module:zrender/core/LRU~Entry}
  3344. */
  3345. this.prev;
  3346. };
  3347. /**
  3348. * LRU Cache
  3349. * @constructor
  3350. * @alias module:zrender/core/LRU
  3351. */
  3352. var LRU = function (maxSize) {
  3353. this._list = new LinkedList();
  3354. this._map = {};
  3355. this._maxSize = maxSize || 10;
  3356. this._lastRemovedEntry = null;
  3357. };
  3358. var LRUProto = LRU.prototype;
  3359. /**
  3360. * @param {string} key
  3361. * @param {} value
  3362. * @return {} Removed value
  3363. */
  3364. LRUProto.put = function (key, value) {
  3365. var list = this._list;
  3366. var map = this._map;
  3367. var removed = null;
  3368. if (map[key] == null) {
  3369. var len = list.len();
  3370. // Reuse last removed entry
  3371. var entry = this._lastRemovedEntry;
  3372. if (len >= this._maxSize && len > 0) {
  3373. // Remove the least recently used
  3374. var leastUsedEntry = list.head;
  3375. list.remove(leastUsedEntry);
  3376. delete map[leastUsedEntry.key];
  3377. removed = leastUsedEntry.value;
  3378. this._lastRemovedEntry = leastUsedEntry;
  3379. }
  3380. if (entry) {
  3381. entry.value = value;
  3382. }
  3383. else {
  3384. entry = new Entry(value);
  3385. }
  3386. entry.key = key;
  3387. list.insertEntry(entry);
  3388. map[key] = entry;
  3389. }
  3390. return removed;
  3391. };
  3392. /**
  3393. * @param {string} key
  3394. * @return {}
  3395. */
  3396. LRUProto.get = function (key) {
  3397. var entry = this._map[key];
  3398. var list = this._list;
  3399. if (entry != null) {
  3400. // Put the latest used entry in the tail
  3401. if (entry !== list.tail) {
  3402. list.remove(entry);
  3403. list.insertEntry(entry);
  3404. }
  3405. return entry.value;
  3406. }
  3407. };
  3408. /**
  3409. * Clear the cache
  3410. */
  3411. LRUProto.clear = function () {
  3412. this._list.clear();
  3413. this._map = {};
  3414. };
  3415. var kCSSColorTable = {
  3416. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3417. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3418. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3419. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3420. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3421. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3422. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3423. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3424. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3425. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3426. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3427. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3428. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3429. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3430. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3431. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3432. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3433. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3434. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3435. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3436. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3437. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3438. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3439. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3440. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3441. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3442. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3443. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3444. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3445. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3446. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3447. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3448. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3449. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3450. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3451. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3452. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3453. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3454. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3455. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3456. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3457. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3458. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3459. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3460. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3461. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3462. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3463. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3464. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3465. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3466. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3467. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3468. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3469. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3470. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3471. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3472. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3473. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3474. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3475. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3476. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3477. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3478. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3479. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3480. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3481. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3482. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3483. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3484. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3485. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3486. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3487. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3488. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3489. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3490. };
  3491. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3492. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3493. return i < 0 ? 0 : i > 255 ? 255 : i;
  3494. }
  3495. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3496. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3497. return i < 0 ? 0 : i > 360 ? 360 : i;
  3498. }
  3499. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3500. return f < 0 ? 0 : f > 1 ? 1 : f;
  3501. }
  3502. function parseCssInt(str) { // int or percentage.
  3503. if (str.length && str.charAt(str.length - 1) === '%') {
  3504. return clampCssByte(parseFloat(str) / 100 * 255);
  3505. }
  3506. return clampCssByte(parseInt(str, 10));
  3507. }
  3508. function parseCssFloat(str) { // float or percentage.
  3509. if (str.length && str.charAt(str.length - 1) === '%') {
  3510. return clampCssFloat(parseFloat(str) / 100);
  3511. }
  3512. return clampCssFloat(parseFloat(str));
  3513. }
  3514. function cssHueToRgb(m1, m2, h) {
  3515. if (h < 0) {
  3516. h += 1;
  3517. }
  3518. else if (h > 1) {
  3519. h -= 1;
  3520. }
  3521. if (h * 6 < 1) {
  3522. return m1 + (m2 - m1) * h * 6;
  3523. }
  3524. if (h * 2 < 1) {
  3525. return m2;
  3526. }
  3527. if (h * 3 < 2) {
  3528. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3529. }
  3530. return m1;
  3531. }
  3532. function lerpNumber(a, b, p) {
  3533. return a + (b - a) * p;
  3534. }
  3535. function setRgba(out, r, g, b, a) {
  3536. out[0] = r;
  3537. out[1] = g;
  3538. out[2] = b;
  3539. out[3] = a;
  3540. return out;
  3541. }
  3542. function copyRgba(out, a) {
  3543. out[0] = a[0];
  3544. out[1] = a[1];
  3545. out[2] = a[2];
  3546. out[3] = a[3];
  3547. return out;
  3548. }
  3549. var colorCache = new LRU(20);
  3550. var lastRemovedArr = null;
  3551. function putToCache(colorStr, rgbaArr) {
  3552. // Reuse removed array
  3553. if (lastRemovedArr) {
  3554. copyRgba(lastRemovedArr, rgbaArr);
  3555. }
  3556. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3557. }
  3558. /**
  3559. * @param {string} colorStr
  3560. * @param {Array.<number>} out
  3561. * @return {Array.<number>}
  3562. * @memberOf module:zrender/util/color
  3563. */
  3564. function parse(colorStr, rgbaArr) {
  3565. if (!colorStr) {
  3566. return;
  3567. }
  3568. rgbaArr = rgbaArr || [];
  3569. var cached = colorCache.get(colorStr);
  3570. if (cached) {
  3571. return copyRgba(rgbaArr, cached);
  3572. }
  3573. // colorStr may be not string
  3574. colorStr = colorStr + '';
  3575. // Remove all whitespace, not compliant, but should just be more accepting.
  3576. var str = colorStr.replace(/ /g, '').toLowerCase();
  3577. // Color keywords (and transparent) lookup.
  3578. if (str in kCSSColorTable) {
  3579. copyRgba(rgbaArr, kCSSColorTable[str]);
  3580. putToCache(colorStr, rgbaArr);
  3581. return rgbaArr;
  3582. }
  3583. // #abc and #abc123 syntax.
  3584. if (str.charAt(0) === '#') {
  3585. if (str.length === 4) {
  3586. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3587. if (!(iv >= 0 && iv <= 0xfff)) {
  3588. setRgba(rgbaArr, 0, 0, 0, 1);
  3589. return; // Covers NaN.
  3590. }
  3591. setRgba(rgbaArr,
  3592. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3593. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3594. (iv & 0xf) | ((iv & 0xf) << 4),
  3595. 1
  3596. );
  3597. putToCache(colorStr, rgbaArr);
  3598. return rgbaArr;
  3599. }
  3600. else if (str.length === 7) {
  3601. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3602. if (!(iv >= 0 && iv <= 0xffffff)) {
  3603. setRgba(rgbaArr, 0, 0, 0, 1);
  3604. return; // Covers NaN.
  3605. }
  3606. setRgba(rgbaArr,
  3607. (iv & 0xff0000) >> 16,
  3608. (iv & 0xff00) >> 8,
  3609. iv & 0xff,
  3610. 1
  3611. );
  3612. putToCache(colorStr, rgbaArr);
  3613. return rgbaArr;
  3614. }
  3615. return;
  3616. }
  3617. var op = str.indexOf('(');
  3618. var ep = str.indexOf(')');
  3619. if (op !== -1 && ep + 1 === str.length) {
  3620. var fname = str.substr(0, op);
  3621. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3622. var alpha = 1; // To allow case fallthrough.
  3623. switch (fname) {
  3624. case 'rgba':
  3625. if (params.length !== 4) {
  3626. setRgba(rgbaArr, 0, 0, 0, 1);
  3627. return;
  3628. }
  3629. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3630. // Fall through.
  3631. case 'rgb':
  3632. if (params.length !== 3) {
  3633. setRgba(rgbaArr, 0, 0, 0, 1);
  3634. return;
  3635. }
  3636. setRgba(rgbaArr,
  3637. parseCssInt(params[0]),
  3638. parseCssInt(params[1]),
  3639. parseCssInt(params[2]),
  3640. alpha
  3641. );
  3642. putToCache(colorStr, rgbaArr);
  3643. return rgbaArr;
  3644. case 'hsla':
  3645. if (params.length !== 4) {
  3646. setRgba(rgbaArr, 0, 0, 0, 1);
  3647. return;
  3648. }
  3649. params[3] = parseCssFloat(params[3]);
  3650. hsla2rgba(params, rgbaArr);
  3651. putToCache(colorStr, rgbaArr);
  3652. return rgbaArr;
  3653. case 'hsl':
  3654. if (params.length !== 3) {
  3655. setRgba(rgbaArr, 0, 0, 0, 1);
  3656. return;
  3657. }
  3658. hsla2rgba(params, rgbaArr);
  3659. putToCache(colorStr, rgbaArr);
  3660. return rgbaArr;
  3661. default:
  3662. return;
  3663. }
  3664. }
  3665. setRgba(rgbaArr, 0, 0, 0, 1);
  3666. return;
  3667. }
  3668. /**
  3669. * @param {Array.<number>} hsla
  3670. * @param {Array.<number>} rgba
  3671. * @return {Array.<number>} rgba
  3672. */
  3673. function hsla2rgba(hsla, rgba) {
  3674. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3675. // NOTE(deanm): According to the CSS spec s/l should only be
  3676. // percentages, but we don't bother and let float or percentage.
  3677. var s = parseCssFloat(hsla[1]);
  3678. var l = parseCssFloat(hsla[2]);
  3679. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3680. var m1 = l * 2 - m2;
  3681. rgba = rgba || [];
  3682. setRgba(rgba,
  3683. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3684. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3685. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3686. 1
  3687. );
  3688. if (hsla.length === 4) {
  3689. rgba[3] = hsla[3];
  3690. }
  3691. return rgba;
  3692. }
  3693. /**
  3694. * @param {Array.<number>} rgba
  3695. * @return {Array.<number>} hsla
  3696. */
  3697. function rgba2hsla(rgba) {
  3698. if (!rgba) {
  3699. return;
  3700. }
  3701. // RGB from 0 to 255
  3702. var R = rgba[0] / 255;
  3703. var G = rgba[1] / 255;
  3704. var B = rgba[2] / 255;
  3705. var vMin = Math.min(R, G, B); // Min. value of RGB
  3706. var vMax = Math.max(R, G, B); // Max. value of RGB
  3707. var delta = vMax - vMin; // Delta RGB value
  3708. var L = (vMax + vMin) / 2;
  3709. var H;
  3710. var S;
  3711. // HSL results from 0 to 1
  3712. if (delta === 0) {
  3713. H = 0;
  3714. S = 0;
  3715. }
  3716. else {
  3717. if (L < 0.5) {
  3718. S = delta / (vMax + vMin);
  3719. }
  3720. else {
  3721. S = delta / (2 - vMax - vMin);
  3722. }
  3723. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3724. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3725. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3726. if (R === vMax) {
  3727. H = deltaB - deltaG;
  3728. }
  3729. else if (G === vMax) {
  3730. H = (1 / 3) + deltaR - deltaB;
  3731. }
  3732. else if (B === vMax) {
  3733. H = (2 / 3) + deltaG - deltaR;
  3734. }
  3735. if (H < 0) {
  3736. H += 1;
  3737. }
  3738. if (H > 1) {
  3739. H -= 1;
  3740. }
  3741. }
  3742. var hsla = [H * 360, S, L];
  3743. if (rgba[3] != null) {
  3744. hsla.push(rgba[3]);
  3745. }
  3746. return hsla;
  3747. }
  3748. /**
  3749. * @param {string} color
  3750. * @param {number} level
  3751. * @return {string}
  3752. * @memberOf module:zrender/util/color
  3753. */
  3754. function lift(color, level) {
  3755. var colorArr = parse(color);
  3756. if (colorArr) {
  3757. for (var i = 0; i < 3; i++) {
  3758. if (level < 0) {
  3759. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3760. }
  3761. else {
  3762. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3763. }
  3764. if (colorArr[i] > 255) {
  3765. colorArr[i] = 255;
  3766. }
  3767. else if (color[i] < 0) {
  3768. colorArr[i] = 0;
  3769. }
  3770. }
  3771. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3772. }
  3773. }
  3774. /**
  3775. * @param {string} color
  3776. * @return {string}
  3777. * @memberOf module:zrender/util/color
  3778. */
  3779. function toHex(color) {
  3780. var colorArr = parse(color);
  3781. if (colorArr) {
  3782. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3783. }
  3784. }
  3785. /**
  3786. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3787. * @param {number} normalizedValue A float between 0 and 1.
  3788. * @param {Array.<Array.<number>>} colors List of rgba color array
  3789. * @param {Array.<number>} [out] Mapped gba color array
  3790. * @return {Array.<number>} will be null/undefined if input illegal.
  3791. */
  3792. function fastLerp(normalizedValue, colors, out) {
  3793. if (!(colors && colors.length)
  3794. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3795. ) {
  3796. return;
  3797. }
  3798. out = out || [];
  3799. var value = normalizedValue * (colors.length - 1);
  3800. var leftIndex = Math.floor(value);
  3801. var rightIndex = Math.ceil(value);
  3802. var leftColor = colors[leftIndex];
  3803. var rightColor = colors[rightIndex];
  3804. var dv = value - leftIndex;
  3805. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3806. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3807. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3808. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3809. return out;
  3810. }
  3811. /**
  3812. * @deprecated
  3813. */
  3814. var fastMapToColor = fastLerp;
  3815. /**
  3816. * @param {number} normalizedValue A float between 0 and 1.
  3817. * @param {Array.<string>} colors Color list.
  3818. * @param {boolean=} fullOutput Default false.
  3819. * @return {(string|Object)} Result color. If fullOutput,
  3820. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3821. * @memberOf module:zrender/util/color
  3822. */
  3823. function lerp$1(normalizedValue, colors, fullOutput) {
  3824. if (!(colors && colors.length)
  3825. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3826. ) {
  3827. return;
  3828. }
  3829. var value = normalizedValue * (colors.length - 1);
  3830. var leftIndex = Math.floor(value);
  3831. var rightIndex = Math.ceil(value);
  3832. var leftColor = parse(colors[leftIndex]);
  3833. var rightColor = parse(colors[rightIndex]);
  3834. var dv = value - leftIndex;
  3835. var color = stringify(
  3836. [
  3837. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3838. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3839. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3840. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3841. ],
  3842. 'rgba'
  3843. );
  3844. return fullOutput
  3845. ? {
  3846. color: color,
  3847. leftIndex: leftIndex,
  3848. rightIndex: rightIndex,
  3849. value: value
  3850. }
  3851. : color;
  3852. }
  3853. /**
  3854. * @deprecated
  3855. */
  3856. var mapToColor = lerp$1;
  3857. /**
  3858. * @param {string} color
  3859. * @param {number=} h 0 ~ 360, ignore when null.
  3860. * @param {number=} s 0 ~ 1, ignore when null.
  3861. * @param {number=} l 0 ~ 1, ignore when null.
  3862. * @return {string} Color string in rgba format.
  3863. * @memberOf module:zrender/util/color
  3864. */
  3865. function modifyHSL(color, h, s, l) {
  3866. color = parse(color);
  3867. if (color) {
  3868. color = rgba2hsla(color);
  3869. h != null && (color[0] = clampCssAngle(h));
  3870. s != null && (color[1] = parseCssFloat(s));
  3871. l != null && (color[2] = parseCssFloat(l));
  3872. return stringify(hsla2rgba(color), 'rgba');
  3873. }
  3874. }
  3875. /**
  3876. * @param {string} color
  3877. * @param {number=} alpha 0 ~ 1
  3878. * @return {string} Color string in rgba format.
  3879. * @memberOf module:zrender/util/color
  3880. */
  3881. function modifyAlpha(color, alpha) {
  3882. color = parse(color);
  3883. if (color && alpha != null) {
  3884. color[3] = clampCssFloat(alpha);
  3885. return stringify(color, 'rgba');
  3886. }
  3887. }
  3888. /**
  3889. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3890. * @param {string} type 'rgba', 'hsva', ...
  3891. * @return {string} Result color. (If input illegal, return undefined).
  3892. */
  3893. function stringify(arrColor, type) {
  3894. if (!arrColor || !arrColor.length) {
  3895. return;
  3896. }
  3897. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3898. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3899. colorStr += ',' + arrColor[3];
  3900. }
  3901. return type + '(' + colorStr + ')';
  3902. }
  3903. var color = (Object.freeze || Object)({
  3904. parse: parse,
  3905. lift: lift,
  3906. toHex: toHex,
  3907. fastLerp: fastLerp,
  3908. fastMapToColor: fastMapToColor,
  3909. lerp: lerp$1,
  3910. mapToColor: mapToColor,
  3911. modifyHSL: modifyHSL,
  3912. modifyAlpha: modifyAlpha,
  3913. stringify: stringify
  3914. });
  3915. /**
  3916. * @module echarts/animation/Animator
  3917. */
  3918. var arraySlice = Array.prototype.slice;
  3919. function defaultGetter(target, key) {
  3920. return target[key];
  3921. }
  3922. function defaultSetter(target, key, value) {
  3923. target[key] = value;
  3924. }
  3925. /**
  3926. * @param {number} p0
  3927. * @param {number} p1
  3928. * @param {number} percent
  3929. * @return {number}
  3930. */
  3931. function interpolateNumber(p0, p1, percent) {
  3932. return (p1 - p0) * percent + p0;
  3933. }
  3934. /**
  3935. * @param {string} p0
  3936. * @param {string} p1
  3937. * @param {number} percent
  3938. * @return {string}
  3939. */
  3940. function interpolateString(p0, p1, percent) {
  3941. return percent > 0.5 ? p1 : p0;
  3942. }
  3943. /**
  3944. * @param {Array} p0
  3945. * @param {Array} p1
  3946. * @param {number} percent
  3947. * @param {Array} out
  3948. * @param {number} arrDim
  3949. */
  3950. function interpolateArray(p0, p1, percent, out, arrDim) {
  3951. var len = p0.length;
  3952. if (arrDim === 1) {
  3953. for (var i = 0; i < len; i++) {
  3954. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3955. }
  3956. }
  3957. else {
  3958. var len2 = len && p0[0].length;
  3959. for (var i = 0; i < len; i++) {
  3960. for (var j = 0; j < len2; j++) {
  3961. out[i][j] = interpolateNumber(
  3962. p0[i][j], p1[i][j], percent
  3963. );
  3964. }
  3965. }
  3966. }
  3967. }
  3968. // arr0 is source array, arr1 is target array.
  3969. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3970. function fillArr(arr0, arr1, arrDim) {
  3971. var arr0Len = arr0.length;
  3972. var arr1Len = arr1.length;
  3973. if (arr0Len !== arr1Len) {
  3974. // FIXME Not work for TypedArray
  3975. var isPreviousLarger = arr0Len > arr1Len;
  3976. if (isPreviousLarger) {
  3977. // Cut the previous
  3978. arr0.length = arr1Len;
  3979. }
  3980. else {
  3981. // Fill the previous
  3982. for (var i = arr0Len; i < arr1Len; i++) {
  3983. arr0.push(
  3984. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3985. );
  3986. }
  3987. }
  3988. }
  3989. // Handling NaN value
  3990. var len2 = arr0[0] && arr0[0].length;
  3991. for (var i = 0; i < arr0.length; i++) {
  3992. if (arrDim === 1) {
  3993. if (isNaN(arr0[i])) {
  3994. arr0[i] = arr1[i];
  3995. }
  3996. }
  3997. else {
  3998. for (var j = 0; j < len2; j++) {
  3999. if (isNaN(arr0[i][j])) {
  4000. arr0[i][j] = arr1[i][j];
  4001. }
  4002. }
  4003. }
  4004. }
  4005. }
  4006. /**
  4007. * @param {Array} arr0
  4008. * @param {Array} arr1
  4009. * @param {number} arrDim
  4010. * @return {boolean}
  4011. */
  4012. function isArraySame(arr0, arr1, arrDim) {
  4013. if (arr0 === arr1) {
  4014. return true;
  4015. }
  4016. var len = arr0.length;
  4017. if (len !== arr1.length) {
  4018. return false;
  4019. }
  4020. if (arrDim === 1) {
  4021. for (var i = 0; i < len; i++) {
  4022. if (arr0[i] !== arr1[i]) {
  4023. return false;
  4024. }
  4025. }
  4026. }
  4027. else {
  4028. var len2 = arr0[0].length;
  4029. for (var i = 0; i < len; i++) {
  4030. for (var j = 0; j < len2; j++) {
  4031. if (arr0[i][j] !== arr1[i][j]) {
  4032. return false;
  4033. }
  4034. }
  4035. }
  4036. }
  4037. return true;
  4038. }
  4039. /**
  4040. * Catmull Rom interpolate array
  4041. * @param {Array} p0
  4042. * @param {Array} p1
  4043. * @param {Array} p2
  4044. * @param {Array} p3
  4045. * @param {number} t
  4046. * @param {number} t2
  4047. * @param {number} t3
  4048. * @param {Array} out
  4049. * @param {number} arrDim
  4050. */
  4051. function catmullRomInterpolateArray(
  4052. p0, p1, p2, p3, t, t2, t3, out, arrDim
  4053. ) {
  4054. var len = p0.length;
  4055. if (arrDim === 1) {
  4056. for (var i = 0; i < len; i++) {
  4057. out[i] = catmullRomInterpolate(
  4058. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  4059. );
  4060. }
  4061. }
  4062. else {
  4063. var len2 = p0[0].length;
  4064. for (var i = 0; i < len; i++) {
  4065. for (var j = 0; j < len2; j++) {
  4066. out[i][j] = catmullRomInterpolate(
  4067. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  4068. t, t2, t3
  4069. );
  4070. }
  4071. }
  4072. }
  4073. }
  4074. /**
  4075. * Catmull Rom interpolate number
  4076. * @param {number} p0
  4077. * @param {number} p1
  4078. * @param {number} p2
  4079. * @param {number} p3
  4080. * @param {number} t
  4081. * @param {number} t2
  4082. * @param {number} t3
  4083. * @return {number}
  4084. */
  4085. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  4086. var v0 = (p2 - p0) * 0.5;
  4087. var v1 = (p3 - p1) * 0.5;
  4088. return (2 * (p1 - p2) + v0 + v1) * t3
  4089. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  4090. + v0 * t + p1;
  4091. }
  4092. function cloneValue(value) {
  4093. if (isArrayLike(value)) {
  4094. var len = value.length;
  4095. if (isArrayLike(value[0])) {
  4096. var ret = [];
  4097. for (var i = 0; i < len; i++) {
  4098. ret.push(arraySlice.call(value[i]));
  4099. }
  4100. return ret;
  4101. }
  4102. return arraySlice.call(value);
  4103. }
  4104. return value;
  4105. }
  4106. function rgba2String(rgba) {
  4107. rgba[0] = Math.floor(rgba[0]);
  4108. rgba[1] = Math.floor(rgba[1]);
  4109. rgba[2] = Math.floor(rgba[2]);
  4110. return 'rgba(' + rgba.join(',') + ')';
  4111. }
  4112. function getArrayDim(keyframes) {
  4113. var lastValue = keyframes[keyframes.length - 1].value;
  4114. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  4115. }
  4116. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  4117. var getter = animator._getter;
  4118. var setter = animator._setter;
  4119. var useSpline = easing === 'spline';
  4120. var trackLen = keyframes.length;
  4121. if (!trackLen) {
  4122. return;
  4123. }
  4124. // Guess data type
  4125. var firstVal = keyframes[0].value;
  4126. var isValueArray = isArrayLike(firstVal);
  4127. var isValueColor = false;
  4128. var isValueString = false;
  4129. // For vertices morphing
  4130. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4131. var trackMaxTime;
  4132. // Sort keyframe as ascending
  4133. keyframes.sort(function (a, b) {
  4134. return a.time - b.time;
  4135. });
  4136. trackMaxTime = keyframes[trackLen - 1].time;
  4137. // Percents of each keyframe
  4138. var kfPercents = [];
  4139. // Value of each keyframe
  4140. var kfValues = [];
  4141. var prevValue = keyframes[0].value;
  4142. var isAllValueEqual = true;
  4143. for (var i = 0; i < trackLen; i++) {
  4144. kfPercents.push(keyframes[i].time / trackMaxTime);
  4145. // Assume value is a color when it is a string
  4146. var value = keyframes[i].value;
  4147. // Check if value is equal, deep check if value is array
  4148. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4149. || (!isValueArray && value === prevValue))) {
  4150. isAllValueEqual = false;
  4151. }
  4152. prevValue = value;
  4153. // Try converting a string to a color array
  4154. if (typeof value === 'string') {
  4155. var colorArray = parse(value);
  4156. if (colorArray) {
  4157. value = colorArray;
  4158. isValueColor = true;
  4159. }
  4160. else {
  4161. isValueString = true;
  4162. }
  4163. }
  4164. kfValues.push(value);
  4165. }
  4166. if (!forceAnimate && isAllValueEqual) {
  4167. return;
  4168. }
  4169. var lastValue = kfValues[trackLen - 1];
  4170. // Polyfill array and NaN value
  4171. for (var i = 0; i < trackLen - 1; i++) {
  4172. if (isValueArray) {
  4173. fillArr(kfValues[i], lastValue, arrDim);
  4174. }
  4175. else {
  4176. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4177. kfValues[i] = lastValue;
  4178. }
  4179. }
  4180. }
  4181. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4182. // Cache the key of last frame to speed up when
  4183. // animation playback is sequency
  4184. var lastFrame = 0;
  4185. var lastFramePercent = 0;
  4186. var start;
  4187. var w;
  4188. var p0;
  4189. var p1;
  4190. var p2;
  4191. var p3;
  4192. if (isValueColor) {
  4193. var rgba = [0, 0, 0, 0];
  4194. }
  4195. var onframe = function (target, percent) {
  4196. // Find the range keyframes
  4197. // kf1-----kf2---------current--------kf3
  4198. // find kf2 and kf3 and do interpolation
  4199. var frame;
  4200. // In the easing function like elasticOut, percent may less than 0
  4201. if (percent < 0) {
  4202. frame = 0;
  4203. }
  4204. else if (percent < lastFramePercent) {
  4205. // Start from next key
  4206. // PENDING start from lastFrame ?
  4207. start = Math.min(lastFrame + 1, trackLen - 1);
  4208. for (frame = start; frame >= 0; frame--) {
  4209. if (kfPercents[frame] <= percent) {
  4210. break;
  4211. }
  4212. }
  4213. // PENDING really need to do this ?
  4214. frame = Math.min(frame, trackLen - 2);
  4215. }
  4216. else {
  4217. for (frame = lastFrame; frame < trackLen; frame++) {
  4218. if (kfPercents[frame] > percent) {
  4219. break;
  4220. }
  4221. }
  4222. frame = Math.min(frame - 1, trackLen - 2);
  4223. }
  4224. lastFrame = frame;
  4225. lastFramePercent = percent;
  4226. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4227. if (range === 0) {
  4228. return;
  4229. }
  4230. else {
  4231. w = (percent - kfPercents[frame]) / range;
  4232. }
  4233. if (useSpline) {
  4234. p1 = kfValues[frame];
  4235. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4236. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4237. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4238. if (isValueArray) {
  4239. catmullRomInterpolateArray(
  4240. p0, p1, p2, p3, w, w * w, w * w * w,
  4241. getter(target, propName),
  4242. arrDim
  4243. );
  4244. }
  4245. else {
  4246. var value;
  4247. if (isValueColor) {
  4248. value = catmullRomInterpolateArray(
  4249. p0, p1, p2, p3, w, w * w, w * w * w,
  4250. rgba, 1
  4251. );
  4252. value = rgba2String(rgba);
  4253. }
  4254. else if (isValueString) {
  4255. // String is step(0.5)
  4256. return interpolateString(p1, p2, w);
  4257. }
  4258. else {
  4259. value = catmullRomInterpolate(
  4260. p0, p1, p2, p3, w, w * w, w * w * w
  4261. );
  4262. }
  4263. setter(
  4264. target,
  4265. propName,
  4266. value
  4267. );
  4268. }
  4269. }
  4270. else {
  4271. if (isValueArray) {
  4272. interpolateArray(
  4273. kfValues[frame], kfValues[frame + 1], w,
  4274. getter(target, propName),
  4275. arrDim
  4276. );
  4277. }
  4278. else {
  4279. var value;
  4280. if (isValueColor) {
  4281. interpolateArray(
  4282. kfValues[frame], kfValues[frame + 1], w,
  4283. rgba, 1
  4284. );
  4285. value = rgba2String(rgba);
  4286. }
  4287. else if (isValueString) {
  4288. // String is step(0.5)
  4289. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4290. }
  4291. else {
  4292. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4293. }
  4294. setter(
  4295. target,
  4296. propName,
  4297. value
  4298. );
  4299. }
  4300. }
  4301. };
  4302. var clip = new Clip({
  4303. target: animator._target,
  4304. life: trackMaxTime,
  4305. loop: animator._loop,
  4306. delay: animator._delay,
  4307. onframe: onframe,
  4308. ondestroy: oneTrackDone
  4309. });
  4310. if (easing && easing !== 'spline') {
  4311. clip.easing = easing;
  4312. }
  4313. return clip;
  4314. }
  4315. /**
  4316. * @alias module:zrender/animation/Animator
  4317. * @constructor
  4318. * @param {Object} target
  4319. * @param {boolean} loop
  4320. * @param {Function} getter
  4321. * @param {Function} setter
  4322. */
  4323. var Animator = function (target, loop, getter, setter) {
  4324. this._tracks = {};
  4325. this._target = target;
  4326. this._loop = loop || false;
  4327. this._getter = getter || defaultGetter;
  4328. this._setter = setter || defaultSetter;
  4329. this._clipCount = 0;
  4330. this._delay = 0;
  4331. this._doneList = [];
  4332. this._onframeList = [];
  4333. this._clipList = [];
  4334. };
  4335. Animator.prototype = {
  4336. /**
  4337. * Set Animation keyframe
  4338. * @param {number} time 关键帧时间,单位是ms
  4339. * @param {Object} props 关键帧的属性值,key-value表示
  4340. * @return {module:zrender/animation/Animator}
  4341. */
  4342. when: function (time /* ms */, props) {
  4343. var tracks = this._tracks;
  4344. for (var propName in props) {
  4345. if (!props.hasOwnProperty(propName)) {
  4346. continue;
  4347. }
  4348. if (!tracks[propName]) {
  4349. tracks[propName] = [];
  4350. // Invalid value
  4351. var value = this._getter(this._target, propName);
  4352. if (value == null) {
  4353. // zrLog('Invalid property ' + propName);
  4354. continue;
  4355. }
  4356. // If time is 0
  4357. // Then props is given initialize value
  4358. // Else
  4359. // Initialize value from current prop value
  4360. if (time !== 0) {
  4361. tracks[propName].push({
  4362. time: 0,
  4363. value: cloneValue(value)
  4364. });
  4365. }
  4366. }
  4367. tracks[propName].push({
  4368. time: time,
  4369. value: props[propName]
  4370. });
  4371. }
  4372. return this;
  4373. },
  4374. /**
  4375. * 添加动画每一帧的回调函数
  4376. * @param {Function} callback
  4377. * @return {module:zrender/animation/Animator}
  4378. */
  4379. during: function (callback) {
  4380. this._onframeList.push(callback);
  4381. return this;
  4382. },
  4383. pause: function () {
  4384. for (var i = 0; i < this._clipList.length; i++) {
  4385. this._clipList[i].pause();
  4386. }
  4387. this._paused = true;
  4388. },
  4389. resume: function () {
  4390. for (var i = 0; i < this._clipList.length; i++) {
  4391. this._clipList[i].resume();
  4392. }
  4393. this._paused = false;
  4394. },
  4395. isPaused: function () {
  4396. return !!this._paused;
  4397. },
  4398. _doneCallback: function () {
  4399. // Clear all tracks
  4400. this._tracks = {};
  4401. // Clear all clips
  4402. this._clipList.length = 0;
  4403. var doneList = this._doneList;
  4404. var len = doneList.length;
  4405. for (var i = 0; i < len; i++) {
  4406. doneList[i].call(this);
  4407. }
  4408. },
  4409. /**
  4410. * Start the animation
  4411. * @param {string|Function} [easing]
  4412. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4413. * @param {boolean} forceAnimate
  4414. * @return {module:zrender/animation/Animator}
  4415. */
  4416. start: function (easing, forceAnimate) {
  4417. var self = this;
  4418. var clipCount = 0;
  4419. var oneTrackDone = function () {
  4420. clipCount--;
  4421. if (!clipCount) {
  4422. self._doneCallback();
  4423. }
  4424. };
  4425. var lastClip;
  4426. for (var propName in this._tracks) {
  4427. if (!this._tracks.hasOwnProperty(propName)) {
  4428. continue;
  4429. }
  4430. var clip = createTrackClip(
  4431. this, easing, oneTrackDone,
  4432. this._tracks[propName], propName, forceAnimate
  4433. );
  4434. if (clip) {
  4435. this._clipList.push(clip);
  4436. clipCount++;
  4437. // If start after added to animation
  4438. if (this.animation) {
  4439. this.animation.addClip(clip);
  4440. }
  4441. lastClip = clip;
  4442. }
  4443. }
  4444. // Add during callback on the last clip
  4445. if (lastClip) {
  4446. var oldOnFrame = lastClip.onframe;
  4447. lastClip.onframe = function (target, percent) {
  4448. oldOnFrame(target, percent);
  4449. for (var i = 0; i < self._onframeList.length; i++) {
  4450. self._onframeList[i](target, percent);
  4451. }
  4452. };
  4453. }
  4454. // This optimization will help the case that in the upper application
  4455. // the view may be refreshed frequently, where animation will be
  4456. // called repeatly but nothing changed.
  4457. if (!clipCount) {
  4458. this._doneCallback();
  4459. }
  4460. return this;
  4461. },
  4462. /**
  4463. * Stop animation
  4464. * @param {boolean} forwardToLast If move to last frame before stop
  4465. */
  4466. stop: function (forwardToLast) {
  4467. var clipList = this._clipList;
  4468. var animation = this.animation;
  4469. for (var i = 0; i < clipList.length; i++) {
  4470. var clip = clipList[i];
  4471. if (forwardToLast) {
  4472. // Move to last frame before stop
  4473. clip.onframe(this._target, 1);
  4474. }
  4475. animation && animation.removeClip(clip);
  4476. }
  4477. clipList.length = 0;
  4478. },
  4479. /**
  4480. * Set when animation delay starts
  4481. * @param {number} time 单位ms
  4482. * @return {module:zrender/animation/Animator}
  4483. */
  4484. delay: function (time) {
  4485. this._delay = time;
  4486. return this;
  4487. },
  4488. /**
  4489. * Add callback for animation end
  4490. * @param {Function} cb
  4491. * @return {module:zrender/animation/Animator}
  4492. */
  4493. done: function (cb) {
  4494. if (cb) {
  4495. this._doneList.push(cb);
  4496. }
  4497. return this;
  4498. },
  4499. /**
  4500. * @return {Array.<module:zrender/animation/Clip>}
  4501. */
  4502. getClips: function () {
  4503. return this._clipList;
  4504. }
  4505. };
  4506. var dpr = 1;
  4507. // If in browser environment
  4508. if (typeof window !== 'undefined') {
  4509. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4510. }
  4511. /**
  4512. * config默认配置项
  4513. * @exports zrender/config
  4514. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4515. */
  4516. /**
  4517. * Debug log mode:
  4518. * 0: Do nothing, for release.
  4519. * 1: console.error, for debug.
  4520. */
  4521. var debugMode = 0;
  4522. // retina 屏幕优化
  4523. var devicePixelRatio = dpr;
  4524. var logError = function () {
  4525. };
  4526. if (debugMode === 1) {
  4527. logError = console.error;
  4528. }
  4529. var logError$1 = logError;
  4530. /**
  4531. * @alias module:zrender/mixin/Animatable
  4532. * @constructor
  4533. */
  4534. var Animatable = function () {
  4535. /**
  4536. * @type {Array.<module:zrender/animation/Animator>}
  4537. * @readOnly
  4538. */
  4539. this.animators = [];
  4540. };
  4541. Animatable.prototype = {
  4542. constructor: Animatable,
  4543. /**
  4544. * 动画
  4545. *
  4546. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4547. * @param {boolean} [loop] Whether to loop animation.
  4548. * @return {module:zrender/animation/Animator}
  4549. * @example:
  4550. * el.animate('style', false)
  4551. * .when(1000, {x: 10} )
  4552. * .done(function(){ // Animation done })
  4553. * .start()
  4554. */
  4555. animate: function (path, loop) {
  4556. var target;
  4557. var animatingShape = false;
  4558. var el = this;
  4559. var zr = this.__zr;
  4560. if (path) {
  4561. var pathSplitted = path.split('.');
  4562. var prop = el;
  4563. // If animating shape
  4564. animatingShape = pathSplitted[0] === 'shape';
  4565. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4566. if (!prop) {
  4567. continue;
  4568. }
  4569. prop = prop[pathSplitted[i]];
  4570. }
  4571. if (prop) {
  4572. target = prop;
  4573. }
  4574. }
  4575. else {
  4576. target = el;
  4577. }
  4578. if (!target) {
  4579. logError$1(
  4580. 'Property "'
  4581. + path
  4582. + '" is not existed in element '
  4583. + el.id
  4584. );
  4585. return;
  4586. }
  4587. var animators = el.animators;
  4588. var animator = new Animator(target, loop);
  4589. animator.during(function (target) {
  4590. el.dirty(animatingShape);
  4591. })
  4592. .done(function () {
  4593. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4594. animators.splice(indexOf(animators, animator), 1);
  4595. });
  4596. animators.push(animator);
  4597. // If animate after added to the zrender
  4598. if (zr) {
  4599. zr.animation.addAnimator(animator);
  4600. }
  4601. return animator;
  4602. },
  4603. /**
  4604. * 停止动画
  4605. * @param {boolean} forwardToLast If move to last frame before stop
  4606. */
  4607. stopAnimation: function (forwardToLast) {
  4608. var animators = this.animators;
  4609. var len = animators.length;
  4610. for (var i = 0; i < len; i++) {
  4611. animators[i].stop(forwardToLast);
  4612. }
  4613. animators.length = 0;
  4614. return this;
  4615. },
  4616. /**
  4617. * Caution: this method will stop previous animation.
  4618. * So do not use this method to one element twice before
  4619. * animation starts, unless you know what you are doing.
  4620. * @param {Object} target
  4621. * @param {number} [time=500] Time in ms
  4622. * @param {string} [easing='linear']
  4623. * @param {number} [delay=0]
  4624. * @param {Function} [callback]
  4625. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4626. * immediently when target values are the same as current values.
  4627. *
  4628. * @example
  4629. * // Animate position
  4630. * el.animateTo({
  4631. * position: [10, 10]
  4632. * }, function () { // done })
  4633. *
  4634. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4635. * el.animateTo({
  4636. * shape: {
  4637. * width: 500
  4638. * },
  4639. * style: {
  4640. * fill: 'red'
  4641. * }
  4642. * position: [10, 10]
  4643. * }, 100, 100, 'cubicOut', function () { // done })
  4644. */
  4645. // TODO Return animation key
  4646. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4647. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4648. },
  4649. /**
  4650. * Animate from the target state to current state.
  4651. * The params and the return value are the same as `this.animateTo`.
  4652. */
  4653. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4654. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4655. }
  4656. };
  4657. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4658. // animateTo(target, time, easing, callback);
  4659. if (isString(delay)) {
  4660. callback = easing;
  4661. easing = delay;
  4662. delay = 0;
  4663. }
  4664. // animateTo(target, time, delay, callback);
  4665. else if (isFunction$1(easing)) {
  4666. callback = easing;
  4667. easing = 'linear';
  4668. delay = 0;
  4669. }
  4670. // animateTo(target, time, callback);
  4671. else if (isFunction$1(delay)) {
  4672. callback = delay;
  4673. delay = 0;
  4674. }
  4675. // animateTo(target, callback)
  4676. else if (isFunction$1(time)) {
  4677. callback = time;
  4678. time = 500;
  4679. }
  4680. // animateTo(target)
  4681. else if (!time) {
  4682. time = 500;
  4683. }
  4684. // Stop all previous animations
  4685. animatable.stopAnimation();
  4686. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4687. // Animators may be removed immediately after start
  4688. // if there is nothing to animate
  4689. var animators = animatable.animators.slice();
  4690. var count = animators.length;
  4691. function done() {
  4692. count--;
  4693. if (!count) {
  4694. callback && callback();
  4695. }
  4696. }
  4697. // No animators. This should be checked before animators[i].start(),
  4698. // because 'done' may be executed immediately if no need to animate.
  4699. if (!count) {
  4700. callback && callback();
  4701. }
  4702. // Start after all animators created
  4703. // Incase any animator is done immediately when all animation properties are not changed
  4704. for (var i = 0; i < animators.length; i++) {
  4705. animators[i]
  4706. .done(done)
  4707. .start(easing, forceAnimate);
  4708. }
  4709. }
  4710. /**
  4711. * @param {string} path=''
  4712. * @param {Object} source=animatable
  4713. * @param {Object} target
  4714. * @param {number} [time=500]
  4715. * @param {number} [delay=0]
  4716. * @param {boolean} [reverse] If `true`, animate
  4717. * from the `target` to current state.
  4718. *
  4719. * @example
  4720. * // Animate position
  4721. * el._animateToShallow({
  4722. * position: [10, 10]
  4723. * })
  4724. *
  4725. * // Animate shape, style and position in 100ms, delayed 100ms
  4726. * el._animateToShallow({
  4727. * shape: {
  4728. * width: 500
  4729. * },
  4730. * style: {
  4731. * fill: 'red'
  4732. * }
  4733. * position: [10, 10]
  4734. * }, 100, 100)
  4735. */
  4736. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4737. var objShallow = {};
  4738. var propertyCount = 0;
  4739. for (var name in target) {
  4740. if (!target.hasOwnProperty(name)) {
  4741. continue;
  4742. }
  4743. if (source[name] != null) {
  4744. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4745. animateToShallow(
  4746. animatable,
  4747. path ? path + '.' + name : name,
  4748. source[name],
  4749. target[name],
  4750. time,
  4751. delay,
  4752. reverse
  4753. );
  4754. }
  4755. else {
  4756. if (reverse) {
  4757. objShallow[name] = source[name];
  4758. setAttrByPath(animatable, path, name, target[name]);
  4759. }
  4760. else {
  4761. objShallow[name] = target[name];
  4762. }
  4763. propertyCount++;
  4764. }
  4765. }
  4766. else if (target[name] != null && !reverse) {
  4767. setAttrByPath(animatable, path, name, target[name]);
  4768. }
  4769. }
  4770. if (propertyCount > 0) {
  4771. animatable.animate(path, false)
  4772. .when(time == null ? 500 : time, objShallow)
  4773. .delay(delay || 0);
  4774. }
  4775. }
  4776. function setAttrByPath(el, path, name, value) {
  4777. // Attr directly if not has property
  4778. // FIXME, if some property not needed for element ?
  4779. if (!path) {
  4780. el.attr(name, value);
  4781. }
  4782. else {
  4783. // Only support set shape or style
  4784. var props = {};
  4785. props[path] = {};
  4786. props[path][name] = value;
  4787. el.attr(props);
  4788. }
  4789. }
  4790. /**
  4791. * @alias module:zrender/Element
  4792. * @constructor
  4793. * @extends {module:zrender/mixin/Animatable}
  4794. * @extends {module:zrender/mixin/Transformable}
  4795. * @extends {module:zrender/mixin/Eventful}
  4796. */
  4797. var Element = function (opts) { // jshint ignore:line
  4798. Transformable.call(this, opts);
  4799. Eventful.call(this, opts);
  4800. Animatable.call(this, opts);
  4801. /**
  4802. * 画布元素ID
  4803. * @type {string}
  4804. */
  4805. this.id = opts.id || guid();
  4806. };
  4807. Element.prototype = {
  4808. /**
  4809. * 元素类型
  4810. * Element type
  4811. * @type {string}
  4812. */
  4813. type: 'element',
  4814. /**
  4815. * 元素名字
  4816. * Element name
  4817. * @type {string}
  4818. */
  4819. name: '',
  4820. /**
  4821. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4822. * ZRender instance will be assigned when element is associated with zrender
  4823. * @name module:/zrender/Element#__zr
  4824. * @type {module:zrender/ZRender}
  4825. */
  4826. __zr: null,
  4827. /**
  4828. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4829. * If ignore drawing and events of the element object
  4830. * @name module:/zrender/Element#ignore
  4831. * @type {boolean}
  4832. * @default false
  4833. */
  4834. ignore: false,
  4835. /**
  4836. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4837. * 该路径会继承被裁减对象的变换
  4838. * @type {module:zrender/graphic/Path}
  4839. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4840. * @readOnly
  4841. */
  4842. clipPath: null,
  4843. /**
  4844. * 是否是 Group
  4845. * @type {boolean}
  4846. */
  4847. isGroup: false,
  4848. /**
  4849. * Drift element
  4850. * @param {number} dx dx on the global space
  4851. * @param {number} dy dy on the global space
  4852. */
  4853. drift: function (dx, dy) {
  4854. switch (this.draggable) {
  4855. case 'horizontal':
  4856. dy = 0;
  4857. break;
  4858. case 'vertical':
  4859. dx = 0;
  4860. break;
  4861. }
  4862. var m = this.transform;
  4863. if (!m) {
  4864. m = this.transform = [1, 0, 0, 1, 0, 0];
  4865. }
  4866. m[4] += dx;
  4867. m[5] += dy;
  4868. this.decomposeTransform();
  4869. this.dirty(false);
  4870. },
  4871. /**
  4872. * Hook before update
  4873. */
  4874. beforeUpdate: function () {},
  4875. /**
  4876. * Hook after update
  4877. */
  4878. afterUpdate: function () {},
  4879. /**
  4880. * Update each frame
  4881. */
  4882. update: function () {
  4883. this.updateTransform();
  4884. },
  4885. /**
  4886. * @param {Function} cb
  4887. * @param {} context
  4888. */
  4889. traverse: function (cb, context) {},
  4890. /**
  4891. * @protected
  4892. */
  4893. attrKV: function (key, value) {
  4894. if (key === 'position' || key === 'scale' || key === 'origin') {
  4895. // Copy the array
  4896. if (value) {
  4897. var target = this[key];
  4898. if (!target) {
  4899. target = this[key] = [];
  4900. }
  4901. target[0] = value[0];
  4902. target[1] = value[1];
  4903. }
  4904. }
  4905. else {
  4906. this[key] = value;
  4907. }
  4908. },
  4909. /**
  4910. * Hide the element
  4911. */
  4912. hide: function () {
  4913. this.ignore = true;
  4914. this.__zr && this.__zr.refresh();
  4915. },
  4916. /**
  4917. * Show the element
  4918. */
  4919. show: function () {
  4920. this.ignore = false;
  4921. this.__zr && this.__zr.refresh();
  4922. },
  4923. /**
  4924. * @param {string|Object} key
  4925. * @param {*} value
  4926. */
  4927. attr: function (key, value) {
  4928. if (typeof key === 'string') {
  4929. this.attrKV(key, value);
  4930. }
  4931. else if (isObject$1(key)) {
  4932. for (var name in key) {
  4933. if (key.hasOwnProperty(name)) {
  4934. this.attrKV(name, key[name]);
  4935. }
  4936. }
  4937. }
  4938. this.dirty(false);
  4939. return this;
  4940. },
  4941. /**
  4942. * @param {module:zrender/graphic/Path} clipPath
  4943. */
  4944. setClipPath: function (clipPath) {
  4945. var zr = this.__zr;
  4946. if (zr) {
  4947. clipPath.addSelfToZr(zr);
  4948. }
  4949. // Remove previous clip path
  4950. if (this.clipPath && this.clipPath !== clipPath) {
  4951. this.removeClipPath();
  4952. }
  4953. this.clipPath = clipPath;
  4954. clipPath.__zr = zr;
  4955. clipPath.__clipTarget = this;
  4956. this.dirty(false);
  4957. },
  4958. /**
  4959. */
  4960. removeClipPath: function () {
  4961. var clipPath = this.clipPath;
  4962. if (clipPath) {
  4963. if (clipPath.__zr) {
  4964. clipPath.removeSelfFromZr(clipPath.__zr);
  4965. }
  4966. clipPath.__zr = null;
  4967. clipPath.__clipTarget = null;
  4968. this.clipPath = null;
  4969. this.dirty(false);
  4970. }
  4971. },
  4972. /**
  4973. * Add self from zrender instance.
  4974. * Not recursively because it will be invoked when element added to storage.
  4975. * @param {module:zrender/ZRender} zr
  4976. */
  4977. addSelfToZr: function (zr) {
  4978. this.__zr = zr;
  4979. // 添加动画
  4980. var animators = this.animators;
  4981. if (animators) {
  4982. for (var i = 0; i < animators.length; i++) {
  4983. zr.animation.addAnimator(animators[i]);
  4984. }
  4985. }
  4986. if (this.clipPath) {
  4987. this.clipPath.addSelfToZr(zr);
  4988. }
  4989. },
  4990. /**
  4991. * Remove self from zrender instance.
  4992. * Not recursively because it will be invoked when element added to storage.
  4993. * @param {module:zrender/ZRender} zr
  4994. */
  4995. removeSelfFromZr: function (zr) {
  4996. this.__zr = null;
  4997. // 移除动画
  4998. var animators = this.animators;
  4999. if (animators) {
  5000. for (var i = 0; i < animators.length; i++) {
  5001. zr.animation.removeAnimator(animators[i]);
  5002. }
  5003. }
  5004. if (this.clipPath) {
  5005. this.clipPath.removeSelfFromZr(zr);
  5006. }
  5007. }
  5008. };
  5009. mixin(Element, Animatable);
  5010. mixin(Element, Transformable);
  5011. mixin(Element, Eventful);
  5012. /**
  5013. * @module echarts/core/BoundingRect
  5014. */
  5015. var v2ApplyTransform = applyTransform;
  5016. var mathMin = Math.min;
  5017. var mathMax = Math.max;
  5018. /**
  5019. * @alias module:echarts/core/BoundingRect
  5020. */
  5021. function BoundingRect(x, y, width, height) {
  5022. if (width < 0) {
  5023. x = x + width;
  5024. width = -width;
  5025. }
  5026. if (height < 0) {
  5027. y = y + height;
  5028. height = -height;
  5029. }
  5030. /**
  5031. * @type {number}
  5032. */
  5033. this.x = x;
  5034. /**
  5035. * @type {number}
  5036. */
  5037. this.y = y;
  5038. /**
  5039. * @type {number}
  5040. */
  5041. this.width = width;
  5042. /**
  5043. * @type {number}
  5044. */
  5045. this.height = height;
  5046. }
  5047. BoundingRect.prototype = {
  5048. constructor: BoundingRect,
  5049. /**
  5050. * @param {module:echarts/core/BoundingRect} other
  5051. */
  5052. union: function (other) {
  5053. var x = mathMin(other.x, this.x);
  5054. var y = mathMin(other.y, this.y);
  5055. this.width = mathMax(
  5056. other.x + other.width,
  5057. this.x + this.width
  5058. ) - x;
  5059. this.height = mathMax(
  5060. other.y + other.height,
  5061. this.y + this.height
  5062. ) - y;
  5063. this.x = x;
  5064. this.y = y;
  5065. },
  5066. /**
  5067. * @param {Array.<number>} m
  5068. * @methods
  5069. */
  5070. applyTransform: (function () {
  5071. var lt = [];
  5072. var rb = [];
  5073. var lb = [];
  5074. var rt = [];
  5075. return function (m) {
  5076. // In case usage like this
  5077. // el.getBoundingRect().applyTransform(el.transform)
  5078. // And element has no transform
  5079. if (!m) {
  5080. return;
  5081. }
  5082. lt[0] = lb[0] = this.x;
  5083. lt[1] = rt[1] = this.y;
  5084. rb[0] = rt[0] = this.x + this.width;
  5085. rb[1] = lb[1] = this.y + this.height;
  5086. v2ApplyTransform(lt, lt, m);
  5087. v2ApplyTransform(rb, rb, m);
  5088. v2ApplyTransform(lb, lb, m);
  5089. v2ApplyTransform(rt, rt, m);
  5090. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  5091. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  5092. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  5093. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  5094. this.width = maxX - this.x;
  5095. this.height = maxY - this.y;
  5096. };
  5097. })(),
  5098. /**
  5099. * Calculate matrix of transforming from self to target rect
  5100. * @param {module:zrender/core/BoundingRect} b
  5101. * @return {Array.<number>}
  5102. */
  5103. calculateTransform: function (b) {
  5104. var a = this;
  5105. var sx = b.width / a.width;
  5106. var sy = b.height / a.height;
  5107. var m = create$1();
  5108. // 矩阵右乘
  5109. translate(m, m, [-a.x, -a.y]);
  5110. scale$1(m, m, [sx, sy]);
  5111. translate(m, m, [b.x, b.y]);
  5112. return m;
  5113. },
  5114. /**
  5115. * @param {(module:echarts/core/BoundingRect|Object)} b
  5116. * @return {boolean}
  5117. */
  5118. intersect: function (b) {
  5119. if (!b) {
  5120. return false;
  5121. }
  5122. if (!(b instanceof BoundingRect)) {
  5123. // Normalize negative width/height.
  5124. b = BoundingRect.create(b);
  5125. }
  5126. var a = this;
  5127. var ax0 = a.x;
  5128. var ax1 = a.x + a.width;
  5129. var ay0 = a.y;
  5130. var ay1 = a.y + a.height;
  5131. var bx0 = b.x;
  5132. var bx1 = b.x + b.width;
  5133. var by0 = b.y;
  5134. var by1 = b.y + b.height;
  5135. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5136. },
  5137. contain: function (x, y) {
  5138. var rect = this;
  5139. return x >= rect.x
  5140. && x <= (rect.x + rect.width)
  5141. && y >= rect.y
  5142. && y <= (rect.y + rect.height);
  5143. },
  5144. /**
  5145. * @return {module:echarts/core/BoundingRect}
  5146. */
  5147. clone: function () {
  5148. return new BoundingRect(this.x, this.y, this.width, this.height);
  5149. },
  5150. /**
  5151. * Copy from another rect
  5152. */
  5153. copy: function (other) {
  5154. this.x = other.x;
  5155. this.y = other.y;
  5156. this.width = other.width;
  5157. this.height = other.height;
  5158. },
  5159. plain: function () {
  5160. return {
  5161. x: this.x,
  5162. y: this.y,
  5163. width: this.width,
  5164. height: this.height
  5165. };
  5166. }
  5167. };
  5168. /**
  5169. * @param {Object|module:zrender/core/BoundingRect} rect
  5170. * @param {number} rect.x
  5171. * @param {number} rect.y
  5172. * @param {number} rect.width
  5173. * @param {number} rect.height
  5174. * @return {module:zrender/core/BoundingRect}
  5175. */
  5176. BoundingRect.create = function (rect) {
  5177. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5178. };
  5179. /**
  5180. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5181. * @module zrender/graphic/Group
  5182. * @example
  5183. * var Group = require('zrender/container/Group');
  5184. * var Circle = require('zrender/graphic/shape/Circle');
  5185. * var g = new Group();
  5186. * g.position[0] = 100;
  5187. * g.position[1] = 100;
  5188. * g.add(new Circle({
  5189. * style: {
  5190. * x: 100,
  5191. * y: 100,
  5192. * r: 20,
  5193. * }
  5194. * }));
  5195. * zr.add(g);
  5196. */
  5197. /**
  5198. * @alias module:zrender/graphic/Group
  5199. * @constructor
  5200. * @extends module:zrender/mixin/Transformable
  5201. * @extends module:zrender/mixin/Eventful
  5202. */
  5203. var Group = function (opts) {
  5204. opts = opts || {};
  5205. Element.call(this, opts);
  5206. for (var key in opts) {
  5207. if (opts.hasOwnProperty(key)) {
  5208. this[key] = opts[key];
  5209. }
  5210. }
  5211. this._children = [];
  5212. this.__storage = null;
  5213. this.__dirty = true;
  5214. };
  5215. Group.prototype = {
  5216. constructor: Group,
  5217. isGroup: true,
  5218. /**
  5219. * @type {string}
  5220. */
  5221. type: 'group',
  5222. /**
  5223. * 所有子孙元素是否响应鼠标事件
  5224. * @name module:/zrender/container/Group#silent
  5225. * @type {boolean}
  5226. * @default false
  5227. */
  5228. silent: false,
  5229. /**
  5230. * @return {Array.<module:zrender/Element>}
  5231. */
  5232. children: function () {
  5233. return this._children.slice();
  5234. },
  5235. /**
  5236. * 获取指定 index 的儿子节点
  5237. * @param {number} idx
  5238. * @return {module:zrender/Element}
  5239. */
  5240. childAt: function (idx) {
  5241. return this._children[idx];
  5242. },
  5243. /**
  5244. * 获取指定名字的儿子节点
  5245. * @param {string} name
  5246. * @return {module:zrender/Element}
  5247. */
  5248. childOfName: function (name) {
  5249. var children = this._children;
  5250. for (var i = 0; i < children.length; i++) {
  5251. if (children[i].name === name) {
  5252. return children[i];
  5253. }
  5254. }
  5255. },
  5256. /**
  5257. * @return {number}
  5258. */
  5259. childCount: function () {
  5260. return this._children.length;
  5261. },
  5262. /**
  5263. * 添加子节点到最后
  5264. * @param {module:zrender/Element} child
  5265. */
  5266. add: function (child) {
  5267. if (child && child !== this && child.parent !== this) {
  5268. this._children.push(child);
  5269. this._doAdd(child);
  5270. }
  5271. return this;
  5272. },
  5273. /**
  5274. * 添加子节点在 nextSibling 之前
  5275. * @param {module:zrender/Element} child
  5276. * @param {module:zrender/Element} nextSibling
  5277. */
  5278. addBefore: function (child, nextSibling) {
  5279. if (child && child !== this && child.parent !== this
  5280. && nextSibling && nextSibling.parent === this) {
  5281. var children = this._children;
  5282. var idx = children.indexOf(nextSibling);
  5283. if (idx >= 0) {
  5284. children.splice(idx, 0, child);
  5285. this._doAdd(child);
  5286. }
  5287. }
  5288. return this;
  5289. },
  5290. _doAdd: function (child) {
  5291. if (child.parent) {
  5292. child.parent.remove(child);
  5293. }
  5294. child.parent = this;
  5295. var storage = this.__storage;
  5296. var zr = this.__zr;
  5297. if (storage && storage !== child.__storage) {
  5298. storage.addToStorage(child);
  5299. if (child instanceof Group) {
  5300. child.addChildrenToStorage(storage);
  5301. }
  5302. }
  5303. zr && zr.refresh();
  5304. },
  5305. /**
  5306. * 移除子节点
  5307. * @param {module:zrender/Element} child
  5308. */
  5309. remove: function (child) {
  5310. var zr = this.__zr;
  5311. var storage = this.__storage;
  5312. var children = this._children;
  5313. var idx = indexOf(children, child);
  5314. if (idx < 0) {
  5315. return this;
  5316. }
  5317. children.splice(idx, 1);
  5318. child.parent = null;
  5319. if (storage) {
  5320. storage.delFromStorage(child);
  5321. if (child instanceof Group) {
  5322. child.delChildrenFromStorage(storage);
  5323. }
  5324. }
  5325. zr && zr.refresh();
  5326. return this;
  5327. },
  5328. /**
  5329. * 移除所有子节点
  5330. */
  5331. removeAll: function () {
  5332. var children = this._children;
  5333. var storage = this.__storage;
  5334. var child;
  5335. var i;
  5336. for (i = 0; i < children.length; i++) {
  5337. child = children[i];
  5338. if (storage) {
  5339. storage.delFromStorage(child);
  5340. if (child instanceof Group) {
  5341. child.delChildrenFromStorage(storage);
  5342. }
  5343. }
  5344. child.parent = null;
  5345. }
  5346. children.length = 0;
  5347. return this;
  5348. },
  5349. /**
  5350. * 遍历所有子节点
  5351. * @param {Function} cb
  5352. * @param {} context
  5353. */
  5354. eachChild: function (cb, context) {
  5355. var children = this._children;
  5356. for (var i = 0; i < children.length; i++) {
  5357. var child = children[i];
  5358. cb.call(context, child, i);
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 深度优先遍历所有子孙节点
  5364. * @param {Function} cb
  5365. * @param {} context
  5366. */
  5367. traverse: function (cb, context) {
  5368. for (var i = 0; i < this._children.length; i++) {
  5369. var child = this._children[i];
  5370. cb.call(context, child);
  5371. if (child.type === 'group') {
  5372. child.traverse(cb, context);
  5373. }
  5374. }
  5375. return this;
  5376. },
  5377. addChildrenToStorage: function (storage) {
  5378. for (var i = 0; i < this._children.length; i++) {
  5379. var child = this._children[i];
  5380. storage.addToStorage(child);
  5381. if (child instanceof Group) {
  5382. child.addChildrenToStorage(storage);
  5383. }
  5384. }
  5385. },
  5386. delChildrenFromStorage: function (storage) {
  5387. for (var i = 0; i < this._children.length; i++) {
  5388. var child = this._children[i];
  5389. storage.delFromStorage(child);
  5390. if (child instanceof Group) {
  5391. child.delChildrenFromStorage(storage);
  5392. }
  5393. }
  5394. },
  5395. dirty: function () {
  5396. this.__dirty = true;
  5397. this.__zr && this.__zr.refresh();
  5398. return this;
  5399. },
  5400. /**
  5401. * @return {module:zrender/core/BoundingRect}
  5402. */
  5403. getBoundingRect: function (includeChildren) {
  5404. // TODO Caching
  5405. var rect = null;
  5406. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5407. var children = includeChildren || this._children;
  5408. var tmpMat = [];
  5409. for (var i = 0; i < children.length; i++) {
  5410. var child = children[i];
  5411. if (child.ignore || child.invisible) {
  5412. continue;
  5413. }
  5414. var childRect = child.getBoundingRect();
  5415. var transform = child.getLocalTransform(tmpMat);
  5416. // TODO
  5417. // The boundingRect cacluated by transforming original
  5418. // rect may be bigger than the actual bundingRect when rotation
  5419. // is used. (Consider a circle rotated aginst its center, where
  5420. // the actual boundingRect should be the same as that not be
  5421. // rotated.) But we can not find better approach to calculate
  5422. // actual boundingRect yet, considering performance.
  5423. if (transform) {
  5424. tmpRect.copy(childRect);
  5425. tmpRect.applyTransform(transform);
  5426. rect = rect || tmpRect.clone();
  5427. rect.union(tmpRect);
  5428. }
  5429. else {
  5430. rect = rect || childRect.clone();
  5431. rect.union(childRect);
  5432. }
  5433. }
  5434. return rect || tmpRect;
  5435. }
  5436. };
  5437. inherits(Group, Element);
  5438. // https://github.com/mziccard/node-timsort
  5439. var DEFAULT_MIN_MERGE = 32;
  5440. var DEFAULT_MIN_GALLOPING = 7;
  5441. function minRunLength(n) {
  5442. var r = 0;
  5443. while (n >= DEFAULT_MIN_MERGE) {
  5444. r |= n & 1;
  5445. n >>= 1;
  5446. }
  5447. return n + r;
  5448. }
  5449. function makeAscendingRun(array, lo, hi, compare) {
  5450. var runHi = lo + 1;
  5451. if (runHi === hi) {
  5452. return 1;
  5453. }
  5454. if (compare(array[runHi++], array[lo]) < 0) {
  5455. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5456. runHi++;
  5457. }
  5458. reverseRun(array, lo, runHi);
  5459. }
  5460. else {
  5461. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5462. runHi++;
  5463. }
  5464. }
  5465. return runHi - lo;
  5466. }
  5467. function reverseRun(array, lo, hi) {
  5468. hi--;
  5469. while (lo < hi) {
  5470. var t = array[lo];
  5471. array[lo++] = array[hi];
  5472. array[hi--] = t;
  5473. }
  5474. }
  5475. function binaryInsertionSort(array, lo, hi, start, compare) {
  5476. if (start === lo) {
  5477. start++;
  5478. }
  5479. for (; start < hi; start++) {
  5480. var pivot = array[start];
  5481. var left = lo;
  5482. var right = start;
  5483. var mid;
  5484. while (left < right) {
  5485. mid = left + right >>> 1;
  5486. if (compare(pivot, array[mid]) < 0) {
  5487. right = mid;
  5488. }
  5489. else {
  5490. left = mid + 1;
  5491. }
  5492. }
  5493. var n = start - left;
  5494. switch (n) {
  5495. case 3:
  5496. array[left + 3] = array[left + 2];
  5497. case 2:
  5498. array[left + 2] = array[left + 1];
  5499. case 1:
  5500. array[left + 1] = array[left];
  5501. break;
  5502. default:
  5503. while (n > 0) {
  5504. array[left + n] = array[left + n - 1];
  5505. n--;
  5506. }
  5507. }
  5508. array[left] = pivot;
  5509. }
  5510. }
  5511. function gallopLeft(value, array, start, length, hint, compare) {
  5512. var lastOffset = 0;
  5513. var maxOffset = 0;
  5514. var offset = 1;
  5515. if (compare(value, array[start + hint]) > 0) {
  5516. maxOffset = length - hint;
  5517. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5518. lastOffset = offset;
  5519. offset = (offset << 1) + 1;
  5520. if (offset <= 0) {
  5521. offset = maxOffset;
  5522. }
  5523. }
  5524. if (offset > maxOffset) {
  5525. offset = maxOffset;
  5526. }
  5527. lastOffset += hint;
  5528. offset += hint;
  5529. }
  5530. else {
  5531. maxOffset = hint + 1;
  5532. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5533. lastOffset = offset;
  5534. offset = (offset << 1) + 1;
  5535. if (offset <= 0) {
  5536. offset = maxOffset;
  5537. }
  5538. }
  5539. if (offset > maxOffset) {
  5540. offset = maxOffset;
  5541. }
  5542. var tmp = lastOffset;
  5543. lastOffset = hint - offset;
  5544. offset = hint - tmp;
  5545. }
  5546. lastOffset++;
  5547. while (lastOffset < offset) {
  5548. var m = lastOffset + (offset - lastOffset >>> 1);
  5549. if (compare(value, array[start + m]) > 0) {
  5550. lastOffset = m + 1;
  5551. }
  5552. else {
  5553. offset = m;
  5554. }
  5555. }
  5556. return offset;
  5557. }
  5558. function gallopRight(value, array, start, length, hint, compare) {
  5559. var lastOffset = 0;
  5560. var maxOffset = 0;
  5561. var offset = 1;
  5562. if (compare(value, array[start + hint]) < 0) {
  5563. maxOffset = hint + 1;
  5564. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5565. lastOffset = offset;
  5566. offset = (offset << 1) + 1;
  5567. if (offset <= 0) {
  5568. offset = maxOffset;
  5569. }
  5570. }
  5571. if (offset > maxOffset) {
  5572. offset = maxOffset;
  5573. }
  5574. var tmp = lastOffset;
  5575. lastOffset = hint - offset;
  5576. offset = hint - tmp;
  5577. }
  5578. else {
  5579. maxOffset = length - hint;
  5580. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5581. lastOffset = offset;
  5582. offset = (offset << 1) + 1;
  5583. if (offset <= 0) {
  5584. offset = maxOffset;
  5585. }
  5586. }
  5587. if (offset > maxOffset) {
  5588. offset = maxOffset;
  5589. }
  5590. lastOffset += hint;
  5591. offset += hint;
  5592. }
  5593. lastOffset++;
  5594. while (lastOffset < offset) {
  5595. var m = lastOffset + (offset - lastOffset >>> 1);
  5596. if (compare(value, array[start + m]) < 0) {
  5597. offset = m;
  5598. }
  5599. else {
  5600. lastOffset = m + 1;
  5601. }
  5602. }
  5603. return offset;
  5604. }
  5605. function TimSort(array, compare) {
  5606. var minGallop = DEFAULT_MIN_GALLOPING;
  5607. var runStart;
  5608. var runLength;
  5609. var stackSize = 0;
  5610. var tmp = [];
  5611. runStart = [];
  5612. runLength = [];
  5613. function pushRun(_runStart, _runLength) {
  5614. runStart[stackSize] = _runStart;
  5615. runLength[stackSize] = _runLength;
  5616. stackSize += 1;
  5617. }
  5618. function mergeRuns() {
  5619. while (stackSize > 1) {
  5620. var n = stackSize - 2;
  5621. if (
  5622. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5623. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5624. ) {
  5625. if (runLength[n - 1] < runLength[n + 1]) {
  5626. n--;
  5627. }
  5628. }
  5629. else if (runLength[n] > runLength[n + 1]) {
  5630. break;
  5631. }
  5632. mergeAt(n);
  5633. }
  5634. }
  5635. function forceMergeRuns() {
  5636. while (stackSize > 1) {
  5637. var n = stackSize - 2;
  5638. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5639. n--;
  5640. }
  5641. mergeAt(n);
  5642. }
  5643. }
  5644. function mergeAt(i) {
  5645. var start1 = runStart[i];
  5646. var length1 = runLength[i];
  5647. var start2 = runStart[i + 1];
  5648. var length2 = runLength[i + 1];
  5649. runLength[i] = length1 + length2;
  5650. if (i === stackSize - 3) {
  5651. runStart[i + 1] = runStart[i + 2];
  5652. runLength[i + 1] = runLength[i + 2];
  5653. }
  5654. stackSize--;
  5655. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5656. start1 += k;
  5657. length1 -= k;
  5658. if (length1 === 0) {
  5659. return;
  5660. }
  5661. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5662. if (length2 === 0) {
  5663. return;
  5664. }
  5665. if (length1 <= length2) {
  5666. mergeLow(start1, length1, start2, length2);
  5667. }
  5668. else {
  5669. mergeHigh(start1, length1, start2, length2);
  5670. }
  5671. }
  5672. function mergeLow(start1, length1, start2, length2) {
  5673. var i = 0;
  5674. for (i = 0; i < length1; i++) {
  5675. tmp[i] = array[start1 + i];
  5676. }
  5677. var cursor1 = 0;
  5678. var cursor2 = start2;
  5679. var dest = start1;
  5680. array[dest++] = array[cursor2++];
  5681. if (--length2 === 0) {
  5682. for (i = 0; i < length1; i++) {
  5683. array[dest + i] = tmp[cursor1 + i];
  5684. }
  5685. return;
  5686. }
  5687. if (length1 === 1) {
  5688. for (i = 0; i < length2; i++) {
  5689. array[dest + i] = array[cursor2 + i];
  5690. }
  5691. array[dest + length2] = tmp[cursor1];
  5692. return;
  5693. }
  5694. var _minGallop = minGallop;
  5695. var count1;
  5696. var count2;
  5697. var exit;
  5698. while (1) {
  5699. count1 = 0;
  5700. count2 = 0;
  5701. exit = false;
  5702. do {
  5703. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5704. array[dest++] = array[cursor2++];
  5705. count2++;
  5706. count1 = 0;
  5707. if (--length2 === 0) {
  5708. exit = true;
  5709. break;
  5710. }
  5711. }
  5712. else {
  5713. array[dest++] = tmp[cursor1++];
  5714. count1++;
  5715. count2 = 0;
  5716. if (--length1 === 1) {
  5717. exit = true;
  5718. break;
  5719. }
  5720. }
  5721. } while ((count1 | count2) < _minGallop);
  5722. if (exit) {
  5723. break;
  5724. }
  5725. do {
  5726. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5727. if (count1 !== 0) {
  5728. for (i = 0; i < count1; i++) {
  5729. array[dest + i] = tmp[cursor1 + i];
  5730. }
  5731. dest += count1;
  5732. cursor1 += count1;
  5733. length1 -= count1;
  5734. if (length1 <= 1) {
  5735. exit = true;
  5736. break;
  5737. }
  5738. }
  5739. array[dest++] = array[cursor2++];
  5740. if (--length2 === 0) {
  5741. exit = true;
  5742. break;
  5743. }
  5744. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5745. if (count2 !== 0) {
  5746. for (i = 0; i < count2; i++) {
  5747. array[dest + i] = array[cursor2 + i];
  5748. }
  5749. dest += count2;
  5750. cursor2 += count2;
  5751. length2 -= count2;
  5752. if (length2 === 0) {
  5753. exit = true;
  5754. break;
  5755. }
  5756. }
  5757. array[dest++] = tmp[cursor1++];
  5758. if (--length1 === 1) {
  5759. exit = true;
  5760. break;
  5761. }
  5762. _minGallop--;
  5763. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5764. if (exit) {
  5765. break;
  5766. }
  5767. if (_minGallop < 0) {
  5768. _minGallop = 0;
  5769. }
  5770. _minGallop += 2;
  5771. }
  5772. minGallop = _minGallop;
  5773. minGallop < 1 && (minGallop = 1);
  5774. if (length1 === 1) {
  5775. for (i = 0; i < length2; i++) {
  5776. array[dest + i] = array[cursor2 + i];
  5777. }
  5778. array[dest + length2] = tmp[cursor1];
  5779. }
  5780. else if (length1 === 0) {
  5781. throw new Error();
  5782. // throw new Error('mergeLow preconditions were not respected');
  5783. }
  5784. else {
  5785. for (i = 0; i < length1; i++) {
  5786. array[dest + i] = tmp[cursor1 + i];
  5787. }
  5788. }
  5789. }
  5790. function mergeHigh(start1, length1, start2, length2) {
  5791. var i = 0;
  5792. for (i = 0; i < length2; i++) {
  5793. tmp[i] = array[start2 + i];
  5794. }
  5795. var cursor1 = start1 + length1 - 1;
  5796. var cursor2 = length2 - 1;
  5797. var dest = start2 + length2 - 1;
  5798. var customCursor = 0;
  5799. var customDest = 0;
  5800. array[dest--] = array[cursor1--];
  5801. if (--length1 === 0) {
  5802. customCursor = dest - (length2 - 1);
  5803. for (i = 0; i < length2; i++) {
  5804. array[customCursor + i] = tmp[i];
  5805. }
  5806. return;
  5807. }
  5808. if (length2 === 1) {
  5809. dest -= length1;
  5810. cursor1 -= length1;
  5811. customDest = dest + 1;
  5812. customCursor = cursor1 + 1;
  5813. for (i = length1 - 1; i >= 0; i--) {
  5814. array[customDest + i] = array[customCursor + i];
  5815. }
  5816. array[dest] = tmp[cursor2];
  5817. return;
  5818. }
  5819. var _minGallop = minGallop;
  5820. while (true) {
  5821. var count1 = 0;
  5822. var count2 = 0;
  5823. var exit = false;
  5824. do {
  5825. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5826. array[dest--] = array[cursor1--];
  5827. count1++;
  5828. count2 = 0;
  5829. if (--length1 === 0) {
  5830. exit = true;
  5831. break;
  5832. }
  5833. }
  5834. else {
  5835. array[dest--] = tmp[cursor2--];
  5836. count2++;
  5837. count1 = 0;
  5838. if (--length2 === 1) {
  5839. exit = true;
  5840. break;
  5841. }
  5842. }
  5843. } while ((count1 | count2) < _minGallop);
  5844. if (exit) {
  5845. break;
  5846. }
  5847. do {
  5848. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5849. if (count1 !== 0) {
  5850. dest -= count1;
  5851. cursor1 -= count1;
  5852. length1 -= count1;
  5853. customDest = dest + 1;
  5854. customCursor = cursor1 + 1;
  5855. for (i = count1 - 1; i >= 0; i--) {
  5856. array[customDest + i] = array[customCursor + i];
  5857. }
  5858. if (length1 === 0) {
  5859. exit = true;
  5860. break;
  5861. }
  5862. }
  5863. array[dest--] = tmp[cursor2--];
  5864. if (--length2 === 1) {
  5865. exit = true;
  5866. break;
  5867. }
  5868. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5869. if (count2 !== 0) {
  5870. dest -= count2;
  5871. cursor2 -= count2;
  5872. length2 -= count2;
  5873. customDest = dest + 1;
  5874. customCursor = cursor2 + 1;
  5875. for (i = 0; i < count2; i++) {
  5876. array[customDest + i] = tmp[customCursor + i];
  5877. }
  5878. if (length2 <= 1) {
  5879. exit = true;
  5880. break;
  5881. }
  5882. }
  5883. array[dest--] = array[cursor1--];
  5884. if (--length1 === 0) {
  5885. exit = true;
  5886. break;
  5887. }
  5888. _minGallop--;
  5889. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5890. if (exit) {
  5891. break;
  5892. }
  5893. if (_minGallop < 0) {
  5894. _minGallop = 0;
  5895. }
  5896. _minGallop += 2;
  5897. }
  5898. minGallop = _minGallop;
  5899. if (minGallop < 1) {
  5900. minGallop = 1;
  5901. }
  5902. if (length2 === 1) {
  5903. dest -= length1;
  5904. cursor1 -= length1;
  5905. customDest = dest + 1;
  5906. customCursor = cursor1 + 1;
  5907. for (i = length1 - 1; i >= 0; i--) {
  5908. array[customDest + i] = array[customCursor + i];
  5909. }
  5910. array[dest] = tmp[cursor2];
  5911. }
  5912. else if (length2 === 0) {
  5913. throw new Error();
  5914. // throw new Error('mergeHigh preconditions were not respected');
  5915. }
  5916. else {
  5917. customCursor = dest - (length2 - 1);
  5918. for (i = 0; i < length2; i++) {
  5919. array[customCursor + i] = tmp[i];
  5920. }
  5921. }
  5922. }
  5923. this.mergeRuns = mergeRuns;
  5924. this.forceMergeRuns = forceMergeRuns;
  5925. this.pushRun = pushRun;
  5926. }
  5927. function sort(array, compare, lo, hi) {
  5928. if (!lo) {
  5929. lo = 0;
  5930. }
  5931. if (!hi) {
  5932. hi = array.length;
  5933. }
  5934. var remaining = hi - lo;
  5935. if (remaining < 2) {
  5936. return;
  5937. }
  5938. var runLength = 0;
  5939. if (remaining < DEFAULT_MIN_MERGE) {
  5940. runLength = makeAscendingRun(array, lo, hi, compare);
  5941. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5942. return;
  5943. }
  5944. var ts = new TimSort(array, compare);
  5945. var minRun = minRunLength(remaining);
  5946. do {
  5947. runLength = makeAscendingRun(array, lo, hi, compare);
  5948. if (runLength < minRun) {
  5949. var force = remaining;
  5950. if (force > minRun) {
  5951. force = minRun;
  5952. }
  5953. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5954. runLength = force;
  5955. }
  5956. ts.pushRun(lo, runLength);
  5957. ts.mergeRuns();
  5958. remaining -= runLength;
  5959. lo += runLength;
  5960. } while (remaining !== 0);
  5961. ts.forceMergeRuns();
  5962. }
  5963. // Use timsort because in most case elements are partially sorted
  5964. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5965. function shapeCompareFunc(a, b) {
  5966. if (a.zlevel === b.zlevel) {
  5967. if (a.z === b.z) {
  5968. // if (a.z2 === b.z2) {
  5969. // // FIXME Slow has renderidx compare
  5970. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5971. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5972. // return a.__renderidx - b.__renderidx;
  5973. // }
  5974. return a.z2 - b.z2;
  5975. }
  5976. return a.z - b.z;
  5977. }
  5978. return a.zlevel - b.zlevel;
  5979. }
  5980. /**
  5981. * 内容仓库 (M)
  5982. * @alias module:zrender/Storage
  5983. * @constructor
  5984. */
  5985. var Storage = function () { // jshint ignore:line
  5986. this._roots = [];
  5987. this._displayList = [];
  5988. this._displayListLen = 0;
  5989. };
  5990. Storage.prototype = {
  5991. constructor: Storage,
  5992. /**
  5993. * @param {Function} cb
  5994. *
  5995. */
  5996. traverse: function (cb, context) {
  5997. for (var i = 0; i < this._roots.length; i++) {
  5998. this._roots[i].traverse(cb, context);
  5999. }
  6000. },
  6001. /**
  6002. * 返回所有图形的绘制队列
  6003. * @param {boolean} [update=false] 是否在返回前更新该数组
  6004. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  6005. *
  6006. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  6007. * @return {Array.<module:zrender/graphic/Displayable>}
  6008. */
  6009. getDisplayList: function (update, includeIgnore) {
  6010. includeIgnore = includeIgnore || false;
  6011. if (update) {
  6012. this.updateDisplayList(includeIgnore);
  6013. }
  6014. return this._displayList;
  6015. },
  6016. /**
  6017. * 更新图形的绘制队列。
  6018. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  6019. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  6020. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  6021. */
  6022. updateDisplayList: function (includeIgnore) {
  6023. this._displayListLen = 0;
  6024. var roots = this._roots;
  6025. var displayList = this._displayList;
  6026. for (var i = 0, len = roots.length; i < len; i++) {
  6027. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  6028. }
  6029. displayList.length = this._displayListLen;
  6030. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  6031. },
  6032. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  6033. if (el.ignore && !includeIgnore) {
  6034. return;
  6035. }
  6036. el.beforeUpdate();
  6037. if (el.__dirty) {
  6038. el.update();
  6039. }
  6040. el.afterUpdate();
  6041. var userSetClipPath = el.clipPath;
  6042. if (userSetClipPath) {
  6043. // FIXME 效率影响
  6044. if (clipPaths) {
  6045. clipPaths = clipPaths.slice();
  6046. }
  6047. else {
  6048. clipPaths = [];
  6049. }
  6050. var currentClipPath = userSetClipPath;
  6051. var parentClipPath = el;
  6052. // Recursively add clip path
  6053. while (currentClipPath) {
  6054. // clipPath 的变换是基于使用这个 clipPath 的元素
  6055. currentClipPath.parent = parentClipPath;
  6056. currentClipPath.updateTransform();
  6057. clipPaths.push(currentClipPath);
  6058. parentClipPath = currentClipPath;
  6059. currentClipPath = currentClipPath.clipPath;
  6060. }
  6061. }
  6062. if (el.isGroup) {
  6063. var children = el._children;
  6064. for (var i = 0; i < children.length; i++) {
  6065. var child = children[i];
  6066. // Force to mark as dirty if group is dirty
  6067. // FIXME __dirtyPath ?
  6068. if (el.__dirty) {
  6069. child.__dirty = true;
  6070. }
  6071. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  6072. }
  6073. // Mark group clean here
  6074. el.__dirty = false;
  6075. }
  6076. else {
  6077. el.__clipPaths = clipPaths;
  6078. this._displayList[this._displayListLen++] = el;
  6079. }
  6080. },
  6081. /**
  6082. * 添加图形(Shape)或者组(Group)到根节点
  6083. * @param {module:zrender/Element} el
  6084. */
  6085. addRoot: function (el) {
  6086. if (el.__storage === this) {
  6087. return;
  6088. }
  6089. if (el instanceof Group) {
  6090. el.addChildrenToStorage(this);
  6091. }
  6092. this.addToStorage(el);
  6093. this._roots.push(el);
  6094. },
  6095. /**
  6096. * 删除指定的图形(Shape)或者组(Group)
  6097. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  6098. */
  6099. delRoot: function (el) {
  6100. if (el == null) {
  6101. // 不指定el清空
  6102. for (var i = 0; i < this._roots.length; i++) {
  6103. var root = this._roots[i];
  6104. if (root instanceof Group) {
  6105. root.delChildrenFromStorage(this);
  6106. }
  6107. }
  6108. this._roots = [];
  6109. this._displayList = [];
  6110. this._displayListLen = 0;
  6111. return;
  6112. }
  6113. if (el instanceof Array) {
  6114. for (var i = 0, l = el.length; i < l; i++) {
  6115. this.delRoot(el[i]);
  6116. }
  6117. return;
  6118. }
  6119. var idx = indexOf(this._roots, el);
  6120. if (idx >= 0) {
  6121. this.delFromStorage(el);
  6122. this._roots.splice(idx, 1);
  6123. if (el instanceof Group) {
  6124. el.delChildrenFromStorage(this);
  6125. }
  6126. }
  6127. },
  6128. addToStorage: function (el) {
  6129. if (el) {
  6130. el.__storage = this;
  6131. el.dirty(false);
  6132. }
  6133. return this;
  6134. },
  6135. delFromStorage: function (el) {
  6136. if (el) {
  6137. el.__storage = null;
  6138. }
  6139. return this;
  6140. },
  6141. /**
  6142. * 清空并且释放Storage
  6143. */
  6144. dispose: function () {
  6145. this._renderList =
  6146. this._roots = null;
  6147. },
  6148. displayableSortFunc: shapeCompareFunc
  6149. };
  6150. var SHADOW_PROPS = {
  6151. 'shadowBlur': 1,
  6152. 'shadowOffsetX': 1,
  6153. 'shadowOffsetY': 1,
  6154. 'textShadowBlur': 1,
  6155. 'textShadowOffsetX': 1,
  6156. 'textShadowOffsetY': 1,
  6157. 'textBoxShadowBlur': 1,
  6158. 'textBoxShadowOffsetX': 1,
  6159. 'textBoxShadowOffsetY': 1
  6160. };
  6161. var fixShadow = function (ctx, propName, value) {
  6162. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6163. return value *= ctx.dpr;
  6164. }
  6165. return value;
  6166. };
  6167. var ContextCachedBy = {
  6168. NONE: 0,
  6169. STYLE_BIND: 1,
  6170. PLAIN_TEXT: 2
  6171. };
  6172. // Avoid confused with 0/false.
  6173. var WILL_BE_RESTORED = 9;
  6174. var STYLE_COMMON_PROPS = [
  6175. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6176. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6177. ];
  6178. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6179. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6180. var Style = function (opts) {
  6181. this.extendFrom(opts, false);
  6182. };
  6183. function createLinearGradient(ctx, obj, rect) {
  6184. var x = obj.x == null ? 0 : obj.x;
  6185. var x2 = obj.x2 == null ? 1 : obj.x2;
  6186. var y = obj.y == null ? 0 : obj.y;
  6187. var y2 = obj.y2 == null ? 0 : obj.y2;
  6188. if (!obj.global) {
  6189. x = x * rect.width + rect.x;
  6190. x2 = x2 * rect.width + rect.x;
  6191. y = y * rect.height + rect.y;
  6192. y2 = y2 * rect.height + rect.y;
  6193. }
  6194. // Fix NaN when rect is Infinity
  6195. x = isNaN(x) ? 0 : x;
  6196. x2 = isNaN(x2) ? 1 : x2;
  6197. y = isNaN(y) ? 0 : y;
  6198. y2 = isNaN(y2) ? 0 : y2;
  6199. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6200. return canvasGradient;
  6201. }
  6202. function createRadialGradient(ctx, obj, rect) {
  6203. var width = rect.width;
  6204. var height = rect.height;
  6205. var min = Math.min(width, height);
  6206. var x = obj.x == null ? 0.5 : obj.x;
  6207. var y = obj.y == null ? 0.5 : obj.y;
  6208. var r = obj.r == null ? 0.5 : obj.r;
  6209. if (!obj.global) {
  6210. x = x * width + rect.x;
  6211. y = y * height + rect.y;
  6212. r = r * min;
  6213. }
  6214. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6215. return canvasGradient;
  6216. }
  6217. Style.prototype = {
  6218. constructor: Style,
  6219. /**
  6220. * @type {string}
  6221. */
  6222. fill: '#000',
  6223. /**
  6224. * @type {string}
  6225. */
  6226. stroke: null,
  6227. /**
  6228. * @type {number}
  6229. */
  6230. opacity: 1,
  6231. /**
  6232. * @type {number}
  6233. */
  6234. fillOpacity: null,
  6235. /**
  6236. * @type {number}
  6237. */
  6238. strokeOpacity: null,
  6239. /**
  6240. * `true` is not supported.
  6241. * `false`/`null`/`undefined` are the same.
  6242. * `false` is used to remove lineDash in some
  6243. * case that `null`/`undefined` can not be set.
  6244. * (e.g., emphasis.lineStyle in echarts)
  6245. * @type {Array.<number>|boolean}
  6246. */
  6247. lineDash: null,
  6248. /**
  6249. * @type {number}
  6250. */
  6251. lineDashOffset: 0,
  6252. /**
  6253. * @type {number}
  6254. */
  6255. shadowBlur: 0,
  6256. /**
  6257. * @type {number}
  6258. */
  6259. shadowOffsetX: 0,
  6260. /**
  6261. * @type {number}
  6262. */
  6263. shadowOffsetY: 0,
  6264. /**
  6265. * @type {number}
  6266. */
  6267. lineWidth: 1,
  6268. /**
  6269. * If stroke ignore scale
  6270. * @type {Boolean}
  6271. */
  6272. strokeNoScale: false,
  6273. // Bounding rect text configuration
  6274. // Not affected by element transform
  6275. /**
  6276. * @type {string}
  6277. */
  6278. text: null,
  6279. /**
  6280. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6281. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6282. * So do not visit it directly in upper application (like echarts),
  6283. * but use `contain/text#makeFont` instead.
  6284. * @type {string}
  6285. */
  6286. font: null,
  6287. /**
  6288. * The same as font. Use font please.
  6289. * @deprecated
  6290. * @type {string}
  6291. */
  6292. textFont: null,
  6293. /**
  6294. * It helps merging respectively, rather than parsing an entire font string.
  6295. * @type {string}
  6296. */
  6297. fontStyle: null,
  6298. /**
  6299. * It helps merging respectively, rather than parsing an entire font string.
  6300. * @type {string}
  6301. */
  6302. fontWeight: null,
  6303. /**
  6304. * It helps merging respectively, rather than parsing an entire font string.
  6305. * Should be 12 but not '12px'.
  6306. * @type {number}
  6307. */
  6308. fontSize: null,
  6309. /**
  6310. * It helps merging respectively, rather than parsing an entire font string.
  6311. * @type {string}
  6312. */
  6313. fontFamily: null,
  6314. /**
  6315. * Reserved for special functinality, like 'hr'.
  6316. * @type {string}
  6317. */
  6318. textTag: null,
  6319. /**
  6320. * @type {string}
  6321. */
  6322. textFill: '#000',
  6323. /**
  6324. * @type {string}
  6325. */
  6326. textStroke: null,
  6327. /**
  6328. * @type {number}
  6329. */
  6330. textWidth: null,
  6331. /**
  6332. * Only for textBackground.
  6333. * @type {number}
  6334. */
  6335. textHeight: null,
  6336. /**
  6337. * textStroke may be set as some color as a default
  6338. * value in upper applicaion, where the default value
  6339. * of textStrokeWidth should be 0 to make sure that
  6340. * user can choose to do not use text stroke.
  6341. * @type {number}
  6342. */
  6343. textStrokeWidth: 0,
  6344. /**
  6345. * @type {number}
  6346. */
  6347. textLineHeight: null,
  6348. /**
  6349. * 'inside', 'left', 'right', 'top', 'bottom'
  6350. * [x, y]
  6351. * Based on x, y of rect.
  6352. * @type {string|Array.<number>}
  6353. * @default 'inside'
  6354. */
  6355. textPosition: 'inside',
  6356. /**
  6357. * If not specified, use the boundingRect of a `displayable`.
  6358. * @type {Object}
  6359. */
  6360. textRect: null,
  6361. /**
  6362. * [x, y]
  6363. * @type {Array.<number>}
  6364. */
  6365. textOffset: null,
  6366. /**
  6367. * @type {string}
  6368. */
  6369. textAlign: null,
  6370. /**
  6371. * @type {string}
  6372. */
  6373. textVerticalAlign: null,
  6374. /**
  6375. * @type {number}
  6376. */
  6377. textDistance: 5,
  6378. /**
  6379. * @type {string}
  6380. */
  6381. textShadowColor: 'transparent',
  6382. /**
  6383. * @type {number}
  6384. */
  6385. textShadowBlur: 0,
  6386. /**
  6387. * @type {number}
  6388. */
  6389. textShadowOffsetX: 0,
  6390. /**
  6391. * @type {number}
  6392. */
  6393. textShadowOffsetY: 0,
  6394. /**
  6395. * @type {string}
  6396. */
  6397. textBoxShadowColor: 'transparent',
  6398. /**
  6399. * @type {number}
  6400. */
  6401. textBoxShadowBlur: 0,
  6402. /**
  6403. * @type {number}
  6404. */
  6405. textBoxShadowOffsetX: 0,
  6406. /**
  6407. * @type {number}
  6408. */
  6409. textBoxShadowOffsetY: 0,
  6410. /**
  6411. * Whether transform text.
  6412. * Only available in Path and Image element,
  6413. * where the text is called as `RectText`.
  6414. * @type {boolean}
  6415. */
  6416. transformText: false,
  6417. /**
  6418. * Text rotate around position of Path or Image.
  6419. * The origin of the rotation can be specified by `textOrigin`.
  6420. * Only available in Path and Image element,
  6421. * where the text is called as `RectText`.
  6422. */
  6423. textRotation: 0,
  6424. /**
  6425. * Text origin of text rotation.
  6426. * Useful in the case like label rotation of circular symbol.
  6427. * Only available in Path and Image element, where the text is called
  6428. * as `RectText` and the element is called as "host element".
  6429. * The value can be:
  6430. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6431. * base on the left-top corner of the rect of its host element.
  6432. * + If specified as a string `center`, it is the center of the rect of
  6433. * its host element.
  6434. * + By default, this origin is the `textPosition`.
  6435. * @type {string|Array.<number>}
  6436. */
  6437. textOrigin: null,
  6438. /**
  6439. * @type {string}
  6440. */
  6441. textBackgroundColor: null,
  6442. /**
  6443. * @type {string}
  6444. */
  6445. textBorderColor: null,
  6446. /**
  6447. * @type {number}
  6448. */
  6449. textBorderWidth: 0,
  6450. /**
  6451. * @type {number}
  6452. */
  6453. textBorderRadius: 0,
  6454. /**
  6455. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6456. * @type {number|Array.<number>}
  6457. */
  6458. textPadding: null,
  6459. /**
  6460. * Text styles for rich text.
  6461. * @type {Object}
  6462. */
  6463. rich: null,
  6464. /**
  6465. * {outerWidth, outerHeight, ellipsis, placeholder}
  6466. * @type {Object}
  6467. */
  6468. truncate: null,
  6469. /**
  6470. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6471. * @type {string}
  6472. */
  6473. blend: null,
  6474. /**
  6475. * @param {CanvasRenderingContext2D} ctx
  6476. */
  6477. bind: function (ctx, el, prevEl) {
  6478. var style = this;
  6479. var prevStyle = prevEl && prevEl.style;
  6480. // If no prevStyle, it means first draw.
  6481. // Only apply cache if the last time cachced by this function.
  6482. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6483. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6484. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6485. var prop = STYLE_COMMON_PROPS[i];
  6486. var styleName = prop[0];
  6487. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6488. // FIXME Invalid property value will cause style leak from previous element.
  6489. ctx[styleName] =
  6490. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6491. }
  6492. }
  6493. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6494. ctx.fillStyle = style.fill;
  6495. }
  6496. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6497. ctx.strokeStyle = style.stroke;
  6498. }
  6499. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6500. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6501. }
  6502. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6503. ctx.globalCompositeOperation = style.blend || 'source-over';
  6504. }
  6505. if (this.hasStroke()) {
  6506. var lineWidth = style.lineWidth;
  6507. ctx.lineWidth = lineWidth / (
  6508. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6509. );
  6510. }
  6511. },
  6512. hasFill: function () {
  6513. var fill = this.fill;
  6514. return fill != null && fill !== 'none';
  6515. },
  6516. hasStroke: function () {
  6517. var stroke = this.stroke;
  6518. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6519. },
  6520. /**
  6521. * Extend from other style
  6522. * @param {zrender/graphic/Style} otherStyle
  6523. * @param {boolean} overwrite true: overwrirte any way.
  6524. * false: overwrite only when !target.hasOwnProperty
  6525. * others: overwrite when property is not null/undefined.
  6526. */
  6527. extendFrom: function (otherStyle, overwrite) {
  6528. if (otherStyle) {
  6529. for (var name in otherStyle) {
  6530. if (otherStyle.hasOwnProperty(name)
  6531. && (overwrite === true
  6532. || (
  6533. overwrite === false
  6534. ? !this.hasOwnProperty(name)
  6535. : otherStyle[name] != null
  6536. )
  6537. )
  6538. ) {
  6539. this[name] = otherStyle[name];
  6540. }
  6541. }
  6542. }
  6543. },
  6544. /**
  6545. * Batch setting style with a given object
  6546. * @param {Object|string} obj
  6547. * @param {*} [obj]
  6548. */
  6549. set: function (obj, value) {
  6550. if (typeof obj === 'string') {
  6551. this[obj] = value;
  6552. }
  6553. else {
  6554. this.extendFrom(obj, true);
  6555. }
  6556. },
  6557. /**
  6558. * Clone
  6559. * @return {zrender/graphic/Style} [description]
  6560. */
  6561. clone: function () {
  6562. var newStyle = new this.constructor();
  6563. newStyle.extendFrom(this, true);
  6564. return newStyle;
  6565. },
  6566. getGradient: function (ctx, obj, rect) {
  6567. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6568. var canvasGradient = method(ctx, obj, rect);
  6569. var colorStops = obj.colorStops;
  6570. for (var i = 0; i < colorStops.length; i++) {
  6571. canvasGradient.addColorStop(
  6572. colorStops[i].offset, colorStops[i].color
  6573. );
  6574. }
  6575. return canvasGradient;
  6576. }
  6577. };
  6578. var styleProto = Style.prototype;
  6579. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6580. var prop = STYLE_COMMON_PROPS[i];
  6581. if (!(prop[0] in styleProto)) {
  6582. styleProto[prop[0]] = prop[1];
  6583. }
  6584. }
  6585. // Provide for others
  6586. Style.getGradient = styleProto.getGradient;
  6587. var Pattern = function (image, repeat) {
  6588. // Should do nothing more in this constructor. Because gradient can be
  6589. // declard by `color: {image: ...}`, where this constructor will not be called.
  6590. this.image = image;
  6591. this.repeat = repeat;
  6592. // Can be cloned
  6593. this.type = 'pattern';
  6594. };
  6595. Pattern.prototype.getCanvasPattern = function (ctx) {
  6596. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6597. };
  6598. /**
  6599. * @module zrender/Layer
  6600. * @author pissang(https://www.github.com/pissang)
  6601. */
  6602. function returnFalse() {
  6603. return false;
  6604. }
  6605. /**
  6606. * 创建dom
  6607. *
  6608. * @inner
  6609. * @param {string} id dom id 待用
  6610. * @param {Painter} painter painter instance
  6611. * @param {number} number
  6612. */
  6613. function createDom(id, painter, dpr) {
  6614. var newDom = createCanvas();
  6615. var width = painter.getWidth();
  6616. var height = painter.getHeight();
  6617. var newDomStyle = newDom.style;
  6618. if (newDomStyle) { // In node or some other non-browser environment
  6619. newDomStyle.position = 'absolute';
  6620. newDomStyle.left = 0;
  6621. newDomStyle.top = 0;
  6622. newDomStyle.width = width + 'px';
  6623. newDomStyle.height = height + 'px';
  6624. newDom.setAttribute('data-zr-dom-id', id);
  6625. }
  6626. newDom.width = width * dpr;
  6627. newDom.height = height * dpr;
  6628. return newDom;
  6629. }
  6630. /**
  6631. * @alias module:zrender/Layer
  6632. * @constructor
  6633. * @extends module:zrender/mixin/Transformable
  6634. * @param {string} id
  6635. * @param {module:zrender/Painter} painter
  6636. * @param {number} [dpr]
  6637. */
  6638. var Layer = function (id, painter, dpr) {
  6639. var dom;
  6640. dpr = dpr || devicePixelRatio;
  6641. if (typeof id === 'string') {
  6642. dom = createDom(id, painter, dpr);
  6643. }
  6644. // Not using isDom because in node it will return false
  6645. else if (isObject$1(id)) {
  6646. dom = id;
  6647. id = dom.id;
  6648. }
  6649. this.id = id;
  6650. this.dom = dom;
  6651. var domStyle = dom.style;
  6652. if (domStyle) { // Not in node
  6653. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6654. domStyle['-webkit-user-select'] = 'none';
  6655. domStyle['user-select'] = 'none';
  6656. domStyle['-webkit-touch-callout'] = 'none';
  6657. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6658. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6659. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6660. domStyle['border-width'] = 0;
  6661. }
  6662. this.domBack = null;
  6663. this.ctxBack = null;
  6664. this.painter = painter;
  6665. this.config = null;
  6666. // Configs
  6667. /**
  6668. * 每次清空画布的颜色
  6669. * @type {string}
  6670. * @default 0
  6671. */
  6672. this.clearColor = 0;
  6673. /**
  6674. * 是否开启动态模糊
  6675. * @type {boolean}
  6676. * @default false
  6677. */
  6678. this.motionBlur = false;
  6679. /**
  6680. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6681. * @type {number}
  6682. * @default 0.7
  6683. */
  6684. this.lastFrameAlpha = 0.7;
  6685. /**
  6686. * Layer dpr
  6687. * @type {number}
  6688. */
  6689. this.dpr = dpr;
  6690. };
  6691. Layer.prototype = {
  6692. constructor: Layer,
  6693. __dirty: true,
  6694. __used: false,
  6695. __drawIndex: 0,
  6696. __startIndex: 0,
  6697. __endIndex: 0,
  6698. incremental: false,
  6699. getElementCount: function () {
  6700. return this.__endIndex - this.__startIndex;
  6701. },
  6702. initContext: function () {
  6703. this.ctx = this.dom.getContext('2d');
  6704. this.ctx.dpr = this.dpr;
  6705. },
  6706. createBackBuffer: function () {
  6707. var dpr = this.dpr;
  6708. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6709. this.ctxBack = this.domBack.getContext('2d');
  6710. if (dpr !== 1) {
  6711. this.ctxBack.scale(dpr, dpr);
  6712. }
  6713. },
  6714. /**
  6715. * @param {number} width
  6716. * @param {number} height
  6717. */
  6718. resize: function (width, height) {
  6719. var dpr = this.dpr;
  6720. var dom = this.dom;
  6721. var domStyle = dom.style;
  6722. var domBack = this.domBack;
  6723. if (domStyle) {
  6724. domStyle.width = width + 'px';
  6725. domStyle.height = height + 'px';
  6726. }
  6727. dom.width = width * dpr;
  6728. dom.height = height * dpr;
  6729. if (domBack) {
  6730. domBack.width = width * dpr;
  6731. domBack.height = height * dpr;
  6732. if (dpr !== 1) {
  6733. this.ctxBack.scale(dpr, dpr);
  6734. }
  6735. }
  6736. },
  6737. /**
  6738. * 清空该层画布
  6739. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6740. * @param {Color} [clearColor]
  6741. */
  6742. clear: function (clearAll, clearColor) {
  6743. var dom = this.dom;
  6744. var ctx = this.ctx;
  6745. var width = dom.width;
  6746. var height = dom.height;
  6747. var clearColor = clearColor || this.clearColor;
  6748. var haveMotionBLur = this.motionBlur && !clearAll;
  6749. var lastFrameAlpha = this.lastFrameAlpha;
  6750. var dpr = this.dpr;
  6751. if (haveMotionBLur) {
  6752. if (!this.domBack) {
  6753. this.createBackBuffer();
  6754. }
  6755. this.ctxBack.globalCompositeOperation = 'copy';
  6756. this.ctxBack.drawImage(
  6757. dom, 0, 0,
  6758. width / dpr,
  6759. height / dpr
  6760. );
  6761. }
  6762. ctx.clearRect(0, 0, width, height);
  6763. if (clearColor && clearColor !== 'transparent') {
  6764. var clearColorGradientOrPattern;
  6765. // Gradient
  6766. if (clearColor.colorStops) {
  6767. // Cache canvas gradient
  6768. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6769. x: 0,
  6770. y: 0,
  6771. width: width,
  6772. height: height
  6773. });
  6774. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6775. }
  6776. // Pattern
  6777. else if (clearColor.image) {
  6778. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6779. }
  6780. ctx.save();
  6781. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6782. ctx.fillRect(0, 0, width, height);
  6783. ctx.restore();
  6784. }
  6785. if (haveMotionBLur) {
  6786. var domBack = this.domBack;
  6787. ctx.save();
  6788. ctx.globalAlpha = lastFrameAlpha;
  6789. ctx.drawImage(domBack, 0, 0, width, height);
  6790. ctx.restore();
  6791. }
  6792. }
  6793. };
  6794. var requestAnimationFrame = (
  6795. typeof window !== 'undefined'
  6796. && (
  6797. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6798. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6799. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6800. || window.mozRequestAnimationFrame
  6801. || window.webkitRequestAnimationFrame
  6802. )
  6803. ) || function (func) {
  6804. setTimeout(func, 16);
  6805. };
  6806. var globalImageCache = new LRU(50);
  6807. /**
  6808. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6809. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6810. */
  6811. function findExistImage(newImageOrSrc) {
  6812. if (typeof newImageOrSrc === 'string') {
  6813. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6814. return cachedImgObj && cachedImgObj.image;
  6815. }
  6816. else {
  6817. return newImageOrSrc;
  6818. }
  6819. }
  6820. /**
  6821. * Caution: User should cache loaded images, but not just count on LRU.
  6822. * Consider if required images more than LRU size, will dead loop occur?
  6823. *
  6824. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6825. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6826. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6827. * @param {Function} [cb] params: (image, cbPayload)
  6828. * @param {Object} [cbPayload] Payload on cb calling.
  6829. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6830. */
  6831. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6832. if (!newImageOrSrc) {
  6833. return image;
  6834. }
  6835. else if (typeof newImageOrSrc === 'string') {
  6836. // Image should not be loaded repeatly.
  6837. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6838. return image;
  6839. }
  6840. // Only when there is no existent image or existent image src
  6841. // is different, this method is responsible for load.
  6842. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6843. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6844. if (cachedImgObj) {
  6845. image = cachedImgObj.image;
  6846. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6847. }
  6848. else {
  6849. image = new Image();
  6850. image.onload = image.onerror = imageOnLoad;
  6851. globalImageCache.put(
  6852. newImageOrSrc,
  6853. image.__cachedImgObj = {
  6854. image: image,
  6855. pending: [pendingWrap]
  6856. }
  6857. );
  6858. image.src = image.__zrImageSrc = newImageOrSrc;
  6859. }
  6860. return image;
  6861. }
  6862. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6863. else {
  6864. return newImageOrSrc;
  6865. }
  6866. }
  6867. function imageOnLoad() {
  6868. var cachedImgObj = this.__cachedImgObj;
  6869. this.onload = this.onerror = this.__cachedImgObj = null;
  6870. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6871. var pendingWrap = cachedImgObj.pending[i];
  6872. var cb = pendingWrap.cb;
  6873. cb && cb(this, pendingWrap.cbPayload);
  6874. pendingWrap.hostEl.dirty();
  6875. }
  6876. cachedImgObj.pending.length = 0;
  6877. }
  6878. function isImageReady(image) {
  6879. return image && image.width && image.height;
  6880. }
  6881. var textWidthCache = {};
  6882. var textWidthCacheCounter = 0;
  6883. var TEXT_CACHE_MAX = 5000;
  6884. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6885. var DEFAULT_FONT$1 = '12px sans-serif';
  6886. // Avoid assign to an exported variable, for transforming to cjs.
  6887. var methods$1 = {};
  6888. function $override$1(name, fn) {
  6889. methods$1[name] = fn;
  6890. }
  6891. /**
  6892. * @public
  6893. * @param {string} text
  6894. * @param {string} font
  6895. * @return {number} width
  6896. */
  6897. function getWidth(text, font) {
  6898. font = font || DEFAULT_FONT$1;
  6899. var key = text + ':' + font;
  6900. if (textWidthCache[key]) {
  6901. return textWidthCache[key];
  6902. }
  6903. var textLines = (text + '').split('\n');
  6904. var width = 0;
  6905. for (var i = 0, l = textLines.length; i < l; i++) {
  6906. // textContain.measureText may be overrided in SVG or VML
  6907. width = Math.max(measureText(textLines[i], font).width, width);
  6908. }
  6909. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6910. textWidthCacheCounter = 0;
  6911. textWidthCache = {};
  6912. }
  6913. textWidthCacheCounter++;
  6914. textWidthCache[key] = width;
  6915. return width;
  6916. }
  6917. /**
  6918. * @public
  6919. * @param {string} text
  6920. * @param {string} font
  6921. * @param {string} [textAlign='left']
  6922. * @param {string} [textVerticalAlign='top']
  6923. * @param {Array.<number>} [textPadding]
  6924. * @param {Object} [rich]
  6925. * @param {Object} [truncate]
  6926. * @return {Object} {x, y, width, height, lineHeight}
  6927. */
  6928. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6929. return rich
  6930. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6931. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6932. }
  6933. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6934. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6935. var outerWidth = getWidth(text, font);
  6936. if (textPadding) {
  6937. outerWidth += textPadding[1] + textPadding[3];
  6938. }
  6939. var outerHeight = contentBlock.outerHeight;
  6940. var x = adjustTextX(0, outerWidth, textAlign);
  6941. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6942. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6943. rect.lineHeight = contentBlock.lineHeight;
  6944. return rect;
  6945. }
  6946. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6947. var contentBlock = parseRichText(text, {
  6948. rich: rich,
  6949. truncate: truncate,
  6950. font: font,
  6951. textAlign: textAlign,
  6952. textPadding: textPadding,
  6953. textLineHeight: textLineHeight
  6954. });
  6955. var outerWidth = contentBlock.outerWidth;
  6956. var outerHeight = contentBlock.outerHeight;
  6957. var x = adjustTextX(0, outerWidth, textAlign);
  6958. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6959. return new BoundingRect(x, y, outerWidth, outerHeight);
  6960. }
  6961. /**
  6962. * @public
  6963. * @param {number} x
  6964. * @param {number} width
  6965. * @param {string} [textAlign='left']
  6966. * @return {number} Adjusted x.
  6967. */
  6968. function adjustTextX(x, width, textAlign) {
  6969. // FIXME Right to left language
  6970. if (textAlign === 'right') {
  6971. x -= width;
  6972. }
  6973. else if (textAlign === 'center') {
  6974. x -= width / 2;
  6975. }
  6976. return x;
  6977. }
  6978. /**
  6979. * @public
  6980. * @param {number} y
  6981. * @param {number} height
  6982. * @param {string} [textVerticalAlign='top']
  6983. * @return {number} Adjusted y.
  6984. */
  6985. function adjustTextY(y, height, textVerticalAlign) {
  6986. if (textVerticalAlign === 'middle') {
  6987. y -= height / 2;
  6988. }
  6989. else if (textVerticalAlign === 'bottom') {
  6990. y -= height;
  6991. }
  6992. return y;
  6993. }
  6994. /**
  6995. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6996. * @public
  6997. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6998. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6999. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  7000. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  7001. */
  7002. function calculateTextPosition(out, style, rect) {
  7003. var textPosition = style.textPosition;
  7004. var distance = style.textDistance;
  7005. var x = rect.x;
  7006. var y = rect.y;
  7007. distance = distance || 0;
  7008. var height = rect.height;
  7009. var width = rect.width;
  7010. var halfHeight = height / 2;
  7011. var textAlign = 'left';
  7012. var textVerticalAlign = 'top';
  7013. switch (textPosition) {
  7014. case 'left':
  7015. x -= distance;
  7016. y += halfHeight;
  7017. textAlign = 'right';
  7018. textVerticalAlign = 'middle';
  7019. break;
  7020. case 'right':
  7021. x += distance + width;
  7022. y += halfHeight;
  7023. textVerticalAlign = 'middle';
  7024. break;
  7025. case 'top':
  7026. x += width / 2;
  7027. y -= distance;
  7028. textAlign = 'center';
  7029. textVerticalAlign = 'bottom';
  7030. break;
  7031. case 'bottom':
  7032. x += width / 2;
  7033. y += height + distance;
  7034. textAlign = 'center';
  7035. break;
  7036. case 'inside':
  7037. x += width / 2;
  7038. y += halfHeight;
  7039. textAlign = 'center';
  7040. textVerticalAlign = 'middle';
  7041. break;
  7042. case 'insideLeft':
  7043. x += distance;
  7044. y += halfHeight;
  7045. textVerticalAlign = 'middle';
  7046. break;
  7047. case 'insideRight':
  7048. x += width - distance;
  7049. y += halfHeight;
  7050. textAlign = 'right';
  7051. textVerticalAlign = 'middle';
  7052. break;
  7053. case 'insideTop':
  7054. x += width / 2;
  7055. y += distance;
  7056. textAlign = 'center';
  7057. break;
  7058. case 'insideBottom':
  7059. x += width / 2;
  7060. y += height - distance;
  7061. textAlign = 'center';
  7062. textVerticalAlign = 'bottom';
  7063. break;
  7064. case 'insideTopLeft':
  7065. x += distance;
  7066. y += distance;
  7067. break;
  7068. case 'insideTopRight':
  7069. x += width - distance;
  7070. y += distance;
  7071. textAlign = 'right';
  7072. break;
  7073. case 'insideBottomLeft':
  7074. x += distance;
  7075. y += height - distance;
  7076. textVerticalAlign = 'bottom';
  7077. break;
  7078. case 'insideBottomRight':
  7079. x += width - distance;
  7080. y += height - distance;
  7081. textAlign = 'right';
  7082. textVerticalAlign = 'bottom';
  7083. break;
  7084. }
  7085. out = out || {};
  7086. out.x = x;
  7087. out.y = y;
  7088. out.textAlign = textAlign;
  7089. out.textVerticalAlign = textVerticalAlign;
  7090. return out;
  7091. }
  7092. /**
  7093. * To be removed. But still do not remove in case that some one has imported it.
  7094. * @deprecated
  7095. * @public
  7096. * @param {stirng} textPosition
  7097. * @param {Object} rect {x, y, width, height}
  7098. * @param {number} distance
  7099. * @return {Object} {x, y, textAlign, textVerticalAlign}
  7100. */
  7101. /**
  7102. * Show ellipsis if overflow.
  7103. *
  7104. * @public
  7105. * @param {string} text
  7106. * @param {string} containerWidth
  7107. * @param {string} font
  7108. * @param {number} [ellipsis='...']
  7109. * @param {Object} [options]
  7110. * @param {number} [options.maxIterations=3]
  7111. * @param {number} [options.minChar=0] If truncate result are less
  7112. * then minChar, ellipsis will not show, which is
  7113. * better for user hint in some cases.
  7114. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  7115. * @return {string}
  7116. */
  7117. function truncateText(text, containerWidth, font, ellipsis, options) {
  7118. if (!containerWidth) {
  7119. return '';
  7120. }
  7121. var textLines = (text + '').split('\n');
  7122. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7123. // FIXME
  7124. // It is not appropriate that every line has '...' when truncate multiple lines.
  7125. for (var i = 0, len = textLines.length; i < len; i++) {
  7126. textLines[i] = truncateSingleLine(textLines[i], options);
  7127. }
  7128. return textLines.join('\n');
  7129. }
  7130. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7131. options = extend({}, options);
  7132. options.font = font;
  7133. var ellipsis = retrieve2(ellipsis, '...');
  7134. options.maxIterations = retrieve2(options.maxIterations, 2);
  7135. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7136. // FIXME
  7137. // Other languages?
  7138. options.cnCharWidth = getWidth('国', font);
  7139. // FIXME
  7140. // Consider proportional font?
  7141. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7142. options.placeholder = retrieve2(options.placeholder, '');
  7143. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7144. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7145. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7146. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7147. contentWidth -= ascCharWidth;
  7148. }
  7149. var ellipsisWidth = getWidth(ellipsis, font);
  7150. if (ellipsisWidth > contentWidth) {
  7151. ellipsis = '';
  7152. ellipsisWidth = 0;
  7153. }
  7154. contentWidth = containerWidth - ellipsisWidth;
  7155. options.ellipsis = ellipsis;
  7156. options.ellipsisWidth = ellipsisWidth;
  7157. options.contentWidth = contentWidth;
  7158. options.containerWidth = containerWidth;
  7159. return options;
  7160. }
  7161. function truncateSingleLine(textLine, options) {
  7162. var containerWidth = options.containerWidth;
  7163. var font = options.font;
  7164. var contentWidth = options.contentWidth;
  7165. if (!containerWidth) {
  7166. return '';
  7167. }
  7168. var lineWidth = getWidth(textLine, font);
  7169. if (lineWidth <= containerWidth) {
  7170. return textLine;
  7171. }
  7172. for (var j = 0; ; j++) {
  7173. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7174. textLine += options.ellipsis;
  7175. break;
  7176. }
  7177. var subLength = j === 0
  7178. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7179. : lineWidth > 0
  7180. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7181. : 0;
  7182. textLine = textLine.substr(0, subLength);
  7183. lineWidth = getWidth(textLine, font);
  7184. }
  7185. if (textLine === '') {
  7186. textLine = options.placeholder;
  7187. }
  7188. return textLine;
  7189. }
  7190. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7191. var width = 0;
  7192. var i = 0;
  7193. for (var len = text.length; i < len && width < contentWidth; i++) {
  7194. var charCode = text.charCodeAt(i);
  7195. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7196. }
  7197. return i;
  7198. }
  7199. /**
  7200. * @public
  7201. * @param {string} font
  7202. * @return {number} line height
  7203. */
  7204. function getLineHeight(font) {
  7205. // FIXME A rough approach.
  7206. return getWidth('国', font);
  7207. }
  7208. /**
  7209. * @public
  7210. * @param {string} text
  7211. * @param {string} font
  7212. * @return {Object} width
  7213. */
  7214. function measureText(text, font) {
  7215. return methods$1.measureText(text, font);
  7216. }
  7217. // Avoid assign to an exported variable, for transforming to cjs.
  7218. methods$1.measureText = function (text, font) {
  7219. var ctx = getContext();
  7220. ctx.font = font || DEFAULT_FONT$1;
  7221. return ctx.measureText(text);
  7222. };
  7223. /**
  7224. * @public
  7225. * @param {string} text
  7226. * @param {string} font
  7227. * @param {Object} [truncate]
  7228. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7229. * Notice: for performance, do not calculate outerWidth util needed.
  7230. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7231. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7232. * without travel the result `lines`.
  7233. */
  7234. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7235. text != null && (text += '');
  7236. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7237. var lines = text ? text.split('\n') : [];
  7238. var height = lines.length * lineHeight;
  7239. var outerHeight = height;
  7240. var canCacheByTextString = true;
  7241. if (padding) {
  7242. outerHeight += padding[0] + padding[2];
  7243. }
  7244. if (text && truncate) {
  7245. canCacheByTextString = false;
  7246. var truncOuterHeight = truncate.outerHeight;
  7247. var truncOuterWidth = truncate.outerWidth;
  7248. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7249. text = '';
  7250. lines = [];
  7251. }
  7252. else if (truncOuterWidth != null) {
  7253. var options = prepareTruncateOptions(
  7254. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7255. font,
  7256. truncate.ellipsis,
  7257. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7258. );
  7259. // FIXME
  7260. // It is not appropriate that every line has '...' when truncate multiple lines.
  7261. for (var i = 0, len = lines.length; i < len; i++) {
  7262. lines[i] = truncateSingleLine(lines[i], options);
  7263. }
  7264. }
  7265. }
  7266. return {
  7267. lines: lines,
  7268. height: height,
  7269. outerHeight: outerHeight,
  7270. lineHeight: lineHeight,
  7271. canCacheByTextString: canCacheByTextString
  7272. };
  7273. }
  7274. /**
  7275. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7276. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7277. *
  7278. * @public
  7279. * @param {string} text
  7280. * @param {Object} style
  7281. * @return {Object} block
  7282. * {
  7283. * width,
  7284. * height,
  7285. * lines: [{
  7286. * lineHeight,
  7287. * width,
  7288. * tokens: [[{
  7289. * styleName,
  7290. * text,
  7291. * width, // include textPadding
  7292. * height, // include textPadding
  7293. * textWidth, // pure text width
  7294. * textHeight, // pure text height
  7295. * lineHeihgt,
  7296. * font,
  7297. * textAlign,
  7298. * textVerticalAlign
  7299. * }], [...], ...]
  7300. * }, ...]
  7301. * }
  7302. * If styleName is undefined, it is plain text.
  7303. */
  7304. function parseRichText(text, style) {
  7305. var contentBlock = {lines: [], width: 0, height: 0};
  7306. text != null && (text += '');
  7307. if (!text) {
  7308. return contentBlock;
  7309. }
  7310. var lastIndex = STYLE_REG.lastIndex = 0;
  7311. var result;
  7312. while ((result = STYLE_REG.exec(text)) != null) {
  7313. var matchedIndex = result.index;
  7314. if (matchedIndex > lastIndex) {
  7315. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7316. }
  7317. pushTokens(contentBlock, result[2], result[1]);
  7318. lastIndex = STYLE_REG.lastIndex;
  7319. }
  7320. if (lastIndex < text.length) {
  7321. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7322. }
  7323. var lines = contentBlock.lines;
  7324. var contentHeight = 0;
  7325. var contentWidth = 0;
  7326. // For `textWidth: 100%`
  7327. var pendingList = [];
  7328. var stlPadding = style.textPadding;
  7329. var truncate = style.truncate;
  7330. var truncateWidth = truncate && truncate.outerWidth;
  7331. var truncateHeight = truncate && truncate.outerHeight;
  7332. if (stlPadding) {
  7333. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7334. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7335. }
  7336. // Calculate layout info of tokens.
  7337. for (var i = 0; i < lines.length; i++) {
  7338. var line = lines[i];
  7339. var lineHeight = 0;
  7340. var lineWidth = 0;
  7341. for (var j = 0; j < line.tokens.length; j++) {
  7342. var token = line.tokens[j];
  7343. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7344. // textPadding should not inherit from style.
  7345. var textPadding = token.textPadding = tokenStyle.textPadding;
  7346. // textFont has been asigned to font by `normalizeStyle`.
  7347. var font = token.font = tokenStyle.font || style.font;
  7348. // textHeight can be used when textVerticalAlign is specified in token.
  7349. var tokenHeight = token.textHeight = retrieve2(
  7350. // textHeight should not be inherited, consider it can be specified
  7351. // as box height of the block.
  7352. tokenStyle.textHeight, getLineHeight(font)
  7353. );
  7354. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7355. token.height = tokenHeight;
  7356. token.lineHeight = retrieve3(
  7357. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7358. );
  7359. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7360. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7361. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7362. return {lines: [], width: 0, height: 0};
  7363. }
  7364. token.textWidth = getWidth(token.text, font);
  7365. var tokenWidth = tokenStyle.textWidth;
  7366. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7367. // Percent width, can be `100%`, can be used in drawing separate
  7368. // line when box width is needed to be auto.
  7369. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7370. token.percentWidth = tokenWidth;
  7371. pendingList.push(token);
  7372. tokenWidth = 0;
  7373. // Do not truncate in this case, because there is no user case
  7374. // and it is too complicated.
  7375. }
  7376. else {
  7377. if (tokenWidthNotSpecified) {
  7378. tokenWidth = token.textWidth;
  7379. // FIXME: If image is not loaded and textWidth is not specified, calling
  7380. // `getBoundingRect()` will not get correct result.
  7381. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7382. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7383. // Use cases:
  7384. // (1) If image is not loaded, it will be loaded at render phase and call
  7385. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7386. // image, and then the right size will be calculated here at the next tick.
  7387. // See `graphic/helper/text.js`.
  7388. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7389. // use `imageHelper.findExistImage` to find cached image.
  7390. // `imageHelper.findExistImage` will always be called here before
  7391. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7392. // which ensures that image will not be rendered before correct size calcualted.
  7393. if (bgImg) {
  7394. bgImg = findExistImage(bgImg);
  7395. if (isImageReady(bgImg)) {
  7396. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7397. }
  7398. }
  7399. }
  7400. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7401. tokenWidth += paddingW;
  7402. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7403. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7404. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7405. token.text = '';
  7406. token.textWidth = tokenWidth = 0;
  7407. }
  7408. else {
  7409. token.text = truncateText(
  7410. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7411. {minChar: truncate.minChar}
  7412. );
  7413. token.textWidth = getWidth(token.text, font);
  7414. tokenWidth = token.textWidth + paddingW;
  7415. }
  7416. }
  7417. }
  7418. lineWidth += (token.width = tokenWidth);
  7419. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7420. }
  7421. line.width = lineWidth;
  7422. line.lineHeight = lineHeight;
  7423. contentHeight += lineHeight;
  7424. contentWidth = Math.max(contentWidth, lineWidth);
  7425. }
  7426. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7427. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7428. if (stlPadding) {
  7429. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7430. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7431. }
  7432. for (var i = 0; i < pendingList.length; i++) {
  7433. var token = pendingList[i];
  7434. var percentWidth = token.percentWidth;
  7435. // Should not base on outerWidth, because token can not be placed out of padding.
  7436. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7437. }
  7438. return contentBlock;
  7439. }
  7440. function pushTokens(block, str, styleName) {
  7441. var isEmptyStr = str === '';
  7442. var strs = str.split('\n');
  7443. var lines = block.lines;
  7444. for (var i = 0; i < strs.length; i++) {
  7445. var text = strs[i];
  7446. var token = {
  7447. styleName: styleName,
  7448. text: text,
  7449. isLineHolder: !text && !isEmptyStr
  7450. };
  7451. // The first token should be appended to the last line.
  7452. if (!i) {
  7453. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7454. // Consider cases:
  7455. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7456. // (which is a placeholder) should be replaced by new token.
  7457. // (2) A image backage, where token likes {a|}.
  7458. // (3) A redundant '' will affect textAlign in line.
  7459. // (4) tokens with the same tplName should not be merged, because
  7460. // they should be displayed in different box (with border and padding).
  7461. var tokensLen = tokens.length;
  7462. (tokensLen === 1 && tokens[0].isLineHolder)
  7463. ? (tokens[0] = token)
  7464. // Consider text is '', only insert when it is the "lineHolder" or
  7465. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7466. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7467. }
  7468. // Other tokens always start a new line.
  7469. else {
  7470. // If there is '', insert it as a placeholder.
  7471. lines.push({tokens: [token]});
  7472. }
  7473. }
  7474. }
  7475. function makeFont(style) {
  7476. // FIXME in node-canvas fontWeight is before fontStyle
  7477. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7478. var font = (style.fontSize || style.fontFamily) && [
  7479. style.fontStyle,
  7480. style.fontWeight,
  7481. (style.fontSize || 12) + 'px',
  7482. // If font properties are defined, `fontFamily` should not be ignored.
  7483. style.fontFamily || 'sans-serif'
  7484. ].join(' ');
  7485. return font && trim(font) || style.textFont || style.font;
  7486. }
  7487. /**
  7488. * @param {Object} ctx
  7489. * @param {Object} shape
  7490. * @param {number} shape.x
  7491. * @param {number} shape.y
  7492. * @param {number} shape.width
  7493. * @param {number} shape.height
  7494. * @param {number} shape.r
  7495. */
  7496. function buildPath(ctx, shape) {
  7497. var x = shape.x;
  7498. var y = shape.y;
  7499. var width = shape.width;
  7500. var height = shape.height;
  7501. var r = shape.r;
  7502. var r1;
  7503. var r2;
  7504. var r3;
  7505. var r4;
  7506. // Convert width and height to positive for better borderRadius
  7507. if (width < 0) {
  7508. x = x + width;
  7509. width = -width;
  7510. }
  7511. if (height < 0) {
  7512. y = y + height;
  7513. height = -height;
  7514. }
  7515. if (typeof r === 'number') {
  7516. r1 = r2 = r3 = r4 = r;
  7517. }
  7518. else if (r instanceof Array) {
  7519. if (r.length === 1) {
  7520. r1 = r2 = r3 = r4 = r[0];
  7521. }
  7522. else if (r.length === 2) {
  7523. r1 = r3 = r[0];
  7524. r2 = r4 = r[1];
  7525. }
  7526. else if (r.length === 3) {
  7527. r1 = r[0];
  7528. r2 = r4 = r[1];
  7529. r3 = r[2];
  7530. }
  7531. else {
  7532. r1 = r[0];
  7533. r2 = r[1];
  7534. r3 = r[2];
  7535. r4 = r[3];
  7536. }
  7537. }
  7538. else {
  7539. r1 = r2 = r3 = r4 = 0;
  7540. }
  7541. var total;
  7542. if (r1 + r2 > width) {
  7543. total = r1 + r2;
  7544. r1 *= width / total;
  7545. r2 *= width / total;
  7546. }
  7547. if (r3 + r4 > width) {
  7548. total = r3 + r4;
  7549. r3 *= width / total;
  7550. r4 *= width / total;
  7551. }
  7552. if (r2 + r3 > height) {
  7553. total = r2 + r3;
  7554. r2 *= height / total;
  7555. r3 *= height / total;
  7556. }
  7557. if (r1 + r4 > height) {
  7558. total = r1 + r4;
  7559. r1 *= height / total;
  7560. r4 *= height / total;
  7561. }
  7562. ctx.moveTo(x + r1, y);
  7563. ctx.lineTo(x + width - r2, y);
  7564. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7565. ctx.lineTo(x + width, y + height - r3);
  7566. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7567. ctx.lineTo(x + r4, y + height);
  7568. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7569. ctx.lineTo(x, y + r1);
  7570. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7571. }
  7572. var DEFAULT_FONT = DEFAULT_FONT$1;
  7573. // TODO: Have not support 'start', 'end' yet.
  7574. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7575. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7576. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7577. // the default value of shadowColor is `'transparent'`.
  7578. var SHADOW_STYLE_COMMON_PROPS = [
  7579. ['textShadowBlur', 'shadowBlur', 0],
  7580. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7581. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7582. ['textShadowColor', 'shadowColor', 'transparent']
  7583. ];
  7584. var _tmpTextPositionResult = {};
  7585. var _tmpBoxPositionResult = {};
  7586. /**
  7587. * @param {module:zrender/graphic/Style} style
  7588. * @return {module:zrender/graphic/Style} The input style.
  7589. */
  7590. function normalizeTextStyle(style) {
  7591. normalizeStyle(style);
  7592. each$1(style.rich, normalizeStyle);
  7593. return style;
  7594. }
  7595. function normalizeStyle(style) {
  7596. if (style) {
  7597. style.font = makeFont(style);
  7598. var textAlign = style.textAlign;
  7599. textAlign === 'middle' && (textAlign = 'center');
  7600. style.textAlign = (
  7601. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7602. ) ? textAlign : 'left';
  7603. // Compatible with textBaseline.
  7604. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7605. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7606. style.textVerticalAlign = (
  7607. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7608. ) ? textVerticalAlign : 'top';
  7609. var textPadding = style.textPadding;
  7610. if (textPadding) {
  7611. style.textPadding = normalizeCssArray(style.textPadding);
  7612. }
  7613. }
  7614. }
  7615. /**
  7616. * @param {CanvasRenderingContext2D} ctx
  7617. * @param {string} text
  7618. * @param {module:zrender/graphic/Style} style
  7619. * @param {Object|boolean} [rect] {x, y, width, height}
  7620. * If set false, rect text is not used.
  7621. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7622. */
  7623. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7624. style.rich
  7625. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7626. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7627. }
  7628. // Avoid setting to ctx according to prevEl if possible for
  7629. // performance in scenarios of large amount text.
  7630. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7631. 'use strict';
  7632. var needDrawBg = needDrawBackground(style);
  7633. var prevStyle;
  7634. var checkCache = false;
  7635. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7636. // Only take and check cache for `Text` el, but not RectText.
  7637. if (prevEl !== WILL_BE_RESTORED) {
  7638. if (prevEl) {
  7639. prevStyle = prevEl.style;
  7640. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7641. }
  7642. // Prevent from using cache in `Style::bind`, because of the case:
  7643. // ctx property is modified by other properties than `Style::bind`
  7644. // used, and Style::bind is called next.
  7645. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7646. }
  7647. // Since this will be restored, prevent from using these props to check cache in the next
  7648. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7649. else if (cachedByMe) {
  7650. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7651. }
  7652. var styleFont = style.font || DEFAULT_FONT;
  7653. // PENDING
  7654. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7655. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7656. // But layer save/restore needed to be considered.
  7657. // if (styleFont !== ctx.__fontCache) {
  7658. // ctx.font = styleFont;
  7659. // if (prevEl !== WILL_BE_RESTORED) {
  7660. // ctx.__fontCache = styleFont;
  7661. // }
  7662. // }
  7663. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7664. ctx.font = styleFont;
  7665. }
  7666. // Use the final font from context-2d, because the final
  7667. // font might not be the style.font when it is illegal.
  7668. // But get `ctx.font` might be time consuming.
  7669. var computedFont = hostEl.__computedFont;
  7670. if (hostEl.__styleFont !== styleFont) {
  7671. hostEl.__styleFont = styleFont;
  7672. computedFont = hostEl.__computedFont = ctx.font;
  7673. }
  7674. var textPadding = style.textPadding;
  7675. var textLineHeight = style.textLineHeight;
  7676. var contentBlock = hostEl.__textCotentBlock;
  7677. if (!contentBlock || hostEl.__dirtyText) {
  7678. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7679. text, computedFont, textPadding, textLineHeight, style.truncate
  7680. );
  7681. }
  7682. var outerHeight = contentBlock.outerHeight;
  7683. var textLines = contentBlock.lines;
  7684. var lineHeight = contentBlock.lineHeight;
  7685. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7686. var baseX = boxPos.baseX;
  7687. var baseY = boxPos.baseY;
  7688. var textAlign = boxPos.textAlign || 'left';
  7689. var textVerticalAlign = boxPos.textVerticalAlign;
  7690. // Origin of textRotation should be the base point of text drawing.
  7691. applyTextRotation(ctx, style, rect, baseX, baseY);
  7692. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7693. var textX = baseX;
  7694. var textY = boxY;
  7695. if (needDrawBg || textPadding) {
  7696. // Consider performance, do not call getTextWidth util necessary.
  7697. var textWidth = getWidth(text, computedFont);
  7698. var outerWidth = textWidth;
  7699. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7700. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7701. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7702. if (textPadding) {
  7703. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7704. textY += textPadding[0];
  7705. }
  7706. }
  7707. // Always set textAlign and textBase line, because it is difficute to calculate
  7708. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7709. // font set happened.
  7710. ctx.textAlign = textAlign;
  7711. // Force baseline to be "middle". Otherwise, if using "top", the
  7712. // text will offset downward a little bit in font "Microsoft YaHei".
  7713. ctx.textBaseline = 'middle';
  7714. // Set text opacity
  7715. ctx.globalAlpha = style.opacity || 1;
  7716. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7717. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7718. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7719. var styleProp = propItem[0];
  7720. var ctxProp = propItem[1];
  7721. var val = style[styleProp];
  7722. if (!checkCache || val !== prevStyle[styleProp]) {
  7723. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7724. }
  7725. }
  7726. // `textBaseline` is set as 'middle'.
  7727. textY += lineHeight / 2;
  7728. var textStrokeWidth = style.textStrokeWidth;
  7729. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7730. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7731. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7732. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7733. var textFill = getFill(style.textFill);
  7734. if (textStroke) {
  7735. if (strokeWidthChanged) {
  7736. ctx.lineWidth = textStrokeWidth;
  7737. }
  7738. if (strokeChanged) {
  7739. ctx.strokeStyle = textStroke;
  7740. }
  7741. }
  7742. if (textFill) {
  7743. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7744. ctx.fillStyle = textFill;
  7745. }
  7746. }
  7747. // Optimize simply, in most cases only one line exists.
  7748. if (textLines.length === 1) {
  7749. // Fill after stroke so the outline will not cover the main part.
  7750. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7751. textFill && ctx.fillText(textLines[0], textX, textY);
  7752. }
  7753. else {
  7754. for (var i = 0; i < textLines.length; i++) {
  7755. // Fill after stroke so the outline will not cover the main part.
  7756. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7757. textFill && ctx.fillText(textLines[i], textX, textY);
  7758. textY += lineHeight;
  7759. }
  7760. }
  7761. }
  7762. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7763. // Do not do cache for rich text because of the complexity.
  7764. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7765. if (prevEl !== WILL_BE_RESTORED) {
  7766. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7767. }
  7768. var contentBlock = hostEl.__textCotentBlock;
  7769. if (!contentBlock || hostEl.__dirtyText) {
  7770. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7771. }
  7772. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7773. }
  7774. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7775. var contentWidth = contentBlock.width;
  7776. var outerWidth = contentBlock.outerWidth;
  7777. var outerHeight = contentBlock.outerHeight;
  7778. var textPadding = style.textPadding;
  7779. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7780. var baseX = boxPos.baseX;
  7781. var baseY = boxPos.baseY;
  7782. var textAlign = boxPos.textAlign;
  7783. var textVerticalAlign = boxPos.textVerticalAlign;
  7784. // Origin of textRotation should be the base point of text drawing.
  7785. applyTextRotation(ctx, style, rect, baseX, baseY);
  7786. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7787. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7788. var xLeft = boxX;
  7789. var lineTop = boxY;
  7790. if (textPadding) {
  7791. xLeft += textPadding[3];
  7792. lineTop += textPadding[0];
  7793. }
  7794. var xRight = xLeft + contentWidth;
  7795. needDrawBackground(style) && drawBackground(
  7796. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7797. );
  7798. for (var i = 0; i < contentBlock.lines.length; i++) {
  7799. var line = contentBlock.lines[i];
  7800. var tokens = line.tokens;
  7801. var tokenCount = tokens.length;
  7802. var lineHeight = line.lineHeight;
  7803. var usedWidth = line.width;
  7804. var leftIndex = 0;
  7805. var lineXLeft = xLeft;
  7806. var lineXRight = xRight;
  7807. var rightIndex = tokenCount - 1;
  7808. var token;
  7809. while (
  7810. leftIndex < tokenCount
  7811. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7812. ) {
  7813. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7814. usedWidth -= token.width;
  7815. lineXLeft += token.width;
  7816. leftIndex++;
  7817. }
  7818. while (
  7819. rightIndex >= 0
  7820. && (token = tokens[rightIndex], token.textAlign === 'right')
  7821. ) {
  7822. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7823. usedWidth -= token.width;
  7824. lineXRight -= token.width;
  7825. rightIndex--;
  7826. }
  7827. // The other tokens are placed as textAlign 'center' if there is enough space.
  7828. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7829. while (leftIndex <= rightIndex) {
  7830. token = tokens[leftIndex];
  7831. // Consider width specified by user, use 'center' rather than 'left'.
  7832. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7833. lineXLeft += token.width;
  7834. leftIndex++;
  7835. }
  7836. lineTop += lineHeight;
  7837. }
  7838. }
  7839. function applyTextRotation(ctx, style, rect, x, y) {
  7840. // textRotation only apply in RectText.
  7841. if (rect && style.textRotation) {
  7842. var origin = style.textOrigin;
  7843. if (origin === 'center') {
  7844. x = rect.width / 2 + rect.x;
  7845. y = rect.height / 2 + rect.y;
  7846. }
  7847. else if (origin) {
  7848. x = origin[0] + rect.x;
  7849. y = origin[1] + rect.y;
  7850. }
  7851. ctx.translate(x, y);
  7852. // Positive: anticlockwise
  7853. ctx.rotate(-style.textRotation);
  7854. ctx.translate(-x, -y);
  7855. }
  7856. }
  7857. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7858. var tokenStyle = style.rich[token.styleName] || {};
  7859. tokenStyle.text = token.text;
  7860. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7861. // the bias of "Microsoft YaHei".
  7862. var textVerticalAlign = token.textVerticalAlign;
  7863. var y = lineTop + lineHeight / 2;
  7864. if (textVerticalAlign === 'top') {
  7865. y = lineTop + token.height / 2;
  7866. }
  7867. else if (textVerticalAlign === 'bottom') {
  7868. y = lineTop + lineHeight - token.height / 2;
  7869. }
  7870. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7871. hostEl,
  7872. ctx,
  7873. tokenStyle,
  7874. textAlign === 'right'
  7875. ? x - token.width
  7876. : textAlign === 'center'
  7877. ? x - token.width / 2
  7878. : x,
  7879. y - token.height / 2,
  7880. token.width,
  7881. token.height
  7882. );
  7883. var textPadding = token.textPadding;
  7884. if (textPadding) {
  7885. x = getTextXForPadding(x, textAlign, textPadding);
  7886. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7887. }
  7888. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7889. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7890. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7891. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7892. setCtx(ctx, 'textAlign', textAlign);
  7893. // Force baseline to be "middle". Otherwise, if using "top", the
  7894. // text will offset downward a little bit in font "Microsoft YaHei".
  7895. setCtx(ctx, 'textBaseline', 'middle');
  7896. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7897. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7898. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7899. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7900. // Fill after stroke so the outline will not cover the main part.
  7901. if (textStroke) {
  7902. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7903. setCtx(ctx, 'strokeStyle', textStroke);
  7904. ctx.strokeText(token.text, x, y);
  7905. }
  7906. if (textFill) {
  7907. setCtx(ctx, 'fillStyle', textFill);
  7908. ctx.fillText(token.text, x, y);
  7909. }
  7910. }
  7911. function needDrawBackground(style) {
  7912. return !!(
  7913. style.textBackgroundColor
  7914. || (style.textBorderWidth && style.textBorderColor)
  7915. );
  7916. }
  7917. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7918. // shape: {x, y, width, height}
  7919. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7920. var textBackgroundColor = style.textBackgroundColor;
  7921. var textBorderWidth = style.textBorderWidth;
  7922. var textBorderColor = style.textBorderColor;
  7923. var isPlainBg = isString(textBackgroundColor);
  7924. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7925. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7926. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7927. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7928. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7929. ctx.beginPath();
  7930. var textBorderRadius = style.textBorderRadius;
  7931. if (!textBorderRadius) {
  7932. ctx.rect(x, y, width, height);
  7933. }
  7934. else {
  7935. buildPath(ctx, {
  7936. x: x, y: y, width: width, height: height, r: textBorderRadius
  7937. });
  7938. }
  7939. ctx.closePath();
  7940. }
  7941. if (isPlainBg) {
  7942. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7943. if (style.fillOpacity != null) {
  7944. var originalGlobalAlpha = ctx.globalAlpha;
  7945. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7946. ctx.fill();
  7947. ctx.globalAlpha = originalGlobalAlpha;
  7948. }
  7949. else {
  7950. ctx.fill();
  7951. }
  7952. }
  7953. else if (isObject$1(textBackgroundColor)) {
  7954. var image = textBackgroundColor.image;
  7955. image = createOrUpdateImage(
  7956. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7957. );
  7958. if (image && isImageReady(image)) {
  7959. ctx.drawImage(image, x, y, width, height);
  7960. }
  7961. }
  7962. if (textBorderWidth && textBorderColor) {
  7963. setCtx(ctx, 'lineWidth', textBorderWidth);
  7964. setCtx(ctx, 'strokeStyle', textBorderColor);
  7965. if (style.strokeOpacity != null) {
  7966. var originalGlobalAlpha = ctx.globalAlpha;
  7967. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7968. ctx.stroke();
  7969. ctx.globalAlpha = originalGlobalAlpha;
  7970. }
  7971. else {
  7972. ctx.stroke();
  7973. }
  7974. }
  7975. }
  7976. function onBgImageLoaded(image, textBackgroundColor) {
  7977. // Replace image, so that `contain/text.js#parseRichText`
  7978. // will get correct result in next tick.
  7979. textBackgroundColor.image = image;
  7980. }
  7981. function getBoxPosition(out, hostEl, style, rect) {
  7982. var baseX = style.x || 0;
  7983. var baseY = style.y || 0;
  7984. var textAlign = style.textAlign;
  7985. var textVerticalAlign = style.textVerticalAlign;
  7986. // Text position represented by coord
  7987. if (rect) {
  7988. var textPosition = style.textPosition;
  7989. if (textPosition instanceof Array) {
  7990. // Percent
  7991. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7992. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7993. }
  7994. else {
  7995. var res = (hostEl && hostEl.calculateTextPosition)
  7996. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7997. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7998. baseX = res.x;
  7999. baseY = res.y;
  8000. // Default align and baseline when has textPosition
  8001. textAlign = textAlign || res.textAlign;
  8002. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  8003. }
  8004. // textOffset is only support in RectText, otherwise
  8005. // we have to adjust boundingRect for textOffset.
  8006. var textOffset = style.textOffset;
  8007. if (textOffset) {
  8008. baseX += textOffset[0];
  8009. baseY += textOffset[1];
  8010. }
  8011. }
  8012. out = out || {};
  8013. out.baseX = baseX;
  8014. out.baseY = baseY;
  8015. out.textAlign = textAlign;
  8016. out.textVerticalAlign = textVerticalAlign;
  8017. return out;
  8018. }
  8019. function setCtx(ctx, prop, value) {
  8020. ctx[prop] = fixShadow(ctx, prop, value);
  8021. return ctx[prop];
  8022. }
  8023. /**
  8024. * @param {string} [stroke] If specified, do not check style.textStroke.
  8025. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  8026. * @param {number} style
  8027. */
  8028. function getStroke(stroke, lineWidth) {
  8029. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  8030. ? null
  8031. // TODO pattern and gradient?
  8032. : (stroke.image || stroke.colorStops)
  8033. ? '#000'
  8034. : stroke;
  8035. }
  8036. function getFill(fill) {
  8037. return (fill == null || fill === 'none')
  8038. ? null
  8039. // TODO pattern and gradient?
  8040. : (fill.image || fill.colorStops)
  8041. ? '#000'
  8042. : fill;
  8043. }
  8044. function parsePercent(value, maxValue) {
  8045. if (typeof value === 'string') {
  8046. if (value.lastIndexOf('%') >= 0) {
  8047. return parseFloat(value) / 100 * maxValue;
  8048. }
  8049. return parseFloat(value);
  8050. }
  8051. return value;
  8052. }
  8053. function getTextXForPadding(x, textAlign, textPadding) {
  8054. return textAlign === 'right'
  8055. ? (x - textPadding[1])
  8056. : textAlign === 'center'
  8057. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  8058. : (x + textPadding[3]);
  8059. }
  8060. /**
  8061. * @param {string} text
  8062. * @param {module:zrender/Style} style
  8063. * @return {boolean}
  8064. */
  8065. function needDrawText(text, style) {
  8066. return text != null
  8067. && (text
  8068. || style.textBackgroundColor
  8069. || (style.textBorderWidth && style.textBorderColor)
  8070. || style.textPadding
  8071. );
  8072. }
  8073. /**
  8074. * Mixin for drawing text in a element bounding rect
  8075. * @module zrender/mixin/RectText
  8076. */
  8077. var tmpRect$1 = new BoundingRect();
  8078. var RectText = function () {};
  8079. RectText.prototype = {
  8080. constructor: RectText,
  8081. /**
  8082. * Draw text in a rect with specified position.
  8083. * @param {CanvasRenderingContext2D} ctx
  8084. * @param {Object} rect Displayable rect
  8085. */
  8086. drawRectText: function (ctx, rect) {
  8087. var style = this.style;
  8088. rect = style.textRect || rect;
  8089. // Optimize, avoid normalize every time.
  8090. this.__dirty && normalizeTextStyle(style, true);
  8091. var text = style.text;
  8092. // Convert to string
  8093. text != null && (text += '');
  8094. if (!needDrawText(text, style)) {
  8095. return;
  8096. }
  8097. // FIXME
  8098. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  8099. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  8100. // text propably break the cache for its host elements.
  8101. ctx.save();
  8102. // Transform rect to view space
  8103. var transform = this.transform;
  8104. if (!style.transformText) {
  8105. if (transform) {
  8106. tmpRect$1.copy(rect);
  8107. tmpRect$1.applyTransform(transform);
  8108. rect = tmpRect$1;
  8109. }
  8110. }
  8111. else {
  8112. this.setTransform(ctx);
  8113. }
  8114. // transformText and textRotation can not be used at the same time.
  8115. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  8116. ctx.restore();
  8117. }
  8118. };
  8119. /**
  8120. * Base class of all displayable graphic objects
  8121. * @module zrender/graphic/Displayable
  8122. */
  8123. /**
  8124. * @alias module:zrender/graphic/Displayable
  8125. * @extends module:zrender/Element
  8126. * @extends module:zrender/graphic/mixin/RectText
  8127. */
  8128. function Displayable(opts) {
  8129. opts = opts || {};
  8130. Element.call(this, opts);
  8131. // Extend properties
  8132. for (var name in opts) {
  8133. if (
  8134. opts.hasOwnProperty(name)
  8135. && name !== 'style'
  8136. ) {
  8137. this[name] = opts[name];
  8138. }
  8139. }
  8140. /**
  8141. * @type {module:zrender/graphic/Style}
  8142. */
  8143. this.style = new Style(opts.style, this);
  8144. this._rect = null;
  8145. // Shapes for cascade clipping.
  8146. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8147. // because it is easy to only using null to check whether clipPaths changed.
  8148. this.__clipPaths = null;
  8149. // FIXME Stateful must be mixined after style is setted
  8150. // Stateful.call(this, opts);
  8151. }
  8152. Displayable.prototype = {
  8153. constructor: Displayable,
  8154. type: 'displayable',
  8155. /**
  8156. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8157. * @name module:zrender/graphic/Displayable#__dirty
  8158. * @type {boolean}
  8159. */
  8160. __dirty: true,
  8161. /**
  8162. * Whether the displayable object is visible. when it is true, the displayable object
  8163. * is not drawn, but the mouse event can still trigger the object.
  8164. * @name module:/zrender/graphic/Displayable#invisible
  8165. * @type {boolean}
  8166. * @default false
  8167. */
  8168. invisible: false,
  8169. /**
  8170. * @name module:/zrender/graphic/Displayable#z
  8171. * @type {number}
  8172. * @default 0
  8173. */
  8174. z: 0,
  8175. /**
  8176. * @name module:/zrender/graphic/Displayable#z
  8177. * @type {number}
  8178. * @default 0
  8179. */
  8180. z2: 0,
  8181. /**
  8182. * The z level determines the displayable object can be drawn in which layer canvas.
  8183. * @name module:/zrender/graphic/Displayable#zlevel
  8184. * @type {number}
  8185. * @default 0
  8186. */
  8187. zlevel: 0,
  8188. /**
  8189. * Whether it can be dragged.
  8190. * @name module:/zrender/graphic/Displayable#draggable
  8191. * @type {boolean}
  8192. * @default false
  8193. */
  8194. draggable: false,
  8195. /**
  8196. * Whether is it dragging.
  8197. * @name module:/zrender/graphic/Displayable#draggable
  8198. * @type {boolean}
  8199. * @default false
  8200. */
  8201. dragging: false,
  8202. /**
  8203. * Whether to respond to mouse events.
  8204. * @name module:/zrender/graphic/Displayable#silent
  8205. * @type {boolean}
  8206. * @default false
  8207. */
  8208. silent: false,
  8209. /**
  8210. * If enable culling
  8211. * @type {boolean}
  8212. * @default false
  8213. */
  8214. culling: false,
  8215. /**
  8216. * Mouse cursor when hovered
  8217. * @name module:/zrender/graphic/Displayable#cursor
  8218. * @type {string}
  8219. */
  8220. cursor: 'pointer',
  8221. /**
  8222. * If hover area is bounding rect
  8223. * @name module:/zrender/graphic/Displayable#rectHover
  8224. * @type {string}
  8225. */
  8226. rectHover: false,
  8227. /**
  8228. * Render the element progressively when the value >= 0,
  8229. * usefull for large data.
  8230. * @type {boolean}
  8231. */
  8232. progressive: false,
  8233. /**
  8234. * @type {boolean}
  8235. */
  8236. incremental: false,
  8237. /**
  8238. * Scale ratio for global scale.
  8239. * @type {boolean}
  8240. */
  8241. globalScaleRatio: 1,
  8242. beforeBrush: function (ctx) {},
  8243. afterBrush: function (ctx) {},
  8244. /**
  8245. * Graphic drawing method.
  8246. * @param {CanvasRenderingContext2D} ctx
  8247. */
  8248. // Interface
  8249. brush: function (ctx, prevEl) {},
  8250. /**
  8251. * Get the minimum bounding box.
  8252. * @return {module:zrender/core/BoundingRect}
  8253. */
  8254. // Interface
  8255. getBoundingRect: function () {},
  8256. /**
  8257. * If displayable element contain coord x, y
  8258. * @param {number} x
  8259. * @param {number} y
  8260. * @return {boolean}
  8261. */
  8262. contain: function (x, y) {
  8263. return this.rectContain(x, y);
  8264. },
  8265. /**
  8266. * @param {Function} cb
  8267. * @param {} context
  8268. */
  8269. traverse: function (cb, context) {
  8270. cb.call(context, this);
  8271. },
  8272. /**
  8273. * If bounding rect of element contain coord x, y
  8274. * @param {number} x
  8275. * @param {number} y
  8276. * @return {boolean}
  8277. */
  8278. rectContain: function (x, y) {
  8279. var coord = this.transformCoordToLocal(x, y);
  8280. var rect = this.getBoundingRect();
  8281. return rect.contain(coord[0], coord[1]);
  8282. },
  8283. /**
  8284. * Mark displayable element dirty and refresh next frame
  8285. */
  8286. dirty: function () {
  8287. this.__dirty = this.__dirtyText = true;
  8288. this._rect = null;
  8289. this.__zr && this.__zr.refresh();
  8290. },
  8291. /**
  8292. * If displayable object binded any event
  8293. * @return {boolean}
  8294. */
  8295. // TODO, events bound by bind
  8296. // isSilent: function () {
  8297. // return !(
  8298. // this.hoverable || this.draggable
  8299. // || this.onmousemove || this.onmouseover || this.onmouseout
  8300. // || this.onmousedown || this.onmouseup || this.onclick
  8301. // || this.ondragenter || this.ondragover || this.ondragleave
  8302. // || this.ondrop
  8303. // );
  8304. // },
  8305. /**
  8306. * Alias for animate('style')
  8307. * @param {boolean} loop
  8308. */
  8309. animateStyle: function (loop) {
  8310. return this.animate('style', loop);
  8311. },
  8312. attrKV: function (key, value) {
  8313. if (key !== 'style') {
  8314. Element.prototype.attrKV.call(this, key, value);
  8315. }
  8316. else {
  8317. this.style.set(value);
  8318. }
  8319. },
  8320. /**
  8321. * @param {Object|string} key
  8322. * @param {*} value
  8323. */
  8324. setStyle: function (key, value) {
  8325. this.style.set(key, value);
  8326. this.dirty(false);
  8327. return this;
  8328. },
  8329. /**
  8330. * Use given style object
  8331. * @param {Object} obj
  8332. */
  8333. useStyle: function (obj) {
  8334. this.style = new Style(obj, this);
  8335. this.dirty(false);
  8336. return this;
  8337. },
  8338. /**
  8339. * The string value of `textPosition` needs to be calculated to a real postion.
  8340. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8341. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8342. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8343. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8344. * for those shapes. It will be called if the `style.textPosition` is a string.
  8345. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8346. * be responsible for creating one.
  8347. * @param {module:zrender/graphic/Style} style
  8348. * @param {Object} rect {x, y, width, height}
  8349. * @return {Obejct} out The same as the input out.
  8350. * {
  8351. * x: number. mandatory.
  8352. * y: number. mandatory.
  8353. * textAlign: string. optional. use style.textAlign by default.
  8354. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8355. * }
  8356. */
  8357. calculateTextPosition: null
  8358. };
  8359. inherits(Displayable, Element);
  8360. mixin(Displayable, RectText);
  8361. /**
  8362. * @alias zrender/graphic/Image
  8363. * @extends module:zrender/graphic/Displayable
  8364. * @constructor
  8365. * @param {Object} opts
  8366. */
  8367. function ZImage(opts) {
  8368. Displayable.call(this, opts);
  8369. }
  8370. ZImage.prototype = {
  8371. constructor: ZImage,
  8372. type: 'image',
  8373. brush: function (ctx, prevEl) {
  8374. var style = this.style;
  8375. var src = style.image;
  8376. // Must bind each time
  8377. style.bind(ctx, this, prevEl);
  8378. var image = this._image = createOrUpdateImage(
  8379. src,
  8380. this._image,
  8381. this,
  8382. this.onload
  8383. );
  8384. if (!image || !isImageReady(image)) {
  8385. return;
  8386. }
  8387. // 图片已经加载完成
  8388. // if (image.nodeName.toUpperCase() == 'IMG') {
  8389. // if (!image.complete) {
  8390. // return;
  8391. // }
  8392. // }
  8393. // Else is canvas
  8394. var x = style.x || 0;
  8395. var y = style.y || 0;
  8396. var width = style.width;
  8397. var height = style.height;
  8398. var aspect = image.width / image.height;
  8399. if (width == null && height != null) {
  8400. // Keep image/height ratio
  8401. width = height * aspect;
  8402. }
  8403. else if (height == null && width != null) {
  8404. height = width / aspect;
  8405. }
  8406. else if (width == null && height == null) {
  8407. width = image.width;
  8408. height = image.height;
  8409. }
  8410. // 设置transform
  8411. this.setTransform(ctx);
  8412. if (style.sWidth && style.sHeight) {
  8413. var sx = style.sx || 0;
  8414. var sy = style.sy || 0;
  8415. ctx.drawImage(
  8416. image,
  8417. sx, sy, style.sWidth, style.sHeight,
  8418. x, y, width, height
  8419. );
  8420. }
  8421. else if (style.sx && style.sy) {
  8422. var sx = style.sx;
  8423. var sy = style.sy;
  8424. var sWidth = width - sx;
  8425. var sHeight = height - sy;
  8426. ctx.drawImage(
  8427. image,
  8428. sx, sy, sWidth, sHeight,
  8429. x, y, width, height
  8430. );
  8431. }
  8432. else {
  8433. ctx.drawImage(image, x, y, width, height);
  8434. }
  8435. // Draw rect text
  8436. if (style.text != null) {
  8437. // Only restore transform when needs draw text.
  8438. this.restoreTransform(ctx);
  8439. this.drawRectText(ctx, this.getBoundingRect());
  8440. }
  8441. },
  8442. getBoundingRect: function () {
  8443. var style = this.style;
  8444. if (!this._rect) {
  8445. this._rect = new BoundingRect(
  8446. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8447. );
  8448. }
  8449. return this._rect;
  8450. }
  8451. };
  8452. inherits(ZImage, Displayable);
  8453. var HOVER_LAYER_ZLEVEL = 1e5;
  8454. var CANVAS_ZLEVEL = 314159;
  8455. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8456. var INCREMENTAL_INC = 0.001;
  8457. function parseInt10(val) {
  8458. return parseInt(val, 10);
  8459. }
  8460. function isLayerValid(layer) {
  8461. if (!layer) {
  8462. return false;
  8463. }
  8464. if (layer.__builtin__) {
  8465. return true;
  8466. }
  8467. if (typeof (layer.resize) !== 'function'
  8468. || typeof (layer.refresh) !== 'function'
  8469. ) {
  8470. return false;
  8471. }
  8472. return true;
  8473. }
  8474. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8475. var viewRect = new BoundingRect(0, 0, 0, 0);
  8476. function isDisplayableCulled(el, width, height) {
  8477. tmpRect.copy(el.getBoundingRect());
  8478. if (el.transform) {
  8479. tmpRect.applyTransform(el.transform);
  8480. }
  8481. viewRect.width = width;
  8482. viewRect.height = height;
  8483. return !tmpRect.intersect(viewRect);
  8484. }
  8485. function isClipPathChanged(clipPaths, prevClipPaths) {
  8486. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8487. if (clipPaths === prevClipPaths) {
  8488. return false;
  8489. }
  8490. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8491. return true;
  8492. }
  8493. for (var i = 0; i < clipPaths.length; i++) {
  8494. if (clipPaths[i] !== prevClipPaths[i]) {
  8495. return true;
  8496. }
  8497. }
  8498. return false;
  8499. }
  8500. function doClip(clipPaths, ctx) {
  8501. for (var i = 0; i < clipPaths.length; i++) {
  8502. var clipPath = clipPaths[i];
  8503. clipPath.setTransform(ctx);
  8504. ctx.beginPath();
  8505. clipPath.buildPath(ctx, clipPath.shape);
  8506. ctx.clip();
  8507. // Transform back
  8508. clipPath.restoreTransform(ctx);
  8509. }
  8510. }
  8511. function createRoot(width, height) {
  8512. var domRoot = document.createElement('div');
  8513. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8514. domRoot.style.cssText = [
  8515. 'position:relative',
  8516. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8517. // dom does not act as expected) when some of the parent dom has
  8518. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8519. // the canvas is not at the top part of the page.
  8520. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8521. // this `overflow:hidden` to avoid the bug.
  8522. // 'overflow:hidden',
  8523. 'width:' + width + 'px',
  8524. 'height:' + height + 'px',
  8525. 'padding:0',
  8526. 'margin:0',
  8527. 'border-width:0'
  8528. ].join(';') + ';';
  8529. return domRoot;
  8530. }
  8531. /**
  8532. * @alias module:zrender/Painter
  8533. * @constructor
  8534. * @param {HTMLElement} root 绘图容器
  8535. * @param {module:zrender/Storage} storage
  8536. * @param {Object} opts
  8537. */
  8538. var Painter = function (root, storage, opts) {
  8539. this.type = 'canvas';
  8540. // In node environment using node-canvas
  8541. var singleCanvas = !root.nodeName // In node ?
  8542. || root.nodeName.toUpperCase() === 'CANVAS';
  8543. this._opts = opts = extend({}, opts || {});
  8544. /**
  8545. * @type {number}
  8546. */
  8547. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8548. /**
  8549. * @type {boolean}
  8550. * @private
  8551. */
  8552. this._singleCanvas = singleCanvas;
  8553. /**
  8554. * 绘图容器
  8555. * @type {HTMLElement}
  8556. */
  8557. this.root = root;
  8558. var rootStyle = root.style;
  8559. if (rootStyle) {
  8560. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8561. rootStyle['-webkit-user-select'] =
  8562. rootStyle['user-select'] =
  8563. rootStyle['-webkit-touch-callout'] = 'none';
  8564. root.innerHTML = '';
  8565. }
  8566. /**
  8567. * @type {module:zrender/Storage}
  8568. */
  8569. this.storage = storage;
  8570. /**
  8571. * @type {Array.<number>}
  8572. * @private
  8573. */
  8574. var zlevelList = this._zlevelList = [];
  8575. /**
  8576. * @type {Object.<string, module:zrender/Layer>}
  8577. * @private
  8578. */
  8579. var layers = this._layers = {};
  8580. /**
  8581. * @type {Object.<string, Object>}
  8582. * @private
  8583. */
  8584. this._layerConfig = {};
  8585. /**
  8586. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8587. */
  8588. this._needsManuallyCompositing = false;
  8589. if (!singleCanvas) {
  8590. this._width = this._getSize(0);
  8591. this._height = this._getSize(1);
  8592. var domRoot = this._domRoot = createRoot(
  8593. this._width, this._height
  8594. );
  8595. root.appendChild(domRoot);
  8596. }
  8597. else {
  8598. var width = root.width;
  8599. var height = root.height;
  8600. if (opts.width != null) {
  8601. width = opts.width;
  8602. }
  8603. if (opts.height != null) {
  8604. height = opts.height;
  8605. }
  8606. this.dpr = opts.devicePixelRatio || 1;
  8607. // Use canvas width and height directly
  8608. root.width = width * this.dpr;
  8609. root.height = height * this.dpr;
  8610. this._width = width;
  8611. this._height = height;
  8612. // Create layer if only one given canvas
  8613. // Device can be specified to create a high dpi image.
  8614. var mainLayer = new Layer(root, this, this.dpr);
  8615. mainLayer.__builtin__ = true;
  8616. mainLayer.initContext();
  8617. // FIXME Use canvas width and height
  8618. // mainLayer.resize(width, height);
  8619. layers[CANVAS_ZLEVEL] = mainLayer;
  8620. mainLayer.zlevel = CANVAS_ZLEVEL;
  8621. // Not use common zlevel.
  8622. zlevelList.push(CANVAS_ZLEVEL);
  8623. this._domRoot = root;
  8624. }
  8625. /**
  8626. * @type {module:zrender/Layer}
  8627. * @private
  8628. */
  8629. this._hoverlayer = null;
  8630. this._hoverElements = [];
  8631. };
  8632. Painter.prototype = {
  8633. constructor: Painter,
  8634. getType: function () {
  8635. return 'canvas';
  8636. },
  8637. /**
  8638. * If painter use a single canvas
  8639. * @return {boolean}
  8640. */
  8641. isSingleCanvas: function () {
  8642. return this._singleCanvas;
  8643. },
  8644. /**
  8645. * @return {HTMLDivElement}
  8646. */
  8647. getViewportRoot: function () {
  8648. return this._domRoot;
  8649. },
  8650. getViewportRootOffset: function () {
  8651. var viewportRoot = this.getViewportRoot();
  8652. if (viewportRoot) {
  8653. return {
  8654. offsetLeft: viewportRoot.offsetLeft || 0,
  8655. offsetTop: viewportRoot.offsetTop || 0
  8656. };
  8657. }
  8658. },
  8659. /**
  8660. * 刷新
  8661. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8662. */
  8663. refresh: function (paintAll) {
  8664. var list = this.storage.getDisplayList(true);
  8665. var zlevelList = this._zlevelList;
  8666. this._redrawId = Math.random();
  8667. this._paintList(list, paintAll, this._redrawId);
  8668. // Paint custum layers
  8669. for (var i = 0; i < zlevelList.length; i++) {
  8670. var z = zlevelList[i];
  8671. var layer = this._layers[z];
  8672. if (!layer.__builtin__ && layer.refresh) {
  8673. var clearColor = i === 0 ? this._backgroundColor : null;
  8674. layer.refresh(clearColor);
  8675. }
  8676. }
  8677. this.refreshHover();
  8678. return this;
  8679. },
  8680. addHover: function (el, hoverStyle) {
  8681. if (el.__hoverMir) {
  8682. return;
  8683. }
  8684. var elMirror = new el.constructor({
  8685. style: el.style,
  8686. shape: el.shape,
  8687. z: el.z,
  8688. z2: el.z2,
  8689. silent: el.silent
  8690. });
  8691. elMirror.__from = el;
  8692. el.__hoverMir = elMirror;
  8693. hoverStyle && elMirror.setStyle(hoverStyle);
  8694. this._hoverElements.push(elMirror);
  8695. return elMirror;
  8696. },
  8697. removeHover: function (el) {
  8698. var elMirror = el.__hoverMir;
  8699. var hoverElements = this._hoverElements;
  8700. var idx = indexOf(hoverElements, elMirror);
  8701. if (idx >= 0) {
  8702. hoverElements.splice(idx, 1);
  8703. }
  8704. el.__hoverMir = null;
  8705. },
  8706. clearHover: function (el) {
  8707. var hoverElements = this._hoverElements;
  8708. for (var i = 0; i < hoverElements.length; i++) {
  8709. var from = hoverElements[i].__from;
  8710. if (from) {
  8711. from.__hoverMir = null;
  8712. }
  8713. }
  8714. hoverElements.length = 0;
  8715. },
  8716. refreshHover: function () {
  8717. var hoverElements = this._hoverElements;
  8718. var len = hoverElements.length;
  8719. var hoverLayer = this._hoverlayer;
  8720. hoverLayer && hoverLayer.clear();
  8721. if (!len) {
  8722. return;
  8723. }
  8724. sort(hoverElements, this.storage.displayableSortFunc);
  8725. // Use a extream large zlevel
  8726. // FIXME?
  8727. if (!hoverLayer) {
  8728. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8729. }
  8730. var scope = {};
  8731. hoverLayer.ctx.save();
  8732. for (var i = 0; i < len;) {
  8733. var el = hoverElements[i];
  8734. var originalEl = el.__from;
  8735. // Original el is removed
  8736. // PENDING
  8737. if (!(originalEl && originalEl.__zr)) {
  8738. hoverElements.splice(i, 1);
  8739. originalEl.__hoverMir = null;
  8740. len--;
  8741. continue;
  8742. }
  8743. i++;
  8744. // Use transform
  8745. // FIXME style and shape ?
  8746. if (!originalEl.invisible) {
  8747. el.transform = originalEl.transform;
  8748. el.invTransform = originalEl.invTransform;
  8749. el.__clipPaths = originalEl.__clipPaths;
  8750. // el.
  8751. this._doPaintEl(el, hoverLayer, true, scope);
  8752. }
  8753. }
  8754. hoverLayer.ctx.restore();
  8755. },
  8756. getHoverLayer: function () {
  8757. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8758. },
  8759. _paintList: function (list, paintAll, redrawId) {
  8760. if (this._redrawId !== redrawId) {
  8761. return;
  8762. }
  8763. paintAll = paintAll || false;
  8764. this._updateLayerStatus(list);
  8765. var finished = this._doPaintList(list, paintAll);
  8766. if (this._needsManuallyCompositing) {
  8767. this._compositeManually();
  8768. }
  8769. if (!finished) {
  8770. var self = this;
  8771. requestAnimationFrame(function () {
  8772. self._paintList(list, paintAll, redrawId);
  8773. });
  8774. }
  8775. },
  8776. _compositeManually: function () {
  8777. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8778. var width = this._domRoot.width;
  8779. var height = this._domRoot.height;
  8780. ctx.clearRect(0, 0, width, height);
  8781. // PENDING, If only builtin layer?
  8782. this.eachBuiltinLayer(function (layer) {
  8783. if (layer.virtual) {
  8784. ctx.drawImage(layer.dom, 0, 0, width, height);
  8785. }
  8786. });
  8787. },
  8788. _doPaintList: function (list, paintAll) {
  8789. var layerList = [];
  8790. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8791. var zlevel = this._zlevelList[zi];
  8792. var layer = this._layers[zlevel];
  8793. if (layer.__builtin__
  8794. && layer !== this._hoverlayer
  8795. && (layer.__dirty || paintAll)
  8796. ) {
  8797. layerList.push(layer);
  8798. }
  8799. }
  8800. var finished = true;
  8801. for (var k = 0; k < layerList.length; k++) {
  8802. var layer = layerList[k];
  8803. var ctx = layer.ctx;
  8804. var scope = {};
  8805. ctx.save();
  8806. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8807. var useTimer = !paintAll && layer.incremental && Date.now;
  8808. var startTime = useTimer && Date.now();
  8809. var clearColor = layer.zlevel === this._zlevelList[0]
  8810. ? this._backgroundColor : null;
  8811. // All elements in this layer are cleared.
  8812. if (layer.__startIndex === layer.__endIndex) {
  8813. layer.clear(false, clearColor);
  8814. }
  8815. else if (start === layer.__startIndex) {
  8816. var firstEl = list[start];
  8817. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8818. layer.clear(false, clearColor);
  8819. }
  8820. }
  8821. if (start === -1) {
  8822. console.error('For some unknown reason. drawIndex is -1');
  8823. start = layer.__startIndex;
  8824. }
  8825. for (var i = start; i < layer.__endIndex; i++) {
  8826. var el = list[i];
  8827. this._doPaintEl(el, layer, paintAll, scope);
  8828. el.__dirty = el.__dirtyText = false;
  8829. if (useTimer) {
  8830. // Date.now can be executed in 13,025,305 ops/second.
  8831. var dTime = Date.now() - startTime;
  8832. // Give 15 millisecond to draw.
  8833. // The rest elements will be drawn in the next frame.
  8834. if (dTime > 15) {
  8835. break;
  8836. }
  8837. }
  8838. }
  8839. layer.__drawIndex = i;
  8840. if (layer.__drawIndex < layer.__endIndex) {
  8841. finished = false;
  8842. }
  8843. if (scope.prevElClipPaths) {
  8844. // Needs restore the state. If last drawn element is in the clipping area.
  8845. ctx.restore();
  8846. }
  8847. ctx.restore();
  8848. }
  8849. if (env$1.wxa) {
  8850. // Flush for weixin application
  8851. each$1(this._layers, function (layer) {
  8852. if (layer && layer.ctx && layer.ctx.draw) {
  8853. layer.ctx.draw();
  8854. }
  8855. });
  8856. }
  8857. return finished;
  8858. },
  8859. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8860. var ctx = currentLayer.ctx;
  8861. var m = el.transform;
  8862. if (
  8863. (currentLayer.__dirty || forcePaint)
  8864. // Ignore invisible element
  8865. && !el.invisible
  8866. // Ignore transparent element
  8867. && el.style.opacity !== 0
  8868. // Ignore scale 0 element, in some environment like node-canvas
  8869. // Draw a scale 0 element can cause all following draw wrong
  8870. // And setTransform with scale 0 will cause set back transform failed.
  8871. && !(m && !m[0] && !m[3])
  8872. // Ignore culled element
  8873. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8874. ) {
  8875. var clipPaths = el.__clipPaths;
  8876. var prevElClipPaths = scope.prevElClipPaths;
  8877. // Optimize when clipping on group with several elements
  8878. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8879. // If has previous clipping state, restore from it
  8880. if (prevElClipPaths) {
  8881. ctx.restore();
  8882. scope.prevElClipPaths = null;
  8883. // Reset prevEl since context has been restored
  8884. scope.prevEl = null;
  8885. }
  8886. // New clipping state
  8887. if (clipPaths) {
  8888. ctx.save();
  8889. doClip(clipPaths, ctx);
  8890. scope.prevElClipPaths = clipPaths;
  8891. }
  8892. }
  8893. el.beforeBrush && el.beforeBrush(ctx);
  8894. el.brush(ctx, scope.prevEl || null);
  8895. scope.prevEl = el;
  8896. el.afterBrush && el.afterBrush(ctx);
  8897. }
  8898. },
  8899. /**
  8900. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8901. * @param {number} zlevel
  8902. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8903. * @return {module:zrender/Layer}
  8904. */
  8905. getLayer: function (zlevel, virtual) {
  8906. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8907. zlevel = CANVAS_ZLEVEL;
  8908. }
  8909. var layer = this._layers[zlevel];
  8910. if (!layer) {
  8911. // Create a new layer
  8912. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8913. layer.zlevel = zlevel;
  8914. layer.__builtin__ = true;
  8915. if (this._layerConfig[zlevel]) {
  8916. merge(layer, this._layerConfig[zlevel], true);
  8917. }
  8918. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8919. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  8920. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  8921. }
  8922. if (virtual) {
  8923. layer.virtual = virtual;
  8924. }
  8925. this.insertLayer(zlevel, layer);
  8926. // Context is created after dom inserted to document
  8927. // Or excanvas will get 0px clientWidth and clientHeight
  8928. layer.initContext();
  8929. }
  8930. return layer;
  8931. },
  8932. insertLayer: function (zlevel, layer) {
  8933. var layersMap = this._layers;
  8934. var zlevelList = this._zlevelList;
  8935. var len = zlevelList.length;
  8936. var prevLayer = null;
  8937. var i = -1;
  8938. var domRoot = this._domRoot;
  8939. if (layersMap[zlevel]) {
  8940. logError$1('ZLevel ' + zlevel + ' has been used already');
  8941. return;
  8942. }
  8943. // Check if is a valid layer
  8944. if (!isLayerValid(layer)) {
  8945. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8946. return;
  8947. }
  8948. if (len > 0 && zlevel > zlevelList[0]) {
  8949. for (i = 0; i < len - 1; i++) {
  8950. if (
  8951. zlevelList[i] < zlevel
  8952. && zlevelList[i + 1] > zlevel
  8953. ) {
  8954. break;
  8955. }
  8956. }
  8957. prevLayer = layersMap[zlevelList[i]];
  8958. }
  8959. zlevelList.splice(i + 1, 0, zlevel);
  8960. layersMap[zlevel] = layer;
  8961. // Vitual layer will not directly show on the screen.
  8962. // (It can be a WebGL layer and assigned to a ZImage element)
  8963. // But it still under management of zrender.
  8964. if (!layer.virtual) {
  8965. if (prevLayer) {
  8966. var prevDom = prevLayer.dom;
  8967. if (prevDom.nextSibling) {
  8968. domRoot.insertBefore(
  8969. layer.dom,
  8970. prevDom.nextSibling
  8971. );
  8972. }
  8973. else {
  8974. domRoot.appendChild(layer.dom);
  8975. }
  8976. }
  8977. else {
  8978. if (domRoot.firstChild) {
  8979. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8980. }
  8981. else {
  8982. domRoot.appendChild(layer.dom);
  8983. }
  8984. }
  8985. }
  8986. },
  8987. // Iterate each layer
  8988. eachLayer: function (cb, context) {
  8989. var zlevelList = this._zlevelList;
  8990. var z;
  8991. var i;
  8992. for (i = 0; i < zlevelList.length; i++) {
  8993. z = zlevelList[i];
  8994. cb.call(context, this._layers[z], z);
  8995. }
  8996. },
  8997. // Iterate each buildin layer
  8998. eachBuiltinLayer: function (cb, context) {
  8999. var zlevelList = this._zlevelList;
  9000. var layer;
  9001. var z;
  9002. var i;
  9003. for (i = 0; i < zlevelList.length; i++) {
  9004. z = zlevelList[i];
  9005. layer = this._layers[z];
  9006. if (layer.__builtin__) {
  9007. cb.call(context, layer, z);
  9008. }
  9009. }
  9010. },
  9011. // Iterate each other layer except buildin layer
  9012. eachOtherLayer: function (cb, context) {
  9013. var zlevelList = this._zlevelList;
  9014. var layer;
  9015. var z;
  9016. var i;
  9017. for (i = 0; i < zlevelList.length; i++) {
  9018. z = zlevelList[i];
  9019. layer = this._layers[z];
  9020. if (!layer.__builtin__) {
  9021. cb.call(context, layer, z);
  9022. }
  9023. }
  9024. },
  9025. /**
  9026. * 获取所有已创建的层
  9027. * @param {Array.<module:zrender/Layer>} [prevLayer]
  9028. */
  9029. getLayers: function () {
  9030. return this._layers;
  9031. },
  9032. _updateLayerStatus: function (list) {
  9033. this.eachBuiltinLayer(function (layer, z) {
  9034. layer.__dirty = layer.__used = false;
  9035. });
  9036. function updatePrevLayer(idx) {
  9037. if (prevLayer) {
  9038. if (prevLayer.__endIndex !== idx) {
  9039. prevLayer.__dirty = true;
  9040. }
  9041. prevLayer.__endIndex = idx;
  9042. }
  9043. }
  9044. if (this._singleCanvas) {
  9045. for (var i = 1; i < list.length; i++) {
  9046. var el = list[i];
  9047. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  9048. this._needsManuallyCompositing = true;
  9049. break;
  9050. }
  9051. }
  9052. }
  9053. var prevLayer = null;
  9054. var incrementalLayerCount = 0;
  9055. var prevZlevel;
  9056. for (var i = 0; i < list.length; i++) {
  9057. var el = list[i];
  9058. var zlevel = el.zlevel;
  9059. var layer;
  9060. if (prevZlevel !== zlevel) {
  9061. prevZlevel = zlevel;
  9062. incrementalLayerCount = 0;
  9063. }
  9064. // TODO Not use magic number on zlevel.
  9065. // Each layer with increment element can be separated to 3 layers.
  9066. // (Other Element drawn after incremental element)
  9067. // -----------------zlevel + EL_AFTER_INCREMENTAL_INC--------------------
  9068. // (Incremental element)
  9069. // ----------------------zlevel + INCREMENTAL_INC------------------------
  9070. // (Element drawn before incremental element)
  9071. // --------------------------------zlevel--------------------------------
  9072. if (el.incremental) {
  9073. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  9074. layer.incremental = true;
  9075. incrementalLayerCount = 1;
  9076. }
  9077. else {
  9078. layer = this.getLayer(
  9079. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  9080. this._needsManuallyCompositing
  9081. );
  9082. }
  9083. if (!layer.__builtin__) {
  9084. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  9085. }
  9086. if (layer !== prevLayer) {
  9087. layer.__used = true;
  9088. if (layer.__startIndex !== i) {
  9089. layer.__dirty = true;
  9090. }
  9091. layer.__startIndex = i;
  9092. if (!layer.incremental) {
  9093. layer.__drawIndex = i;
  9094. }
  9095. else {
  9096. // Mark layer draw index needs to update.
  9097. layer.__drawIndex = -1;
  9098. }
  9099. updatePrevLayer(i);
  9100. prevLayer = layer;
  9101. }
  9102. if (el.__dirty) {
  9103. layer.__dirty = true;
  9104. if (layer.incremental && layer.__drawIndex < 0) {
  9105. // Start draw from the first dirty element.
  9106. layer.__drawIndex = i;
  9107. }
  9108. }
  9109. }
  9110. updatePrevLayer(i);
  9111. this.eachBuiltinLayer(function (layer, z) {
  9112. // Used in last frame but not in this frame. Needs clear
  9113. if (!layer.__used && layer.getElementCount() > 0) {
  9114. layer.__dirty = true;
  9115. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  9116. }
  9117. // For incremental layer. In case start index changed and no elements are dirty.
  9118. if (layer.__dirty && layer.__drawIndex < 0) {
  9119. layer.__drawIndex = layer.__startIndex;
  9120. }
  9121. });
  9122. },
  9123. /**
  9124. * 清除hover层外所有内容
  9125. */
  9126. clear: function () {
  9127. this.eachBuiltinLayer(this._clearLayer);
  9128. return this;
  9129. },
  9130. _clearLayer: function (layer) {
  9131. layer.clear();
  9132. },
  9133. setBackgroundColor: function (backgroundColor) {
  9134. this._backgroundColor = backgroundColor;
  9135. },
  9136. /**
  9137. * 修改指定zlevel的绘制参数
  9138. *
  9139. * @param {string} zlevel
  9140. * @param {Object} config 配置对象
  9141. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9142. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9143. * @param {number} [config.lastFrameAlpha=0.7]
  9144. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9145. */
  9146. configLayer: function (zlevel, config) {
  9147. if (config) {
  9148. var layerConfig = this._layerConfig;
  9149. if (!layerConfig[zlevel]) {
  9150. layerConfig[zlevel] = config;
  9151. }
  9152. else {
  9153. merge(layerConfig[zlevel], config, true);
  9154. }
  9155. for (var i = 0; i < this._zlevelList.length; i++) {
  9156. var _zlevel = this._zlevelList[i];
  9157. // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  9158. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9159. var layer = this._layers[_zlevel];
  9160. merge(layer, layerConfig[zlevel], true);
  9161. }
  9162. }
  9163. }
  9164. },
  9165. /**
  9166. * 删除指定层
  9167. * @param {number} zlevel 层所在的zlevel
  9168. */
  9169. delLayer: function (zlevel) {
  9170. var layers = this._layers;
  9171. var zlevelList = this._zlevelList;
  9172. var layer = layers[zlevel];
  9173. if (!layer) {
  9174. return;
  9175. }
  9176. layer.dom.parentNode.removeChild(layer.dom);
  9177. delete layers[zlevel];
  9178. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9179. },
  9180. /**
  9181. * 区域大小变化后重绘
  9182. */
  9183. resize: function (width, height) {
  9184. if (!this._domRoot.style) { // Maybe in node or worker
  9185. if (width == null || height == null) {
  9186. return;
  9187. }
  9188. this._width = width;
  9189. this._height = height;
  9190. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9191. }
  9192. else {
  9193. var domRoot = this._domRoot;
  9194. // FIXME Why ?
  9195. domRoot.style.display = 'none';
  9196. // Save input w/h
  9197. var opts = this._opts;
  9198. width != null && (opts.width = width);
  9199. height != null && (opts.height = height);
  9200. width = this._getSize(0);
  9201. height = this._getSize(1);
  9202. domRoot.style.display = '';
  9203. // 优化没有实际改变的resize
  9204. if (this._width !== width || height !== this._height) {
  9205. domRoot.style.width = width + 'px';
  9206. domRoot.style.height = height + 'px';
  9207. for (var id in this._layers) {
  9208. if (this._layers.hasOwnProperty(id)) {
  9209. this._layers[id].resize(width, height);
  9210. }
  9211. }
  9212. each$1(this._progressiveLayers, function (layer) {
  9213. layer.resize(width, height);
  9214. });
  9215. this.refresh(true);
  9216. }
  9217. this._width = width;
  9218. this._height = height;
  9219. }
  9220. return this;
  9221. },
  9222. /**
  9223. * 清除单独的一个层
  9224. * @param {number} zlevel
  9225. */
  9226. clearLayer: function (zlevel) {
  9227. var layer = this._layers[zlevel];
  9228. if (layer) {
  9229. layer.clear();
  9230. }
  9231. },
  9232. /**
  9233. * 释放
  9234. */
  9235. dispose: function () {
  9236. this.root.innerHTML = '';
  9237. this.root =
  9238. this.storage =
  9239. this._domRoot =
  9240. this._layers = null;
  9241. },
  9242. /**
  9243. * Get canvas which has all thing rendered
  9244. * @param {Object} opts
  9245. * @param {string} [opts.backgroundColor]
  9246. * @param {number} [opts.pixelRatio]
  9247. */
  9248. getRenderedCanvas: function (opts) {
  9249. opts = opts || {};
  9250. if (this._singleCanvas && !this._compositeManually) {
  9251. return this._layers[CANVAS_ZLEVEL].dom;
  9252. }
  9253. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9254. imageLayer.initContext();
  9255. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9256. if (opts.pixelRatio <= this.dpr) {
  9257. this.refresh();
  9258. var width = imageLayer.dom.width;
  9259. var height = imageLayer.dom.height;
  9260. var ctx = imageLayer.ctx;
  9261. this.eachLayer(function (layer) {
  9262. if (layer.__builtin__) {
  9263. ctx.drawImage(layer.dom, 0, 0, width, height);
  9264. }
  9265. else if (layer.renderToCanvas) {
  9266. imageLayer.ctx.save();
  9267. layer.renderToCanvas(imageLayer.ctx);
  9268. imageLayer.ctx.restore();
  9269. }
  9270. });
  9271. }
  9272. else {
  9273. // PENDING, echarts-gl and incremental rendering.
  9274. var scope = {};
  9275. var displayList = this.storage.getDisplayList(true);
  9276. for (var i = 0; i < displayList.length; i++) {
  9277. var el = displayList[i];
  9278. this._doPaintEl(el, imageLayer, true, scope);
  9279. }
  9280. }
  9281. return imageLayer.dom;
  9282. },
  9283. /**
  9284. * 获取绘图区域宽度
  9285. */
  9286. getWidth: function () {
  9287. return this._width;
  9288. },
  9289. /**
  9290. * 获取绘图区域高度
  9291. */
  9292. getHeight: function () {
  9293. return this._height;
  9294. },
  9295. _getSize: function (whIdx) {
  9296. var opts = this._opts;
  9297. var wh = ['width', 'height'][whIdx];
  9298. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9299. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9300. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9301. if (opts[wh] != null && opts[wh] !== 'auto') {
  9302. return parseFloat(opts[wh]);
  9303. }
  9304. var root = this.root;
  9305. // IE8 does not support getComputedStyle, but it use VML.
  9306. var stl = document.defaultView.getComputedStyle(root);
  9307. return (
  9308. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9309. - (parseInt10(stl[plt]) || 0)
  9310. - (parseInt10(stl[prb]) || 0)
  9311. ) | 0;
  9312. },
  9313. pathToImage: function (path, dpr) {
  9314. dpr = dpr || this.dpr;
  9315. var canvas = document.createElement('canvas');
  9316. var ctx = canvas.getContext('2d');
  9317. var rect = path.getBoundingRect();
  9318. var style = path.style;
  9319. var shadowBlurSize = style.shadowBlur * dpr;
  9320. var shadowOffsetX = style.shadowOffsetX * dpr;
  9321. var shadowOffsetY = style.shadowOffsetY * dpr;
  9322. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9323. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9324. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9325. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9326. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9327. var width = rect.width + leftMargin + rightMargin;
  9328. var height = rect.height + topMargin + bottomMargin;
  9329. canvas.width = width * dpr;
  9330. canvas.height = height * dpr;
  9331. ctx.scale(dpr, dpr);
  9332. ctx.clearRect(0, 0, width, height);
  9333. ctx.dpr = dpr;
  9334. var pathTransform = {
  9335. position: path.position,
  9336. rotation: path.rotation,
  9337. scale: path.scale
  9338. };
  9339. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9340. path.rotation = 0;
  9341. path.scale = [1, 1];
  9342. path.updateTransform();
  9343. if (path) {
  9344. path.brush(ctx);
  9345. }
  9346. var ImageShape = ZImage;
  9347. var imgShape = new ImageShape({
  9348. style: {
  9349. x: 0,
  9350. y: 0,
  9351. image: canvas
  9352. }
  9353. });
  9354. if (pathTransform.position != null) {
  9355. imgShape.position = path.position = pathTransform.position;
  9356. }
  9357. if (pathTransform.rotation != null) {
  9358. imgShape.rotation = path.rotation = pathTransform.rotation;
  9359. }
  9360. if (pathTransform.scale != null) {
  9361. imgShape.scale = path.scale = pathTransform.scale;
  9362. }
  9363. return imgShape;
  9364. }
  9365. };
  9366. /**
  9367. * Animation main class, dispatch and manage all animation controllers
  9368. *
  9369. * @module zrender/animation/Animation
  9370. * @author pissang(https://github.com/pissang)
  9371. */
  9372. // TODO Additive animation
  9373. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9374. // https://developer.apple.com/videos/wwdc2014/#236
  9375. /**
  9376. * @typedef {Object} IZRenderStage
  9377. * @property {Function} update
  9378. */
  9379. /**
  9380. * @alias module:zrender/animation/Animation
  9381. * @constructor
  9382. * @param {Object} [options]
  9383. * @param {Function} [options.onframe]
  9384. * @param {IZRenderStage} [options.stage]
  9385. * @example
  9386. * var animation = new Animation();
  9387. * var obj = {
  9388. * x: 100,
  9389. * y: 100
  9390. * };
  9391. * animation.animate(node.position)
  9392. * .when(1000, {
  9393. * x: 500,
  9394. * y: 500
  9395. * })
  9396. * .when(2000, {
  9397. * x: 100,
  9398. * y: 100
  9399. * })
  9400. * .start('spline');
  9401. */
  9402. var Animation = function (options) {
  9403. options = options || {};
  9404. this.stage = options.stage || {};
  9405. this.onframe = options.onframe || function () {};
  9406. // private properties
  9407. this._clips = [];
  9408. this._running = false;
  9409. this._time;
  9410. this._pausedTime;
  9411. this._pauseStart;
  9412. this._paused = false;
  9413. Eventful.call(this);
  9414. };
  9415. Animation.prototype = {
  9416. constructor: Animation,
  9417. /**
  9418. * Add clip
  9419. * @param {module:zrender/animation/Clip} clip
  9420. */
  9421. addClip: function (clip) {
  9422. this._clips.push(clip);
  9423. },
  9424. /**
  9425. * Add animator
  9426. * @param {module:zrender/animation/Animator} animator
  9427. */
  9428. addAnimator: function (animator) {
  9429. animator.animation = this;
  9430. var clips = animator.getClips();
  9431. for (var i = 0; i < clips.length; i++) {
  9432. this.addClip(clips[i]);
  9433. }
  9434. },
  9435. /**
  9436. * Delete animation clip
  9437. * @param {module:zrender/animation/Clip} clip
  9438. */
  9439. removeClip: function (clip) {
  9440. var idx = indexOf(this._clips, clip);
  9441. if (idx >= 0) {
  9442. this._clips.splice(idx, 1);
  9443. }
  9444. },
  9445. /**
  9446. * Delete animation clip
  9447. * @param {module:zrender/animation/Animator} animator
  9448. */
  9449. removeAnimator: function (animator) {
  9450. var clips = animator.getClips();
  9451. for (var i = 0; i < clips.length; i++) {
  9452. this.removeClip(clips[i]);
  9453. }
  9454. animator.animation = null;
  9455. },
  9456. _update: function () {
  9457. var time = new Date().getTime() - this._pausedTime;
  9458. var delta = time - this._time;
  9459. var clips = this._clips;
  9460. var len = clips.length;
  9461. var deferredEvents = [];
  9462. var deferredClips = [];
  9463. for (var i = 0; i < len; i++) {
  9464. var clip = clips[i];
  9465. var e = clip.step(time, delta);
  9466. // Throw out the events need to be called after
  9467. // stage.update, like destroy
  9468. if (e) {
  9469. deferredEvents.push(e);
  9470. deferredClips.push(clip);
  9471. }
  9472. }
  9473. // Remove the finished clip
  9474. for (var i = 0; i < len;) {
  9475. if (clips[i]._needsRemove) {
  9476. clips[i] = clips[len - 1];
  9477. clips.pop();
  9478. len--;
  9479. }
  9480. else {
  9481. i++;
  9482. }
  9483. }
  9484. len = deferredEvents.length;
  9485. for (var i = 0; i < len; i++) {
  9486. deferredClips[i].fire(deferredEvents[i]);
  9487. }
  9488. this._time = time;
  9489. this.onframe(delta);
  9490. // 'frame' should be triggered before stage, because upper application
  9491. // depends on the sequence (e.g., echarts-stream and finish
  9492. // event judge)
  9493. this.trigger('frame', delta);
  9494. if (this.stage.update) {
  9495. this.stage.update();
  9496. }
  9497. },
  9498. _startLoop: function () {
  9499. var self = this;
  9500. this._running = true;
  9501. function step() {
  9502. if (self._running) {
  9503. requestAnimationFrame(step);
  9504. !self._paused && self._update();
  9505. }
  9506. }
  9507. requestAnimationFrame(step);
  9508. },
  9509. /**
  9510. * Start animation.
  9511. */
  9512. start: function () {
  9513. this._time = new Date().getTime();
  9514. this._pausedTime = 0;
  9515. this._startLoop();
  9516. },
  9517. /**
  9518. * Stop animation.
  9519. */
  9520. stop: function () {
  9521. this._running = false;
  9522. },
  9523. /**
  9524. * Pause animation.
  9525. */
  9526. pause: function () {
  9527. if (!this._paused) {
  9528. this._pauseStart = new Date().getTime();
  9529. this._paused = true;
  9530. }
  9531. },
  9532. /**
  9533. * Resume animation.
  9534. */
  9535. resume: function () {
  9536. if (this._paused) {
  9537. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9538. this._paused = false;
  9539. }
  9540. },
  9541. /**
  9542. * Clear animation.
  9543. */
  9544. clear: function () {
  9545. this._clips = [];
  9546. },
  9547. /**
  9548. * Whether animation finished.
  9549. */
  9550. isFinished: function () {
  9551. return !this._clips.length;
  9552. },
  9553. /**
  9554. * Creat animator for a target, whose props can be animated.
  9555. *
  9556. * @param {Object} target
  9557. * @param {Object} options
  9558. * @param {boolean} [options.loop=false] Whether loop animation.
  9559. * @param {Function} [options.getter=null] Get value from target.
  9560. * @param {Function} [options.setter=null] Set value to target.
  9561. * @return {module:zrender/animation/Animation~Animator}
  9562. */
  9563. // TODO Gap
  9564. animate: function (target, options) {
  9565. options = options || {};
  9566. var animator = new Animator(
  9567. target,
  9568. options.loop,
  9569. options.getter,
  9570. options.setter
  9571. );
  9572. this.addAnimator(animator);
  9573. return animator;
  9574. }
  9575. };
  9576. mixin(Animation, Eventful);
  9577. /* global document */
  9578. var TOUCH_CLICK_DELAY = 300;
  9579. var globalEventSupported = env$1.domSupported;
  9580. var localNativeListenerNames = (function () {
  9581. var mouseHandlerNames = [
  9582. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9583. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9584. ];
  9585. var touchHandlerNames = [
  9586. 'touchstart', 'touchend', 'touchmove'
  9587. ];
  9588. var pointerEventNameMap = {
  9589. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9590. };
  9591. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9592. var nm = name.replace('mouse', 'pointer');
  9593. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9594. });
  9595. return {
  9596. mouse: mouseHandlerNames,
  9597. touch: touchHandlerNames,
  9598. pointer: pointerHandlerNames
  9599. };
  9600. })();
  9601. var globalNativeListenerNames = {
  9602. mouse: ['mousemove', 'mouseup'],
  9603. pointer: ['pointermove', 'pointerup']
  9604. };
  9605. function eventNameFix(name) {
  9606. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9607. }
  9608. function isPointerFromTouch(event) {
  9609. var pointerType = event.pointerType;
  9610. return pointerType === 'pen' || pointerType === 'touch';
  9611. }
  9612. // function useMSGuesture(handlerProxy, event) {
  9613. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9614. // }
  9615. // function onMSGestureChange(proxy, event) {
  9616. // if (event.translationX || event.translationY) {
  9617. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9618. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9619. // }
  9620. // if (event.scale !== 1) {
  9621. // event.pinchX = event.offsetX;
  9622. // event.pinchY = event.offsetY;
  9623. // event.pinchScale = event.scale;
  9624. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9625. // }
  9626. // }
  9627. /**
  9628. * Prevent mouse event from being dispatched after Touch Events action
  9629. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9630. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9631. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9632. * Result: Blocking Mouse Events for 700ms.
  9633. *
  9634. * @param {DOMHandlerScope} scope
  9635. */
  9636. function setTouchTimer(scope) {
  9637. scope.touching = true;
  9638. if (scope.touchTimer != null) {
  9639. clearTimeout(scope.touchTimer);
  9640. scope.touchTimer = null;
  9641. }
  9642. scope.touchTimer = setTimeout(function () {
  9643. scope.touching = false;
  9644. scope.touchTimer = null;
  9645. }, 700);
  9646. }
  9647. // Mark touch, which is useful in distinguish touch and
  9648. // mouse event in upper applicatoin.
  9649. function markTouch(event) {
  9650. event && (event.zrByTouch = true);
  9651. }
  9652. // function markTriggeredFromLocal(event) {
  9653. // event && (event.__zrIsFromLocal = true);
  9654. // }
  9655. // function isTriggeredFromLocal(instance, event) {
  9656. // return !!(event && event.__zrIsFromLocal);
  9657. // }
  9658. function normalizeGlobalEvent(instance, event) {
  9659. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9660. // handlers of the upper applications. Set `true` to force calculate them.
  9661. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9662. }
  9663. /**
  9664. * Detect whether the given el is in `painterRoot`.
  9665. */
  9666. function isLocalEl(instance, el) {
  9667. var elTmp = el;
  9668. var isLocal = false;
  9669. while (elTmp && elTmp.nodeType !== 9
  9670. && !(
  9671. isLocal = elTmp.domBelongToZr
  9672. || (elTmp !== el && elTmp === instance.painterRoot)
  9673. )
  9674. ) {
  9675. elTmp = elTmp.parentNode;
  9676. }
  9677. return isLocal;
  9678. }
  9679. /**
  9680. * Make a fake event but not change the original event,
  9681. * becuase the global event probably be used by other
  9682. * listeners not belonging to zrender.
  9683. * @class
  9684. */
  9685. function FakeGlobalEvent(instance, event) {
  9686. this.type = event.type;
  9687. this.target = this.currentTarget = instance.dom;
  9688. this.pointerType = event.pointerType;
  9689. // Necessray for the force calculation of zrX, zrY
  9690. this.clientX = event.clientX;
  9691. this.clientY = event.clientY;
  9692. // Because we do not mount global listeners to touch events,
  9693. // we do not copy `targetTouches` and `changedTouches` here.
  9694. }
  9695. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9696. // we make the default methods on the event do nothing,
  9697. // otherwise it is dangerous. See more details in
  9698. // [Drag outside] in `Handler.js`.
  9699. fakeGlobalEventProto.stopPropagation =
  9700. fakeGlobalEventProto.stopImmediatePropagation =
  9701. fakeGlobalEventProto.preventDefault = noop;
  9702. /**
  9703. * Local DOM Handlers
  9704. * @this {HandlerProxy}
  9705. */
  9706. var localDOMHandlers = {
  9707. mousedown: function (event) {
  9708. event = normalizeEvent(this.dom, event);
  9709. this._mayPointerCapture = [event.zrX, event.zrY];
  9710. this.trigger('mousedown', event);
  9711. },
  9712. mousemove: function (event) {
  9713. event = normalizeEvent(this.dom, event);
  9714. var downPoint = this._mayPointerCapture;
  9715. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9716. togglePointerCapture(this, true);
  9717. }
  9718. this.trigger('mousemove', event);
  9719. },
  9720. mouseup: function (event) {
  9721. event = normalizeEvent(this.dom, event);
  9722. togglePointerCapture(this, false);
  9723. this.trigger('mouseup', event);
  9724. },
  9725. mouseout: function (event) {
  9726. event = normalizeEvent(this.dom, event);
  9727. // Similarly to the browser did on `document` and touch event,
  9728. // `globalout` will be delayed to final pointer cature release.
  9729. if (this._pointerCapturing) {
  9730. event.zrEventControl = 'no_globalout';
  9731. }
  9732. // There might be some doms created by upper layer application
  9733. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9734. // dom created by echarts), where 'globalout' event should not
  9735. // be triggered when mouse enters these doms. (But 'mouseout'
  9736. // should be triggered at the original hovered element as usual).
  9737. var element = event.toElement || event.relatedTarget;
  9738. event.zrIsToLocalDOM = isLocalEl(this, element);
  9739. this.trigger('mouseout', event);
  9740. },
  9741. touchstart: function (event) {
  9742. // Default mouse behaviour should not be disabled here.
  9743. // For example, page may needs to be slided.
  9744. event = normalizeEvent(this.dom, event);
  9745. markTouch(event);
  9746. this._lastTouchMoment = new Date();
  9747. this.handler.processGesture(event, 'start');
  9748. // For consistent event listener for both touch device and mouse device,
  9749. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9750. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9751. // `mousedown`.
  9752. localDOMHandlers.mousemove.call(this, event);
  9753. localDOMHandlers.mousedown.call(this, event);
  9754. },
  9755. touchmove: function (event) {
  9756. event = normalizeEvent(this.dom, event);
  9757. markTouch(event);
  9758. this.handler.processGesture(event, 'change');
  9759. // Mouse move should always be triggered no matter whether
  9760. // there is gestrue event, because mouse move and pinch may
  9761. // be used at the same time.
  9762. localDOMHandlers.mousemove.call(this, event);
  9763. },
  9764. touchend: function (event) {
  9765. event = normalizeEvent(this.dom, event);
  9766. markTouch(event);
  9767. this.handler.processGesture(event, 'end');
  9768. localDOMHandlers.mouseup.call(this, event);
  9769. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9770. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9771. // we can conveniently implement "hover style" in both PC and touch device just
  9772. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9773. // to remove "hover style" on an element, without any additional code for
  9774. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9775. // style" will remain for user view)
  9776. // click event should always be triggered no matter whether
  9777. // there is gestrue event. System click can not be prevented.
  9778. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9779. localDOMHandlers.click.call(this, event);
  9780. }
  9781. },
  9782. pointerdown: function (event) {
  9783. localDOMHandlers.mousedown.call(this, event);
  9784. // if (useMSGuesture(this, event)) {
  9785. // this._msGesture.addPointer(event.pointerId);
  9786. // }
  9787. },
  9788. pointermove: function (event) {
  9789. // FIXME
  9790. // pointermove is so sensitive that it always triggered when
  9791. // tap(click) on touch screen, which affect some judgement in
  9792. // upper application. So, we dont support mousemove on MS touch
  9793. // device yet.
  9794. if (!isPointerFromTouch(event)) {
  9795. localDOMHandlers.mousemove.call(this, event);
  9796. }
  9797. },
  9798. pointerup: function (event) {
  9799. localDOMHandlers.mouseup.call(this, event);
  9800. },
  9801. pointerout: function (event) {
  9802. // pointerout will be triggered when tap on touch screen
  9803. // (IE11+/Edge on MS Surface) after click event triggered,
  9804. // which is inconsistent with the mousout behavior we defined
  9805. // in touchend. So we unify them.
  9806. // (check localDOMHandlers.touchend for detailed explanation)
  9807. if (!isPointerFromTouch(event)) {
  9808. localDOMHandlers.mouseout.call(this, event);
  9809. }
  9810. }
  9811. };
  9812. /**
  9813. * Othere DOM UI Event handlers for zr dom.
  9814. * @this {HandlerProxy}
  9815. */
  9816. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9817. localDOMHandlers[name] = function (event) {
  9818. event = normalizeEvent(this.dom, event);
  9819. this.trigger(name, event);
  9820. };
  9821. });
  9822. /**
  9823. * DOM UI Event handlers for global page.
  9824. *
  9825. * [Caution]:
  9826. * those handlers should both support in capture phase and bubble phase!
  9827. *
  9828. * @this {HandlerProxy}
  9829. */
  9830. var globalDOMHandlers = {
  9831. pointermove: function (event) {
  9832. // FIXME
  9833. // pointermove is so sensitive that it always triggered when
  9834. // tap(click) on touch screen, which affect some judgement in
  9835. // upper application. So, we dont support mousemove on MS touch
  9836. // device yet.
  9837. if (!isPointerFromTouch(event)) {
  9838. globalDOMHandlers.mousemove.call(this, event);
  9839. }
  9840. },
  9841. pointerup: function (event) {
  9842. globalDOMHandlers.mouseup.call(this, event);
  9843. },
  9844. mousemove: function (event) {
  9845. this.trigger('mousemove', event);
  9846. },
  9847. mouseup: function (event) {
  9848. var pointerCaptureReleasing = this._pointerCapturing;
  9849. togglePointerCapture(this, false);
  9850. this.trigger('mouseup', event);
  9851. if (pointerCaptureReleasing) {
  9852. event.zrEventControl = 'only_globalout';
  9853. this.trigger('mouseout', event);
  9854. }
  9855. }
  9856. };
  9857. /**
  9858. * @param {HandlerProxy} instance
  9859. * @param {DOMHandlerScope} scope
  9860. */
  9861. function mountLocalDOMEventListeners(instance, scope) {
  9862. var domHandlers = scope.domHandlers;
  9863. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9864. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9865. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9866. // at the same time.
  9867. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9868. // screen, which do not occurs in pointer event.
  9869. // So we use pointer event to both detect touch gesture and mouse behavior.
  9870. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9871. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9872. // markTriggeredFromLocal(event);
  9873. domHandlers[nativeEventName].call(instance, event);
  9874. });
  9875. });
  9876. // FIXME
  9877. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9878. // which does not prevent defuault behavior occasionally (which may cause view port
  9879. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9880. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9881. // touch screen. And we only support click behavior on MS touch screen now.
  9882. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9883. // We dont support touch on IE on win7.
  9884. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9885. // if (typeof MSGesture === 'function') {
  9886. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9887. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9888. // }
  9889. }
  9890. else {
  9891. if (env$1.touchEventsSupported) {
  9892. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9893. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9894. // markTriggeredFromLocal(event);
  9895. domHandlers[nativeEventName].call(instance, event);
  9896. setTouchTimer(scope);
  9897. });
  9898. });
  9899. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9900. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9901. }
  9902. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9903. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9904. // mouse event can not be handle in those devices.
  9905. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9906. // mouseevent after touch event triggered, see `setTouchTimer`.
  9907. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9908. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9909. event = getNativeEvent(event);
  9910. if (!scope.touching) {
  9911. // markTriggeredFromLocal(event);
  9912. domHandlers[nativeEventName].call(instance, event);
  9913. }
  9914. });
  9915. });
  9916. }
  9917. }
  9918. /**
  9919. * @param {HandlerProxy} instance
  9920. * @param {DOMHandlerScope} scope
  9921. */
  9922. function mountGlobalDOMEventListeners(instance, scope) {
  9923. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9924. if (env$1.pointerEventsSupported) {
  9925. each$1(globalNativeListenerNames.pointer, mount);
  9926. }
  9927. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9928. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9929. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9930. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9931. else if (!env$1.touchEventsSupported) {
  9932. each$1(globalNativeListenerNames.mouse, mount);
  9933. }
  9934. function mount(nativeEventName) {
  9935. function nativeEventListener(event) {
  9936. event = getNativeEvent(event);
  9937. // See the reason in [Drag outside] in `Handler.js`
  9938. // This checking supports both `useCapture` or not.
  9939. // PENDING: if there is performance issue in some devices,
  9940. // we probably can not use `useCapture` and change a easier
  9941. // to judes whether local (mark).
  9942. if (!isLocalEl(instance, event.target)) {
  9943. event = normalizeGlobalEvent(instance, event);
  9944. scope.domHandlers[nativeEventName].call(instance, event);
  9945. }
  9946. }
  9947. mountSingleDOMEventListener(
  9948. scope, nativeEventName, nativeEventListener,
  9949. {capture: true} // See [Drag Outside] in `Handler.js`
  9950. );
  9951. }
  9952. }
  9953. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9954. scope.mounted[nativeEventName] = listener;
  9955. scope.listenerOpts[nativeEventName] = opt;
  9956. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9957. }
  9958. function unmountDOMEventListeners(scope) {
  9959. var mounted = scope.mounted;
  9960. for (var nativeEventName in mounted) {
  9961. if (mounted.hasOwnProperty(nativeEventName)) {
  9962. removeEventListener(
  9963. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9964. scope.listenerOpts[nativeEventName]
  9965. );
  9966. }
  9967. }
  9968. scope.mounted = {};
  9969. }
  9970. /**
  9971. * See [Drag Outside] in `Handler.js`.
  9972. * @implement
  9973. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9974. * `true`: start to capture pointer if it is not capturing.
  9975. * `false`: end the capture if it is capturing.
  9976. */
  9977. function togglePointerCapture(instance, isPointerCapturing) {
  9978. instance._mayPointerCapture = null;
  9979. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9980. instance._pointerCapturing = isPointerCapturing;
  9981. var globalHandlerScope = instance._globalHandlerScope;
  9982. isPointerCapturing
  9983. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9984. : unmountDOMEventListeners(globalHandlerScope);
  9985. }
  9986. }
  9987. /**
  9988. * @inner
  9989. * @class
  9990. */
  9991. function DOMHandlerScope(domTarget, domHandlers) {
  9992. this.domTarget = domTarget;
  9993. this.domHandlers = domHandlers;
  9994. // Key: eventName, value: mounted handler funcitons.
  9995. // Used for unmount.
  9996. this.mounted = {};
  9997. this.listenerOpts = {};
  9998. this.touchTimer = null;
  9999. this.touching = false;
  10000. }
  10001. /**
  10002. * @public
  10003. * @class
  10004. */
  10005. function HandlerDomProxy(dom, painterRoot) {
  10006. Eventful.call(this);
  10007. this.dom = dom;
  10008. this.painterRoot = painterRoot;
  10009. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  10010. if (globalEventSupported) {
  10011. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  10012. }
  10013. /**
  10014. * @type {boolean}
  10015. */
  10016. this._pointerCapturing = false;
  10017. /**
  10018. * @type {Array.<number>} [x, y] or null.
  10019. */
  10020. this._mayPointerCapture = null;
  10021. mountLocalDOMEventListeners(this, this._localHandlerScope);
  10022. }
  10023. var handlerDomProxyProto = HandlerDomProxy.prototype;
  10024. handlerDomProxyProto.dispose = function () {
  10025. unmountDOMEventListeners(this._localHandlerScope);
  10026. if (globalEventSupported) {
  10027. unmountDOMEventListeners(this._globalHandlerScope);
  10028. }
  10029. };
  10030. handlerDomProxyProto.setCursor = function (cursorStyle) {
  10031. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  10032. };
  10033. mixin(HandlerDomProxy, Eventful);
  10034. /*!
  10035. * ZRender, a high performance 2d drawing library.
  10036. *
  10037. * Copyright (c) 2013, Baidu Inc.
  10038. * All rights reserved.
  10039. *
  10040. * LICENSE
  10041. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  10042. */
  10043. var useVML = !env$1.canvasSupported;
  10044. var painterCtors = {
  10045. canvas: Painter
  10046. };
  10047. var instances$1 = {}; // ZRender实例map索引
  10048. /**
  10049. * @type {string}
  10050. */
  10051. var version$1 = '4.3.1';
  10052. /**
  10053. * Initializing a zrender instance
  10054. * @param {HTMLElement} dom
  10055. * @param {Object} [opts]
  10056. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10057. * @param {number} [opts.devicePixelRatio]
  10058. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10059. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10060. * @return {module:zrender/ZRender}
  10061. */
  10062. function init$1(dom, opts) {
  10063. var zr = new ZRender(guid(), dom, opts);
  10064. instances$1[zr.id] = zr;
  10065. return zr;
  10066. }
  10067. /**
  10068. * Dispose zrender instance
  10069. * @param {module:zrender/ZRender} zr
  10070. */
  10071. function dispose$1(zr) {
  10072. if (zr) {
  10073. zr.dispose();
  10074. }
  10075. else {
  10076. for (var key in instances$1) {
  10077. if (instances$1.hasOwnProperty(key)) {
  10078. instances$1[key].dispose();
  10079. }
  10080. }
  10081. instances$1 = {};
  10082. }
  10083. return this;
  10084. }
  10085. /**
  10086. * Get zrender instance by id
  10087. * @param {string} id zrender instance id
  10088. * @return {module:zrender/ZRender}
  10089. */
  10090. function getInstance(id) {
  10091. return instances$1[id];
  10092. }
  10093. function registerPainter(name, Ctor) {
  10094. painterCtors[name] = Ctor;
  10095. }
  10096. function delInstance(id) {
  10097. delete instances$1[id];
  10098. }
  10099. /**
  10100. * @module zrender/ZRender
  10101. */
  10102. /**
  10103. * @constructor
  10104. * @alias module:zrender/ZRender
  10105. * @param {string} id
  10106. * @param {HTMLElement} dom
  10107. * @param {Object} opts
  10108. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  10109. * @param {number} [opts.devicePixelRatio]
  10110. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  10111. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  10112. */
  10113. var ZRender = function (id, dom, opts) {
  10114. opts = opts || {};
  10115. /**
  10116. * @type {HTMLDomElement}
  10117. */
  10118. this.dom = dom;
  10119. /**
  10120. * @type {string}
  10121. */
  10122. this.id = id;
  10123. var self = this;
  10124. var storage = new Storage();
  10125. var rendererType = opts.renderer;
  10126. // TODO WebGL
  10127. if (useVML) {
  10128. if (!painterCtors.vml) {
  10129. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  10130. }
  10131. rendererType = 'vml';
  10132. }
  10133. else if (!rendererType || !painterCtors[rendererType]) {
  10134. rendererType = 'canvas';
  10135. }
  10136. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  10137. this.storage = storage;
  10138. this.painter = painter;
  10139. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10140. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10141. /**
  10142. * @type {module:zrender/animation/Animation}
  10143. */
  10144. this.animation = new Animation({
  10145. stage: {
  10146. update: bind(this.flush, this)
  10147. }
  10148. });
  10149. this.animation.start();
  10150. /**
  10151. * @type {boolean}
  10152. * @private
  10153. */
  10154. this._needsRefresh;
  10155. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10156. // FIXME 有点ugly
  10157. var oldDelFromStorage = storage.delFromStorage;
  10158. var oldAddToStorage = storage.addToStorage;
  10159. storage.delFromStorage = function (el) {
  10160. oldDelFromStorage.call(storage, el);
  10161. el && el.removeSelfFromZr(self);
  10162. };
  10163. storage.addToStorage = function (el) {
  10164. oldAddToStorage.call(storage, el);
  10165. el.addSelfToZr(self);
  10166. };
  10167. };
  10168. ZRender.prototype = {
  10169. constructor: ZRender,
  10170. /**
  10171. * 获取实例唯一标识
  10172. * @return {string}
  10173. */
  10174. getId: function () {
  10175. return this.id;
  10176. },
  10177. /**
  10178. * 添加元素
  10179. * @param {module:zrender/Element} el
  10180. */
  10181. add: function (el) {
  10182. this.storage.addRoot(el);
  10183. this._needsRefresh = true;
  10184. },
  10185. /**
  10186. * 删除元素
  10187. * @param {module:zrender/Element} el
  10188. */
  10189. remove: function (el) {
  10190. this.storage.delRoot(el);
  10191. this._needsRefresh = true;
  10192. },
  10193. /**
  10194. * Change configuration of layer
  10195. * @param {string} zLevel
  10196. * @param {Object} config
  10197. * @param {string} [config.clearColor=0] Clear color
  10198. * @param {string} [config.motionBlur=false] If enable motion blur
  10199. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10200. */
  10201. configLayer: function (zLevel, config) {
  10202. if (this.painter.configLayer) {
  10203. this.painter.configLayer(zLevel, config);
  10204. }
  10205. this._needsRefresh = true;
  10206. },
  10207. /**
  10208. * Set background color
  10209. * @param {string} backgroundColor
  10210. */
  10211. setBackgroundColor: function (backgroundColor) {
  10212. if (this.painter.setBackgroundColor) {
  10213. this.painter.setBackgroundColor(backgroundColor);
  10214. }
  10215. this._needsRefresh = true;
  10216. },
  10217. /**
  10218. * Repaint the canvas immediately
  10219. */
  10220. refreshImmediately: function () {
  10221. // var start = new Date();
  10222. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10223. // Or it will cause zrender refreshes again and again.
  10224. this._needsRefresh = this._needsRefreshHover = false;
  10225. this.painter.refresh();
  10226. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10227. this._needsRefresh = this._needsRefreshHover = false;
  10228. // var end = new Date();
  10229. // var log = document.getElementById('log');
  10230. // if (log) {
  10231. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10232. // }
  10233. },
  10234. /**
  10235. * Mark and repaint the canvas in the next frame of browser
  10236. */
  10237. refresh: function () {
  10238. this._needsRefresh = true;
  10239. },
  10240. /**
  10241. * Perform all refresh
  10242. */
  10243. flush: function () {
  10244. var triggerRendered;
  10245. if (this._needsRefresh) {
  10246. triggerRendered = true;
  10247. this.refreshImmediately();
  10248. }
  10249. if (this._needsRefreshHover) {
  10250. triggerRendered = true;
  10251. this.refreshHoverImmediately();
  10252. }
  10253. triggerRendered && this.trigger('rendered');
  10254. },
  10255. /**
  10256. * Add element to hover layer
  10257. * @param {module:zrender/Element} el
  10258. * @param {Object} style
  10259. */
  10260. addHover: function (el, style) {
  10261. if (this.painter.addHover) {
  10262. var elMirror = this.painter.addHover(el, style);
  10263. this.refreshHover();
  10264. return elMirror;
  10265. }
  10266. },
  10267. /**
  10268. * Add element from hover layer
  10269. * @param {module:zrender/Element} el
  10270. */
  10271. removeHover: function (el) {
  10272. if (this.painter.removeHover) {
  10273. this.painter.removeHover(el);
  10274. this.refreshHover();
  10275. }
  10276. },
  10277. /**
  10278. * Clear all hover elements in hover layer
  10279. * @param {module:zrender/Element} el
  10280. */
  10281. clearHover: function () {
  10282. if (this.painter.clearHover) {
  10283. this.painter.clearHover();
  10284. this.refreshHover();
  10285. }
  10286. },
  10287. /**
  10288. * Refresh hover in next frame
  10289. */
  10290. refreshHover: function () {
  10291. this._needsRefreshHover = true;
  10292. },
  10293. /**
  10294. * Refresh hover immediately
  10295. */
  10296. refreshHoverImmediately: function () {
  10297. this._needsRefreshHover = false;
  10298. this.painter.refreshHover && this.painter.refreshHover();
  10299. },
  10300. /**
  10301. * Resize the canvas.
  10302. * Should be invoked when container size is changed
  10303. * @param {Object} [opts]
  10304. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10305. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10306. */
  10307. resize: function (opts) {
  10308. opts = opts || {};
  10309. this.painter.resize(opts.width, opts.height);
  10310. this.handler.resize();
  10311. },
  10312. /**
  10313. * Stop and clear all animation immediately
  10314. */
  10315. clearAnimation: function () {
  10316. this.animation.clear();
  10317. },
  10318. /**
  10319. * Get container width
  10320. */
  10321. getWidth: function () {
  10322. return this.painter.getWidth();
  10323. },
  10324. /**
  10325. * Get container height
  10326. */
  10327. getHeight: function () {
  10328. return this.painter.getHeight();
  10329. },
  10330. /**
  10331. * Export the canvas as Base64 URL
  10332. * @param {string} type
  10333. * @param {string} [backgroundColor='#fff']
  10334. * @return {string} Base64 URL
  10335. */
  10336. // toDataURL: function(type, backgroundColor) {
  10337. // return this.painter.getRenderedCanvas({
  10338. // backgroundColor: backgroundColor
  10339. // }).toDataURL(type);
  10340. // },
  10341. /**
  10342. * Converting a path to image.
  10343. * It has much better performance of drawing image rather than drawing a vector path.
  10344. * @param {module:zrender/graphic/Path} e
  10345. * @param {number} width
  10346. * @param {number} height
  10347. */
  10348. pathToImage: function (e, dpr) {
  10349. return this.painter.pathToImage(e, dpr);
  10350. },
  10351. /**
  10352. * Set default cursor
  10353. * @param {string} [cursorStyle='default'] 例如 crosshair
  10354. */
  10355. setCursorStyle: function (cursorStyle) {
  10356. this.handler.setCursorStyle(cursorStyle);
  10357. },
  10358. /**
  10359. * Find hovered element
  10360. * @param {number} x
  10361. * @param {number} y
  10362. * @return {Object} {target, topTarget}
  10363. */
  10364. findHover: function (x, y) {
  10365. return this.handler.findHover(x, y);
  10366. },
  10367. /**
  10368. * Bind event
  10369. *
  10370. * @param {string} eventName Event name
  10371. * @param {Function} eventHandler Handler function
  10372. * @param {Object} [context] Context object
  10373. */
  10374. on: function (eventName, eventHandler, context) {
  10375. this.handler.on(eventName, eventHandler, context);
  10376. },
  10377. /**
  10378. * Unbind event
  10379. * @param {string} eventName Event name
  10380. * @param {Function} [eventHandler] Handler function
  10381. */
  10382. off: function (eventName, eventHandler) {
  10383. this.handler.off(eventName, eventHandler);
  10384. },
  10385. /**
  10386. * Trigger event manually
  10387. *
  10388. * @param {string} eventName Event name
  10389. * @param {event=} event Event object
  10390. */
  10391. trigger: function (eventName, event) {
  10392. this.handler.trigger(eventName, event);
  10393. },
  10394. /**
  10395. * Clear all objects and the canvas.
  10396. */
  10397. clear: function () {
  10398. this.storage.delRoot();
  10399. this.painter.clear();
  10400. },
  10401. /**
  10402. * Dispose self.
  10403. */
  10404. dispose: function () {
  10405. this.animation.stop();
  10406. this.clear();
  10407. this.storage.dispose();
  10408. this.painter.dispose();
  10409. this.handler.dispose();
  10410. this.animation =
  10411. this.storage =
  10412. this.painter =
  10413. this.handler = null;
  10414. delInstance(this.id);
  10415. }
  10416. };
  10417. var zrender = (Object.freeze || Object)({
  10418. version: version$1,
  10419. init: init$1,
  10420. dispose: dispose$1,
  10421. getInstance: getInstance,
  10422. registerPainter: registerPainter
  10423. });
  10424. /*
  10425. * Licensed to the Apache Software Foundation (ASF) under one
  10426. * or more contributor license agreements. See the NOTICE file
  10427. * distributed with this work for additional information
  10428. * regarding copyright ownership. The ASF licenses this file
  10429. * to you under the Apache License, Version 2.0 (the
  10430. * "License"); you may not use this file except in compliance
  10431. * with the License. You may obtain a copy of the License at
  10432. *
  10433. * http://www.apache.org/licenses/LICENSE-2.0
  10434. *
  10435. * Unless required by applicable law or agreed to in writing,
  10436. * software distributed under the License is distributed on an
  10437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10438. * KIND, either express or implied. See the License for the
  10439. * specific language governing permissions and limitations
  10440. * under the License.
  10441. */
  10442. var each$2 = each$1;
  10443. var isObject$2 = isObject$1;
  10444. var isArray$1 = isArray;
  10445. /**
  10446. * Make the name displayable. But we should
  10447. * make sure it is not duplicated with user
  10448. * specified name, so use '\0';
  10449. */
  10450. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10451. /**
  10452. * If value is not array, then translate it to array.
  10453. * @param {*} value
  10454. * @return {Array} [value] or value
  10455. */
  10456. function normalizeToArray(value) {
  10457. return value instanceof Array
  10458. ? value
  10459. : value == null
  10460. ? []
  10461. : [value];
  10462. }
  10463. /**
  10464. * Sync default option between normal and emphasis like `position` and `show`
  10465. * In case some one will write code like
  10466. * label: {
  10467. * show: false,
  10468. * position: 'outside',
  10469. * fontSize: 18
  10470. * },
  10471. * emphasis: {
  10472. * label: { show: true }
  10473. * }
  10474. * @param {Object} opt
  10475. * @param {string} key
  10476. * @param {Array.<string>} subOpts
  10477. */
  10478. function defaultEmphasis(opt, key, subOpts) {
  10479. // Caution: performance sensitive.
  10480. if (opt) {
  10481. opt[key] = opt[key] || {};
  10482. opt.emphasis = opt.emphasis || {};
  10483. opt.emphasis[key] = opt.emphasis[key] || {};
  10484. // Default emphasis option from normal
  10485. for (var i = 0, len = subOpts.length; i < len; i++) {
  10486. var subOptName = subOpts[i];
  10487. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10488. && opt[key].hasOwnProperty(subOptName)
  10489. ) {
  10490. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10491. }
  10492. }
  10493. }
  10494. }
  10495. var TEXT_STYLE_OPTIONS = [
  10496. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10497. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10498. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10499. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10500. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10501. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10502. ];
  10503. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10504. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10505. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10506. // // FIXME: deprecated, check and remove it.
  10507. // 'textStyle'
  10508. // ]);
  10509. /**
  10510. * The method do not ensure performance.
  10511. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10512. * This helper method retieves value from data.
  10513. * @param {string|number|Date|Array|Object} dataItem
  10514. * @return {number|string|Date|Array.<number|string|Date>}
  10515. */
  10516. function getDataItemValue(dataItem) {
  10517. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10518. ? dataItem.value : dataItem;
  10519. }
  10520. /**
  10521. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10522. * This helper method determine if dataItem has extra option besides value
  10523. * @param {string|number|Date|Array|Object} dataItem
  10524. */
  10525. function isDataItemOption(dataItem) {
  10526. return isObject$2(dataItem)
  10527. && !(dataItem instanceof Array);
  10528. // // markLine data can be array
  10529. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10530. }
  10531. /**
  10532. * Mapping to exists for merge.
  10533. *
  10534. * @public
  10535. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10536. * @param {Object|Array.<Object>} newCptOptions
  10537. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10538. * index of which is the same as exists.
  10539. */
  10540. function mappingToExists(exists, newCptOptions) {
  10541. // Mapping by the order by original option (but not order of
  10542. // new option) in merge mode. Because we should ensure
  10543. // some specified index (like xAxisIndex) is consistent with
  10544. // original option, which is easy to understand, espatially in
  10545. // media query. And in most case, merge option is used to
  10546. // update partial option but not be expected to change order.
  10547. newCptOptions = (newCptOptions || []).slice();
  10548. var result = map(exists || [], function (obj, index) {
  10549. return {exist: obj};
  10550. });
  10551. // Mapping by id or name if specified.
  10552. each$2(newCptOptions, function (cptOption, index) {
  10553. if (!isObject$2(cptOption)) {
  10554. return;
  10555. }
  10556. // id has highest priority.
  10557. for (var i = 0; i < result.length; i++) {
  10558. if (!result[i].option // Consider name: two map to one.
  10559. && cptOption.id != null
  10560. && result[i].exist.id === cptOption.id + ''
  10561. ) {
  10562. result[i].option = cptOption;
  10563. newCptOptions[index] = null;
  10564. return;
  10565. }
  10566. }
  10567. for (var i = 0; i < result.length; i++) {
  10568. var exist = result[i].exist;
  10569. if (!result[i].option // Consider name: two map to one.
  10570. // Can not match when both ids exist but different.
  10571. && (exist.id == null || cptOption.id == null)
  10572. && cptOption.name != null
  10573. && !isIdInner(cptOption)
  10574. && !isIdInner(exist)
  10575. && exist.name === cptOption.name + ''
  10576. ) {
  10577. result[i].option = cptOption;
  10578. newCptOptions[index] = null;
  10579. return;
  10580. }
  10581. }
  10582. });
  10583. // Otherwise mapping by index.
  10584. each$2(newCptOptions, function (cptOption, index) {
  10585. if (!isObject$2(cptOption)) {
  10586. return;
  10587. }
  10588. var i = 0;
  10589. for (; i < result.length; i++) {
  10590. var exist = result[i].exist;
  10591. if (!result[i].option
  10592. // Existing model that already has id should be able to
  10593. // mapped to (because after mapping performed model may
  10594. // be assigned with a id, whish should not affect next
  10595. // mapping), except those has inner id.
  10596. && !isIdInner(exist)
  10597. // Caution:
  10598. // Do not overwrite id. But name can be overwritten,
  10599. // because axis use name as 'show label text'.
  10600. // 'exist' always has id and name and we dont
  10601. // need to check it.
  10602. && cptOption.id == null
  10603. ) {
  10604. result[i].option = cptOption;
  10605. break;
  10606. }
  10607. }
  10608. if (i >= result.length) {
  10609. result.push({option: cptOption});
  10610. }
  10611. });
  10612. return result;
  10613. }
  10614. /**
  10615. * Make id and name for mapping result (result of mappingToExists)
  10616. * into `keyInfo` field.
  10617. *
  10618. * @public
  10619. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10620. * which order is the same as exists.
  10621. * @return {Array.<Object>} The input.
  10622. */
  10623. function makeIdAndName(mapResult) {
  10624. // We use this id to hash component models and view instances
  10625. // in echarts. id can be specified by user, or auto generated.
  10626. // The id generation rule ensures new view instance are able
  10627. // to mapped to old instance when setOption are called in
  10628. // no-merge mode. So we generate model id by name and plus
  10629. // type in view id.
  10630. // name can be duplicated among components, which is convenient
  10631. // to specify multi components (like series) by one name.
  10632. // Ensure that each id is distinct.
  10633. var idMap = createHashMap();
  10634. each$2(mapResult, function (item, index) {
  10635. var existCpt = item.exist;
  10636. existCpt && idMap.set(existCpt.id, item);
  10637. });
  10638. each$2(mapResult, function (item, index) {
  10639. var opt = item.option;
  10640. assert$1(
  10641. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10642. 'id duplicates: ' + (opt && opt.id)
  10643. );
  10644. opt && opt.id != null && idMap.set(opt.id, item);
  10645. !item.keyInfo && (item.keyInfo = {});
  10646. });
  10647. // Make name and id.
  10648. each$2(mapResult, function (item, index) {
  10649. var existCpt = item.exist;
  10650. var opt = item.option;
  10651. var keyInfo = item.keyInfo;
  10652. if (!isObject$2(opt)) {
  10653. return;
  10654. }
  10655. // name can be overwitten. Consider case: axis.name = '20km'.
  10656. // But id generated by name will not be changed, which affect
  10657. // only in that case: setOption with 'not merge mode' and view
  10658. // instance will be recreated, which can be accepted.
  10659. keyInfo.name = opt.name != null
  10660. ? opt.name + ''
  10661. : existCpt
  10662. ? existCpt.name
  10663. // Avoid diffferent series has the same name,
  10664. // because name may be used like in color pallet.
  10665. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10666. if (existCpt) {
  10667. keyInfo.id = existCpt.id;
  10668. }
  10669. else if (opt.id != null) {
  10670. keyInfo.id = opt.id + '';
  10671. }
  10672. else {
  10673. // Consider this situatoin:
  10674. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10675. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10676. // Series with the same name between optionA and optionB
  10677. // should be mapped.
  10678. var idNum = 0;
  10679. do {
  10680. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10681. }
  10682. while (idMap.get(keyInfo.id));
  10683. }
  10684. idMap.set(keyInfo.id, item);
  10685. });
  10686. }
  10687. function isNameSpecified(componentModel) {
  10688. var name = componentModel.name;
  10689. // Is specified when `indexOf` get -1 or > 0.
  10690. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10691. }
  10692. /**
  10693. * @public
  10694. * @param {Object} cptOption
  10695. * @return {boolean}
  10696. */
  10697. function isIdInner(cptOption) {
  10698. return isObject$2(cptOption)
  10699. && cptOption.id
  10700. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10701. }
  10702. /**
  10703. * A helper for removing duplicate items between batchA and batchB,
  10704. * and in themselves, and categorize by series.
  10705. *
  10706. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10707. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10708. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10709. */
  10710. /**
  10711. * @param {module:echarts/data/List} data
  10712. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10713. * each of which can be Array or primary type.
  10714. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10715. */
  10716. function queryDataIndex(data, payload) {
  10717. if (payload.dataIndexInside != null) {
  10718. return payload.dataIndexInside;
  10719. }
  10720. else if (payload.dataIndex != null) {
  10721. return isArray(payload.dataIndex)
  10722. ? map(payload.dataIndex, function (value) {
  10723. return data.indexOfRawIndex(value);
  10724. })
  10725. : data.indexOfRawIndex(payload.dataIndex);
  10726. }
  10727. else if (payload.name != null) {
  10728. return isArray(payload.name)
  10729. ? map(payload.name, function (value) {
  10730. return data.indexOfName(value);
  10731. })
  10732. : data.indexOfName(payload.name);
  10733. }
  10734. }
  10735. /**
  10736. * Enable property storage to any host object.
  10737. * Notice: Serialization is not supported.
  10738. *
  10739. * For example:
  10740. * var inner = zrUitl.makeInner();
  10741. *
  10742. * function some1(hostObj) {
  10743. * inner(hostObj).someProperty = 1212;
  10744. * ...
  10745. * }
  10746. * function some2() {
  10747. * var fields = inner(this);
  10748. * fields.someProperty1 = 1212;
  10749. * fields.someProperty2 = 'xx';
  10750. * ...
  10751. * }
  10752. *
  10753. * @return {Function}
  10754. */
  10755. function makeInner() {
  10756. // Consider different scope by es module import.
  10757. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10758. return function (hostObj) {
  10759. return hostObj[key] || (hostObj[key] = {});
  10760. };
  10761. }
  10762. var innerUniqueIndex = 0;
  10763. /**
  10764. * @param {module:echarts/model/Global} ecModel
  10765. * @param {string|Object} finder
  10766. * If string, e.g., 'geo', means {geoIndex: 0}.
  10767. * If Object, could contain some of these properties below:
  10768. * {
  10769. * seriesIndex, seriesId, seriesName,
  10770. * geoIndex, geoId, geoName,
  10771. * bmapIndex, bmapId, bmapName,
  10772. * xAxisIndex, xAxisId, xAxisName,
  10773. * yAxisIndex, yAxisId, yAxisName,
  10774. * gridIndex, gridId, gridName,
  10775. * ... (can be extended)
  10776. * }
  10777. * Each properties can be number|string|Array.<number>|Array.<string>
  10778. * For example, a finder could be
  10779. * {
  10780. * seriesIndex: 3,
  10781. * geoId: ['aa', 'cc'],
  10782. * gridName: ['xx', 'rr']
  10783. * }
  10784. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10785. * If nothing or null/undefined specified, return nothing.
  10786. * @param {Object} [opt]
  10787. * @param {string} [opt.defaultMainType]
  10788. * @param {Array.<string>} [opt.includeMainTypes]
  10789. * @return {Object} result like:
  10790. * {
  10791. * seriesModels: [seriesModel1, seriesModel2],
  10792. * seriesModel: seriesModel1, // The first model
  10793. * geoModels: [geoModel1, geoModel2],
  10794. * geoModel: geoModel1, // The first model
  10795. * ...
  10796. * }
  10797. */
  10798. function parseFinder(ecModel, finder, opt) {
  10799. if (isString(finder)) {
  10800. var obj = {};
  10801. obj[finder + 'Index'] = 0;
  10802. finder = obj;
  10803. }
  10804. var defaultMainType = opt && opt.defaultMainType;
  10805. if (defaultMainType
  10806. && !has(finder, defaultMainType + 'Index')
  10807. && !has(finder, defaultMainType + 'Id')
  10808. && !has(finder, defaultMainType + 'Name')
  10809. ) {
  10810. finder[defaultMainType + 'Index'] = 0;
  10811. }
  10812. var result = {};
  10813. each$2(finder, function (value, key) {
  10814. var value = finder[key];
  10815. // Exclude 'dataIndex' and other illgal keys.
  10816. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10817. result[key] = value;
  10818. return;
  10819. }
  10820. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10821. var mainType = parsedKey[1];
  10822. var queryType = (parsedKey[2] || '').toLowerCase();
  10823. if (!mainType
  10824. || !queryType
  10825. || value == null
  10826. || (queryType === 'index' && value === 'none')
  10827. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10828. ) {
  10829. return;
  10830. }
  10831. var queryParam = {mainType: mainType};
  10832. if (queryType !== 'index' || value !== 'all') {
  10833. queryParam[queryType] = value;
  10834. }
  10835. var models = ecModel.queryComponents(queryParam);
  10836. result[mainType + 'Models'] = models;
  10837. result[mainType + 'Model'] = models[0];
  10838. });
  10839. return result;
  10840. }
  10841. function has(obj, prop) {
  10842. return obj && obj.hasOwnProperty(prop);
  10843. }
  10844. function setAttribute(dom, key, value) {
  10845. dom.setAttribute
  10846. ? dom.setAttribute(key, value)
  10847. : (dom[key] = value);
  10848. }
  10849. function getAttribute(dom, key) {
  10850. return dom.getAttribute
  10851. ? dom.getAttribute(key)
  10852. : dom[key];
  10853. }
  10854. function getTooltipRenderMode(renderModeOption) {
  10855. if (renderModeOption === 'auto') {
  10856. // Using html when `document` exists, use richText otherwise
  10857. return env$1.domSupported ? 'html' : 'richText';
  10858. }
  10859. else {
  10860. return renderModeOption || 'html';
  10861. }
  10862. }
  10863. /**
  10864. * Group a list by key.
  10865. *
  10866. * @param {Array} array
  10867. * @param {Function} getKey
  10868. * param {*} Array item
  10869. * return {string} key
  10870. * @return {Object} Result
  10871. * {Array}: keys,
  10872. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10873. */
  10874. /*
  10875. * Licensed to the Apache Software Foundation (ASF) under one
  10876. * or more contributor license agreements. See the NOTICE file
  10877. * distributed with this work for additional information
  10878. * regarding copyright ownership. The ASF licenses this file
  10879. * to you under the Apache License, Version 2.0 (the
  10880. * "License"); you may not use this file except in compliance
  10881. * with the License. You may obtain a copy of the License at
  10882. *
  10883. * http://www.apache.org/licenses/LICENSE-2.0
  10884. *
  10885. * Unless required by applicable law or agreed to in writing,
  10886. * software distributed under the License is distributed on an
  10887. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10888. * KIND, either express or implied. See the License for the
  10889. * specific language governing permissions and limitations
  10890. * under the License.
  10891. */
  10892. var TYPE_DELIMITER = '.';
  10893. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10894. /**
  10895. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10896. * @public
  10897. */
  10898. function parseClassType$1(componentType) {
  10899. var ret = {main: '', sub: ''};
  10900. if (componentType) {
  10901. componentType = componentType.split(TYPE_DELIMITER);
  10902. ret.main = componentType[0] || '';
  10903. ret.sub = componentType[1] || '';
  10904. }
  10905. return ret;
  10906. }
  10907. /**
  10908. * @public
  10909. */
  10910. function checkClassType(componentType) {
  10911. assert$1(
  10912. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10913. 'componentType "' + componentType + '" illegal'
  10914. );
  10915. }
  10916. /**
  10917. * @public
  10918. */
  10919. function enableClassExtend(RootClass, mandatoryMethods) {
  10920. RootClass.$constructor = RootClass;
  10921. RootClass.extend = function (proto) {
  10922. if (__DEV__) {
  10923. each$1(mandatoryMethods, function (method) {
  10924. if (!proto[method]) {
  10925. console.warn(
  10926. 'Method `' + method + '` should be implemented'
  10927. + (proto.type ? ' in ' + proto.type : '') + '.'
  10928. );
  10929. }
  10930. });
  10931. }
  10932. var superClass = this;
  10933. var ExtendedClass = function () {
  10934. if (!proto.$constructor) {
  10935. superClass.apply(this, arguments);
  10936. }
  10937. else {
  10938. proto.$constructor.apply(this, arguments);
  10939. }
  10940. };
  10941. extend(ExtendedClass.prototype, proto);
  10942. ExtendedClass.extend = this.extend;
  10943. ExtendedClass.superCall = superCall;
  10944. ExtendedClass.superApply = superApply;
  10945. inherits(ExtendedClass, this);
  10946. ExtendedClass.superClass = superClass;
  10947. return ExtendedClass;
  10948. };
  10949. }
  10950. var classBase = 0;
  10951. /**
  10952. * Can not use instanceof, consider different scope by
  10953. * cross domain or es module import in ec extensions.
  10954. * Mount a method "isInstance()" to Clz.
  10955. */
  10956. function enableClassCheck(Clz) {
  10957. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10958. Clz.prototype[classAttr] = true;
  10959. if (__DEV__) {
  10960. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10961. }
  10962. Clz.isInstance = function (obj) {
  10963. return !!(obj && obj[classAttr]);
  10964. };
  10965. }
  10966. // superCall should have class info, which can not be fetch from 'this'.
  10967. // Consider this case:
  10968. // class A has method f,
  10969. // class B inherits class A, overrides method f, f call superApply('f'),
  10970. // class C inherits class B, do not overrides method f,
  10971. // then when method of class C is called, dead loop occured.
  10972. function superCall(context, methodName) {
  10973. var args = slice(arguments, 2);
  10974. return this.superClass.prototype[methodName].apply(context, args);
  10975. }
  10976. function superApply(context, methodName, args) {
  10977. return this.superClass.prototype[methodName].apply(context, args);
  10978. }
  10979. /**
  10980. * @param {Object} entity
  10981. * @param {Object} options
  10982. * @param {boolean} [options.registerWhenExtend]
  10983. * @public
  10984. */
  10985. function enableClassManagement(entity, options) {
  10986. options = options || {};
  10987. /**
  10988. * Component model classes
  10989. * key: componentType,
  10990. * value:
  10991. * componentClass, when componentType is 'xxx'
  10992. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10993. * @type {Object}
  10994. */
  10995. var storage = {};
  10996. entity.registerClass = function (Clazz, componentType) {
  10997. if (componentType) {
  10998. checkClassType(componentType);
  10999. componentType = parseClassType$1(componentType);
  11000. if (!componentType.sub) {
  11001. if (__DEV__) {
  11002. if (storage[componentType.main]) {
  11003. console.warn(componentType.main + ' exists.');
  11004. }
  11005. }
  11006. storage[componentType.main] = Clazz;
  11007. }
  11008. else if (componentType.sub !== IS_CONTAINER) {
  11009. var container = makeContainer(componentType);
  11010. container[componentType.sub] = Clazz;
  11011. }
  11012. }
  11013. return Clazz;
  11014. };
  11015. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  11016. var Clazz = storage[componentMainType];
  11017. if (Clazz && Clazz[IS_CONTAINER]) {
  11018. Clazz = subType ? Clazz[subType] : null;
  11019. }
  11020. if (throwWhenNotFound && !Clazz) {
  11021. throw new Error(
  11022. !subType
  11023. ? componentMainType + '.' + 'type should be specified.'
  11024. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  11025. );
  11026. }
  11027. return Clazz;
  11028. };
  11029. entity.getClassesByMainType = function (componentType) {
  11030. componentType = parseClassType$1(componentType);
  11031. var result = [];
  11032. var obj = storage[componentType.main];
  11033. if (obj && obj[IS_CONTAINER]) {
  11034. each$1(obj, function (o, type) {
  11035. type !== IS_CONTAINER && result.push(o);
  11036. });
  11037. }
  11038. else {
  11039. result.push(obj);
  11040. }
  11041. return result;
  11042. };
  11043. entity.hasClass = function (componentType) {
  11044. // Just consider componentType.main.
  11045. componentType = parseClassType$1(componentType);
  11046. return !!storage[componentType.main];
  11047. };
  11048. /**
  11049. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  11050. */
  11051. entity.getAllClassMainTypes = function () {
  11052. var types = [];
  11053. each$1(storage, function (obj, type) {
  11054. types.push(type);
  11055. });
  11056. return types;
  11057. };
  11058. /**
  11059. * If a main type is container and has sub types
  11060. * @param {string} mainType
  11061. * @return {boolean}
  11062. */
  11063. entity.hasSubTypes = function (componentType) {
  11064. componentType = parseClassType$1(componentType);
  11065. var obj = storage[componentType.main];
  11066. return obj && obj[IS_CONTAINER];
  11067. };
  11068. entity.parseClassType = parseClassType$1;
  11069. function makeContainer(componentType) {
  11070. var container = storage[componentType.main];
  11071. if (!container || !container[IS_CONTAINER]) {
  11072. container = storage[componentType.main] = {};
  11073. container[IS_CONTAINER] = true;
  11074. }
  11075. return container;
  11076. }
  11077. if (options.registerWhenExtend) {
  11078. var originalExtend = entity.extend;
  11079. if (originalExtend) {
  11080. entity.extend = function (proto) {
  11081. var ExtendedClass = originalExtend.call(this, proto);
  11082. return entity.registerClass(ExtendedClass, proto.type);
  11083. };
  11084. }
  11085. }
  11086. return entity;
  11087. }
  11088. /**
  11089. * @param {string|Array.<string>} properties
  11090. */
  11091. /*
  11092. * Licensed to the Apache Software Foundation (ASF) under one
  11093. * or more contributor license agreements. See the NOTICE file
  11094. * distributed with this work for additional information
  11095. * regarding copyright ownership. The ASF licenses this file
  11096. * to you under the Apache License, Version 2.0 (the
  11097. * "License"); you may not use this file except in compliance
  11098. * with the License. You may obtain a copy of the License at
  11099. *
  11100. * http://www.apache.org/licenses/LICENSE-2.0
  11101. *
  11102. * Unless required by applicable law or agreed to in writing,
  11103. * software distributed under the License is distributed on an
  11104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11105. * KIND, either express or implied. See the License for the
  11106. * specific language governing permissions and limitations
  11107. * under the License.
  11108. */
  11109. // TODO Parse shadow style
  11110. // TODO Only shallow path support
  11111. var makeStyleMapper = function (properties) {
  11112. // Normalize
  11113. for (var i = 0; i < properties.length; i++) {
  11114. if (!properties[i][1]) {
  11115. properties[i][1] = properties[i][0];
  11116. }
  11117. }
  11118. return function (model, excludes, includes) {
  11119. var style = {};
  11120. for (var i = 0; i < properties.length; i++) {
  11121. var propName = properties[i][1];
  11122. if ((excludes && indexOf(excludes, propName) >= 0)
  11123. || (includes && indexOf(includes, propName) < 0)
  11124. ) {
  11125. continue;
  11126. }
  11127. var val = model.getShallow(propName);
  11128. if (val != null) {
  11129. style[properties[i][0]] = val;
  11130. }
  11131. }
  11132. return style;
  11133. };
  11134. };
  11135. /*
  11136. * Licensed to the Apache Software Foundation (ASF) under one
  11137. * or more contributor license agreements. See the NOTICE file
  11138. * distributed with this work for additional information
  11139. * regarding copyright ownership. The ASF licenses this file
  11140. * to you under the Apache License, Version 2.0 (the
  11141. * "License"); you may not use this file except in compliance
  11142. * with the License. You may obtain a copy of the License at
  11143. *
  11144. * http://www.apache.org/licenses/LICENSE-2.0
  11145. *
  11146. * Unless required by applicable law or agreed to in writing,
  11147. * software distributed under the License is distributed on an
  11148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11149. * KIND, either express or implied. See the License for the
  11150. * specific language governing permissions and limitations
  11151. * under the License.
  11152. */
  11153. var getLineStyle = makeStyleMapper(
  11154. [
  11155. ['lineWidth', 'width'],
  11156. ['stroke', 'color'],
  11157. ['opacity'],
  11158. ['shadowBlur'],
  11159. ['shadowOffsetX'],
  11160. ['shadowOffsetY'],
  11161. ['shadowColor']
  11162. ]
  11163. );
  11164. var lineStyleMixin = {
  11165. getLineStyle: function (excludes) {
  11166. var style = getLineStyle(this, excludes);
  11167. // Always set lineDash whether dashed, otherwise we can not
  11168. // erase the previous style when assigning to el.style.
  11169. style.lineDash = this.getLineDash(style.lineWidth);
  11170. return style;
  11171. },
  11172. getLineDash: function (lineWidth) {
  11173. if (lineWidth == null) {
  11174. lineWidth = 1;
  11175. }
  11176. var lineType = this.get('type');
  11177. var dotSize = Math.max(lineWidth, 2);
  11178. var dashSize = lineWidth * 4;
  11179. return (lineType === 'solid' || lineType == null)
  11180. // Use `false` but not `null` for the solid line here, because `null` might be
  11181. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  11182. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  11183. // `lineDash` gotten form the latter one is not able to erase that from the former
  11184. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  11185. ? false
  11186. : lineType === 'dashed'
  11187. ? [dashSize, dashSize]
  11188. : [dotSize, dotSize];
  11189. }
  11190. };
  11191. /*
  11192. * Licensed to the Apache Software Foundation (ASF) under one
  11193. * or more contributor license agreements. See the NOTICE file
  11194. * distributed with this work for additional information
  11195. * regarding copyright ownership. The ASF licenses this file
  11196. * to you under the Apache License, Version 2.0 (the
  11197. * "License"); you may not use this file except in compliance
  11198. * with the License. You may obtain a copy of the License at
  11199. *
  11200. * http://www.apache.org/licenses/LICENSE-2.0
  11201. *
  11202. * Unless required by applicable law or agreed to in writing,
  11203. * software distributed under the License is distributed on an
  11204. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  11205. * KIND, either express or implied. See the License for the
  11206. * specific language governing permissions and limitations
  11207. * under the License.
  11208. */
  11209. var getAreaStyle = makeStyleMapper(
  11210. [
  11211. ['fill', 'color'],
  11212. ['shadowBlur'],
  11213. ['shadowOffsetX'],
  11214. ['shadowOffsetY'],
  11215. ['opacity'],
  11216. ['shadowColor']
  11217. ]
  11218. );
  11219. var areaStyleMixin = {
  11220. getAreaStyle: function (excludes, includes) {
  11221. return getAreaStyle(this, excludes, includes);
  11222. }
  11223. };
  11224. /**
  11225. * 曲线辅助模块
  11226. * @module zrender/core/curve
  11227. * @author pissang(https://www.github.com/pissang)
  11228. */
  11229. var mathPow = Math.pow;
  11230. var mathSqrt$2 = Math.sqrt;
  11231. var EPSILON$1 = 1e-8;
  11232. var EPSILON_NUMERIC = 1e-4;
  11233. var THREE_SQRT = mathSqrt$2(3);
  11234. var ONE_THIRD = 1 / 3;
  11235. // 临时变量
  11236. var _v0 = create();
  11237. var _v1 = create();
  11238. var _v2 = create();
  11239. function isAroundZero(val) {
  11240. return val > -EPSILON$1 && val < EPSILON$1;
  11241. }
  11242. function isNotAroundZero$1(val) {
  11243. return val > EPSILON$1 || val < -EPSILON$1;
  11244. }
  11245. /**
  11246. * 计算三次贝塞尔值
  11247. * @memberOf module:zrender/core/curve
  11248. * @param {number} p0
  11249. * @param {number} p1
  11250. * @param {number} p2
  11251. * @param {number} p3
  11252. * @param {number} t
  11253. * @return {number}
  11254. */
  11255. function cubicAt(p0, p1, p2, p3, t) {
  11256. var onet = 1 - t;
  11257. return onet * onet * (onet * p0 + 3 * t * p1)
  11258. + t * t * (t * p3 + 3 * onet * p2);
  11259. }
  11260. /**
  11261. * 计算三次贝塞尔导数值
  11262. * @memberOf module:zrender/core/curve
  11263. * @param {number} p0
  11264. * @param {number} p1
  11265. * @param {number} p2
  11266. * @param {number} p3
  11267. * @param {number} t
  11268. * @return {number}
  11269. */
  11270. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  11271. var onet = 1 - t;
  11272. return 3 * (
  11273. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  11274. + (p3 - p2) * t * t
  11275. );
  11276. }
  11277. /**
  11278. * 计算三次贝塞尔方程根,使用盛金公式
  11279. * @memberOf module:zrender/core/curve
  11280. * @param {number} p0
  11281. * @param {number} p1
  11282. * @param {number} p2
  11283. * @param {number} p3
  11284. * @param {number} val
  11285. * @param {Array.<number>} roots
  11286. * @return {number} 有效根数目
  11287. */
  11288. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  11289. // Evaluate roots of cubic functions
  11290. var a = p3 + 3 * (p1 - p2) - p0;
  11291. var b = 3 * (p2 - p1 * 2 + p0);
  11292. var c = 3 * (p1 - p0);
  11293. var d = p0 - val;
  11294. var A = b * b - 3 * a * c;
  11295. var B = b * c - 9 * a * d;
  11296. var C = c * c - 3 * b * d;
  11297. var n = 0;
  11298. if (isAroundZero(A) && isAroundZero(B)) {
  11299. if (isAroundZero(b)) {
  11300. roots[0] = 0;
  11301. }
  11302. else {
  11303. var t1 = -c / b; //t1, t2, t3, b is not zero
  11304. if (t1 >= 0 && t1 <= 1) {
  11305. roots[n++] = t1;
  11306. }
  11307. }
  11308. }
  11309. else {
  11310. var disc = B * B - 4 * A * C;
  11311. if (isAroundZero(disc)) {
  11312. var K = B / A;
  11313. var t1 = -b / a + K; // t1, a is not zero
  11314. var t2 = -K / 2; // t2, t3
  11315. if (t1 >= 0 && t1 <= 1) {
  11316. roots[n++] = t1;
  11317. }
  11318. if (t2 >= 0 && t2 <= 1) {
  11319. roots[n++] = t2;
  11320. }
  11321. }
  11322. else if (disc > 0) {
  11323. var discSqrt = mathSqrt$2(disc);
  11324. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  11325. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  11326. if (Y1 < 0) {
  11327. Y1 = -mathPow(-Y1, ONE_THIRD);
  11328. }
  11329. else {
  11330. Y1 = mathPow(Y1, ONE_THIRD);
  11331. }
  11332. if (Y2 < 0) {
  11333. Y2 = -mathPow(-Y2, ONE_THIRD);
  11334. }
  11335. else {
  11336. Y2 = mathPow(Y2, ONE_THIRD);
  11337. }
  11338. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  11339. if (t1 >= 0 && t1 <= 1) {
  11340. roots[n++] = t1;
  11341. }
  11342. }
  11343. else {
  11344. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11345. var theta = Math.acos(T) / 3;
  11346. var ASqrt = mathSqrt$2(A);
  11347. var tmp = Math.cos(theta);
  11348. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11349. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11350. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11351. if (t1 >= 0 && t1 <= 1) {
  11352. roots[n++] = t1;
  11353. }
  11354. if (t2 >= 0 && t2 <= 1) {
  11355. roots[n++] = t2;
  11356. }
  11357. if (t3 >= 0 && t3 <= 1) {
  11358. roots[n++] = t3;
  11359. }
  11360. }
  11361. }
  11362. return n;
  11363. }
  11364. /**
  11365. * 计算三次贝塞尔方程极限值的位置
  11366. * @memberOf module:zrender/core/curve
  11367. * @param {number} p0
  11368. * @param {number} p1
  11369. * @param {number} p2
  11370. * @param {number} p3
  11371. * @param {Array.<number>} extrema
  11372. * @return {number} 有效数目
  11373. */
  11374. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11375. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11376. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11377. var c = 3 * p1 - 3 * p0;
  11378. var n = 0;
  11379. if (isAroundZero(a)) {
  11380. if (isNotAroundZero$1(b)) {
  11381. var t1 = -c / b;
  11382. if (t1 >= 0 && t1 <= 1) {
  11383. extrema[n++] = t1;
  11384. }
  11385. }
  11386. }
  11387. else {
  11388. var disc = b * b - 4 * a * c;
  11389. if (isAroundZero(disc)) {
  11390. extrema[0] = -b / (2 * a);
  11391. }
  11392. else if (disc > 0) {
  11393. var discSqrt = mathSqrt$2(disc);
  11394. var t1 = (-b + discSqrt) / (2 * a);
  11395. var t2 = (-b - discSqrt) / (2 * a);
  11396. if (t1 >= 0 && t1 <= 1) {
  11397. extrema[n++] = t1;
  11398. }
  11399. if (t2 >= 0 && t2 <= 1) {
  11400. extrema[n++] = t2;
  11401. }
  11402. }
  11403. }
  11404. return n;
  11405. }
  11406. /**
  11407. * 细分三次贝塞尔曲线
  11408. * @memberOf module:zrender/core/curve
  11409. * @param {number} p0
  11410. * @param {number} p1
  11411. * @param {number} p2
  11412. * @param {number} p3
  11413. * @param {number} t
  11414. * @param {Array.<number>} out
  11415. */
  11416. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11417. var p01 = (p1 - p0) * t + p0;
  11418. var p12 = (p2 - p1) * t + p1;
  11419. var p23 = (p3 - p2) * t + p2;
  11420. var p012 = (p12 - p01) * t + p01;
  11421. var p123 = (p23 - p12) * t + p12;
  11422. var p0123 = (p123 - p012) * t + p012;
  11423. // Seg0
  11424. out[0] = p0;
  11425. out[1] = p01;
  11426. out[2] = p012;
  11427. out[3] = p0123;
  11428. // Seg1
  11429. out[4] = p0123;
  11430. out[5] = p123;
  11431. out[6] = p23;
  11432. out[7] = p3;
  11433. }
  11434. /**
  11435. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11436. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11437. * @param {number} x0
  11438. * @param {number} y0
  11439. * @param {number} x1
  11440. * @param {number} y1
  11441. * @param {number} x2
  11442. * @param {number} y2
  11443. * @param {number} x3
  11444. * @param {number} y3
  11445. * @param {number} x
  11446. * @param {number} y
  11447. * @param {Array.<number>} [out] 投射点
  11448. * @return {number}
  11449. */
  11450. function cubicProjectPoint(
  11451. x0, y0, x1, y1, x2, y2, x3, y3,
  11452. x, y, out
  11453. ) {
  11454. // http://pomax.github.io/bezierinfo/#projections
  11455. var t;
  11456. var interval = 0.005;
  11457. var d = Infinity;
  11458. var prev;
  11459. var next;
  11460. var d1;
  11461. var d2;
  11462. _v0[0] = x;
  11463. _v0[1] = y;
  11464. // 先粗略估计一下可能的最小距离的 t 值
  11465. // PENDING
  11466. for (var _t = 0; _t < 1; _t += 0.05) {
  11467. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11468. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11469. d1 = distSquare(_v0, _v1);
  11470. if (d1 < d) {
  11471. t = _t;
  11472. d = d1;
  11473. }
  11474. }
  11475. d = Infinity;
  11476. // At most 32 iteration
  11477. for (var i = 0; i < 32; i++) {
  11478. if (interval < EPSILON_NUMERIC) {
  11479. break;
  11480. }
  11481. prev = t - interval;
  11482. next = t + interval;
  11483. // t - interval
  11484. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11485. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11486. d1 = distSquare(_v1, _v0);
  11487. if (prev >= 0 && d1 < d) {
  11488. t = prev;
  11489. d = d1;
  11490. }
  11491. else {
  11492. // t + interval
  11493. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11494. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11495. d2 = distSquare(_v2, _v0);
  11496. if (next <= 1 && d2 < d) {
  11497. t = next;
  11498. d = d2;
  11499. }
  11500. else {
  11501. interval *= 0.5;
  11502. }
  11503. }
  11504. }
  11505. // t
  11506. if (out) {
  11507. out[0] = cubicAt(x0, x1, x2, x3, t);
  11508. out[1] = cubicAt(y0, y1, y2, y3, t);
  11509. }
  11510. // console.log(interval, i);
  11511. return mathSqrt$2(d);
  11512. }
  11513. /**
  11514. * 计算二次方贝塞尔值
  11515. * @param {number} p0
  11516. * @param {number} p1
  11517. * @param {number} p2
  11518. * @param {number} t
  11519. * @return {number}
  11520. */
  11521. function quadraticAt(p0, p1, p2, t) {
  11522. var onet = 1 - t;
  11523. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11524. }
  11525. /**
  11526. * 计算二次方贝塞尔导数值
  11527. * @param {number} p0
  11528. * @param {number} p1
  11529. * @param {number} p2
  11530. * @param {number} t
  11531. * @return {number}
  11532. */
  11533. function quadraticDerivativeAt(p0, p1, p2, t) {
  11534. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11535. }
  11536. /**
  11537. * 计算二次方贝塞尔方程根
  11538. * @param {number} p0
  11539. * @param {number} p1
  11540. * @param {number} p2
  11541. * @param {number} t
  11542. * @param {Array.<number>} roots
  11543. * @return {number} 有效根数目
  11544. */
  11545. function quadraticRootAt(p0, p1, p2, val, roots) {
  11546. var a = p0 - 2 * p1 + p2;
  11547. var b = 2 * (p1 - p0);
  11548. var c = p0 - val;
  11549. var n = 0;
  11550. if (isAroundZero(a)) {
  11551. if (isNotAroundZero$1(b)) {
  11552. var t1 = -c / b;
  11553. if (t1 >= 0 && t1 <= 1) {
  11554. roots[n++] = t1;
  11555. }
  11556. }
  11557. }
  11558. else {
  11559. var disc = b * b - 4 * a * c;
  11560. if (isAroundZero(disc)) {
  11561. var t1 = -b / (2 * a);
  11562. if (t1 >= 0 && t1 <= 1) {
  11563. roots[n++] = t1;
  11564. }
  11565. }
  11566. else if (disc > 0) {
  11567. var discSqrt = mathSqrt$2(disc);
  11568. var t1 = (-b + discSqrt) / (2 * a);
  11569. var t2 = (-b - discSqrt) / (2 * a);
  11570. if (t1 >= 0 && t1 <= 1) {
  11571. roots[n++] = t1;
  11572. }
  11573. if (t2 >= 0 && t2 <= 1) {
  11574. roots[n++] = t2;
  11575. }
  11576. }
  11577. }
  11578. return n;
  11579. }
  11580. /**
  11581. * 计算二次贝塞尔方程极限值
  11582. * @memberOf module:zrender/core/curve
  11583. * @param {number} p0
  11584. * @param {number} p1
  11585. * @param {number} p2
  11586. * @return {number}
  11587. */
  11588. function quadraticExtremum(p0, p1, p2) {
  11589. var divider = p0 + p2 - 2 * p1;
  11590. if (divider === 0) {
  11591. // p1 is center of p0 and p2
  11592. return 0.5;
  11593. }
  11594. else {
  11595. return (p0 - p1) / divider;
  11596. }
  11597. }
  11598. /**
  11599. * 细分二次贝塞尔曲线
  11600. * @memberOf module:zrender/core/curve
  11601. * @param {number} p0
  11602. * @param {number} p1
  11603. * @param {number} p2
  11604. * @param {number} t
  11605. * @param {Array.<number>} out
  11606. */
  11607. function quadraticSubdivide(p0, p1, p2, t, out) {
  11608. var p01 = (p1 - p0) * t + p0;
  11609. var p12 = (p2 - p1) * t + p1;
  11610. var p012 = (p12 - p01) * t + p01;
  11611. // Seg0
  11612. out[0] = p0;
  11613. out[1] = p01;
  11614. out[2] = p012;
  11615. // Seg1
  11616. out[3] = p012;
  11617. out[4] = p12;
  11618. out[5] = p2;
  11619. }
  11620. /**
  11621. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11622. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11623. * @param {number} x0
  11624. * @param {number} y0
  11625. * @param {number} x1
  11626. * @param {number} y1
  11627. * @param {number} x2
  11628. * @param {number} y2
  11629. * @param {number} x
  11630. * @param {number} y
  11631. * @param {Array.<number>} out 投射点
  11632. * @return {number}
  11633. */
  11634. function quadraticProjectPoint(
  11635. x0, y0, x1, y1, x2, y2,
  11636. x, y, out
  11637. ) {
  11638. // http://pomax.github.io/bezierinfo/#projections
  11639. var t;
  11640. var interval = 0.005;
  11641. var d = Infinity;
  11642. _v0[0] = x;
  11643. _v0[1] = y;
  11644. // 先粗略估计一下可能的最小距离的 t 值
  11645. // PENDING
  11646. for (var _t = 0; _t < 1; _t += 0.05) {
  11647. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11648. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11649. var d1 = distSquare(_v0, _v1);
  11650. if (d1 < d) {
  11651. t = _t;
  11652. d = d1;
  11653. }
  11654. }
  11655. d = Infinity;
  11656. // At most 32 iteration
  11657. for (var i = 0; i < 32; i++) {
  11658. if (interval < EPSILON_NUMERIC) {
  11659. break;
  11660. }
  11661. var prev = t - interval;
  11662. var next = t + interval;
  11663. // t - interval
  11664. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11665. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11666. var d1 = distSquare(_v1, _v0);
  11667. if (prev >= 0 && d1 < d) {
  11668. t = prev;
  11669. d = d1;
  11670. }
  11671. else {
  11672. // t + interval
  11673. _v2[0] = quadraticAt(x0, x1, x2, next);
  11674. _v2[1] = quadraticAt(y0, y1, y2, next);
  11675. var d2 = distSquare(_v2, _v0);
  11676. if (next <= 1 && d2 < d) {
  11677. t = next;
  11678. d = d2;
  11679. }
  11680. else {
  11681. interval *= 0.5;
  11682. }
  11683. }
  11684. }
  11685. // t
  11686. if (out) {
  11687. out[0] = quadraticAt(x0, x1, x2, t);
  11688. out[1] = quadraticAt(y0, y1, y2, t);
  11689. }
  11690. // console.log(interval, i);
  11691. return mathSqrt$2(d);
  11692. }
  11693. /**
  11694. * @author Yi Shen(https://github.com/pissang)
  11695. */
  11696. var mathMin$3 = Math.min;
  11697. var mathMax$3 = Math.max;
  11698. var mathSin$2 = Math.sin;
  11699. var mathCos$2 = Math.cos;
  11700. var PI2 = Math.PI * 2;
  11701. var start = create();
  11702. var end = create();
  11703. var extremity = create();
  11704. /**
  11705. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11706. * @module zrender/core/bbox
  11707. * @param {Array<Object>} points 顶点数组
  11708. * @param {number} min
  11709. * @param {number} max
  11710. */
  11711. function fromPoints(points, min$$1, max$$1) {
  11712. if (points.length === 0) {
  11713. return;
  11714. }
  11715. var p = points[0];
  11716. var left = p[0];
  11717. var right = p[0];
  11718. var top = p[1];
  11719. var bottom = p[1];
  11720. var i;
  11721. for (i = 1; i < points.length; i++) {
  11722. p = points[i];
  11723. left = mathMin$3(left, p[0]);
  11724. right = mathMax$3(right, p[0]);
  11725. top = mathMin$3(top, p[1]);
  11726. bottom = mathMax$3(bottom, p[1]);
  11727. }
  11728. min$$1[0] = left;
  11729. min$$1[1] = top;
  11730. max$$1[0] = right;
  11731. max$$1[1] = bottom;
  11732. }
  11733. /**
  11734. * @memberOf module:zrender/core/bbox
  11735. * @param {number} x0
  11736. * @param {number} y0
  11737. * @param {number} x1
  11738. * @param {number} y1
  11739. * @param {Array.<number>} min
  11740. * @param {Array.<number>} max
  11741. */
  11742. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11743. min$$1[0] = mathMin$3(x0, x1);
  11744. min$$1[1] = mathMin$3(y0, y1);
  11745. max$$1[0] = mathMax$3(x0, x1);
  11746. max$$1[1] = mathMax$3(y0, y1);
  11747. }
  11748. var xDim = [];
  11749. var yDim = [];
  11750. /**
  11751. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11752. * @memberOf module:zrender/core/bbox
  11753. * @param {number} x0
  11754. * @param {number} y0
  11755. * @param {number} x1
  11756. * @param {number} y1
  11757. * @param {number} x2
  11758. * @param {number} y2
  11759. * @param {number} x3
  11760. * @param {number} y3
  11761. * @param {Array.<number>} min
  11762. * @param {Array.<number>} max
  11763. */
  11764. function fromCubic(
  11765. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11766. ) {
  11767. var cubicExtrema$$1 = cubicExtrema;
  11768. var cubicAt$$1 = cubicAt;
  11769. var i;
  11770. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11771. min$$1[0] = Infinity;
  11772. min$$1[1] = Infinity;
  11773. max$$1[0] = -Infinity;
  11774. max$$1[1] = -Infinity;
  11775. for (i = 0; i < n; i++) {
  11776. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11777. min$$1[0] = mathMin$3(x, min$$1[0]);
  11778. max$$1[0] = mathMax$3(x, max$$1[0]);
  11779. }
  11780. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11781. for (i = 0; i < n; i++) {
  11782. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11783. min$$1[1] = mathMin$3(y, min$$1[1]);
  11784. max$$1[1] = mathMax$3(y, max$$1[1]);
  11785. }
  11786. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11787. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11788. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11789. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11790. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11791. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11792. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11793. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11794. }
  11795. /**
  11796. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11797. * @memberOf module:zrender/core/bbox
  11798. * @param {number} x0
  11799. * @param {number} y0
  11800. * @param {number} x1
  11801. * @param {number} y1
  11802. * @param {number} x2
  11803. * @param {number} y2
  11804. * @param {Array.<number>} min
  11805. * @param {Array.<number>} max
  11806. */
  11807. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11808. var quadraticExtremum$$1 = quadraticExtremum;
  11809. var quadraticAt$$1 = quadraticAt;
  11810. // Find extremities, where derivative in x dim or y dim is zero
  11811. var tx =
  11812. mathMax$3(
  11813. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11814. );
  11815. var ty =
  11816. mathMax$3(
  11817. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11818. );
  11819. var x = quadraticAt$$1(x0, x1, x2, tx);
  11820. var y = quadraticAt$$1(y0, y1, y2, ty);
  11821. min$$1[0] = mathMin$3(x0, x2, x);
  11822. min$$1[1] = mathMin$3(y0, y2, y);
  11823. max$$1[0] = mathMax$3(x0, x2, x);
  11824. max$$1[1] = mathMax$3(y0, y2, y);
  11825. }
  11826. /**
  11827. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11828. * @method
  11829. * @memberOf module:zrender/core/bbox
  11830. * @param {number} x
  11831. * @param {number} y
  11832. * @param {number} rx
  11833. * @param {number} ry
  11834. * @param {number} startAngle
  11835. * @param {number} endAngle
  11836. * @param {number} anticlockwise
  11837. * @param {Array.<number>} min
  11838. * @param {Array.<number>} max
  11839. */
  11840. function fromArc(
  11841. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11842. ) {
  11843. var vec2Min = min;
  11844. var vec2Max = max;
  11845. var diff = Math.abs(startAngle - endAngle);
  11846. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11847. // Is a circle
  11848. min$$1[0] = x - rx;
  11849. min$$1[1] = y - ry;
  11850. max$$1[0] = x + rx;
  11851. max$$1[1] = y + ry;
  11852. return;
  11853. }
  11854. start[0] = mathCos$2(startAngle) * rx + x;
  11855. start[1] = mathSin$2(startAngle) * ry + y;
  11856. end[0] = mathCos$2(endAngle) * rx + x;
  11857. end[1] = mathSin$2(endAngle) * ry + y;
  11858. vec2Min(min$$1, start, end);
  11859. vec2Max(max$$1, start, end);
  11860. // Thresh to [0, Math.PI * 2]
  11861. startAngle = startAngle % (PI2);
  11862. if (startAngle < 0) {
  11863. startAngle = startAngle + PI2;
  11864. }
  11865. endAngle = endAngle % (PI2);
  11866. if (endAngle < 0) {
  11867. endAngle = endAngle + PI2;
  11868. }
  11869. if (startAngle > endAngle && !anticlockwise) {
  11870. endAngle += PI2;
  11871. }
  11872. else if (startAngle < endAngle && anticlockwise) {
  11873. startAngle += PI2;
  11874. }
  11875. if (anticlockwise) {
  11876. var tmp = endAngle;
  11877. endAngle = startAngle;
  11878. startAngle = tmp;
  11879. }
  11880. // var number = 0;
  11881. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11882. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11883. if (angle > startAngle) {
  11884. extremity[0] = mathCos$2(angle) * rx + x;
  11885. extremity[1] = mathSin$2(angle) * ry + y;
  11886. vec2Min(min$$1, extremity, min$$1);
  11887. vec2Max(max$$1, extremity, max$$1);
  11888. }
  11889. }
  11890. }
  11891. /**
  11892. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11893. * 可以用于 isInsidePath 判断以及获取boundingRect
  11894. *
  11895. * @module zrender/core/PathProxy
  11896. * @author Yi Shen (http://www.github.com/pissang)
  11897. */
  11898. // TODO getTotalLength, getPointAtLength
  11899. /* global Float32Array */
  11900. var CMD = {
  11901. M: 1,
  11902. L: 2,
  11903. C: 3,
  11904. Q: 4,
  11905. A: 5,
  11906. Z: 6,
  11907. // Rect
  11908. R: 7
  11909. };
  11910. // var CMD_MEM_SIZE = {
  11911. // M: 3,
  11912. // L: 3,
  11913. // C: 7,
  11914. // Q: 5,
  11915. // A: 9,
  11916. // R: 5,
  11917. // Z: 1
  11918. // };
  11919. var min$1 = [];
  11920. var max$1 = [];
  11921. var min2 = [];
  11922. var max2 = [];
  11923. var mathMin$2 = Math.min;
  11924. var mathMax$2 = Math.max;
  11925. var mathCos$1 = Math.cos;
  11926. var mathSin$1 = Math.sin;
  11927. var mathSqrt$1 = Math.sqrt;
  11928. var mathAbs = Math.abs;
  11929. var hasTypedArray = typeof Float32Array !== 'undefined';
  11930. /**
  11931. * @alias module:zrender/core/PathProxy
  11932. * @constructor
  11933. */
  11934. var PathProxy = function (notSaveData) {
  11935. this._saveData = !(notSaveData || false);
  11936. if (this._saveData) {
  11937. /**
  11938. * Path data. Stored as flat array
  11939. * @type {Array.<Object>}
  11940. */
  11941. this.data = [];
  11942. }
  11943. this._ctx = null;
  11944. };
  11945. /**
  11946. * 快速计算Path包围盒(并不是最小包围盒)
  11947. * @return {Object}
  11948. */
  11949. PathProxy.prototype = {
  11950. constructor: PathProxy,
  11951. _xi: 0,
  11952. _yi: 0,
  11953. _x0: 0,
  11954. _y0: 0,
  11955. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11956. _ux: 0,
  11957. _uy: 0,
  11958. _len: 0,
  11959. _lineDash: null,
  11960. _dashOffset: 0,
  11961. _dashIdx: 0,
  11962. _dashSum: 0,
  11963. /**
  11964. * @readOnly
  11965. */
  11966. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11967. // Compat. Previously there is no segmentIgnoreThreshold.
  11968. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11969. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11970. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11971. },
  11972. getContext: function () {
  11973. return this._ctx;
  11974. },
  11975. /**
  11976. * @param {CanvasRenderingContext2D} ctx
  11977. * @return {module:zrender/core/PathProxy}
  11978. */
  11979. beginPath: function (ctx) {
  11980. this._ctx = ctx;
  11981. ctx && ctx.beginPath();
  11982. ctx && (this.dpr = ctx.dpr);
  11983. // Reset
  11984. if (this._saveData) {
  11985. this._len = 0;
  11986. }
  11987. if (this._lineDash) {
  11988. this._lineDash = null;
  11989. this._dashOffset = 0;
  11990. }
  11991. return this;
  11992. },
  11993. /**
  11994. * @param {number} x
  11995. * @param {number} y
  11996. * @return {module:zrender/core/PathProxy}
  11997. */
  11998. moveTo: function (x, y) {
  11999. this.addData(CMD.M, x, y);
  12000. this._ctx && this._ctx.moveTo(x, y);
  12001. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  12002. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  12003. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  12004. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  12005. this._x0 = x;
  12006. this._y0 = y;
  12007. this._xi = x;
  12008. this._yi = y;
  12009. return this;
  12010. },
  12011. /**
  12012. * @param {number} x
  12013. * @param {number} y
  12014. * @return {module:zrender/core/PathProxy}
  12015. */
  12016. lineTo: function (x, y) {
  12017. var exceedUnit = mathAbs(x - this._xi) > this._ux
  12018. || mathAbs(y - this._yi) > this._uy
  12019. // Force draw the first segment
  12020. || this._len < 5;
  12021. this.addData(CMD.L, x, y);
  12022. if (this._ctx && exceedUnit) {
  12023. this._needsDash() ? this._dashedLineTo(x, y)
  12024. : this._ctx.lineTo(x, y);
  12025. }
  12026. if (exceedUnit) {
  12027. this._xi = x;
  12028. this._yi = y;
  12029. }
  12030. return this;
  12031. },
  12032. /**
  12033. * @param {number} x1
  12034. * @param {number} y1
  12035. * @param {number} x2
  12036. * @param {number} y2
  12037. * @param {number} x3
  12038. * @param {number} y3
  12039. * @return {module:zrender/core/PathProxy}
  12040. */
  12041. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  12042. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  12043. if (this._ctx) {
  12044. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  12045. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  12046. }
  12047. this._xi = x3;
  12048. this._yi = y3;
  12049. return this;
  12050. },
  12051. /**
  12052. * @param {number} x1
  12053. * @param {number} y1
  12054. * @param {number} x2
  12055. * @param {number} y2
  12056. * @return {module:zrender/core/PathProxy}
  12057. */
  12058. quadraticCurveTo: function (x1, y1, x2, y2) {
  12059. this.addData(CMD.Q, x1, y1, x2, y2);
  12060. if (this._ctx) {
  12061. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  12062. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  12063. }
  12064. this._xi = x2;
  12065. this._yi = y2;
  12066. return this;
  12067. },
  12068. /**
  12069. * @param {number} cx
  12070. * @param {number} cy
  12071. * @param {number} r
  12072. * @param {number} startAngle
  12073. * @param {number} endAngle
  12074. * @param {boolean} anticlockwise
  12075. * @return {module:zrender/core/PathProxy}
  12076. */
  12077. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  12078. this.addData(
  12079. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  12080. );
  12081. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  12082. this._xi = mathCos$1(endAngle) * r + cx;
  12083. this._yi = mathSin$1(endAngle) * r + cy;
  12084. return this;
  12085. },
  12086. // TODO
  12087. arcTo: function (x1, y1, x2, y2, radius) {
  12088. if (this._ctx) {
  12089. this._ctx.arcTo(x1, y1, x2, y2, radius);
  12090. }
  12091. return this;
  12092. },
  12093. // TODO
  12094. rect: function (x, y, w, h) {
  12095. this._ctx && this._ctx.rect(x, y, w, h);
  12096. this.addData(CMD.R, x, y, w, h);
  12097. return this;
  12098. },
  12099. /**
  12100. * @return {module:zrender/core/PathProxy}
  12101. */
  12102. closePath: function () {
  12103. this.addData(CMD.Z);
  12104. var ctx = this._ctx;
  12105. var x0 = this._x0;
  12106. var y0 = this._y0;
  12107. if (ctx) {
  12108. this._needsDash() && this._dashedLineTo(x0, y0);
  12109. ctx.closePath();
  12110. }
  12111. this._xi = x0;
  12112. this._yi = y0;
  12113. return this;
  12114. },
  12115. /**
  12116. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  12117. * stroke 同样
  12118. * @param {CanvasRenderingContext2D} ctx
  12119. * @return {module:zrender/core/PathProxy}
  12120. */
  12121. fill: function (ctx) {
  12122. ctx && ctx.fill();
  12123. this.toStatic();
  12124. },
  12125. /**
  12126. * @param {CanvasRenderingContext2D} ctx
  12127. * @return {module:zrender/core/PathProxy}
  12128. */
  12129. stroke: function (ctx) {
  12130. ctx && ctx.stroke();
  12131. this.toStatic();
  12132. },
  12133. /**
  12134. * 必须在其它绘制命令前调用
  12135. * Must be invoked before all other path drawing methods
  12136. * @return {module:zrender/core/PathProxy}
  12137. */
  12138. setLineDash: function (lineDash) {
  12139. if (lineDash instanceof Array) {
  12140. this._lineDash = lineDash;
  12141. this._dashIdx = 0;
  12142. var lineDashSum = 0;
  12143. for (var i = 0; i < lineDash.length; i++) {
  12144. lineDashSum += lineDash[i];
  12145. }
  12146. this._dashSum = lineDashSum;
  12147. }
  12148. return this;
  12149. },
  12150. /**
  12151. * 必须在其它绘制命令前调用
  12152. * Must be invoked before all other path drawing methods
  12153. * @return {module:zrender/core/PathProxy}
  12154. */
  12155. setLineDashOffset: function (offset) {
  12156. this._dashOffset = offset;
  12157. return this;
  12158. },
  12159. /**
  12160. *
  12161. * @return {boolean}
  12162. */
  12163. len: function () {
  12164. return this._len;
  12165. },
  12166. /**
  12167. * 直接设置 Path 数据
  12168. */
  12169. setData: function (data) {
  12170. var len$$1 = data.length;
  12171. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  12172. this.data = new Float32Array(len$$1);
  12173. }
  12174. for (var i = 0; i < len$$1; i++) {
  12175. this.data[i] = data[i];
  12176. }
  12177. this._len = len$$1;
  12178. },
  12179. /**
  12180. * 添加子路径
  12181. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  12182. */
  12183. appendPath: function (path) {
  12184. if (!(path instanceof Array)) {
  12185. path = [path];
  12186. }
  12187. var len$$1 = path.length;
  12188. var appendSize = 0;
  12189. var offset = this._len;
  12190. for (var i = 0; i < len$$1; i++) {
  12191. appendSize += path[i].len();
  12192. }
  12193. if (hasTypedArray && (this.data instanceof Float32Array)) {
  12194. this.data = new Float32Array(offset + appendSize);
  12195. }
  12196. for (var i = 0; i < len$$1; i++) {
  12197. var appendPathData = path[i].data;
  12198. for (var k = 0; k < appendPathData.length; k++) {
  12199. this.data[offset++] = appendPathData[k];
  12200. }
  12201. }
  12202. this._len = offset;
  12203. },
  12204. /**
  12205. * 填充 Path 数据。
  12206. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  12207. */
  12208. addData: function (cmd) {
  12209. if (!this._saveData) {
  12210. return;
  12211. }
  12212. var data = this.data;
  12213. if (this._len + arguments.length > data.length) {
  12214. // 因为之前的数组已经转换成静态的 Float32Array
  12215. // 所以不够用时需要扩展一个新的动态数组
  12216. this._expandData();
  12217. data = this.data;
  12218. }
  12219. for (var i = 0; i < arguments.length; i++) {
  12220. data[this._len++] = arguments[i];
  12221. }
  12222. this._prevCmd = cmd;
  12223. },
  12224. _expandData: function () {
  12225. // Only if data is Float32Array
  12226. if (!(this.data instanceof Array)) {
  12227. var newData = [];
  12228. for (var i = 0; i < this._len; i++) {
  12229. newData[i] = this.data[i];
  12230. }
  12231. this.data = newData;
  12232. }
  12233. },
  12234. /**
  12235. * If needs js implemented dashed line
  12236. * @return {boolean}
  12237. * @private
  12238. */
  12239. _needsDash: function () {
  12240. return this._lineDash;
  12241. },
  12242. _dashedLineTo: function (x1, y1) {
  12243. var dashSum = this._dashSum;
  12244. var offset = this._dashOffset;
  12245. var lineDash = this._lineDash;
  12246. var ctx = this._ctx;
  12247. var x0 = this._xi;
  12248. var y0 = this._yi;
  12249. var dx = x1 - x0;
  12250. var dy = y1 - y0;
  12251. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  12252. var x = x0;
  12253. var y = y0;
  12254. var dash;
  12255. var nDash = lineDash.length;
  12256. var idx;
  12257. dx /= dist$$1;
  12258. dy /= dist$$1;
  12259. if (offset < 0) {
  12260. // Convert to positive offset
  12261. offset = dashSum + offset;
  12262. }
  12263. offset %= dashSum;
  12264. x -= offset * dx;
  12265. y -= offset * dy;
  12266. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  12267. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  12268. idx = this._dashIdx;
  12269. dash = lineDash[idx];
  12270. x += dx * dash;
  12271. y += dy * dash;
  12272. this._dashIdx = (idx + 1) % nDash;
  12273. // Skip positive offset
  12274. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  12275. continue;
  12276. }
  12277. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  12278. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  12279. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  12280. );
  12281. }
  12282. // Offset for next lineTo
  12283. dx = x - x1;
  12284. dy = y - y1;
  12285. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12286. },
  12287. // Not accurate dashed line to
  12288. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  12289. var dashSum = this._dashSum;
  12290. var offset = this._dashOffset;
  12291. var lineDash = this._lineDash;
  12292. var ctx = this._ctx;
  12293. var x0 = this._xi;
  12294. var y0 = this._yi;
  12295. var t;
  12296. var dx;
  12297. var dy;
  12298. var cubicAt$$1 = cubicAt;
  12299. var bezierLen = 0;
  12300. var idx = this._dashIdx;
  12301. var nDash = lineDash.length;
  12302. var x;
  12303. var y;
  12304. var tmpLen = 0;
  12305. if (offset < 0) {
  12306. // Convert to positive offset
  12307. offset = dashSum + offset;
  12308. }
  12309. offset %= dashSum;
  12310. // Bezier approx length
  12311. for (t = 0; t < 1; t += 0.1) {
  12312. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  12313. - cubicAt$$1(x0, x1, x2, x3, t);
  12314. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  12315. - cubicAt$$1(y0, y1, y2, y3, t);
  12316. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  12317. }
  12318. // Find idx after add offset
  12319. for (; idx < nDash; idx++) {
  12320. tmpLen += lineDash[idx];
  12321. if (tmpLen > offset) {
  12322. break;
  12323. }
  12324. }
  12325. t = (tmpLen - offset) / bezierLen;
  12326. while (t <= 1) {
  12327. x = cubicAt$$1(x0, x1, x2, x3, t);
  12328. y = cubicAt$$1(y0, y1, y2, y3, t);
  12329. // Use line to approximate dashed bezier
  12330. // Bad result if dash is long
  12331. idx % 2 ? ctx.moveTo(x, y)
  12332. : ctx.lineTo(x, y);
  12333. t += lineDash[idx] / bezierLen;
  12334. idx = (idx + 1) % nDash;
  12335. }
  12336. // Finish the last segment and calculate the new offset
  12337. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  12338. dx = x3 - x;
  12339. dy = y3 - y;
  12340. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  12341. },
  12342. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  12343. // Convert quadratic to cubic using degree elevation
  12344. var x3 = x2;
  12345. var y3 = y2;
  12346. x2 = (x2 + 2 * x1) / 3;
  12347. y2 = (y2 + 2 * y1) / 3;
  12348. x1 = (this._xi + 2 * x1) / 3;
  12349. y1 = (this._yi + 2 * y1) / 3;
  12350. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  12351. },
  12352. /**
  12353. * 转成静态的 Float32Array 减少堆内存占用
  12354. * Convert dynamic array to static Float32Array
  12355. */
  12356. toStatic: function () {
  12357. var data = this.data;
  12358. if (data instanceof Array) {
  12359. data.length = this._len;
  12360. if (hasTypedArray) {
  12361. this.data = new Float32Array(data);
  12362. }
  12363. }
  12364. },
  12365. /**
  12366. * @return {module:zrender/core/BoundingRect}
  12367. */
  12368. getBoundingRect: function () {
  12369. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12370. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12371. var data = this.data;
  12372. var xi = 0;
  12373. var yi = 0;
  12374. var x0 = 0;
  12375. var y0 = 0;
  12376. for (var i = 0; i < data.length;) {
  12377. var cmd = data[i++];
  12378. if (i === 1) {
  12379. // 如果第一个命令是 L, C, Q
  12380. // 则 previous point 同绘制命令的第一个 point
  12381. //
  12382. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12383. xi = data[i];
  12384. yi = data[i + 1];
  12385. x0 = xi;
  12386. y0 = yi;
  12387. }
  12388. switch (cmd) {
  12389. case CMD.M:
  12390. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12391. // 在 closePath 的时候使用
  12392. x0 = data[i++];
  12393. y0 = data[i++];
  12394. xi = x0;
  12395. yi = y0;
  12396. min2[0] = x0;
  12397. min2[1] = y0;
  12398. max2[0] = x0;
  12399. max2[1] = y0;
  12400. break;
  12401. case CMD.L:
  12402. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12403. xi = data[i++];
  12404. yi = data[i++];
  12405. break;
  12406. case CMD.C:
  12407. fromCubic(
  12408. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12409. min2, max2
  12410. );
  12411. xi = data[i++];
  12412. yi = data[i++];
  12413. break;
  12414. case CMD.Q:
  12415. fromQuadratic(
  12416. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12417. min2, max2
  12418. );
  12419. xi = data[i++];
  12420. yi = data[i++];
  12421. break;
  12422. case CMD.A:
  12423. // TODO Arc 判断的开销比较大
  12424. var cx = data[i++];
  12425. var cy = data[i++];
  12426. var rx = data[i++];
  12427. var ry = data[i++];
  12428. var startAngle = data[i++];
  12429. var endAngle = data[i++] + startAngle;
  12430. // TODO Arc 旋转
  12431. i += 1;
  12432. var anticlockwise = 1 - data[i++];
  12433. if (i === 1) {
  12434. // 直接使用 arc 命令
  12435. // 第一个命令起点还未定义
  12436. x0 = mathCos$1(startAngle) * rx + cx;
  12437. y0 = mathSin$1(startAngle) * ry + cy;
  12438. }
  12439. fromArc(
  12440. cx, cy, rx, ry, startAngle, endAngle,
  12441. anticlockwise, min2, max2
  12442. );
  12443. xi = mathCos$1(endAngle) * rx + cx;
  12444. yi = mathSin$1(endAngle) * ry + cy;
  12445. break;
  12446. case CMD.R:
  12447. x0 = xi = data[i++];
  12448. y0 = yi = data[i++];
  12449. var width = data[i++];
  12450. var height = data[i++];
  12451. // Use fromLine
  12452. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12453. break;
  12454. case CMD.Z:
  12455. xi = x0;
  12456. yi = y0;
  12457. break;
  12458. }
  12459. // Union
  12460. min(min$1, min$1, min2);
  12461. max(max$1, max$1, max2);
  12462. }
  12463. // No data
  12464. if (i === 0) {
  12465. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12466. }
  12467. return new BoundingRect(
  12468. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12469. );
  12470. },
  12471. /**
  12472. * Rebuild path from current data
  12473. * Rebuild path will not consider javascript implemented line dash.
  12474. * @param {CanvasRenderingContext2D} ctx
  12475. */
  12476. rebuildPath: function (ctx) {
  12477. var d = this.data;
  12478. var x0;
  12479. var y0;
  12480. var xi;
  12481. var yi;
  12482. var x;
  12483. var y;
  12484. var ux = this._ux;
  12485. var uy = this._uy;
  12486. var len$$1 = this._len;
  12487. for (var i = 0; i < len$$1;) {
  12488. var cmd = d[i++];
  12489. if (i === 1) {
  12490. // 如果第一个命令是 L, C, Q
  12491. // 则 previous point 同绘制命令的第一个 point
  12492. //
  12493. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12494. xi = d[i];
  12495. yi = d[i + 1];
  12496. x0 = xi;
  12497. y0 = yi;
  12498. }
  12499. switch (cmd) {
  12500. case CMD.M:
  12501. x0 = xi = d[i++];
  12502. y0 = yi = d[i++];
  12503. ctx.moveTo(xi, yi);
  12504. break;
  12505. case CMD.L:
  12506. x = d[i++];
  12507. y = d[i++];
  12508. // Not draw too small seg between
  12509. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12510. ctx.lineTo(x, y);
  12511. xi = x;
  12512. yi = y;
  12513. }
  12514. break;
  12515. case CMD.C:
  12516. ctx.bezierCurveTo(
  12517. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12518. );
  12519. xi = d[i - 2];
  12520. yi = d[i - 1];
  12521. break;
  12522. case CMD.Q:
  12523. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12524. xi = d[i - 2];
  12525. yi = d[i - 1];
  12526. break;
  12527. case CMD.A:
  12528. var cx = d[i++];
  12529. var cy = d[i++];
  12530. var rx = d[i++];
  12531. var ry = d[i++];
  12532. var theta = d[i++];
  12533. var dTheta = d[i++];
  12534. var psi = d[i++];
  12535. var fs = d[i++];
  12536. var r = (rx > ry) ? rx : ry;
  12537. var scaleX = (rx > ry) ? 1 : rx / ry;
  12538. var scaleY = (rx > ry) ? ry / rx : 1;
  12539. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12540. var endAngle = theta + dTheta;
  12541. if (isEllipse) {
  12542. ctx.translate(cx, cy);
  12543. ctx.rotate(psi);
  12544. ctx.scale(scaleX, scaleY);
  12545. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12546. ctx.scale(1 / scaleX, 1 / scaleY);
  12547. ctx.rotate(-psi);
  12548. ctx.translate(-cx, -cy);
  12549. }
  12550. else {
  12551. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12552. }
  12553. if (i === 1) {
  12554. // 直接使用 arc 命令
  12555. // 第一个命令起点还未定义
  12556. x0 = mathCos$1(theta) * rx + cx;
  12557. y0 = mathSin$1(theta) * ry + cy;
  12558. }
  12559. xi = mathCos$1(endAngle) * rx + cx;
  12560. yi = mathSin$1(endAngle) * ry + cy;
  12561. break;
  12562. case CMD.R:
  12563. x0 = xi = d[i];
  12564. y0 = yi = d[i + 1];
  12565. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12566. break;
  12567. case CMD.Z:
  12568. ctx.closePath();
  12569. xi = x0;
  12570. yi = y0;
  12571. }
  12572. }
  12573. }
  12574. };
  12575. PathProxy.CMD = CMD;
  12576. /**
  12577. * 线段包含判断
  12578. * @param {number} x0
  12579. * @param {number} y0
  12580. * @param {number} x1
  12581. * @param {number} y1
  12582. * @param {number} lineWidth
  12583. * @param {number} x
  12584. * @param {number} y
  12585. * @return {boolean}
  12586. */
  12587. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12588. if (lineWidth === 0) {
  12589. return false;
  12590. }
  12591. var _l = lineWidth;
  12592. var _a = 0;
  12593. var _b = x0;
  12594. // Quick reject
  12595. if (
  12596. (y > y0 + _l && y > y1 + _l)
  12597. || (y < y0 - _l && y < y1 - _l)
  12598. || (x > x0 + _l && x > x1 + _l)
  12599. || (x < x0 - _l && x < x1 - _l)
  12600. ) {
  12601. return false;
  12602. }
  12603. if (x0 !== x1) {
  12604. _a = (y0 - y1) / (x0 - x1);
  12605. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12606. }
  12607. else {
  12608. return Math.abs(x - x0) <= _l / 2;
  12609. }
  12610. var tmp = _a * x - y + _b;
  12611. var _s = tmp * tmp / (_a * _a + 1);
  12612. return _s <= _l / 2 * _l / 2;
  12613. }
  12614. /**
  12615. * 三次贝塞尔曲线描边包含判断
  12616. * @param {number} x0
  12617. * @param {number} y0
  12618. * @param {number} x1
  12619. * @param {number} y1
  12620. * @param {number} x2
  12621. * @param {number} y2
  12622. * @param {number} x3
  12623. * @param {number} y3
  12624. * @param {number} lineWidth
  12625. * @param {number} x
  12626. * @param {number} y
  12627. * @return {boolean}
  12628. */
  12629. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12630. if (lineWidth === 0) {
  12631. return false;
  12632. }
  12633. var _l = lineWidth;
  12634. // Quick reject
  12635. if (
  12636. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12637. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12638. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12639. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12640. ) {
  12641. return false;
  12642. }
  12643. var d = cubicProjectPoint(
  12644. x0, y0, x1, y1, x2, y2, x3, y3,
  12645. x, y, null
  12646. );
  12647. return d <= _l / 2;
  12648. }
  12649. /**
  12650. * 二次贝塞尔曲线描边包含判断
  12651. * @param {number} x0
  12652. * @param {number} y0
  12653. * @param {number} x1
  12654. * @param {number} y1
  12655. * @param {number} x2
  12656. * @param {number} y2
  12657. * @param {number} lineWidth
  12658. * @param {number} x
  12659. * @param {number} y
  12660. * @return {boolean}
  12661. */
  12662. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12663. if (lineWidth === 0) {
  12664. return false;
  12665. }
  12666. var _l = lineWidth;
  12667. // Quick reject
  12668. if (
  12669. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12670. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12671. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12672. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12673. ) {
  12674. return false;
  12675. }
  12676. var d = quadraticProjectPoint(
  12677. x0, y0, x1, y1, x2, y2,
  12678. x, y, null
  12679. );
  12680. return d <= _l / 2;
  12681. }
  12682. var PI2$3 = Math.PI * 2;
  12683. function normalizeRadian(angle) {
  12684. angle %= PI2$3;
  12685. if (angle < 0) {
  12686. angle += PI2$3;
  12687. }
  12688. return angle;
  12689. }
  12690. var PI2$2 = Math.PI * 2;
  12691. /**
  12692. * 圆弧描边包含判断
  12693. * @param {number} cx
  12694. * @param {number} cy
  12695. * @param {number} r
  12696. * @param {number} startAngle
  12697. * @param {number} endAngle
  12698. * @param {boolean} anticlockwise
  12699. * @param {number} lineWidth
  12700. * @param {number} x
  12701. * @param {number} y
  12702. * @return {Boolean}
  12703. */
  12704. function containStroke$4(
  12705. cx, cy, r, startAngle, endAngle, anticlockwise,
  12706. lineWidth, x, y
  12707. ) {
  12708. if (lineWidth === 0) {
  12709. return false;
  12710. }
  12711. var _l = lineWidth;
  12712. x -= cx;
  12713. y -= cy;
  12714. var d = Math.sqrt(x * x + y * y);
  12715. if ((d - _l > r) || (d + _l < r)) {
  12716. return false;
  12717. }
  12718. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12719. // Is a circle
  12720. return true;
  12721. }
  12722. if (anticlockwise) {
  12723. var tmp = startAngle;
  12724. startAngle = normalizeRadian(endAngle);
  12725. endAngle = normalizeRadian(tmp);
  12726. }
  12727. else {
  12728. startAngle = normalizeRadian(startAngle);
  12729. endAngle = normalizeRadian(endAngle);
  12730. }
  12731. if (startAngle > endAngle) {
  12732. endAngle += PI2$2;
  12733. }
  12734. var angle = Math.atan2(y, x);
  12735. if (angle < 0) {
  12736. angle += PI2$2;
  12737. }
  12738. return (angle >= startAngle && angle <= endAngle)
  12739. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12740. }
  12741. function windingLine(x0, y0, x1, y1, x, y) {
  12742. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12743. return 0;
  12744. }
  12745. // Ignore horizontal line
  12746. if (y1 === y0) {
  12747. return 0;
  12748. }
  12749. var dir = y1 < y0 ? 1 : -1;
  12750. var t = (y - y0) / (y1 - y0);
  12751. // Avoid winding error when intersection point is the connect point of two line of polygon
  12752. if (t === 1 || t === 0) {
  12753. dir = y1 < y0 ? 0.5 : -0.5;
  12754. }
  12755. var x_ = t * (x1 - x0) + x0;
  12756. // If (x, y) on the line, considered as "contain".
  12757. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12758. }
  12759. var CMD$1 = PathProxy.CMD;
  12760. var PI2$1 = Math.PI * 2;
  12761. var EPSILON$2 = 1e-4;
  12762. function isAroundEqual(a, b) {
  12763. return Math.abs(a - b) < EPSILON$2;
  12764. }
  12765. // 临时数组
  12766. var roots = [-1, -1, -1];
  12767. var extrema = [-1, -1];
  12768. function swapExtrema() {
  12769. var tmp = extrema[0];
  12770. extrema[0] = extrema[1];
  12771. extrema[1] = tmp;
  12772. }
  12773. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12774. // Quick reject
  12775. if (
  12776. (y > y0 && y > y1 && y > y2 && y > y3)
  12777. || (y < y0 && y < y1 && y < y2 && y < y3)
  12778. ) {
  12779. return 0;
  12780. }
  12781. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12782. if (nRoots === 0) {
  12783. return 0;
  12784. }
  12785. else {
  12786. var w = 0;
  12787. var nExtrema = -1;
  12788. var y0_;
  12789. var y1_;
  12790. for (var i = 0; i < nRoots; i++) {
  12791. var t = roots[i];
  12792. // Avoid winding error when intersection point is the connect point of two line of polygon
  12793. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12794. var x_ = cubicAt(x0, x1, x2, x3, t);
  12795. if (x_ < x) { // Quick reject
  12796. continue;
  12797. }
  12798. if (nExtrema < 0) {
  12799. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12800. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12801. swapExtrema();
  12802. }
  12803. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12804. if (nExtrema > 1) {
  12805. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12806. }
  12807. }
  12808. if (nExtrema === 2) {
  12809. // 分成三段单调函数
  12810. if (t < extrema[0]) {
  12811. w += y0_ < y0 ? unit : -unit;
  12812. }
  12813. else if (t < extrema[1]) {
  12814. w += y1_ < y0_ ? unit : -unit;
  12815. }
  12816. else {
  12817. w += y3 < y1_ ? unit : -unit;
  12818. }
  12819. }
  12820. else {
  12821. // 分成两段单调函数
  12822. if (t < extrema[0]) {
  12823. w += y0_ < y0 ? unit : -unit;
  12824. }
  12825. else {
  12826. w += y3 < y0_ ? unit : -unit;
  12827. }
  12828. }
  12829. }
  12830. return w;
  12831. }
  12832. }
  12833. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12834. // Quick reject
  12835. if (
  12836. (y > y0 && y > y1 && y > y2)
  12837. || (y < y0 && y < y1 && y < y2)
  12838. ) {
  12839. return 0;
  12840. }
  12841. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12842. if (nRoots === 0) {
  12843. return 0;
  12844. }
  12845. else {
  12846. var t = quadraticExtremum(y0, y1, y2);
  12847. if (t >= 0 && t <= 1) {
  12848. var w = 0;
  12849. var y_ = quadraticAt(y0, y1, y2, t);
  12850. for (var i = 0; i < nRoots; i++) {
  12851. // Remove one endpoint.
  12852. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12853. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12854. if (x_ < x) { // Quick reject
  12855. continue;
  12856. }
  12857. if (roots[i] < t) {
  12858. w += y_ < y0 ? unit : -unit;
  12859. }
  12860. else {
  12861. w += y2 < y_ ? unit : -unit;
  12862. }
  12863. }
  12864. return w;
  12865. }
  12866. else {
  12867. // Remove one endpoint.
  12868. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12869. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12870. if (x_ < x) { // Quick reject
  12871. return 0;
  12872. }
  12873. return y2 < y0 ? unit : -unit;
  12874. }
  12875. }
  12876. }
  12877. // TODO
  12878. // Arc 旋转
  12879. function windingArc(
  12880. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12881. ) {
  12882. y -= cy;
  12883. if (y > r || y < -r) {
  12884. return 0;
  12885. }
  12886. var tmp = Math.sqrt(r * r - y * y);
  12887. roots[0] = -tmp;
  12888. roots[1] = tmp;
  12889. var diff = Math.abs(startAngle - endAngle);
  12890. if (diff < 1e-4) {
  12891. return 0;
  12892. }
  12893. if (diff % PI2$1 < 1e-4) {
  12894. // Is a circle
  12895. startAngle = 0;
  12896. endAngle = PI2$1;
  12897. var dir = anticlockwise ? 1 : -1;
  12898. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12899. return dir;
  12900. }
  12901. else {
  12902. return 0;
  12903. }
  12904. }
  12905. if (anticlockwise) {
  12906. var tmp = startAngle;
  12907. startAngle = normalizeRadian(endAngle);
  12908. endAngle = normalizeRadian(tmp);
  12909. }
  12910. else {
  12911. startAngle = normalizeRadian(startAngle);
  12912. endAngle = normalizeRadian(endAngle);
  12913. }
  12914. if (startAngle > endAngle) {
  12915. endAngle += PI2$1;
  12916. }
  12917. var w = 0;
  12918. for (var i = 0; i < 2; i++) {
  12919. var x_ = roots[i];
  12920. if (x_ + cx > x) {
  12921. var angle = Math.atan2(y, x_);
  12922. var dir = anticlockwise ? 1 : -1;
  12923. if (angle < 0) {
  12924. angle = PI2$1 + angle;
  12925. }
  12926. if (
  12927. (angle >= startAngle && angle <= endAngle)
  12928. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12929. ) {
  12930. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12931. dir = -dir;
  12932. }
  12933. w += dir;
  12934. }
  12935. }
  12936. }
  12937. return w;
  12938. }
  12939. function containPath(data, lineWidth, isStroke, x, y) {
  12940. var w = 0;
  12941. var xi = 0;
  12942. var yi = 0;
  12943. var x0 = 0;
  12944. var y0 = 0;
  12945. for (var i = 0; i < data.length;) {
  12946. var cmd = data[i++];
  12947. // Begin a new subpath
  12948. if (cmd === CMD$1.M && i > 1) {
  12949. // Close previous subpath
  12950. if (!isStroke) {
  12951. w += windingLine(xi, yi, x0, y0, x, y);
  12952. }
  12953. // 如果被任何一个 subpath 包含
  12954. // if (w !== 0) {
  12955. // return true;
  12956. // }
  12957. }
  12958. if (i === 1) {
  12959. // 如果第一个命令是 L, C, Q
  12960. // 则 previous point 同绘制命令的第一个 point
  12961. //
  12962. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12963. xi = data[i];
  12964. yi = data[i + 1];
  12965. x0 = xi;
  12966. y0 = yi;
  12967. }
  12968. switch (cmd) {
  12969. case CMD$1.M:
  12970. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12971. // 在 closePath 的时候使用
  12972. x0 = data[i++];
  12973. y0 = data[i++];
  12974. xi = x0;
  12975. yi = y0;
  12976. break;
  12977. case CMD$1.L:
  12978. if (isStroke) {
  12979. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12980. return true;
  12981. }
  12982. }
  12983. else {
  12984. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12985. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12986. }
  12987. xi = data[i++];
  12988. yi = data[i++];
  12989. break;
  12990. case CMD$1.C:
  12991. if (isStroke) {
  12992. if (containStroke$2(xi, yi,
  12993. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12994. lineWidth, x, y
  12995. )) {
  12996. return true;
  12997. }
  12998. }
  12999. else {
  13000. w += windingCubic(
  13001. xi, yi,
  13002. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  13003. x, y
  13004. ) || 0;
  13005. }
  13006. xi = data[i++];
  13007. yi = data[i++];
  13008. break;
  13009. case CMD$1.Q:
  13010. if (isStroke) {
  13011. if (containStroke$3(xi, yi,
  13012. data[i++], data[i++], data[i], data[i + 1],
  13013. lineWidth, x, y
  13014. )) {
  13015. return true;
  13016. }
  13017. }
  13018. else {
  13019. w += windingQuadratic(
  13020. xi, yi,
  13021. data[i++], data[i++], data[i], data[i + 1],
  13022. x, y
  13023. ) || 0;
  13024. }
  13025. xi = data[i++];
  13026. yi = data[i++];
  13027. break;
  13028. case CMD$1.A:
  13029. // TODO Arc 判断的开销比较大
  13030. var cx = data[i++];
  13031. var cy = data[i++];
  13032. var rx = data[i++];
  13033. var ry = data[i++];
  13034. var theta = data[i++];
  13035. var dTheta = data[i++];
  13036. // TODO Arc 旋转
  13037. i += 1;
  13038. var anticlockwise = 1 - data[i++];
  13039. var x1 = Math.cos(theta) * rx + cx;
  13040. var y1 = Math.sin(theta) * ry + cy;
  13041. // 不是直接使用 arc 命令
  13042. if (i > 1) {
  13043. w += windingLine(xi, yi, x1, y1, x, y);
  13044. }
  13045. else {
  13046. // 第一个命令起点还未定义
  13047. x0 = x1;
  13048. y0 = y1;
  13049. }
  13050. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  13051. var _x = (x - cx) * ry / rx + cx;
  13052. if (isStroke) {
  13053. if (containStroke$4(
  13054. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13055. lineWidth, _x, y
  13056. )) {
  13057. return true;
  13058. }
  13059. }
  13060. else {
  13061. w += windingArc(
  13062. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  13063. _x, y
  13064. );
  13065. }
  13066. xi = Math.cos(theta + dTheta) * rx + cx;
  13067. yi = Math.sin(theta + dTheta) * ry + cy;
  13068. break;
  13069. case CMD$1.R:
  13070. x0 = xi = data[i++];
  13071. y0 = yi = data[i++];
  13072. var width = data[i++];
  13073. var height = data[i++];
  13074. var x1 = x0 + width;
  13075. var y1 = y0 + height;
  13076. if (isStroke) {
  13077. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  13078. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  13079. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  13080. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  13081. ) {
  13082. return true;
  13083. }
  13084. }
  13085. else {
  13086. // FIXME Clockwise ?
  13087. w += windingLine(x1, y0, x1, y1, x, y);
  13088. w += windingLine(x0, y1, x0, y0, x, y);
  13089. }
  13090. break;
  13091. case CMD$1.Z:
  13092. if (isStroke) {
  13093. if (containStroke$1(
  13094. xi, yi, x0, y0, lineWidth, x, y
  13095. )) {
  13096. return true;
  13097. }
  13098. }
  13099. else {
  13100. // Close a subpath
  13101. w += windingLine(xi, yi, x0, y0, x, y);
  13102. // 如果被任何一个 subpath 包含
  13103. // FIXME subpaths may overlap
  13104. // if (w !== 0) {
  13105. // return true;
  13106. // }
  13107. }
  13108. xi = x0;
  13109. yi = y0;
  13110. break;
  13111. }
  13112. }
  13113. if (!isStroke && !isAroundEqual(yi, y0)) {
  13114. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  13115. }
  13116. return w !== 0;
  13117. }
  13118. function contain(pathData, x, y) {
  13119. return containPath(pathData, 0, false, x, y);
  13120. }
  13121. function containStroke(pathData, lineWidth, x, y) {
  13122. return containPath(pathData, lineWidth, true, x, y);
  13123. }
  13124. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  13125. var abs = Math.abs;
  13126. var pathProxyForDraw = new PathProxy(true);
  13127. /**
  13128. * @alias module:zrender/graphic/Path
  13129. * @extends module:zrender/graphic/Displayable
  13130. * @constructor
  13131. * @param {Object} opts
  13132. */
  13133. function Path(opts) {
  13134. Displayable.call(this, opts);
  13135. /**
  13136. * @type {module:zrender/core/PathProxy}
  13137. * @readOnly
  13138. */
  13139. this.path = null;
  13140. }
  13141. Path.prototype = {
  13142. constructor: Path,
  13143. type: 'path',
  13144. __dirtyPath: true,
  13145. strokeContainThreshold: 5,
  13146. // This item default to be false. But in map series in echarts,
  13147. // in order to improve performance, it should be set to true,
  13148. // so the shorty segment won't draw.
  13149. segmentIgnoreThreshold: 0,
  13150. /**
  13151. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  13152. * @type {boolean}
  13153. */
  13154. subPixelOptimize: false,
  13155. brush: function (ctx, prevEl) {
  13156. var style = this.style;
  13157. var path = this.path || pathProxyForDraw;
  13158. var hasStroke = style.hasStroke();
  13159. var hasFill = style.hasFill();
  13160. var fill = style.fill;
  13161. var stroke = style.stroke;
  13162. var hasFillGradient = hasFill && !!(fill.colorStops);
  13163. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  13164. var hasFillPattern = hasFill && !!(fill.image);
  13165. var hasStrokePattern = hasStroke && !!(stroke.image);
  13166. style.bind(ctx, this, prevEl);
  13167. this.setTransform(ctx);
  13168. if (this.__dirty) {
  13169. var rect;
  13170. // Update gradient because bounding rect may changed
  13171. if (hasFillGradient) {
  13172. rect = rect || this.getBoundingRect();
  13173. this._fillGradient = style.getGradient(ctx, fill, rect);
  13174. }
  13175. if (hasStrokeGradient) {
  13176. rect = rect || this.getBoundingRect();
  13177. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  13178. }
  13179. }
  13180. // Use the gradient or pattern
  13181. if (hasFillGradient) {
  13182. // PENDING If may have affect the state
  13183. ctx.fillStyle = this._fillGradient;
  13184. }
  13185. else if (hasFillPattern) {
  13186. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  13187. }
  13188. if (hasStrokeGradient) {
  13189. ctx.strokeStyle = this._strokeGradient;
  13190. }
  13191. else if (hasStrokePattern) {
  13192. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  13193. }
  13194. var lineDash = style.lineDash;
  13195. var lineDashOffset = style.lineDashOffset;
  13196. var ctxLineDash = !!ctx.setLineDash;
  13197. // Update path sx, sy
  13198. var scale = this.getGlobalScale();
  13199. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  13200. // Proxy context
  13201. // Rebuild path in following 2 cases
  13202. // 1. Path is dirty
  13203. // 2. Path needs javascript implemented lineDash stroking.
  13204. // In this case, lineDash information will not be saved in PathProxy
  13205. if (this.__dirtyPath
  13206. || (lineDash && !ctxLineDash && hasStroke)
  13207. ) {
  13208. path.beginPath(ctx);
  13209. // Setting line dash before build path
  13210. if (lineDash && !ctxLineDash) {
  13211. path.setLineDash(lineDash);
  13212. path.setLineDashOffset(lineDashOffset);
  13213. }
  13214. this.buildPath(path, this.shape, false);
  13215. // Clear path dirty flag
  13216. if (this.path) {
  13217. this.__dirtyPath = false;
  13218. }
  13219. }
  13220. else {
  13221. // Replay path building
  13222. ctx.beginPath();
  13223. this.path.rebuildPath(ctx);
  13224. }
  13225. if (hasFill) {
  13226. if (style.fillOpacity != null) {
  13227. var originalGlobalAlpha = ctx.globalAlpha;
  13228. ctx.globalAlpha = style.fillOpacity * style.opacity;
  13229. path.fill(ctx);
  13230. ctx.globalAlpha = originalGlobalAlpha;
  13231. }
  13232. else {
  13233. path.fill(ctx);
  13234. }
  13235. }
  13236. if (lineDash && ctxLineDash) {
  13237. ctx.setLineDash(lineDash);
  13238. ctx.lineDashOffset = lineDashOffset;
  13239. }
  13240. if (hasStroke) {
  13241. if (style.strokeOpacity != null) {
  13242. var originalGlobalAlpha = ctx.globalAlpha;
  13243. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  13244. path.stroke(ctx);
  13245. ctx.globalAlpha = originalGlobalAlpha;
  13246. }
  13247. else {
  13248. path.stroke(ctx);
  13249. }
  13250. }
  13251. if (lineDash && ctxLineDash) {
  13252. // PENDING
  13253. // Remove lineDash
  13254. ctx.setLineDash([]);
  13255. }
  13256. // Draw rect text
  13257. if (style.text != null) {
  13258. // Only restore transform when needs draw text.
  13259. this.restoreTransform(ctx);
  13260. this.drawRectText(ctx, this.getBoundingRect());
  13261. }
  13262. },
  13263. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  13264. // Like in circle
  13265. buildPath: function (ctx, shapeCfg, inBundle) {},
  13266. createPathProxy: function () {
  13267. this.path = new PathProxy();
  13268. },
  13269. getBoundingRect: function () {
  13270. var rect = this._rect;
  13271. var style = this.style;
  13272. var needsUpdateRect = !rect;
  13273. if (needsUpdateRect) {
  13274. var path = this.path;
  13275. if (!path) {
  13276. // Create path on demand.
  13277. path = this.path = new PathProxy();
  13278. }
  13279. if (this.__dirtyPath) {
  13280. path.beginPath();
  13281. this.buildPath(path, this.shape, false);
  13282. }
  13283. rect = path.getBoundingRect();
  13284. }
  13285. this._rect = rect;
  13286. if (style.hasStroke()) {
  13287. // Needs update rect with stroke lineWidth when
  13288. // 1. Element changes scale or lineWidth
  13289. // 2. Shape is changed
  13290. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  13291. if (this.__dirty || needsUpdateRect) {
  13292. rectWithStroke.copy(rect);
  13293. // FIXME Must after updateTransform
  13294. var w = style.lineWidth;
  13295. // PENDING, Min line width is needed when line is horizontal or vertical
  13296. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13297. // Only add extra hover lineWidth when there are no fill
  13298. if (!style.hasFill()) {
  13299. w = Math.max(w, this.strokeContainThreshold || 4);
  13300. }
  13301. // Consider line width
  13302. // Line scale can't be 0;
  13303. if (lineScale > 1e-10) {
  13304. rectWithStroke.width += w / lineScale;
  13305. rectWithStroke.height += w / lineScale;
  13306. rectWithStroke.x -= w / lineScale / 2;
  13307. rectWithStroke.y -= w / lineScale / 2;
  13308. }
  13309. }
  13310. // Return rect with stroke
  13311. return rectWithStroke;
  13312. }
  13313. return rect;
  13314. },
  13315. contain: function (x, y) {
  13316. var localPos = this.transformCoordToLocal(x, y);
  13317. var rect = this.getBoundingRect();
  13318. var style = this.style;
  13319. x = localPos[0];
  13320. y = localPos[1];
  13321. if (rect.contain(x, y)) {
  13322. var pathData = this.path.data;
  13323. if (style.hasStroke()) {
  13324. var lineWidth = style.lineWidth;
  13325. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  13326. // Line scale can't be 0;
  13327. if (lineScale > 1e-10) {
  13328. // Only add extra hover lineWidth when there are no fill
  13329. if (!style.hasFill()) {
  13330. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  13331. }
  13332. if (containStroke(
  13333. pathData, lineWidth / lineScale, x, y
  13334. )) {
  13335. return true;
  13336. }
  13337. }
  13338. }
  13339. if (style.hasFill()) {
  13340. return contain(pathData, x, y);
  13341. }
  13342. }
  13343. return false;
  13344. },
  13345. /**
  13346. * @param {boolean} dirtyPath
  13347. */
  13348. dirty: function (dirtyPath) {
  13349. if (dirtyPath == null) {
  13350. dirtyPath = true;
  13351. }
  13352. // Only mark dirty, not mark clean
  13353. if (dirtyPath) {
  13354. this.__dirtyPath = dirtyPath;
  13355. this._rect = null;
  13356. }
  13357. this.__dirty = this.__dirtyText = true;
  13358. this.__zr && this.__zr.refresh();
  13359. // Used as a clipping path
  13360. if (this.__clipTarget) {
  13361. this.__clipTarget.dirty();
  13362. }
  13363. },
  13364. /**
  13365. * Alias for animate('shape')
  13366. * @param {boolean} loop
  13367. */
  13368. animateShape: function (loop) {
  13369. return this.animate('shape', loop);
  13370. },
  13371. // Overwrite attrKV
  13372. attrKV: function (key, value) {
  13373. // FIXME
  13374. if (key === 'shape') {
  13375. this.setShape(value);
  13376. this.__dirtyPath = true;
  13377. this._rect = null;
  13378. }
  13379. else {
  13380. Displayable.prototype.attrKV.call(this, key, value);
  13381. }
  13382. },
  13383. /**
  13384. * @param {Object|string} key
  13385. * @param {*} value
  13386. */
  13387. setShape: function (key, value) {
  13388. var shape = this.shape;
  13389. // Path from string may not have shape
  13390. if (shape) {
  13391. if (isObject$1(key)) {
  13392. for (var name in key) {
  13393. if (key.hasOwnProperty(name)) {
  13394. shape[name] = key[name];
  13395. }
  13396. }
  13397. }
  13398. else {
  13399. shape[key] = value;
  13400. }
  13401. this.dirty(true);
  13402. }
  13403. return this;
  13404. },
  13405. getLineScale: function () {
  13406. var m = this.transform;
  13407. // Get the line scale.
  13408. // Determinant of `m` means how much the area is enlarged by the
  13409. // transformation. So its square root can be used as a scale factor
  13410. // for width.
  13411. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13412. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13413. : 1;
  13414. }
  13415. };
  13416. /**
  13417. * 扩展一个 Path element, 比如星形,圆等。
  13418. * Extend a path element
  13419. * @param {Object} props
  13420. * @param {string} props.type Path type
  13421. * @param {Function} props.init Initialize
  13422. * @param {Function} props.buildPath Overwrite buildPath method
  13423. * @param {Object} [props.style] Extended default style config
  13424. * @param {Object} [props.shape] Extended default shape config
  13425. */
  13426. Path.extend = function (defaults$$1) {
  13427. var Sub = function (opts) {
  13428. Path.call(this, opts);
  13429. if (defaults$$1.style) {
  13430. // Extend default style
  13431. this.style.extendFrom(defaults$$1.style, false);
  13432. }
  13433. // Extend default shape
  13434. var defaultShape = defaults$$1.shape;
  13435. if (defaultShape) {
  13436. this.shape = this.shape || {};
  13437. var thisShape = this.shape;
  13438. for (var name in defaultShape) {
  13439. if (
  13440. !thisShape.hasOwnProperty(name)
  13441. && defaultShape.hasOwnProperty(name)
  13442. ) {
  13443. thisShape[name] = defaultShape[name];
  13444. }
  13445. }
  13446. }
  13447. defaults$$1.init && defaults$$1.init.call(this, opts);
  13448. };
  13449. inherits(Sub, Path);
  13450. // FIXME 不能 extend position, rotation 等引用对象
  13451. for (var name in defaults$$1) {
  13452. // Extending prototype values and methods
  13453. if (name !== 'style' && name !== 'shape') {
  13454. Sub.prototype[name] = defaults$$1[name];
  13455. }
  13456. }
  13457. return Sub;
  13458. };
  13459. inherits(Path, Displayable);
  13460. var CMD$2 = PathProxy.CMD;
  13461. var points = [[], [], []];
  13462. var mathSqrt$3 = Math.sqrt;
  13463. var mathAtan2 = Math.atan2;
  13464. var transformPath = function (path, m) {
  13465. var data = path.data;
  13466. var cmd;
  13467. var nPoint;
  13468. var i;
  13469. var j;
  13470. var k;
  13471. var p;
  13472. var M = CMD$2.M;
  13473. var C = CMD$2.C;
  13474. var L = CMD$2.L;
  13475. var R = CMD$2.R;
  13476. var A = CMD$2.A;
  13477. var Q = CMD$2.Q;
  13478. for (i = 0, j = 0; i < data.length;) {
  13479. cmd = data[i++];
  13480. j = i;
  13481. nPoint = 0;
  13482. switch (cmd) {
  13483. case M:
  13484. nPoint = 1;
  13485. break;
  13486. case L:
  13487. nPoint = 1;
  13488. break;
  13489. case C:
  13490. nPoint = 3;
  13491. break;
  13492. case Q:
  13493. nPoint = 2;
  13494. break;
  13495. case A:
  13496. var x = m[4];
  13497. var y = m[5];
  13498. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13499. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13500. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13501. // cx
  13502. data[i] *= sx;
  13503. data[i++] += x;
  13504. // cy
  13505. data[i] *= sy;
  13506. data[i++] += y;
  13507. // Scale rx and ry
  13508. // FIXME Assume psi is 0 here
  13509. data[i++] *= sx;
  13510. data[i++] *= sy;
  13511. // Start angle
  13512. data[i++] += angle;
  13513. // end angle
  13514. data[i++] += angle;
  13515. // FIXME psi
  13516. i += 2;
  13517. j = i;
  13518. break;
  13519. case R:
  13520. // x0, y0
  13521. p[0] = data[i++];
  13522. p[1] = data[i++];
  13523. applyTransform(p, p, m);
  13524. data[j++] = p[0];
  13525. data[j++] = p[1];
  13526. // x1, y1
  13527. p[0] += data[i++];
  13528. p[1] += data[i++];
  13529. applyTransform(p, p, m);
  13530. data[j++] = p[0];
  13531. data[j++] = p[1];
  13532. }
  13533. for (k = 0; k < nPoint; k++) {
  13534. var p = points[k];
  13535. p[0] = data[i++];
  13536. p[1] = data[i++];
  13537. applyTransform(p, p, m);
  13538. // Write back
  13539. data[j++] = p[0];
  13540. data[j++] = p[1];
  13541. }
  13542. }
  13543. };
  13544. // command chars
  13545. // var cc = [
  13546. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13547. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13548. // ];
  13549. var mathSqrt = Math.sqrt;
  13550. var mathSin = Math.sin;
  13551. var mathCos = Math.cos;
  13552. var PI = Math.PI;
  13553. var vMag = function (v) {
  13554. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13555. };
  13556. var vRatio = function (u, v) {
  13557. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13558. };
  13559. var vAngle = function (u, v) {
  13560. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13561. * Math.acos(vRatio(u, v));
  13562. };
  13563. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13564. var psi = psiDeg * (PI / 180.0);
  13565. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13566. + mathSin(psi) * (y1 - y2) / 2.0;
  13567. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13568. + mathCos(psi) * (y1 - y2) / 2.0;
  13569. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13570. if (lambda > 1) {
  13571. rx *= mathSqrt(lambda);
  13572. ry *= mathSqrt(lambda);
  13573. }
  13574. var f = (fa === fs ? -1 : 1)
  13575. * mathSqrt((((rx * rx) * (ry * ry))
  13576. - ((rx * rx) * (yp * yp))
  13577. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13578. + (ry * ry) * (xp * xp))
  13579. ) || 0;
  13580. var cxp = f * rx * yp / ry;
  13581. var cyp = f * -ry * xp / rx;
  13582. var cx = (x1 + x2) / 2.0
  13583. + mathCos(psi) * cxp
  13584. - mathSin(psi) * cyp;
  13585. var cy = (y1 + y2) / 2.0
  13586. + mathSin(psi) * cxp
  13587. + mathCos(psi) * cyp;
  13588. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13589. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13590. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13591. var dTheta = vAngle(u, v);
  13592. if (vRatio(u, v) <= -1) {
  13593. dTheta = PI;
  13594. }
  13595. if (vRatio(u, v) >= 1) {
  13596. dTheta = 0;
  13597. }
  13598. if (fs === 0 && dTheta > 0) {
  13599. dTheta = dTheta - 2 * PI;
  13600. }
  13601. if (fs === 1 && dTheta < 0) {
  13602. dTheta = dTheta + 2 * PI;
  13603. }
  13604. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13605. }
  13606. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13607. // Consider case:
  13608. // (1) delimiter can be comma or space, where continuous commas
  13609. // or spaces should be seen as one comma.
  13610. // (2) value can be like:
  13611. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13612. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13613. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13614. // var valueSplitReg = /[\s,]+/;
  13615. function createPathProxyFromString(data) {
  13616. if (!data) {
  13617. return new PathProxy();
  13618. }
  13619. // var data = data.replace(/-/g, ' -')
  13620. // .replace(/ /g, ' ')
  13621. // .replace(/ /g, ',')
  13622. // .replace(/,,/g, ',');
  13623. // var n;
  13624. // create pipes so that we can split the data
  13625. // for (n = 0; n < cc.length; n++) {
  13626. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13627. // }
  13628. // data = data.replace(/-/g, ',-');
  13629. // create array
  13630. // var arr = cs.split('|');
  13631. // init context point
  13632. var cpx = 0;
  13633. var cpy = 0;
  13634. var subpathX = cpx;
  13635. var subpathY = cpy;
  13636. var prevCmd;
  13637. var path = new PathProxy();
  13638. var CMD = PathProxy.CMD;
  13639. // commandReg.lastIndex = 0;
  13640. // var cmdResult;
  13641. // while ((cmdResult = commandReg.exec(data)) != null) {
  13642. // var cmdStr = cmdResult[1];
  13643. // var cmdContent = cmdResult[2];
  13644. var cmdList = data.match(commandReg);
  13645. for (var l = 0; l < cmdList.length; l++) {
  13646. var cmdText = cmdList[l];
  13647. var cmdStr = cmdText.charAt(0);
  13648. var cmd;
  13649. // String#split is faster a little bit than String#replace or RegExp#exec.
  13650. // var p = cmdContent.split(valueSplitReg);
  13651. // var pLen = 0;
  13652. // for (var i = 0; i < p.length; i++) {
  13653. // // '' and other invalid str => NaN
  13654. // var val = parseFloat(p[i]);
  13655. // !isNaN(val) && (p[pLen++] = val);
  13656. // }
  13657. var p = cmdText.match(numberReg) || [];
  13658. var pLen = p.length;
  13659. for (var i = 0; i < pLen; i++) {
  13660. p[i] = parseFloat(p[i]);
  13661. }
  13662. var off = 0;
  13663. while (off < pLen) {
  13664. var ctlPtx;
  13665. var ctlPty;
  13666. var rx;
  13667. var ry;
  13668. var psi;
  13669. var fa;
  13670. var fs;
  13671. var x1 = cpx;
  13672. var y1 = cpy;
  13673. // convert l, H, h, V, and v to L
  13674. switch (cmdStr) {
  13675. case 'l':
  13676. cpx += p[off++];
  13677. cpy += p[off++];
  13678. cmd = CMD.L;
  13679. path.addData(cmd, cpx, cpy);
  13680. break;
  13681. case 'L':
  13682. cpx = p[off++];
  13683. cpy = p[off++];
  13684. cmd = CMD.L;
  13685. path.addData(cmd, cpx, cpy);
  13686. break;
  13687. case 'm':
  13688. cpx += p[off++];
  13689. cpy += p[off++];
  13690. cmd = CMD.M;
  13691. path.addData(cmd, cpx, cpy);
  13692. subpathX = cpx;
  13693. subpathY = cpy;
  13694. cmdStr = 'l';
  13695. break;
  13696. case 'M':
  13697. cpx = p[off++];
  13698. cpy = p[off++];
  13699. cmd = CMD.M;
  13700. path.addData(cmd, cpx, cpy);
  13701. subpathX = cpx;
  13702. subpathY = cpy;
  13703. cmdStr = 'L';
  13704. break;
  13705. case 'h':
  13706. cpx += p[off++];
  13707. cmd = CMD.L;
  13708. path.addData(cmd, cpx, cpy);
  13709. break;
  13710. case 'H':
  13711. cpx = p[off++];
  13712. cmd = CMD.L;
  13713. path.addData(cmd, cpx, cpy);
  13714. break;
  13715. case 'v':
  13716. cpy += p[off++];
  13717. cmd = CMD.L;
  13718. path.addData(cmd, cpx, cpy);
  13719. break;
  13720. case 'V':
  13721. cpy = p[off++];
  13722. cmd = CMD.L;
  13723. path.addData(cmd, cpx, cpy);
  13724. break;
  13725. case 'C':
  13726. cmd = CMD.C;
  13727. path.addData(
  13728. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13729. );
  13730. cpx = p[off - 2];
  13731. cpy = p[off - 1];
  13732. break;
  13733. case 'c':
  13734. cmd = CMD.C;
  13735. path.addData(
  13736. cmd,
  13737. p[off++] + cpx, p[off++] + cpy,
  13738. p[off++] + cpx, p[off++] + cpy,
  13739. p[off++] + cpx, p[off++] + cpy
  13740. );
  13741. cpx += p[off - 2];
  13742. cpy += p[off - 1];
  13743. break;
  13744. case 'S':
  13745. ctlPtx = cpx;
  13746. ctlPty = cpy;
  13747. var len = path.len();
  13748. var pathData = path.data;
  13749. if (prevCmd === CMD.C) {
  13750. ctlPtx += cpx - pathData[len - 4];
  13751. ctlPty += cpy - pathData[len - 3];
  13752. }
  13753. cmd = CMD.C;
  13754. x1 = p[off++];
  13755. y1 = p[off++];
  13756. cpx = p[off++];
  13757. cpy = p[off++];
  13758. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13759. break;
  13760. case 's':
  13761. ctlPtx = cpx;
  13762. ctlPty = cpy;
  13763. var len = path.len();
  13764. var pathData = path.data;
  13765. if (prevCmd === CMD.C) {
  13766. ctlPtx += cpx - pathData[len - 4];
  13767. ctlPty += cpy - pathData[len - 3];
  13768. }
  13769. cmd = CMD.C;
  13770. x1 = cpx + p[off++];
  13771. y1 = cpy + p[off++];
  13772. cpx += p[off++];
  13773. cpy += p[off++];
  13774. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13775. break;
  13776. case 'Q':
  13777. x1 = p[off++];
  13778. y1 = p[off++];
  13779. cpx = p[off++];
  13780. cpy = p[off++];
  13781. cmd = CMD.Q;
  13782. path.addData(cmd, x1, y1, cpx, cpy);
  13783. break;
  13784. case 'q':
  13785. x1 = p[off++] + cpx;
  13786. y1 = p[off++] + cpy;
  13787. cpx += p[off++];
  13788. cpy += p[off++];
  13789. cmd = CMD.Q;
  13790. path.addData(cmd, x1, y1, cpx, cpy);
  13791. break;
  13792. case 'T':
  13793. ctlPtx = cpx;
  13794. ctlPty = cpy;
  13795. var len = path.len();
  13796. var pathData = path.data;
  13797. if (prevCmd === CMD.Q) {
  13798. ctlPtx += cpx - pathData[len - 4];
  13799. ctlPty += cpy - pathData[len - 3];
  13800. }
  13801. cpx = p[off++];
  13802. cpy = p[off++];
  13803. cmd = CMD.Q;
  13804. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13805. break;
  13806. case 't':
  13807. ctlPtx = cpx;
  13808. ctlPty = cpy;
  13809. var len = path.len();
  13810. var pathData = path.data;
  13811. if (prevCmd === CMD.Q) {
  13812. ctlPtx += cpx - pathData[len - 4];
  13813. ctlPty += cpy - pathData[len - 3];
  13814. }
  13815. cpx += p[off++];
  13816. cpy += p[off++];
  13817. cmd = CMD.Q;
  13818. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13819. break;
  13820. case 'A':
  13821. rx = p[off++];
  13822. ry = p[off++];
  13823. psi = p[off++];
  13824. fa = p[off++];
  13825. fs = p[off++];
  13826. x1 = cpx, y1 = cpy;
  13827. cpx = p[off++];
  13828. cpy = p[off++];
  13829. cmd = CMD.A;
  13830. processArc(
  13831. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13832. );
  13833. break;
  13834. case 'a':
  13835. rx = p[off++];
  13836. ry = p[off++];
  13837. psi = p[off++];
  13838. fa = p[off++];
  13839. fs = p[off++];
  13840. x1 = cpx, y1 = cpy;
  13841. cpx += p[off++];
  13842. cpy += p[off++];
  13843. cmd = CMD.A;
  13844. processArc(
  13845. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13846. );
  13847. break;
  13848. }
  13849. }
  13850. if (cmdStr === 'z' || cmdStr === 'Z') {
  13851. cmd = CMD.Z;
  13852. path.addData(cmd);
  13853. // z may be in the middle of the path.
  13854. cpx = subpathX;
  13855. cpy = subpathY;
  13856. }
  13857. prevCmd = cmd;
  13858. }
  13859. path.toStatic();
  13860. return path;
  13861. }
  13862. // TODO Optimize double memory cost problem
  13863. function createPathOptions(str, opts) {
  13864. var pathProxy = createPathProxyFromString(str);
  13865. opts = opts || {};
  13866. opts.buildPath = function (path) {
  13867. if (path.setData) {
  13868. path.setData(pathProxy.data);
  13869. // Svg and vml renderer don't have context
  13870. var ctx = path.getContext();
  13871. if (ctx) {
  13872. path.rebuildPath(ctx);
  13873. }
  13874. }
  13875. else {
  13876. var ctx = path;
  13877. pathProxy.rebuildPath(ctx);
  13878. }
  13879. };
  13880. opts.applyTransform = function (m) {
  13881. transformPath(pathProxy, m);
  13882. this.dirty(true);
  13883. };
  13884. return opts;
  13885. }
  13886. /**
  13887. * Create a Path object from path string data
  13888. * http://www.w3.org/TR/SVG/paths.html#PathData
  13889. * @param {Object} opts Other options
  13890. */
  13891. function createFromString(str, opts) {
  13892. return new Path(createPathOptions(str, opts));
  13893. }
  13894. /**
  13895. * Create a Path class from path string data
  13896. * @param {string} str
  13897. * @param {Object} opts Other options
  13898. */
  13899. function extendFromString(str, opts) {
  13900. return Path.extend(createPathOptions(str, opts));
  13901. }
  13902. /**
  13903. * Merge multiple paths
  13904. */
  13905. // TODO Apply transform
  13906. // TODO stroke dash
  13907. // TODO Optimize double memory cost problem
  13908. function mergePath$1(pathEls, opts) {
  13909. var pathList = [];
  13910. var len = pathEls.length;
  13911. for (var i = 0; i < len; i++) {
  13912. var pathEl = pathEls[i];
  13913. if (!pathEl.path) {
  13914. pathEl.createPathProxy();
  13915. }
  13916. if (pathEl.__dirtyPath) {
  13917. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13918. }
  13919. pathList.push(pathEl.path);
  13920. }
  13921. var pathBundle = new Path(opts);
  13922. // Need path proxy.
  13923. pathBundle.createPathProxy();
  13924. pathBundle.buildPath = function (path) {
  13925. path.appendPath(pathList);
  13926. // Svg and vml renderer don't have context
  13927. var ctx = path.getContext();
  13928. if (ctx) {
  13929. path.rebuildPath(ctx);
  13930. }
  13931. };
  13932. return pathBundle;
  13933. }
  13934. /**
  13935. * @alias zrender/graphic/Text
  13936. * @extends module:zrender/graphic/Displayable
  13937. * @constructor
  13938. * @param {Object} opts
  13939. */
  13940. var Text = function (opts) { // jshint ignore:line
  13941. Displayable.call(this, opts);
  13942. };
  13943. Text.prototype = {
  13944. constructor: Text,
  13945. type: 'text',
  13946. brush: function (ctx, prevEl) {
  13947. var style = this.style;
  13948. // Optimize, avoid normalize every time.
  13949. this.__dirty && normalizeTextStyle(style, true);
  13950. // Use props with prefix 'text'.
  13951. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13952. style.shadowOffsetX = style.shadowOffsetY = null;
  13953. var text = style.text;
  13954. // Convert to string
  13955. text != null && (text += '');
  13956. // Do not apply style.bind in Text node. Because the real bind job
  13957. // is in textHelper.renderText, and performance of text render should
  13958. // be considered.
  13959. // style.bind(ctx, this, prevEl);
  13960. if (!needDrawText(text, style)) {
  13961. // The current el.style is not applied
  13962. // and should not be used as cache.
  13963. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13964. return;
  13965. }
  13966. this.setTransform(ctx);
  13967. renderText(this, ctx, text, style, null, prevEl);
  13968. this.restoreTransform(ctx);
  13969. },
  13970. getBoundingRect: function () {
  13971. var style = this.style;
  13972. // Optimize, avoid normalize every time.
  13973. this.__dirty && normalizeTextStyle(style, true);
  13974. if (!this._rect) {
  13975. var text = style.text;
  13976. text != null ? (text += '') : (text = '');
  13977. var rect = getBoundingRect(
  13978. style.text + '',
  13979. style.font,
  13980. style.textAlign,
  13981. style.textVerticalAlign,
  13982. style.textPadding,
  13983. style.textLineHeight,
  13984. style.rich
  13985. );
  13986. rect.x += style.x || 0;
  13987. rect.y += style.y || 0;
  13988. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13989. var w = style.textStrokeWidth;
  13990. rect.x -= w / 2;
  13991. rect.y -= w / 2;
  13992. rect.width += w;
  13993. rect.height += w;
  13994. }
  13995. this._rect = rect;
  13996. }
  13997. return this._rect;
  13998. }
  13999. };
  14000. inherits(Text, Displayable);
  14001. /**
  14002. * 圆形
  14003. * @module zrender/shape/Circle
  14004. */
  14005. var Circle = Path.extend({
  14006. type: 'circle',
  14007. shape: {
  14008. cx: 0,
  14009. cy: 0,
  14010. r: 0
  14011. },
  14012. buildPath: function (ctx, shape, inBundle) {
  14013. // Better stroking in ShapeBundle
  14014. // Always do it may have performence issue ( fill may be 2x more cost)
  14015. if (inBundle) {
  14016. ctx.moveTo(shape.cx + shape.r, shape.cy);
  14017. }
  14018. // else {
  14019. // if (ctx.allocate && !ctx.data.length) {
  14020. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  14021. // }
  14022. // }
  14023. // Better stroking in ShapeBundle
  14024. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  14025. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  14026. }
  14027. });
  14028. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  14029. // where exception "unexpected call to method or property access"
  14030. // might be thrown when calling ctx.fill or ctx.stroke after a path
  14031. // whose area size is zero is drawn and ctx.clip() is called and
  14032. // shadowBlur is set. See #4572, #3112, #5777.
  14033. // (e.g.,
  14034. // ctx.moveTo(10, 10);
  14035. // ctx.lineTo(20, 10);
  14036. // ctx.closePath();
  14037. // ctx.clip();
  14038. // ctx.shadowBlur = 10;
  14039. // ...
  14040. // ctx.fill();
  14041. // )
  14042. var shadowTemp = [
  14043. ['shadowBlur', 0],
  14044. ['shadowColor', '#000'],
  14045. ['shadowOffsetX', 0],
  14046. ['shadowOffsetY', 0]
  14047. ];
  14048. var fixClipWithShadow = function (orignalBrush) {
  14049. // version string can be: '11.0'
  14050. return (env$1.browser.ie && env$1.browser.version >= 11)
  14051. ? function () {
  14052. var clipPaths = this.__clipPaths;
  14053. var style = this.style;
  14054. var modified;
  14055. if (clipPaths) {
  14056. for (var i = 0; i < clipPaths.length; i++) {
  14057. var clipPath = clipPaths[i];
  14058. var shape = clipPath && clipPath.shape;
  14059. var type = clipPath && clipPath.type;
  14060. if (shape && (
  14061. (type === 'sector' && shape.startAngle === shape.endAngle)
  14062. || (type === 'rect' && (!shape.width || !shape.height))
  14063. )) {
  14064. for (var j = 0; j < shadowTemp.length; j++) {
  14065. // It is save to put shadowTemp static, because shadowTemp
  14066. // will be all modified each item brush called.
  14067. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14068. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14069. }
  14070. modified = true;
  14071. break;
  14072. }
  14073. }
  14074. }
  14075. orignalBrush.apply(this, arguments);
  14076. if (modified) {
  14077. for (var j = 0; j < shadowTemp.length; j++) {
  14078. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14079. }
  14080. }
  14081. }
  14082. : orignalBrush;
  14083. };
  14084. /**
  14085. * 扇形
  14086. * @module zrender/graphic/shape/Sector
  14087. */
  14088. var Sector = Path.extend({
  14089. type: 'sector',
  14090. shape: {
  14091. cx: 0,
  14092. cy: 0,
  14093. r0: 0,
  14094. r: 0,
  14095. startAngle: 0,
  14096. endAngle: Math.PI * 2,
  14097. clockwise: true
  14098. },
  14099. brush: fixClipWithShadow(Path.prototype.brush),
  14100. buildPath: function (ctx, shape) {
  14101. var x = shape.cx;
  14102. var y = shape.cy;
  14103. var r0 = Math.max(shape.r0 || 0, 0);
  14104. var r = Math.max(shape.r, 0);
  14105. var startAngle = shape.startAngle;
  14106. var endAngle = shape.endAngle;
  14107. var clockwise = shape.clockwise;
  14108. var unitX = Math.cos(startAngle);
  14109. var unitY = Math.sin(startAngle);
  14110. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14111. ctx.lineTo(unitX * r + x, unitY * r + y);
  14112. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14113. ctx.lineTo(
  14114. Math.cos(endAngle) * r0 + x,
  14115. Math.sin(endAngle) * r0 + y
  14116. );
  14117. if (r0 !== 0) {
  14118. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14119. }
  14120. ctx.closePath();
  14121. }
  14122. });
  14123. /**
  14124. * 圆环
  14125. * @module zrender/graphic/shape/Ring
  14126. */
  14127. var Ring = Path.extend({
  14128. type: 'ring',
  14129. shape: {
  14130. cx: 0,
  14131. cy: 0,
  14132. r: 0,
  14133. r0: 0
  14134. },
  14135. buildPath: function (ctx, shape) {
  14136. var x = shape.cx;
  14137. var y = shape.cy;
  14138. var PI2 = Math.PI * 2;
  14139. ctx.moveTo(x + shape.r, y);
  14140. ctx.arc(x, y, shape.r, 0, PI2, false);
  14141. ctx.moveTo(x + shape.r0, y);
  14142. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14143. }
  14144. });
  14145. /**
  14146. * Catmull-Rom spline 插值折线
  14147. * @module zrender/shape/util/smoothSpline
  14148. * @author pissang (https://www.github.com/pissang)
  14149. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14150. * errorrik (errorrik@gmail.com)
  14151. */
  14152. /**
  14153. * @inner
  14154. */
  14155. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14156. var v0 = (p2 - p0) * 0.5;
  14157. var v1 = (p3 - p1) * 0.5;
  14158. return (2 * (p1 - p2) + v0 + v1) * t3
  14159. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  14160. + v0 * t + p1;
  14161. }
  14162. /**
  14163. * @alias module:zrender/shape/util/smoothSpline
  14164. * @param {Array} points 线段顶点数组
  14165. * @param {boolean} isLoop
  14166. * @return {Array}
  14167. */
  14168. var smoothSpline = function (points, isLoop) {
  14169. var len$$1 = points.length;
  14170. var ret = [];
  14171. var distance$$1 = 0;
  14172. for (var i = 1; i < len$$1; i++) {
  14173. distance$$1 += distance(points[i - 1], points[i]);
  14174. }
  14175. var segs = distance$$1 / 2;
  14176. segs = segs < len$$1 ? len$$1 : segs;
  14177. for (var i = 0; i < segs; i++) {
  14178. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  14179. var idx = Math.floor(pos);
  14180. var w = pos - idx;
  14181. var p0;
  14182. var p1 = points[idx % len$$1];
  14183. var p2;
  14184. var p3;
  14185. if (!isLoop) {
  14186. p0 = points[idx === 0 ? idx : idx - 1];
  14187. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  14188. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  14189. }
  14190. else {
  14191. p0 = points[(idx - 1 + len$$1) % len$$1];
  14192. p2 = points[(idx + 1) % len$$1];
  14193. p3 = points[(idx + 2) % len$$1];
  14194. }
  14195. var w2 = w * w;
  14196. var w3 = w * w2;
  14197. ret.push([
  14198. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  14199. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  14200. ]);
  14201. }
  14202. return ret;
  14203. };
  14204. /**
  14205. * 贝塞尔平滑曲线
  14206. * @module zrender/shape/util/smoothBezier
  14207. * @author pissang (https://www.github.com/pissang)
  14208. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  14209. * errorrik (errorrik@gmail.com)
  14210. */
  14211. /**
  14212. * 贝塞尔平滑曲线
  14213. * @alias module:zrender/shape/util/smoothBezier
  14214. * @param {Array} points 线段顶点数组
  14215. * @param {number} smooth 平滑等级, 0-1
  14216. * @param {boolean} isLoop
  14217. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  14218. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  14219. * 整个折线的包围盒做一个并集用来约束控制点。
  14220. * @param {Array} 计算出来的控制点数组
  14221. */
  14222. var smoothBezier = function (points, smooth, isLoop, constraint) {
  14223. var cps = [];
  14224. var v = [];
  14225. var v1 = [];
  14226. var v2 = [];
  14227. var prevPoint;
  14228. var nextPoint;
  14229. var min$$1;
  14230. var max$$1;
  14231. if (constraint) {
  14232. min$$1 = [Infinity, Infinity];
  14233. max$$1 = [-Infinity, -Infinity];
  14234. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14235. min(min$$1, min$$1, points[i]);
  14236. max(max$$1, max$$1, points[i]);
  14237. }
  14238. // 与指定的包围盒做并集
  14239. min(min$$1, min$$1, constraint[0]);
  14240. max(max$$1, max$$1, constraint[1]);
  14241. }
  14242. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  14243. var point = points[i];
  14244. if (isLoop) {
  14245. prevPoint = points[i ? i - 1 : len$$1 - 1];
  14246. nextPoint = points[(i + 1) % len$$1];
  14247. }
  14248. else {
  14249. if (i === 0 || i === len$$1 - 1) {
  14250. cps.push(clone$1(points[i]));
  14251. continue;
  14252. }
  14253. else {
  14254. prevPoint = points[i - 1];
  14255. nextPoint = points[i + 1];
  14256. }
  14257. }
  14258. sub(v, nextPoint, prevPoint);
  14259. // use degree to scale the handle length
  14260. scale(v, v, smooth);
  14261. var d0 = distance(point, prevPoint);
  14262. var d1 = distance(point, nextPoint);
  14263. var sum = d0 + d1;
  14264. if (sum !== 0) {
  14265. d0 /= sum;
  14266. d1 /= sum;
  14267. }
  14268. scale(v1, v, -d0);
  14269. scale(v2, v, d1);
  14270. var cp0 = add([], point, v1);
  14271. var cp1 = add([], point, v2);
  14272. if (constraint) {
  14273. max(cp0, cp0, min$$1);
  14274. min(cp0, cp0, max$$1);
  14275. max(cp1, cp1, min$$1);
  14276. min(cp1, cp1, max$$1);
  14277. }
  14278. cps.push(cp0);
  14279. cps.push(cp1);
  14280. }
  14281. if (isLoop) {
  14282. cps.push(cps.shift());
  14283. }
  14284. return cps;
  14285. };
  14286. function buildPath$1(ctx, shape, closePath) {
  14287. var points = shape.points;
  14288. var smooth = shape.smooth;
  14289. if (points && points.length >= 2) {
  14290. if (smooth && smooth !== 'spline') {
  14291. var controlPoints = smoothBezier(
  14292. points, smooth, closePath, shape.smoothConstraint
  14293. );
  14294. ctx.moveTo(points[0][0], points[0][1]);
  14295. var len = points.length;
  14296. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  14297. var cp1 = controlPoints[i * 2];
  14298. var cp2 = controlPoints[i * 2 + 1];
  14299. var p = points[(i + 1) % len];
  14300. ctx.bezierCurveTo(
  14301. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  14302. );
  14303. }
  14304. }
  14305. else {
  14306. if (smooth === 'spline') {
  14307. points = smoothSpline(points, closePath);
  14308. }
  14309. ctx.moveTo(points[0][0], points[0][1]);
  14310. for (var i = 1, l = points.length; i < l; i++) {
  14311. ctx.lineTo(points[i][0], points[i][1]);
  14312. }
  14313. }
  14314. closePath && ctx.closePath();
  14315. }
  14316. }
  14317. /**
  14318. * 多边形
  14319. * @module zrender/shape/Polygon
  14320. */
  14321. var Polygon = Path.extend({
  14322. type: 'polygon',
  14323. shape: {
  14324. points: null,
  14325. smooth: false,
  14326. smoothConstraint: null
  14327. },
  14328. buildPath: function (ctx, shape) {
  14329. buildPath$1(ctx, shape, true);
  14330. }
  14331. });
  14332. /**
  14333. * @module zrender/graphic/shape/Polyline
  14334. */
  14335. var Polyline = Path.extend({
  14336. type: 'polyline',
  14337. shape: {
  14338. points: null,
  14339. smooth: false,
  14340. smoothConstraint: null
  14341. },
  14342. style: {
  14343. stroke: '#000',
  14344. fill: null
  14345. },
  14346. buildPath: function (ctx, shape) {
  14347. buildPath$1(ctx, shape, false);
  14348. }
  14349. });
  14350. /**
  14351. * Sub-pixel optimize for canvas rendering, prevent from blur
  14352. * when rendering a thin vertical/horizontal line.
  14353. */
  14354. var round = Math.round;
  14355. /**
  14356. * Sub pixel optimize line for canvas
  14357. *
  14358. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14359. * `outputShape` and `inputShape` can be the same object.
  14360. * `outputShape` object can be used repeatly, because all of
  14361. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  14362. * @param {Object} [inputShape]
  14363. * @param {number} [inputShape.x1]
  14364. * @param {number} [inputShape.y1]
  14365. * @param {number} [inputShape.x2]
  14366. * @param {number} [inputShape.y2]
  14367. * @param {Object} [style]
  14368. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14369. */
  14370. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14371. if (!inputShape) {
  14372. return;
  14373. }
  14374. var x1 = inputShape.x1;
  14375. var x2 = inputShape.x2;
  14376. var y1 = inputShape.y1;
  14377. var y2 = inputShape.y2;
  14378. outputShape.x1 = x1;
  14379. outputShape.x2 = x2;
  14380. outputShape.y1 = y1;
  14381. outputShape.y2 = y2;
  14382. var lineWidth = style && style.lineWidth;
  14383. if (!lineWidth) {
  14384. return;
  14385. }
  14386. if (round(x1 * 2) === round(x2 * 2)) {
  14387. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14388. }
  14389. if (round(y1 * 2) === round(y2 * 2)) {
  14390. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14391. }
  14392. }
  14393. /**
  14394. * Sub pixel optimize rect for canvas
  14395. *
  14396. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14397. * `outputShape` and `inputShape` can be the same object.
  14398. * `outputShape` object can be used repeatly, because all of
  14399. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14400. * @param {Object} [inputShape]
  14401. * @param {number} [inputShape.x]
  14402. * @param {number} [inputShape.y]
  14403. * @param {number} [inputShape.width]
  14404. * @param {number} [inputShape.height]
  14405. * @param {Object} [style]
  14406. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14407. */
  14408. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14409. if (!inputShape) {
  14410. return;
  14411. }
  14412. var originX = inputShape.x;
  14413. var originY = inputShape.y;
  14414. var originWidth = inputShape.width;
  14415. var originHeight = inputShape.height;
  14416. outputShape.x = originX;
  14417. outputShape.y = originY;
  14418. outputShape.width = originWidth;
  14419. outputShape.height = originHeight;
  14420. var lineWidth = style && style.lineWidth;
  14421. if (!lineWidth) {
  14422. return;
  14423. }
  14424. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14425. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14426. outputShape.width = Math.max(
  14427. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14428. originWidth === 0 ? 0 : 1
  14429. );
  14430. outputShape.height = Math.max(
  14431. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14432. originHeight === 0 ? 0 : 1
  14433. );
  14434. }
  14435. /**
  14436. * Sub pixel optimize for canvas
  14437. *
  14438. * @param {number} position Coordinate, such as x, y
  14439. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  14440. * @param {boolean=} positiveOrNegative Default false (negative).
  14441. * @return {number} Optimized position.
  14442. */
  14443. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14444. if (!lineWidth) {
  14445. return position;
  14446. }
  14447. // Assure that (position + lineWidth / 2) is near integer edge,
  14448. // otherwise line will be fuzzy in canvas.
  14449. var doubledPosition = round(position * 2);
  14450. return (doubledPosition + round(lineWidth)) % 2 === 0
  14451. ? doubledPosition / 2
  14452. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14453. }
  14454. /**
  14455. * 矩形
  14456. * @module zrender/graphic/shape/Rect
  14457. */
  14458. // Avoid create repeatly.
  14459. var subPixelOptimizeOutputShape = {};
  14460. var Rect = Path.extend({
  14461. type: 'rect',
  14462. shape: {
  14463. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14464. // r缩写为1 相当于 [1, 1, 1, 1]
  14465. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14466. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14467. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14468. r: 0,
  14469. x: 0,
  14470. y: 0,
  14471. width: 0,
  14472. height: 0
  14473. },
  14474. buildPath: function (ctx, shape) {
  14475. var x;
  14476. var y;
  14477. var width;
  14478. var height;
  14479. if (this.subPixelOptimize) {
  14480. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14481. x = subPixelOptimizeOutputShape.x;
  14482. y = subPixelOptimizeOutputShape.y;
  14483. width = subPixelOptimizeOutputShape.width;
  14484. height = subPixelOptimizeOutputShape.height;
  14485. subPixelOptimizeOutputShape.r = shape.r;
  14486. shape = subPixelOptimizeOutputShape;
  14487. }
  14488. else {
  14489. x = shape.x;
  14490. y = shape.y;
  14491. width = shape.width;
  14492. height = shape.height;
  14493. }
  14494. if (!shape.r) {
  14495. ctx.rect(x, y, width, height);
  14496. }
  14497. else {
  14498. buildPath(ctx, shape);
  14499. }
  14500. ctx.closePath();
  14501. return;
  14502. }
  14503. });
  14504. /**
  14505. * 直线
  14506. * @module zrender/graphic/shape/Line
  14507. */
  14508. // Avoid create repeatly.
  14509. var subPixelOptimizeOutputShape$1 = {};
  14510. var Line = Path.extend({
  14511. type: 'line',
  14512. shape: {
  14513. // Start point
  14514. x1: 0,
  14515. y1: 0,
  14516. // End point
  14517. x2: 0,
  14518. y2: 0,
  14519. percent: 1
  14520. },
  14521. style: {
  14522. stroke: '#000',
  14523. fill: null
  14524. },
  14525. buildPath: function (ctx, shape) {
  14526. var x1;
  14527. var y1;
  14528. var x2;
  14529. var y2;
  14530. if (this.subPixelOptimize) {
  14531. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14532. x1 = subPixelOptimizeOutputShape$1.x1;
  14533. y1 = subPixelOptimizeOutputShape$1.y1;
  14534. x2 = subPixelOptimizeOutputShape$1.x2;
  14535. y2 = subPixelOptimizeOutputShape$1.y2;
  14536. }
  14537. else {
  14538. x1 = shape.x1;
  14539. y1 = shape.y1;
  14540. x2 = shape.x2;
  14541. y2 = shape.y2;
  14542. }
  14543. var percent = shape.percent;
  14544. if (percent === 0) {
  14545. return;
  14546. }
  14547. ctx.moveTo(x1, y1);
  14548. if (percent < 1) {
  14549. x2 = x1 * (1 - percent) + x2 * percent;
  14550. y2 = y1 * (1 - percent) + y2 * percent;
  14551. }
  14552. ctx.lineTo(x2, y2);
  14553. },
  14554. /**
  14555. * Get point at percent
  14556. * @param {number} percent
  14557. * @return {Array.<number>}
  14558. */
  14559. pointAt: function (p) {
  14560. var shape = this.shape;
  14561. return [
  14562. shape.x1 * (1 - p) + shape.x2 * p,
  14563. shape.y1 * (1 - p) + shape.y2 * p
  14564. ];
  14565. }
  14566. });
  14567. /**
  14568. * 贝塞尔曲线
  14569. * @module zrender/shape/BezierCurve
  14570. */
  14571. var out = [];
  14572. function someVectorAt(shape, t, isTangent) {
  14573. var cpx2 = shape.cpx2;
  14574. var cpy2 = shape.cpy2;
  14575. if (cpx2 === null || cpy2 === null) {
  14576. return [
  14577. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14578. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14579. ];
  14580. }
  14581. else {
  14582. return [
  14583. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14584. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14585. ];
  14586. }
  14587. }
  14588. var BezierCurve = Path.extend({
  14589. type: 'bezier-curve',
  14590. shape: {
  14591. x1: 0,
  14592. y1: 0,
  14593. x2: 0,
  14594. y2: 0,
  14595. cpx1: 0,
  14596. cpy1: 0,
  14597. // cpx2: 0,
  14598. // cpy2: 0
  14599. // Curve show percent, for animating
  14600. percent: 1
  14601. },
  14602. style: {
  14603. stroke: '#000',
  14604. fill: null
  14605. },
  14606. buildPath: function (ctx, shape) {
  14607. var x1 = shape.x1;
  14608. var y1 = shape.y1;
  14609. var x2 = shape.x2;
  14610. var y2 = shape.y2;
  14611. var cpx1 = shape.cpx1;
  14612. var cpy1 = shape.cpy1;
  14613. var cpx2 = shape.cpx2;
  14614. var cpy2 = shape.cpy2;
  14615. var percent = shape.percent;
  14616. if (percent === 0) {
  14617. return;
  14618. }
  14619. ctx.moveTo(x1, y1);
  14620. if (cpx2 == null || cpy2 == null) {
  14621. if (percent < 1) {
  14622. quadraticSubdivide(
  14623. x1, cpx1, x2, percent, out
  14624. );
  14625. cpx1 = out[1];
  14626. x2 = out[2];
  14627. quadraticSubdivide(
  14628. y1, cpy1, y2, percent, out
  14629. );
  14630. cpy1 = out[1];
  14631. y2 = out[2];
  14632. }
  14633. ctx.quadraticCurveTo(
  14634. cpx1, cpy1,
  14635. x2, y2
  14636. );
  14637. }
  14638. else {
  14639. if (percent < 1) {
  14640. cubicSubdivide(
  14641. x1, cpx1, cpx2, x2, percent, out
  14642. );
  14643. cpx1 = out[1];
  14644. cpx2 = out[2];
  14645. x2 = out[3];
  14646. cubicSubdivide(
  14647. y1, cpy1, cpy2, y2, percent, out
  14648. );
  14649. cpy1 = out[1];
  14650. cpy2 = out[2];
  14651. y2 = out[3];
  14652. }
  14653. ctx.bezierCurveTo(
  14654. cpx1, cpy1,
  14655. cpx2, cpy2,
  14656. x2, y2
  14657. );
  14658. }
  14659. },
  14660. /**
  14661. * Get point at percent
  14662. * @param {number} t
  14663. * @return {Array.<number>}
  14664. */
  14665. pointAt: function (t) {
  14666. return someVectorAt(this.shape, t, false);
  14667. },
  14668. /**
  14669. * Get tangent at percent
  14670. * @param {number} t
  14671. * @return {Array.<number>}
  14672. */
  14673. tangentAt: function (t) {
  14674. var p = someVectorAt(this.shape, t, true);
  14675. return normalize(p, p);
  14676. }
  14677. });
  14678. /**
  14679. * 圆弧
  14680. * @module zrender/graphic/shape/Arc
  14681. */
  14682. var Arc = Path.extend({
  14683. type: 'arc',
  14684. shape: {
  14685. cx: 0,
  14686. cy: 0,
  14687. r: 0,
  14688. startAngle: 0,
  14689. endAngle: Math.PI * 2,
  14690. clockwise: true
  14691. },
  14692. style: {
  14693. stroke: '#000',
  14694. fill: null
  14695. },
  14696. buildPath: function (ctx, shape) {
  14697. var x = shape.cx;
  14698. var y = shape.cy;
  14699. var r = Math.max(shape.r, 0);
  14700. var startAngle = shape.startAngle;
  14701. var endAngle = shape.endAngle;
  14702. var clockwise = shape.clockwise;
  14703. var unitX = Math.cos(startAngle);
  14704. var unitY = Math.sin(startAngle);
  14705. ctx.moveTo(unitX * r + x, unitY * r + y);
  14706. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14707. }
  14708. });
  14709. // CompoundPath to improve performance
  14710. var CompoundPath = Path.extend({
  14711. type: 'compound',
  14712. shape: {
  14713. paths: null
  14714. },
  14715. _updatePathDirty: function () {
  14716. var dirtyPath = this.__dirtyPath;
  14717. var paths = this.shape.paths;
  14718. for (var i = 0; i < paths.length; i++) {
  14719. // Mark as dirty if any subpath is dirty
  14720. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14721. }
  14722. this.__dirtyPath = dirtyPath;
  14723. this.__dirty = this.__dirty || dirtyPath;
  14724. },
  14725. beforeBrush: function () {
  14726. this._updatePathDirty();
  14727. var paths = this.shape.paths || [];
  14728. var scale = this.getGlobalScale();
  14729. // Update path scale
  14730. for (var i = 0; i < paths.length; i++) {
  14731. if (!paths[i].path) {
  14732. paths[i].createPathProxy();
  14733. }
  14734. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14735. }
  14736. },
  14737. buildPath: function (ctx, shape) {
  14738. var paths = shape.paths || [];
  14739. for (var i = 0; i < paths.length; i++) {
  14740. paths[i].buildPath(ctx, paths[i].shape, true);
  14741. }
  14742. },
  14743. afterBrush: function () {
  14744. var paths = this.shape.paths || [];
  14745. for (var i = 0; i < paths.length; i++) {
  14746. paths[i].__dirtyPath = false;
  14747. }
  14748. },
  14749. getBoundingRect: function () {
  14750. this._updatePathDirty();
  14751. return Path.prototype.getBoundingRect.call(this);
  14752. }
  14753. });
  14754. /**
  14755. * @param {Array.<Object>} colorStops
  14756. */
  14757. var Gradient = function (colorStops) {
  14758. this.colorStops = colorStops || [];
  14759. };
  14760. Gradient.prototype = {
  14761. constructor: Gradient,
  14762. addColorStop: function (offset, color) {
  14763. this.colorStops.push({
  14764. offset: offset,
  14765. color: color
  14766. });
  14767. }
  14768. };
  14769. /**
  14770. * x, y, x2, y2 are all percent from 0 to 1
  14771. * @param {number} [x=0]
  14772. * @param {number} [y=0]
  14773. * @param {number} [x2=1]
  14774. * @param {number} [y2=0]
  14775. * @param {Array.<Object>} colorStops
  14776. * @param {boolean} [globalCoord=false]
  14777. */
  14778. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14779. // Should do nothing more in this constructor. Because gradient can be
  14780. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14781. // this constructor will not be called.
  14782. this.x = x == null ? 0 : x;
  14783. this.y = y == null ? 0 : y;
  14784. this.x2 = x2 == null ? 1 : x2;
  14785. this.y2 = y2 == null ? 0 : y2;
  14786. // Can be cloned
  14787. this.type = 'linear';
  14788. // If use global coord
  14789. this.global = globalCoord || false;
  14790. Gradient.call(this, colorStops);
  14791. };
  14792. LinearGradient.prototype = {
  14793. constructor: LinearGradient
  14794. };
  14795. inherits(LinearGradient, Gradient);
  14796. /**
  14797. * x, y, r are all percent from 0 to 1
  14798. * @param {number} [x=0.5]
  14799. * @param {number} [y=0.5]
  14800. * @param {number} [r=0.5]
  14801. * @param {Array.<Object>} [colorStops]
  14802. * @param {boolean} [globalCoord=false]
  14803. */
  14804. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14805. // Should do nothing more in this constructor. Because gradient can be
  14806. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14807. // this constructor will not be called.
  14808. this.x = x == null ? 0.5 : x;
  14809. this.y = y == null ? 0.5 : y;
  14810. this.r = r == null ? 0.5 : r;
  14811. // Can be cloned
  14812. this.type = 'radial';
  14813. // If use global coord
  14814. this.global = globalCoord || false;
  14815. Gradient.call(this, colorStops);
  14816. };
  14817. RadialGradient.prototype = {
  14818. constructor: RadialGradient
  14819. };
  14820. inherits(RadialGradient, Gradient);
  14821. /**
  14822. * Displayable for incremental rendering. It will be rendered in a separate layer
  14823. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14824. * addDisplayables will render the added displayables incremetally.
  14825. *
  14826. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14827. */
  14828. // TODO Style override ?
  14829. function IncrementalDisplayble(opts) {
  14830. Displayable.call(this, opts);
  14831. this._displayables = [];
  14832. this._temporaryDisplayables = [];
  14833. this._cursor = 0;
  14834. this.notClear = true;
  14835. }
  14836. IncrementalDisplayble.prototype.incremental = true;
  14837. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14838. this._displayables = [];
  14839. this._temporaryDisplayables = [];
  14840. this._cursor = 0;
  14841. this.dirty();
  14842. this.notClear = false;
  14843. };
  14844. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14845. if (notPersistent) {
  14846. this._temporaryDisplayables.push(displayable);
  14847. }
  14848. else {
  14849. this._displayables.push(displayable);
  14850. }
  14851. this.dirty();
  14852. };
  14853. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14854. notPersistent = notPersistent || false;
  14855. for (var i = 0; i < displayables.length; i++) {
  14856. this.addDisplayable(displayables[i], notPersistent);
  14857. }
  14858. };
  14859. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14860. for (var i = this._cursor; i < this._displayables.length; i++) {
  14861. cb && cb(this._displayables[i]);
  14862. }
  14863. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14864. cb && cb(this._temporaryDisplayables[i]);
  14865. }
  14866. };
  14867. IncrementalDisplayble.prototype.update = function () {
  14868. this.updateTransform();
  14869. for (var i = this._cursor; i < this._displayables.length; i++) {
  14870. var displayable = this._displayables[i];
  14871. // PENDING
  14872. displayable.parent = this;
  14873. displayable.update();
  14874. displayable.parent = null;
  14875. }
  14876. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14877. var displayable = this._temporaryDisplayables[i];
  14878. // PENDING
  14879. displayable.parent = this;
  14880. displayable.update();
  14881. displayable.parent = null;
  14882. }
  14883. };
  14884. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14885. // Render persistant displayables.
  14886. for (var i = this._cursor; i < this._displayables.length; i++) {
  14887. var displayable = this._displayables[i];
  14888. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14889. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14890. displayable.afterBrush && displayable.afterBrush(ctx);
  14891. }
  14892. this._cursor = i;
  14893. // Render temporary displayables.
  14894. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14895. var displayable = this._temporaryDisplayables[i];
  14896. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14897. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14898. displayable.afterBrush && displayable.afterBrush(ctx);
  14899. }
  14900. this._temporaryDisplayables = [];
  14901. this.notClear = true;
  14902. };
  14903. var m = [];
  14904. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14905. if (!this._rect) {
  14906. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14907. for (var i = 0; i < this._displayables.length; i++) {
  14908. var displayable = this._displayables[i];
  14909. var childRect = displayable.getBoundingRect().clone();
  14910. if (displayable.needLocalTransform()) {
  14911. childRect.applyTransform(displayable.getLocalTransform(m));
  14912. }
  14913. rect.union(childRect);
  14914. }
  14915. this._rect = rect;
  14916. }
  14917. return this._rect;
  14918. };
  14919. IncrementalDisplayble.prototype.contain = function (x, y) {
  14920. var localPos = this.transformCoordToLocal(x, y);
  14921. var rect = this.getBoundingRect();
  14922. if (rect.contain(localPos[0], localPos[1])) {
  14923. for (var i = 0; i < this._displayables.length; i++) {
  14924. var displayable = this._displayables[i];
  14925. if (displayable.contain(x, y)) {
  14926. return true;
  14927. }
  14928. }
  14929. }
  14930. return false;
  14931. };
  14932. inherits(IncrementalDisplayble, Displayable);
  14933. /*
  14934. * Licensed to the Apache Software Foundation (ASF) under one
  14935. * or more contributor license agreements. See the NOTICE file
  14936. * distributed with this work for additional information
  14937. * regarding copyright ownership. The ASF licenses this file
  14938. * to you under the Apache License, Version 2.0 (the
  14939. * "License"); you may not use this file except in compliance
  14940. * with the License. You may obtain a copy of the License at
  14941. *
  14942. * http://www.apache.org/licenses/LICENSE-2.0
  14943. *
  14944. * Unless required by applicable law or agreed to in writing,
  14945. * software distributed under the License is distributed on an
  14946. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14947. * KIND, either express or implied. See the License for the
  14948. * specific language governing permissions and limitations
  14949. * under the License.
  14950. */
  14951. var mathMax$1 = Math.max;
  14952. var mathMin$1 = Math.min;
  14953. var EMPTY_OBJ = {};
  14954. var Z2_EMPHASIS_LIFT = 1;
  14955. // key: label model property nane, value: style property name.
  14956. var CACHED_LABEL_STYLE_PROPERTIES = {
  14957. color: 'textFill',
  14958. textBorderColor: 'textStroke',
  14959. textBorderWidth: 'textStrokeWidth'
  14960. };
  14961. var EMPHASIS = 'emphasis';
  14962. var NORMAL = 'normal';
  14963. // Reserve 0 as default.
  14964. var _highlightNextDigit = 1;
  14965. var _highlightKeyMap = {};
  14966. var _customShapeMap = {};
  14967. /**
  14968. * Extend shape with parameters
  14969. */
  14970. function extendShape(opts) {
  14971. return Path.extend(opts);
  14972. }
  14973. /**
  14974. * Extend path
  14975. */
  14976. function extendPath(pathData, opts) {
  14977. return extendFromString(pathData, opts);
  14978. }
  14979. /**
  14980. * Register a user defined shape.
  14981. * The shape class can be fetched by `getShapeClass`
  14982. * This method will overwrite the registered shapes, including
  14983. * the registered built-in shapes, if using the same `name`.
  14984. * The shape can be used in `custom series` and
  14985. * `graphic component` by declaring `{type: name}`.
  14986. *
  14987. * @param {string} name
  14988. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14989. */
  14990. function registerShape(name, ShapeClass) {
  14991. _customShapeMap[name] = ShapeClass;
  14992. }
  14993. /**
  14994. * Find shape class registered by `registerShape`. Usually used in
  14995. * fetching user defined shape.
  14996. *
  14997. * [Caution]:
  14998. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14999. * to use user registered shapes.
  15000. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  15001. * `registerShape` by default. That enables users to get both built-in
  15002. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  15003. * the built-in shapes by using names like 'circle', 'rect' via calling
  15004. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  15005. * in case that it is overwritten by users, except that some features, like
  15006. * `custom series`, `graphic component`, do it deliberately.
  15007. *
  15008. * (2) In the features like `custom series`, `graphic component`, the user input
  15009. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  15010. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  15011. * are reserved names, that is, if some user register a shape named `'image'`,
  15012. * the shape will not be used. If we intending to add some more reserved names
  15013. * in feature, that might bring break changes (disable some existing user shape
  15014. * names). But that case probably rearly happen. So we dont make more mechanism
  15015. * to resolve this issue here.
  15016. *
  15017. * @param {string} name
  15018. * @return {Object} The shape class. If not found, return nothing.
  15019. */
  15020. function getShapeClass(name) {
  15021. if (_customShapeMap.hasOwnProperty(name)) {
  15022. return _customShapeMap[name];
  15023. }
  15024. }
  15025. /**
  15026. * Create a path element from path data string
  15027. * @param {string} pathData
  15028. * @param {Object} opts
  15029. * @param {module:zrender/core/BoundingRect} rect
  15030. * @param {string} [layout=cover] 'center' or 'cover'
  15031. */
  15032. function makePath(pathData, opts, rect, layout) {
  15033. var path = createFromString(pathData, opts);
  15034. if (rect) {
  15035. if (layout === 'center') {
  15036. rect = centerGraphic(rect, path.getBoundingRect());
  15037. }
  15038. resizePath(path, rect);
  15039. }
  15040. return path;
  15041. }
  15042. /**
  15043. * Create a image element from image url
  15044. * @param {string} imageUrl image url
  15045. * @param {Object} opts options
  15046. * @param {module:zrender/core/BoundingRect} rect constrain rect
  15047. * @param {string} [layout=cover] 'center' or 'cover'
  15048. */
  15049. function makeImage(imageUrl, rect, layout) {
  15050. var path = new ZImage({
  15051. style: {
  15052. image: imageUrl,
  15053. x: rect.x,
  15054. y: rect.y,
  15055. width: rect.width,
  15056. height: rect.height
  15057. },
  15058. onload: function (img) {
  15059. if (layout === 'center') {
  15060. var boundingRect = {
  15061. width: img.width,
  15062. height: img.height
  15063. };
  15064. path.setStyle(centerGraphic(rect, boundingRect));
  15065. }
  15066. }
  15067. });
  15068. return path;
  15069. }
  15070. /**
  15071. * Get position of centered element in bounding box.
  15072. *
  15073. * @param {Object} rect element local bounding box
  15074. * @param {Object} boundingRect constraint bounding box
  15075. * @return {Object} element position containing x, y, width, and height
  15076. */
  15077. function centerGraphic(rect, boundingRect) {
  15078. // Set rect to center, keep width / height ratio.
  15079. var aspect = boundingRect.width / boundingRect.height;
  15080. var width = rect.height * aspect;
  15081. var height;
  15082. if (width <= rect.width) {
  15083. height = rect.height;
  15084. }
  15085. else {
  15086. width = rect.width;
  15087. height = width / aspect;
  15088. }
  15089. var cx = rect.x + rect.width / 2;
  15090. var cy = rect.y + rect.height / 2;
  15091. return {
  15092. x: cx - width / 2,
  15093. y: cy - height / 2,
  15094. width: width,
  15095. height: height
  15096. };
  15097. }
  15098. var mergePath = mergePath$1;
  15099. /**
  15100. * Resize a path to fit the rect
  15101. * @param {module:zrender/graphic/Path} path
  15102. * @param {Object} rect
  15103. */
  15104. function resizePath(path, rect) {
  15105. if (!path.applyTransform) {
  15106. return;
  15107. }
  15108. var pathRect = path.getBoundingRect();
  15109. var m = pathRect.calculateTransform(rect);
  15110. path.applyTransform(m);
  15111. }
  15112. /**
  15113. * Sub pixel optimize line for canvas
  15114. *
  15115. * @param {Object} param
  15116. * @param {Object} [param.shape]
  15117. * @param {number} [param.shape.x1]
  15118. * @param {number} [param.shape.y1]
  15119. * @param {number} [param.shape.x2]
  15120. * @param {number} [param.shape.y2]
  15121. * @param {Object} [param.style]
  15122. * @param {number} [param.style.lineWidth]
  15123. * @return {Object} Modified param
  15124. */
  15125. function subPixelOptimizeLine(param) {
  15126. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  15127. return param;
  15128. }
  15129. /**
  15130. * Sub pixel optimize rect for canvas
  15131. *
  15132. * @param {Object} param
  15133. * @param {Object} [param.shape]
  15134. * @param {number} [param.shape.x]
  15135. * @param {number} [param.shape.y]
  15136. * @param {number} [param.shape.width]
  15137. * @param {number} [param.shape.height]
  15138. * @param {Object} [param.style]
  15139. * @param {number} [param.style.lineWidth]
  15140. * @return {Object} Modified param
  15141. */
  15142. function subPixelOptimizeRect(param) {
  15143. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  15144. return param;
  15145. }
  15146. /**
  15147. * Sub pixel optimize for canvas
  15148. *
  15149. * @param {number} position Coordinate, such as x, y
  15150. * @param {number} lineWidth Should be nonnegative integer.
  15151. * @param {boolean=} positiveOrNegative Default false (negative).
  15152. * @return {number} Optimized position.
  15153. */
  15154. var subPixelOptimize = subPixelOptimize$1;
  15155. function hasFillOrStroke(fillOrStroke) {
  15156. return fillOrStroke != null && fillOrStroke !== 'none';
  15157. }
  15158. // Most lifted color are duplicated.
  15159. var liftedColorMap = createHashMap();
  15160. var liftedColorCount = 0;
  15161. function liftColor(color) {
  15162. if (typeof color !== 'string') {
  15163. return color;
  15164. }
  15165. var liftedColor = liftedColorMap.get(color);
  15166. if (!liftedColor) {
  15167. liftedColor = lift(color, -0.1);
  15168. if (liftedColorCount < 10000) {
  15169. liftedColorMap.set(color, liftedColor);
  15170. liftedColorCount++;
  15171. }
  15172. }
  15173. return liftedColor;
  15174. }
  15175. function cacheElementStl(el) {
  15176. if (!el.__hoverStlDirty) {
  15177. return;
  15178. }
  15179. el.__hoverStlDirty = false;
  15180. var hoverStyle = el.__hoverStl;
  15181. if (!hoverStyle) {
  15182. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  15183. return;
  15184. }
  15185. var normalStyle = el.__cachedNormalStl = {};
  15186. el.__cachedNormalZ2 = el.z2;
  15187. var elStyle = el.style;
  15188. for (var name in hoverStyle) {
  15189. // See comment in `singleEnterEmphasis`.
  15190. if (hoverStyle[name] != null) {
  15191. normalStyle[name] = elStyle[name];
  15192. }
  15193. }
  15194. // Always cache fill and stroke to normalStyle for lifting color.
  15195. normalStyle.fill = elStyle.fill;
  15196. normalStyle.stroke = elStyle.stroke;
  15197. }
  15198. function singleEnterEmphasis(el) {
  15199. var hoverStl = el.__hoverStl;
  15200. if (!hoverStl || el.__highlighted) {
  15201. return;
  15202. }
  15203. var zr = el.__zr;
  15204. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  15205. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  15206. if (el.isGroup || (!zr && el.useHoverLayer)) {
  15207. return;
  15208. }
  15209. var elTarget = el;
  15210. var targetStyle = el.style;
  15211. if (useHoverLayer) {
  15212. elTarget = zr.addHover(el);
  15213. targetStyle = elTarget.style;
  15214. }
  15215. rollbackDefaultTextStyle(targetStyle);
  15216. if (!useHoverLayer) {
  15217. cacheElementStl(elTarget);
  15218. }
  15219. // styles can be:
  15220. // {
  15221. // label: {
  15222. // show: false,
  15223. // position: 'outside',
  15224. // fontSize: 18
  15225. // },
  15226. // emphasis: {
  15227. // label: {
  15228. // show: true
  15229. // }
  15230. // }
  15231. // },
  15232. // where properties of `emphasis` may not appear in `normal`. We previously use
  15233. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  15234. // But consider rich text and setOption in merge mode, it is impossible to cover
  15235. // all properties in merge. So we use merge mode when setting style here.
  15236. // But we choose the merge strategy that only properties that is not `null/undefined`.
  15237. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  15238. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  15239. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  15240. // style any more in `emphasis`. Users can both set properties directly on normal and
  15241. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  15242. targetStyle.extendFrom(hoverStl);
  15243. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  15244. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  15245. applyDefaultTextStyle(targetStyle);
  15246. if (!useHoverLayer) {
  15247. el.dirty(false);
  15248. el.z2 += Z2_EMPHASIS_LIFT;
  15249. }
  15250. }
  15251. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  15252. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  15253. targetStyle[prop] = liftColor(targetStyle[prop]);
  15254. }
  15255. }
  15256. function singleEnterNormal(el) {
  15257. var highlighted = el.__highlighted;
  15258. if (!highlighted) {
  15259. return;
  15260. }
  15261. el.__highlighted = false;
  15262. if (el.isGroup) {
  15263. return;
  15264. }
  15265. if (highlighted === 'layer') {
  15266. el.__zr && el.__zr.removeHover(el);
  15267. }
  15268. else {
  15269. var style = el.style;
  15270. var normalStl = el.__cachedNormalStl;
  15271. if (normalStl) {
  15272. rollbackDefaultTextStyle(style);
  15273. el.setStyle(normalStl);
  15274. applyDefaultTextStyle(style);
  15275. }
  15276. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  15277. // when `el` is on emphasis state. So here by comparing with 1, we try
  15278. // hard to make the bug case rare.
  15279. var normalZ2 = el.__cachedNormalZ2;
  15280. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  15281. el.z2 = normalZ2;
  15282. }
  15283. }
  15284. }
  15285. function traverseUpdate(el, updater, commonParam) {
  15286. // If root is group, also enter updater for `highDownOnUpdate`.
  15287. var fromState = NORMAL;
  15288. var toState = NORMAL;
  15289. var trigger;
  15290. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  15291. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  15292. updater(el, commonParam);
  15293. el.__highlighted && (toState = EMPHASIS, trigger = true);
  15294. el.isGroup && el.traverse(function (child) {
  15295. !child.isGroup && updater(child, commonParam);
  15296. });
  15297. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  15298. }
  15299. /**
  15300. * Set hover style (namely "emphasis style") of element, based on the current
  15301. * style of the given `el`.
  15302. * This method should be called after all of the normal styles have been adopted
  15303. * to the `el`. See the reason on `setHoverStyle`.
  15304. *
  15305. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  15306. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  15307. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  15308. * Often used when item group has a label element and it's hoverStyle is different.
  15309. * @param {Object|boolean} [hoverStl] The specified hover style.
  15310. * If set as `false`, disable the hover style.
  15311. * Similarly, The `el.hoverStyle` can alse be set
  15312. * as `false` to disable the hover style.
  15313. * Otherwise, use the default hover style if not provided.
  15314. */
  15315. function setElementHoverStyle(el, hoverStl) {
  15316. // For performance consideration, it might be better to make the "hover style" only the
  15317. // difference properties from the "normal style", but not a entire copy of all styles.
  15318. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  15319. el.__hoverStlDirty = true;
  15320. // FIXME
  15321. // It is not completely right to save "normal"/"emphasis" flag on elements.
  15322. // It probably should be saved on `data` of series. Consider the cases:
  15323. // (1) A highlighted elements are moved out of the view port and re-enter
  15324. // again by dataZoom.
  15325. // (2) call `setOption` and replace elements totally when they are highlighted.
  15326. if (el.__highlighted) {
  15327. // Consider the case:
  15328. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  15329. // should be adapted to the `el`. Notice here new "normal styles" should have
  15330. // been set outside and the cached "normal style" is out of date.
  15331. el.__cachedNormalStl = null;
  15332. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  15333. // of this method. In most cases, `z2` is not set and hover style should be able
  15334. // to rollback. Of course, that would bring bug, but only in a rare case, see
  15335. // `doSingleLeaveHover` for details.
  15336. singleEnterNormal(el);
  15337. singleEnterEmphasis(el);
  15338. }
  15339. }
  15340. function onElementMouseOver(e) {
  15341. !shouldSilent(this, e)
  15342. // "emphasis" event highlight has higher priority than mouse highlight.
  15343. && !this.__highByOuter
  15344. && traverseUpdate(this, singleEnterEmphasis);
  15345. }
  15346. function onElementMouseOut(e) {
  15347. !shouldSilent(this, e)
  15348. // "emphasis" event highlight has higher priority than mouse highlight.
  15349. && !this.__highByOuter
  15350. && traverseUpdate(this, singleEnterNormal);
  15351. }
  15352. function onElementEmphasisEvent(highlightDigit) {
  15353. this.__highByOuter |= 1 << (highlightDigit || 0);
  15354. traverseUpdate(this, singleEnterEmphasis);
  15355. }
  15356. function onElementNormalEvent(highlightDigit) {
  15357. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  15358. && traverseUpdate(this, singleEnterNormal);
  15359. }
  15360. function shouldSilent(el, e) {
  15361. return el.__highDownSilentOnTouch && e.zrByTouch;
  15362. }
  15363. /**
  15364. * Set hover style (namely "emphasis style") of element,
  15365. * based on the current style of the given `el`.
  15366. *
  15367. * (1)
  15368. * **CONSTRAINTS** for this method:
  15369. * <A> This method MUST be called after all of the normal styles having been adopted
  15370. * to the `el`.
  15371. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15372. * "normal style" having been set to the el.
  15373. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15374. * a default hover style).
  15375. *
  15376. * The reason: this method treat the current style of the `el` as the "normal style"
  15377. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15378. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15379. * logic, where the el should shift from the original emphasis style to the new
  15380. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15381. *
  15382. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15383. * not found a better solution yet to fit the backward compatibility, performance and
  15384. * the current programming style.
  15385. *
  15386. * (2)
  15387. * Call the method for a "root" element once. Do not call it for each descendants.
  15388. * If the descendants elemenets of a group has itself hover style different from the
  15389. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15390. * not call this method for them.
  15391. *
  15392. * (3) These input parameters can be set directly on `el`:
  15393. *
  15394. * @param {module:zrender/Element} el
  15395. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15396. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15397. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15398. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15399. */
  15400. function setHoverStyle(el, hoverStyle) {
  15401. setAsHighDownDispatcher(el, true);
  15402. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15403. }
  15404. /**
  15405. * @param {module:zrender/Element} el
  15406. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15407. * Since `setHoverStyle` has the constraint that it must be called after
  15408. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15409. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15410. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15411. * to sync outside style settings to "emphasis" state.
  15412. * @this {string} This dispatcher `el`.
  15413. * @param {string} fromState Can be "normal" or "emphasis".
  15414. * `fromState` might equal to `toState`,
  15415. * for example, when this method is called when `el` is
  15416. * on "emphasis" state.
  15417. * @param {string} toState Can be "normal" or "emphasis".
  15418. *
  15419. * FIXME
  15420. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15421. * Because it is not a complete solution. The update
  15422. * listener should not have been mount in element,
  15423. * and the normal/emphasis state should not have
  15424. * mantained on elements.
  15425. *
  15426. * @param {boolean} [el.highDownSilentOnTouch=false]
  15427. * In touch device, mouseover event will be trigger on touchstart event
  15428. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15429. * conveniently use hoverStyle when tap on touch screen without additional
  15430. * code for compatibility.
  15431. * But if the chart/component has select feature, which usually also use
  15432. * hoverStyle, there might be conflict between 'select-highlight' and
  15433. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15434. * In this case, `highDownSilentOnTouch` should be used to disable
  15435. * hover-highlight on touch device.
  15436. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15437. */
  15438. function setAsHighDownDispatcher(el, asDispatcher) {
  15439. var disable = asDispatcher === false;
  15440. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15441. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15442. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15443. el.__highDownOnUpdate = el.highDownOnUpdate;
  15444. // Simple optimize, since this method might be
  15445. // called for each elements of a group in some cases.
  15446. if (!disable || el.__highDownDispatcher) {
  15447. var method = disable ? 'off' : 'on';
  15448. // Duplicated function will be auto-ignored, see Eventful.js.
  15449. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15450. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15451. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15452. // Also keep previous record.
  15453. el.__highByOuter = el.__highByOuter || 0;
  15454. el.__highDownDispatcher = !disable;
  15455. }
  15456. }
  15457. /**
  15458. * @param {module:zrender/src/Element} el
  15459. * @return {boolean}
  15460. */
  15461. function isHighDownDispatcher(el) {
  15462. return !!(el && el.__highDownDispatcher);
  15463. }
  15464. /**
  15465. * Support hightlight/downplay record on each elements.
  15466. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15467. * user triggerred hightlight/downplay should not conflict.
  15468. * Only all of the highlightDigit cleared, return to normal.
  15469. * @param {string} highlightKey
  15470. * @return {number} highlightDigit
  15471. */
  15472. function getHighlightDigit(highlightKey) {
  15473. var highlightDigit = _highlightKeyMap[highlightKey];
  15474. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15475. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15476. }
  15477. return highlightDigit;
  15478. }
  15479. /**
  15480. * See more info in `setTextStyleCommon`.
  15481. * @param {Object|module:zrender/graphic/Style} normalStyle
  15482. * @param {Object} emphasisStyle
  15483. * @param {module:echarts/model/Model} normalModel
  15484. * @param {module:echarts/model/Model} emphasisModel
  15485. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15486. * @param {string|Function} [opt.defaultText]
  15487. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15488. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15489. * @param {number} [opt.labelDataIndex] Fetch text by
  15490. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15491. * @param {number} [opt.labelDimIndex] Fetch text by
  15492. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15493. * @param {string} [opt.labelProp] Fetch text by
  15494. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  15495. * @param {Object} [normalSpecified]
  15496. * @param {Object} [emphasisSpecified]
  15497. */
  15498. function setLabelStyle(
  15499. normalStyle, emphasisStyle,
  15500. normalModel, emphasisModel,
  15501. opt,
  15502. normalSpecified, emphasisSpecified
  15503. ) {
  15504. opt = opt || EMPTY_OBJ;
  15505. var labelFetcher = opt.labelFetcher;
  15506. var labelDataIndex = opt.labelDataIndex;
  15507. var labelDimIndex = opt.labelDimIndex;
  15508. var labelProp = opt.labelProp;
  15509. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15510. // is not supported util someone requests.
  15511. var showNormal = normalModel.getShallow('show');
  15512. var showEmphasis = emphasisModel.getShallow('show');
  15513. // Consider performance, only fetch label when necessary.
  15514. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15515. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15516. var baseText;
  15517. if (showNormal || showEmphasis) {
  15518. if (labelFetcher) {
  15519. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, labelProp);
  15520. }
  15521. if (baseText == null) {
  15522. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15523. }
  15524. }
  15525. var normalStyleText = showNormal ? baseText : null;
  15526. var emphasisStyleText = showEmphasis
  15527. ? retrieve2(
  15528. labelFetcher
  15529. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex, labelProp)
  15530. : null,
  15531. baseText
  15532. )
  15533. : null;
  15534. // Optimize: If style.text is null, text will not be drawn.
  15535. if (normalStyleText != null || emphasisStyleText != null) {
  15536. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15537. // values have to be set on `normalStyle`.
  15538. // If we set default values on `emphasisStyle`, consider case:
  15539. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15540. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15541. // Then the 'red' will not work on emphasis.
  15542. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15543. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15544. }
  15545. normalStyle.text = normalStyleText;
  15546. emphasisStyle.text = emphasisStyleText;
  15547. }
  15548. /**
  15549. * Modify label style manually.
  15550. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15551. *
  15552. * @param {module:zrender/src/Element} el
  15553. * @param {Object} [normalStyleProps] optional
  15554. * @param {Object} [emphasisStyleProps] optional
  15555. */
  15556. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15557. var elStyle = el.style;
  15558. if (normalStyleProps) {
  15559. rollbackDefaultTextStyle(elStyle);
  15560. el.setStyle(normalStyleProps);
  15561. applyDefaultTextStyle(elStyle);
  15562. }
  15563. elStyle = el.__hoverStl;
  15564. if (emphasisStyleProps && elStyle) {
  15565. rollbackDefaultTextStyle(elStyle);
  15566. extend(elStyle, emphasisStyleProps);
  15567. applyDefaultTextStyle(elStyle);
  15568. }
  15569. }
  15570. /**
  15571. * Set basic textStyle properties.
  15572. * See more info in `setTextStyleCommon`.
  15573. * @param {Object|module:zrender/graphic/Style} textStyle
  15574. * @param {module:echarts/model/Model} model
  15575. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15576. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15577. * @param {boolean} [isEmphasis]
  15578. */
  15579. function setTextStyle(
  15580. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15581. ) {
  15582. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15583. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15584. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15585. return textStyle;
  15586. }
  15587. /**
  15588. * Set text option in the style.
  15589. * See more info in `setTextStyleCommon`.
  15590. * @deprecated
  15591. * @param {Object} textStyle
  15592. * @param {module:echarts/model/Model} labelModel
  15593. * @param {string|boolean} defaultColor Default text color.
  15594. * If set as false, it will be processed as a emphasis style.
  15595. */
  15596. function setText(textStyle, labelModel, defaultColor) {
  15597. var opt = {isRectText: true};
  15598. var isEmphasis;
  15599. if (defaultColor === false) {
  15600. isEmphasis = true;
  15601. }
  15602. else {
  15603. // Support setting color as 'auto' to get visual color.
  15604. opt.autoColor = defaultColor;
  15605. }
  15606. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15607. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15608. }
  15609. /**
  15610. * The uniform entry of set text style, that is, retrieve style definitions
  15611. * from `model` and set to `textStyle` object.
  15612. *
  15613. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15614. * properties will be set. (Consider the states of normal and emphasis and
  15615. * default value can be adopted, merge would make the logic too complicated
  15616. * to manage.)
  15617. *
  15618. * The `textStyle` object can either be a plain object or an instance of
  15619. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15620. * After this mothod called, the `textStyle` object can then be used in
  15621. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15622. *
  15623. * Default value will be adopted and `insideRollbackOpt` will be created.
  15624. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15625. *
  15626. * opt: {
  15627. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15628. * isRectText: boolean,
  15629. * autoColor: string, specify a color when color is 'auto',
  15630. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15631. * If autoColor specified, it is used as default textFill.
  15632. * useInsideStyle:
  15633. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15634. * if `textFill` is not specified.
  15635. * `false`: Do not use inside style.
  15636. * `null/undefined`: use inside style if `isRectText` is true and
  15637. * `textFill` is not specified and textPosition contains `'inside'`.
  15638. * forceRich: boolean
  15639. * }
  15640. */
  15641. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15642. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15643. opt = opt || EMPTY_OBJ;
  15644. if (opt.isRectText) {
  15645. var textPosition;
  15646. if (opt.getTextPosition) {
  15647. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15648. }
  15649. else {
  15650. textPosition = textStyleModel.getShallow('position')
  15651. || (isEmphasis ? null : 'inside');
  15652. // 'outside' is not a valid zr textPostion value, but used
  15653. // in bar series, and magric type should be considered.
  15654. textPosition === 'outside' && (textPosition = 'top');
  15655. }
  15656. textStyle.textPosition = textPosition;
  15657. textStyle.textOffset = textStyleModel.getShallow('offset');
  15658. var labelRotate = textStyleModel.getShallow('rotate');
  15659. labelRotate != null && (labelRotate *= Math.PI / 180);
  15660. textStyle.textRotation = labelRotate;
  15661. textStyle.textDistance = retrieve2(
  15662. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15663. );
  15664. }
  15665. var ecModel = textStyleModel.ecModel;
  15666. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15667. // Consider case:
  15668. // {
  15669. // data: [{
  15670. // value: 12,
  15671. // label: {
  15672. // rich: {
  15673. // // no 'a' here but using parent 'a'.
  15674. // }
  15675. // }
  15676. // }],
  15677. // rich: {
  15678. // a: { ... }
  15679. // }
  15680. // }
  15681. var richItemNames = getRichItemNames(textStyleModel);
  15682. var richResult;
  15683. if (richItemNames) {
  15684. richResult = {};
  15685. for (var name in richItemNames) {
  15686. if (richItemNames.hasOwnProperty(name)) {
  15687. // Cascade is supported in rich.
  15688. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15689. // In rich, never `disableBox`.
  15690. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15691. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15692. // That might confuses users. So probably we should put `textStyleModel` as the
  15693. // root ancestor of the `richTextStyle`. But that would be a break change.
  15694. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15695. }
  15696. }
  15697. }
  15698. textStyle.rich = richResult;
  15699. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15700. if (opt.forceRich && !opt.textStyle) {
  15701. opt.textStyle = {};
  15702. }
  15703. return textStyle;
  15704. }
  15705. // Consider case:
  15706. // {
  15707. // data: [{
  15708. // value: 12,
  15709. // label: {
  15710. // rich: {
  15711. // // no 'a' here but using parent 'a'.
  15712. // }
  15713. // }
  15714. // }],
  15715. // rich: {
  15716. // a: { ... }
  15717. // }
  15718. // }
  15719. function getRichItemNames(textStyleModel) {
  15720. // Use object to remove duplicated names.
  15721. var richItemNameMap;
  15722. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15723. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15724. if (rich) {
  15725. richItemNameMap = richItemNameMap || {};
  15726. for (var name in rich) {
  15727. if (rich.hasOwnProperty(name)) {
  15728. richItemNameMap[name] = 1;
  15729. }
  15730. }
  15731. }
  15732. textStyleModel = textStyleModel.parentModel;
  15733. }
  15734. return richItemNameMap;
  15735. }
  15736. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15737. // In merge mode, default value should not be given.
  15738. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15739. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15740. || globalTextStyle.color;
  15741. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15742. || globalTextStyle.textBorderColor;
  15743. textStyle.textStrokeWidth = retrieve2(
  15744. textStyleModel.getShallow('textBorderWidth'),
  15745. globalTextStyle.textBorderWidth
  15746. );
  15747. if (!isEmphasis) {
  15748. if (isBlock) {
  15749. textStyle.insideRollbackOpt = opt;
  15750. applyDefaultTextStyle(textStyle);
  15751. }
  15752. // Set default finally.
  15753. if (textStyle.textFill == null) {
  15754. textStyle.textFill = opt.autoColor;
  15755. }
  15756. }
  15757. // Do not use `getFont` here, because merge should be supported, where
  15758. // part of these properties may be changed in emphasis style, and the
  15759. // others should remain their original value got from normal style.
  15760. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15761. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15762. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15763. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15764. textStyle.textAlign = textStyleModel.getShallow('align');
  15765. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15766. || textStyleModel.getShallow('baseline');
  15767. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15768. textStyle.textWidth = textStyleModel.getShallow('width');
  15769. textStyle.textHeight = textStyleModel.getShallow('height');
  15770. textStyle.textTag = textStyleModel.getShallow('tag');
  15771. if (!isBlock || !opt.disableBox) {
  15772. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15773. textStyle.textPadding = textStyleModel.getShallow('padding');
  15774. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15775. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15776. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15777. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15778. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15779. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15780. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15781. }
  15782. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15783. || globalTextStyle.textShadowColor;
  15784. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15785. || globalTextStyle.textShadowBlur;
  15786. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15787. || globalTextStyle.textShadowOffsetX;
  15788. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15789. || globalTextStyle.textShadowOffsetY;
  15790. }
  15791. function getAutoColor(color, opt) {
  15792. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15793. }
  15794. /**
  15795. * Give some default value to the input `textStyle` object, based on the current settings
  15796. * in this `textStyle` object.
  15797. *
  15798. * The Scenario:
  15799. * when text position is `inside` and `textFill` is not specified, we show
  15800. * text border by default for better view. But it should be considered that text position
  15801. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15802. * restore the style.
  15803. *
  15804. * Usage (& NOTICE):
  15805. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15806. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15807. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15808. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15809. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15810. */
  15811. function applyDefaultTextStyle(textStyle) {
  15812. var textPosition = textStyle.textPosition;
  15813. var opt = textStyle.insideRollbackOpt;
  15814. var insideRollback;
  15815. if (opt && textStyle.textFill == null) {
  15816. var autoColor = opt.autoColor;
  15817. var isRectText = opt.isRectText;
  15818. var useInsideStyle = opt.useInsideStyle;
  15819. var useInsideStyleCache = useInsideStyle !== false
  15820. && (useInsideStyle === true
  15821. || (isRectText
  15822. && textPosition
  15823. // textPosition can be [10, 30]
  15824. && typeof textPosition === 'string'
  15825. && textPosition.indexOf('inside') >= 0
  15826. )
  15827. );
  15828. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15829. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15830. if (useInsideStyleCache || useAutoColorCache) {
  15831. insideRollback = {
  15832. textFill: textStyle.textFill,
  15833. textStroke: textStyle.textStroke,
  15834. textStrokeWidth: textStyle.textStrokeWidth
  15835. };
  15836. }
  15837. if (useInsideStyleCache) {
  15838. textStyle.textFill = '#fff';
  15839. // Consider text with #fff overflow its container.
  15840. if (textStyle.textStroke == null) {
  15841. textStyle.textStroke = autoColor;
  15842. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15843. }
  15844. }
  15845. if (useAutoColorCache) {
  15846. textStyle.textFill = autoColor;
  15847. }
  15848. }
  15849. // Always set `insideRollback`, so that the previous one can be cleared.
  15850. textStyle.insideRollback = insideRollback;
  15851. }
  15852. /**
  15853. * Consider the case: in a scatter,
  15854. * label: {
  15855. * normal: {position: 'inside'},
  15856. * emphasis: {position: 'top'}
  15857. * }
  15858. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15859. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15860. * should be retured to 'autoColor', but not keep '#fff'.
  15861. */
  15862. function rollbackDefaultTextStyle(style) {
  15863. var insideRollback = style.insideRollback;
  15864. if (insideRollback) {
  15865. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15866. style.textFill = insideRollback.textFill;
  15867. style.textStroke = insideRollback.textStroke;
  15868. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15869. style.insideRollback = null;
  15870. }
  15871. }
  15872. function getFont(opt, ecModel) {
  15873. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15874. return trim([
  15875. // FIXME in node-canvas fontWeight is before fontStyle
  15876. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15877. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15878. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15879. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15880. ].join(' '));
  15881. }
  15882. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15883. if (typeof dataIndex === 'function') {
  15884. cb = dataIndex;
  15885. dataIndex = null;
  15886. }
  15887. // Do not check 'animation' property directly here. Consider this case:
  15888. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15889. // but its parent model (`seriesModel`) does.
  15890. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15891. if (animationEnabled) {
  15892. var postfix = isUpdate ? 'Update' : '';
  15893. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15894. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15895. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15896. if (typeof animationDelay === 'function') {
  15897. animationDelay = animationDelay(
  15898. dataIndex,
  15899. animatableModel.getAnimationDelayParams
  15900. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15901. : null
  15902. );
  15903. }
  15904. if (typeof duration === 'function') {
  15905. duration = duration(dataIndex);
  15906. }
  15907. duration > 0
  15908. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15909. : (el.stopAnimation(), el.attr(props), cb && cb());
  15910. }
  15911. else {
  15912. el.stopAnimation();
  15913. el.attr(props);
  15914. cb && cb();
  15915. }
  15916. }
  15917. /**
  15918. * Update graphic element properties with or without animation according to the
  15919. * configuration in series.
  15920. *
  15921. * Caution: this method will stop previous animation.
  15922. * So do not use this method to one element twice before
  15923. * animation starts, unless you know what you are doing.
  15924. *
  15925. * @param {module:zrender/Element} el
  15926. * @param {Object} props
  15927. * @param {module:echarts/model/Model} [animatableModel]
  15928. * @param {number} [dataIndex]
  15929. * @param {Function} [cb]
  15930. * @example
  15931. * graphic.updateProps(el, {
  15932. * position: [100, 100]
  15933. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15934. * // Or
  15935. * graphic.updateProps(el, {
  15936. * position: [100, 100]
  15937. * }, seriesModel, function () { console.log('Animation done!'); });
  15938. */
  15939. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15940. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15941. }
  15942. /**
  15943. * Init graphic element properties with or without animation according to the
  15944. * configuration in series.
  15945. *
  15946. * Caution: this method will stop previous animation.
  15947. * So do not use this method to one element twice before
  15948. * animation starts, unless you know what you are doing.
  15949. *
  15950. * @param {module:zrender/Element} el
  15951. * @param {Object} props
  15952. * @param {module:echarts/model/Model} [animatableModel]
  15953. * @param {number} [dataIndex]
  15954. * @param {Function} cb
  15955. */
  15956. function initProps(el, props, animatableModel, dataIndex, cb) {
  15957. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15958. }
  15959. /**
  15960. * Get transform matrix of target (param target),
  15961. * in coordinate of its ancestor (param ancestor)
  15962. *
  15963. * @param {module:zrender/mixin/Transformable} target
  15964. * @param {module:zrender/mixin/Transformable} [ancestor]
  15965. */
  15966. function getTransform(target, ancestor) {
  15967. var mat = identity([]);
  15968. while (target && target !== ancestor) {
  15969. mul$1(mat, target.getLocalTransform(), mat);
  15970. target = target.parent;
  15971. }
  15972. return mat;
  15973. }
  15974. /**
  15975. * Apply transform to an vertex.
  15976. * @param {Array.<number>} target [x, y]
  15977. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15978. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15979. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15980. * @param {boolean=} invert Whether use invert matrix.
  15981. * @return {Array.<number>} [x, y]
  15982. */
  15983. function applyTransform$1(target, transform, invert$$1) {
  15984. if (transform && !isArrayLike(transform)) {
  15985. transform = Transformable.getLocalTransform(transform);
  15986. }
  15987. if (invert$$1) {
  15988. transform = invert([], transform);
  15989. }
  15990. return applyTransform([], target, transform);
  15991. }
  15992. /**
  15993. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15994. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15995. * @param {boolean=} invert Whether use invert matrix.
  15996. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15997. */
  15998. function transformDirection(direction, transform, invert$$1) {
  15999. // Pick a base, ensure that transform result will not be (0, 0).
  16000. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  16001. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  16002. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  16003. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  16004. var vertex = [
  16005. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  16006. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  16007. ];
  16008. vertex = applyTransform$1(vertex, transform, invert$$1);
  16009. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  16010. ? (vertex[0] > 0 ? 'right' : 'left')
  16011. : (vertex[1] > 0 ? 'bottom' : 'top');
  16012. }
  16013. /**
  16014. * Apply group transition animation from g1 to g2.
  16015. * If no animatableModel, no animation.
  16016. */
  16017. function groupTransition(g1, g2, animatableModel, cb) {
  16018. if (!g1 || !g2) {
  16019. return;
  16020. }
  16021. function getElMap(g) {
  16022. var elMap = {};
  16023. g.traverse(function (el) {
  16024. if (!el.isGroup && el.anid) {
  16025. elMap[el.anid] = el;
  16026. }
  16027. });
  16028. return elMap;
  16029. }
  16030. function getAnimatableProps(el) {
  16031. var obj = {
  16032. position: clone$1(el.position),
  16033. rotation: el.rotation
  16034. };
  16035. if (el.shape) {
  16036. obj.shape = extend({}, el.shape);
  16037. }
  16038. return obj;
  16039. }
  16040. var elMap1 = getElMap(g1);
  16041. g2.traverse(function (el) {
  16042. if (!el.isGroup && el.anid) {
  16043. var oldEl = elMap1[el.anid];
  16044. if (oldEl) {
  16045. var newProp = getAnimatableProps(el);
  16046. el.attr(getAnimatableProps(oldEl));
  16047. updateProps(el, newProp, animatableModel, el.dataIndex);
  16048. }
  16049. // else {
  16050. // if (el.previousProps) {
  16051. // graphic.updateProps
  16052. // }
  16053. // }
  16054. }
  16055. });
  16056. }
  16057. /**
  16058. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  16059. * @param {Object} rect {x, y, width, height}
  16060. * @return {Array.<Array.<number>>} A new clipped points.
  16061. */
  16062. function clipPointsByRect(points, rect) {
  16063. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  16064. // and when element have border.
  16065. return map(points, function (point) {
  16066. var x = point[0];
  16067. x = mathMax$1(x, rect.x);
  16068. x = mathMin$1(x, rect.x + rect.width);
  16069. var y = point[1];
  16070. y = mathMax$1(y, rect.y);
  16071. y = mathMin$1(y, rect.y + rect.height);
  16072. return [x, y];
  16073. });
  16074. }
  16075. /**
  16076. * @param {Object} targetRect {x, y, width, height}
  16077. * @param {Object} rect {x, y, width, height}
  16078. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  16079. */
  16080. function clipRectByRect(targetRect, rect) {
  16081. var x = mathMax$1(targetRect.x, rect.x);
  16082. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  16083. var y = mathMax$1(targetRect.y, rect.y);
  16084. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  16085. // If the total rect is cliped, nothing, including the border,
  16086. // should be painted. So return undefined.
  16087. if (x2 >= x && y2 >= y) {
  16088. return {
  16089. x: x,
  16090. y: y,
  16091. width: x2 - x,
  16092. height: y2 - y
  16093. };
  16094. }
  16095. }
  16096. /**
  16097. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  16098. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  16099. * @param {Object} [rect] {x, y, width, height}
  16100. * @return {module:zrender/Element} Icon path or image element.
  16101. */
  16102. function createIcon(iconStr, opt, rect) {
  16103. opt = extend({rectHover: true}, opt);
  16104. var style = opt.style = {strokeNoScale: true};
  16105. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  16106. if (iconStr) {
  16107. return iconStr.indexOf('image://') === 0
  16108. ? (
  16109. style.image = iconStr.slice(8),
  16110. defaults(style, rect),
  16111. new ZImage(opt)
  16112. )
  16113. : (
  16114. makePath(
  16115. iconStr.replace('path://', ''),
  16116. opt,
  16117. rect,
  16118. 'center'
  16119. )
  16120. );
  16121. }
  16122. }
  16123. /**
  16124. * Return `true` if the given line (line `a`) and the given polygon
  16125. * are intersect.
  16126. * Note that we do not count colinear as intersect here because no
  16127. * requirement for that. We could do that if required in future.
  16128. *
  16129. * @param {number} a1x
  16130. * @param {number} a1y
  16131. * @param {number} a2x
  16132. * @param {number} a2y
  16133. * @param {Array.<Array.<number>>} points Points of the polygon.
  16134. * @return {boolean}
  16135. */
  16136. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  16137. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  16138. var p = points[i];
  16139. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  16140. return true;
  16141. }
  16142. p2 = p;
  16143. }
  16144. }
  16145. /**
  16146. * Return `true` if the given two lines (line `a` and line `b`)
  16147. * are intersect.
  16148. * Note that we do not count colinear as intersect here because no
  16149. * requirement for that. We could do that if required in future.
  16150. *
  16151. * @param {number} a1x
  16152. * @param {number} a1y
  16153. * @param {number} a2x
  16154. * @param {number} a2y
  16155. * @param {number} b1x
  16156. * @param {number} b1y
  16157. * @param {number} b2x
  16158. * @param {number} b2y
  16159. * @return {boolean}
  16160. */
  16161. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  16162. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  16163. var mx = a2x - a1x;
  16164. var my = a2y - a1y;
  16165. var nx = b2x - b1x;
  16166. var ny = b2y - b1y;
  16167. // `vec_m` and `vec_n` are parallel iff
  16168. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  16169. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  16170. if (nearZero(nmCrossProduct)) {
  16171. return false;
  16172. }
  16173. // `vec_m` and `vec_n` are intersect iff
  16174. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  16175. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  16176. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  16177. var b1a1x = a1x - b1x;
  16178. var b1a1y = a1y - b1y;
  16179. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  16180. if (q < 0 || q > 1) {
  16181. return false;
  16182. }
  16183. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  16184. if (p < 0 || p > 1) {
  16185. return false;
  16186. }
  16187. return true;
  16188. }
  16189. /**
  16190. * Cross product of 2-dimension vector.
  16191. */
  16192. function crossProduct2d(x1, y1, x2, y2) {
  16193. return x1 * y2 - x2 * y1;
  16194. }
  16195. function nearZero(val) {
  16196. return val <= (1e-6) && val >= -(1e-6);
  16197. }
  16198. // Register built-in shapes. These shapes might be overwirtten
  16199. // by users, although we do not recommend that.
  16200. registerShape('circle', Circle);
  16201. registerShape('sector', Sector);
  16202. registerShape('ring', Ring);
  16203. registerShape('polygon', Polygon);
  16204. registerShape('polyline', Polyline);
  16205. registerShape('rect', Rect);
  16206. registerShape('line', Line);
  16207. registerShape('bezierCurve', BezierCurve);
  16208. registerShape('arc', Arc);
  16209. var graphic = (Object.freeze || Object)({
  16210. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  16211. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  16212. extendShape: extendShape,
  16213. extendPath: extendPath,
  16214. registerShape: registerShape,
  16215. getShapeClass: getShapeClass,
  16216. makePath: makePath,
  16217. makeImage: makeImage,
  16218. mergePath: mergePath,
  16219. resizePath: resizePath,
  16220. subPixelOptimizeLine: subPixelOptimizeLine,
  16221. subPixelOptimizeRect: subPixelOptimizeRect,
  16222. subPixelOptimize: subPixelOptimize,
  16223. setElementHoverStyle: setElementHoverStyle,
  16224. setHoverStyle: setHoverStyle,
  16225. setAsHighDownDispatcher: setAsHighDownDispatcher,
  16226. isHighDownDispatcher: isHighDownDispatcher,
  16227. getHighlightDigit: getHighlightDigit,
  16228. setLabelStyle: setLabelStyle,
  16229. modifyLabelStyle: modifyLabelStyle,
  16230. setTextStyle: setTextStyle,
  16231. setText: setText,
  16232. getFont: getFont,
  16233. updateProps: updateProps,
  16234. initProps: initProps,
  16235. getTransform: getTransform,
  16236. applyTransform: applyTransform$1,
  16237. transformDirection: transformDirection,
  16238. groupTransition: groupTransition,
  16239. clipPointsByRect: clipPointsByRect,
  16240. clipRectByRect: clipRectByRect,
  16241. createIcon: createIcon,
  16242. linePolygonIntersect: linePolygonIntersect,
  16243. lineLineIntersect: lineLineIntersect,
  16244. Group: Group,
  16245. Image: ZImage,
  16246. Text: Text,
  16247. Circle: Circle,
  16248. Sector: Sector,
  16249. Ring: Ring,
  16250. Polygon: Polygon,
  16251. Polyline: Polyline,
  16252. Rect: Rect,
  16253. Line: Line,
  16254. BezierCurve: BezierCurve,
  16255. Arc: Arc,
  16256. IncrementalDisplayable: IncrementalDisplayble,
  16257. CompoundPath: CompoundPath,
  16258. LinearGradient: LinearGradient,
  16259. RadialGradient: RadialGradient,
  16260. BoundingRect: BoundingRect
  16261. });
  16262. /*
  16263. * Licensed to the Apache Software Foundation (ASF) under one
  16264. * or more contributor license agreements. See the NOTICE file
  16265. * distributed with this work for additional information
  16266. * regarding copyright ownership. The ASF licenses this file
  16267. * to you under the Apache License, Version 2.0 (the
  16268. * "License"); you may not use this file except in compliance
  16269. * with the License. You may obtain a copy of the License at
  16270. *
  16271. * http://www.apache.org/licenses/LICENSE-2.0
  16272. *
  16273. * Unless required by applicable law or agreed to in writing,
  16274. * software distributed under the License is distributed on an
  16275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16276. * KIND, either express or implied. See the License for the
  16277. * specific language governing permissions and limitations
  16278. * under the License.
  16279. */
  16280. var PATH_COLOR = ['textStyle', 'color'];
  16281. var textStyleMixin = {
  16282. /**
  16283. * Get color property or get color from option.textStyle.color
  16284. * @param {boolean} [isEmphasis]
  16285. * @return {string}
  16286. */
  16287. getTextColor: function (isEmphasis) {
  16288. var ecModel = this.ecModel;
  16289. return this.getShallow('color')
  16290. || (
  16291. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  16292. );
  16293. },
  16294. /**
  16295. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  16296. * @return {string}
  16297. */
  16298. getFont: function () {
  16299. return getFont({
  16300. fontStyle: this.getShallow('fontStyle'),
  16301. fontWeight: this.getShallow('fontWeight'),
  16302. fontSize: this.getShallow('fontSize'),
  16303. fontFamily: this.getShallow('fontFamily')
  16304. }, this.ecModel);
  16305. },
  16306. getTextRect: function (text) {
  16307. return getBoundingRect(
  16308. text,
  16309. this.getFont(),
  16310. this.getShallow('align'),
  16311. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  16312. this.getShallow('padding'),
  16313. this.getShallow('lineHeight'),
  16314. this.getShallow('rich'),
  16315. this.getShallow('truncateText')
  16316. );
  16317. }
  16318. };
  16319. /*
  16320. * Licensed to the Apache Software Foundation (ASF) under one
  16321. * or more contributor license agreements. See the NOTICE file
  16322. * distributed with this work for additional information
  16323. * regarding copyright ownership. The ASF licenses this file
  16324. * to you under the Apache License, Version 2.0 (the
  16325. * "License"); you may not use this file except in compliance
  16326. * with the License. You may obtain a copy of the License at
  16327. *
  16328. * http://www.apache.org/licenses/LICENSE-2.0
  16329. *
  16330. * Unless required by applicable law or agreed to in writing,
  16331. * software distributed under the License is distributed on an
  16332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16333. * KIND, either express or implied. See the License for the
  16334. * specific language governing permissions and limitations
  16335. * under the License.
  16336. */
  16337. var getItemStyle = makeStyleMapper(
  16338. [
  16339. ['fill', 'color'],
  16340. ['stroke', 'borderColor'],
  16341. ['lineWidth', 'borderWidth'],
  16342. ['opacity'],
  16343. ['shadowBlur'],
  16344. ['shadowOffsetX'],
  16345. ['shadowOffsetY'],
  16346. ['shadowColor'],
  16347. ['textPosition'],
  16348. ['textAlign']
  16349. ]
  16350. );
  16351. var itemStyleMixin = {
  16352. getItemStyle: function (excludes, includes) {
  16353. var style = getItemStyle(this, excludes, includes);
  16354. var lineDash = this.getBorderLineDash();
  16355. lineDash && (style.lineDash = lineDash);
  16356. return style;
  16357. },
  16358. getBorderLineDash: function () {
  16359. var lineType = this.get('borderType');
  16360. return (lineType === 'solid' || lineType == null) ? null
  16361. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  16362. }
  16363. };
  16364. /*
  16365. * Licensed to the Apache Software Foundation (ASF) under one
  16366. * or more contributor license agreements. See the NOTICE file
  16367. * distributed with this work for additional information
  16368. * regarding copyright ownership. The ASF licenses this file
  16369. * to you under the Apache License, Version 2.0 (the
  16370. * "License"); you may not use this file except in compliance
  16371. * with the License. You may obtain a copy of the License at
  16372. *
  16373. * http://www.apache.org/licenses/LICENSE-2.0
  16374. *
  16375. * Unless required by applicable law or agreed to in writing,
  16376. * software distributed under the License is distributed on an
  16377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16378. * KIND, either express or implied. See the License for the
  16379. * specific language governing permissions and limitations
  16380. * under the License.
  16381. */
  16382. /**
  16383. * @module echarts/model/Model
  16384. */
  16385. var mixin$1 = mixin;
  16386. var inner = makeInner();
  16387. /**
  16388. * @alias module:echarts/model/Model
  16389. * @constructor
  16390. * @param {Object} [option]
  16391. * @param {module:echarts/model/Model} [parentModel]
  16392. * @param {module:echarts/model/Global} [ecModel]
  16393. */
  16394. function Model(option, parentModel, ecModel) {
  16395. /**
  16396. * @type {module:echarts/model/Model}
  16397. * @readOnly
  16398. */
  16399. this.parentModel = parentModel;
  16400. /**
  16401. * @type {module:echarts/model/Global}
  16402. * @readOnly
  16403. */
  16404. this.ecModel = ecModel;
  16405. /**
  16406. * @type {Object}
  16407. * @protected
  16408. */
  16409. this.option = option;
  16410. // Simple optimization
  16411. // if (this.init) {
  16412. // if (arguments.length <= 4) {
  16413. // this.init(option, parentModel, ecModel, extraOpt);
  16414. // }
  16415. // else {
  16416. // this.init.apply(this, arguments);
  16417. // }
  16418. // }
  16419. }
  16420. Model.prototype = {
  16421. constructor: Model,
  16422. /**
  16423. * Model 的初始化函数
  16424. * @param {Object} option
  16425. */
  16426. init: null,
  16427. /**
  16428. * 从新的 Option merge
  16429. */
  16430. mergeOption: function (option) {
  16431. merge(this.option, option, true);
  16432. },
  16433. /**
  16434. * @param {string|Array.<string>} path
  16435. * @param {boolean} [ignoreParent=false]
  16436. * @return {*}
  16437. */
  16438. get: function (path, ignoreParent) {
  16439. if (path == null) {
  16440. return this.option;
  16441. }
  16442. return doGet(
  16443. this.option,
  16444. this.parsePath(path),
  16445. !ignoreParent && getParent(this, path)
  16446. );
  16447. },
  16448. /**
  16449. * @param {string} key
  16450. * @param {boolean} [ignoreParent=false]
  16451. * @return {*}
  16452. */
  16453. getShallow: function (key, ignoreParent) {
  16454. var option = this.option;
  16455. var val = option == null ? option : option[key];
  16456. var parentModel = !ignoreParent && getParent(this, key);
  16457. if (val == null && parentModel) {
  16458. val = parentModel.getShallow(key);
  16459. }
  16460. return val;
  16461. },
  16462. /**
  16463. * @param {string|Array.<string>} [path]
  16464. * @param {module:echarts/model/Model} [parentModel]
  16465. * @return {module:echarts/model/Model}
  16466. */
  16467. getModel: function (path, parentModel) {
  16468. var obj = path == null
  16469. ? this.option
  16470. : doGet(this.option, path = this.parsePath(path));
  16471. var thisParentModel;
  16472. parentModel = parentModel || (
  16473. (thisParentModel = getParent(this, path))
  16474. && thisParentModel.getModel(path)
  16475. );
  16476. return new Model(obj, parentModel, this.ecModel);
  16477. },
  16478. /**
  16479. * If model has option
  16480. */
  16481. isEmpty: function () {
  16482. return this.option == null;
  16483. },
  16484. restoreData: function () {},
  16485. // Pending
  16486. clone: function () {
  16487. var Ctor = this.constructor;
  16488. return new Ctor(clone(this.option));
  16489. },
  16490. setReadOnly: function (properties) {
  16491. // clazzUtil.setReadOnly(this, properties);
  16492. },
  16493. // If path is null/undefined, return null/undefined.
  16494. parsePath: function (path) {
  16495. if (typeof path === 'string') {
  16496. path = path.split('.');
  16497. }
  16498. return path;
  16499. },
  16500. /**
  16501. * @param {Function} getParentMethod
  16502. * param {Array.<string>|string} path
  16503. * return {module:echarts/model/Model}
  16504. */
  16505. customizeGetParent: function (getParentMethod) {
  16506. inner(this).getParent = getParentMethod;
  16507. },
  16508. isAnimationEnabled: function () {
  16509. if (!env$1.node) {
  16510. if (this.option.animation != null) {
  16511. return !!this.option.animation;
  16512. }
  16513. else if (this.parentModel) {
  16514. return this.parentModel.isAnimationEnabled();
  16515. }
  16516. }
  16517. }
  16518. };
  16519. function doGet(obj, pathArr, parentModel) {
  16520. for (var i = 0; i < pathArr.length; i++) {
  16521. // Ignore empty
  16522. if (!pathArr[i]) {
  16523. continue;
  16524. }
  16525. // obj could be number/string/... (like 0)
  16526. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16527. if (obj == null) {
  16528. break;
  16529. }
  16530. }
  16531. if (obj == null && parentModel) {
  16532. obj = parentModel.get(pathArr);
  16533. }
  16534. return obj;
  16535. }
  16536. // `path` can be null/undefined
  16537. function getParent(model, path) {
  16538. var getParentMethod = inner(model).getParent;
  16539. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16540. }
  16541. // Enable Model.extend.
  16542. enableClassExtend(Model);
  16543. enableClassCheck(Model);
  16544. mixin$1(Model, lineStyleMixin);
  16545. mixin$1(Model, areaStyleMixin);
  16546. mixin$1(Model, textStyleMixin);
  16547. mixin$1(Model, itemStyleMixin);
  16548. /*
  16549. * Licensed to the Apache Software Foundation (ASF) under one
  16550. * or more contributor license agreements. See the NOTICE file
  16551. * distributed with this work for additional information
  16552. * regarding copyright ownership. The ASF licenses this file
  16553. * to you under the Apache License, Version 2.0 (the
  16554. * "License"); you may not use this file except in compliance
  16555. * with the License. You may obtain a copy of the License at
  16556. *
  16557. * http://www.apache.org/licenses/LICENSE-2.0
  16558. *
  16559. * Unless required by applicable law or agreed to in writing,
  16560. * software distributed under the License is distributed on an
  16561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16562. * KIND, either express or implied. See the License for the
  16563. * specific language governing permissions and limitations
  16564. * under the License.
  16565. */
  16566. var base = 0;
  16567. /**
  16568. * @public
  16569. * @param {string} type
  16570. * @return {string}
  16571. */
  16572. function getUID(type) {
  16573. // Considering the case of crossing js context,
  16574. // use Math.random to make id as unique as possible.
  16575. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16576. }
  16577. /**
  16578. * @inner
  16579. */
  16580. function enableSubTypeDefaulter(entity) {
  16581. var subTypeDefaulters = {};
  16582. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16583. componentType = parseClassType$1(componentType);
  16584. subTypeDefaulters[componentType.main] = defaulter;
  16585. };
  16586. entity.determineSubType = function (componentType, option) {
  16587. var type = option.type;
  16588. if (!type) {
  16589. var componentTypeMain = parseClassType$1(componentType).main;
  16590. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16591. type = subTypeDefaulters[componentTypeMain](option);
  16592. }
  16593. }
  16594. return type;
  16595. };
  16596. return entity;
  16597. }
  16598. /**
  16599. * Topological travel on Activity Network (Activity On Vertices).
  16600. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16601. *
  16602. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16603. *
  16604. * If there is circle dependencey, Error will be thrown.
  16605. *
  16606. */
  16607. function enableTopologicalTravel(entity, dependencyGetter) {
  16608. /**
  16609. * @public
  16610. * @param {Array.<string>} targetNameList Target Component type list.
  16611. * Can be ['aa', 'bb', 'aa.xx']
  16612. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16613. * @param {Function} callback Params: componentType, dependencies.
  16614. * @param {Object} context Scope of callback.
  16615. */
  16616. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16617. if (!targetNameList.length) {
  16618. return;
  16619. }
  16620. var result = makeDepndencyGraph(fullNameList);
  16621. var graph = result.graph;
  16622. var stack = result.noEntryList;
  16623. var targetNameSet = {};
  16624. each$1(targetNameList, function (name) {
  16625. targetNameSet[name] = true;
  16626. });
  16627. while (stack.length) {
  16628. var currComponentType = stack.pop();
  16629. var currVertex = graph[currComponentType];
  16630. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16631. if (isInTargetNameSet) {
  16632. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16633. delete targetNameSet[currComponentType];
  16634. }
  16635. each$1(
  16636. currVertex.successor,
  16637. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16638. );
  16639. }
  16640. each$1(targetNameSet, function () {
  16641. throw new Error('Circle dependency may exists');
  16642. });
  16643. function removeEdge(succComponentType) {
  16644. graph[succComponentType].entryCount--;
  16645. if (graph[succComponentType].entryCount === 0) {
  16646. stack.push(succComponentType);
  16647. }
  16648. }
  16649. // Consider this case: legend depends on series, and we call
  16650. // chart.setOption({series: [...]}), where only series is in option.
  16651. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16652. // not be called, but only sereis.mergeOption is called. Thus legend
  16653. // have no chance to update its local record about series (like which
  16654. // name of series is available in legend).
  16655. function removeEdgeAndAdd(succComponentType) {
  16656. targetNameSet[succComponentType] = true;
  16657. removeEdge(succComponentType);
  16658. }
  16659. };
  16660. /**
  16661. * DepndencyGraph: {Object}
  16662. * key: conponentType,
  16663. * value: {
  16664. * successor: [conponentTypes...],
  16665. * originalDeps: [conponentTypes...],
  16666. * entryCount: {number}
  16667. * }
  16668. */
  16669. function makeDepndencyGraph(fullNameList) {
  16670. var graph = {};
  16671. var noEntryList = [];
  16672. each$1(fullNameList, function (name) {
  16673. var thisItem = createDependencyGraphItem(graph, name);
  16674. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16675. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16676. thisItem.entryCount = availableDeps.length;
  16677. if (thisItem.entryCount === 0) {
  16678. noEntryList.push(name);
  16679. }
  16680. each$1(availableDeps, function (dependentName) {
  16681. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16682. thisItem.predecessor.push(dependentName);
  16683. }
  16684. var thatItem = createDependencyGraphItem(graph, dependentName);
  16685. if (indexOf(thatItem.successor, dependentName) < 0) {
  16686. thatItem.successor.push(name);
  16687. }
  16688. });
  16689. });
  16690. return {graph: graph, noEntryList: noEntryList};
  16691. }
  16692. function createDependencyGraphItem(graph, name) {
  16693. if (!graph[name]) {
  16694. graph[name] = {predecessor: [], successor: []};
  16695. }
  16696. return graph[name];
  16697. }
  16698. function getAvailableDependencies(originalDeps, fullNameList) {
  16699. var availableDeps = [];
  16700. each$1(originalDeps, function (dep) {
  16701. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16702. });
  16703. return availableDeps;
  16704. }
  16705. }
  16706. /*
  16707. * Licensed to the Apache Software Foundation (ASF) under one
  16708. * or more contributor license agreements. See the NOTICE file
  16709. * distributed with this work for additional information
  16710. * regarding copyright ownership. The ASF licenses this file
  16711. * to you under the Apache License, Version 2.0 (the
  16712. * "License"); you may not use this file except in compliance
  16713. * with the License. You may obtain a copy of the License at
  16714. *
  16715. * http://www.apache.org/licenses/LICENSE-2.0
  16716. *
  16717. * Unless required by applicable law or agreed to in writing,
  16718. * software distributed under the License is distributed on an
  16719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16720. * KIND, either express or implied. See the License for the
  16721. * specific language governing permissions and limitations
  16722. * under the License.
  16723. */
  16724. /*
  16725. * A third-party license is embeded for some of the code in this file:
  16726. * The method "quantile" was copied from "d3.js".
  16727. * (See more details in the comment of the method below.)
  16728. * The use of the source code of this file is also subject to the terms
  16729. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16730. * </licenses/LICENSE-d3>).
  16731. */
  16732. var RADIAN_EPSILON = 1e-4;
  16733. function _trim(str) {
  16734. return str.replace(/^\s+|\s+$/g, '');
  16735. }
  16736. /**
  16737. * Linear mapping a value from domain to range
  16738. * @memberOf module:echarts/util/number
  16739. * @param {(number|Array.<number>)} val
  16740. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16741. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16742. * @param {boolean} clamp
  16743. * @return {(number|Array.<number>}
  16744. */
  16745. function linearMap(val, domain, range, clamp) {
  16746. var subDomain = domain[1] - domain[0];
  16747. var subRange = range[1] - range[0];
  16748. if (subDomain === 0) {
  16749. return subRange === 0
  16750. ? range[0]
  16751. : (range[0] + range[1]) / 2;
  16752. }
  16753. // Avoid accuracy problem in edge, such as
  16754. // 146.39 - 62.83 === 83.55999999999999.
  16755. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16756. // It is a little verbose for efficiency considering this method
  16757. // is a hotspot.
  16758. if (clamp) {
  16759. if (subDomain > 0) {
  16760. if (val <= domain[0]) {
  16761. return range[0];
  16762. }
  16763. else if (val >= domain[1]) {
  16764. return range[1];
  16765. }
  16766. }
  16767. else {
  16768. if (val >= domain[0]) {
  16769. return range[0];
  16770. }
  16771. else if (val <= domain[1]) {
  16772. return range[1];
  16773. }
  16774. }
  16775. }
  16776. else {
  16777. if (val === domain[0]) {
  16778. return range[0];
  16779. }
  16780. if (val === domain[1]) {
  16781. return range[1];
  16782. }
  16783. }
  16784. return (val - domain[0]) / subDomain * subRange + range[0];
  16785. }
  16786. /**
  16787. * Convert a percent string to absolute number.
  16788. * Returns NaN if percent is not a valid string or number
  16789. * @memberOf module:echarts/util/number
  16790. * @param {string|number} percent
  16791. * @param {number} all
  16792. * @return {number}
  16793. */
  16794. function parsePercent$1(percent, all) {
  16795. switch (percent) {
  16796. case 'center':
  16797. case 'middle':
  16798. percent = '50%';
  16799. break;
  16800. case 'left':
  16801. case 'top':
  16802. percent = '0%';
  16803. break;
  16804. case 'right':
  16805. case 'bottom':
  16806. percent = '100%';
  16807. break;
  16808. }
  16809. if (typeof percent === 'string') {
  16810. if (_trim(percent).match(/%$/)) {
  16811. return parseFloat(percent) / 100 * all;
  16812. }
  16813. return parseFloat(percent);
  16814. }
  16815. return percent == null ? NaN : +percent;
  16816. }
  16817. /**
  16818. * (1) Fix rounding error of float numbers.
  16819. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16820. *
  16821. * @param {number} x
  16822. * @param {number} [precision]
  16823. * @param {boolean} [returnStr]
  16824. * @return {number|string}
  16825. */
  16826. function round$1(x, precision, returnStr) {
  16827. if (precision == null) {
  16828. precision = 10;
  16829. }
  16830. // Avoid range error
  16831. precision = Math.min(Math.max(0, precision), 20);
  16832. x = (+x).toFixed(precision);
  16833. return returnStr ? x : +x;
  16834. }
  16835. /**
  16836. * asc sort arr.
  16837. * The input arr will be modified.
  16838. *
  16839. * @param {Array} arr
  16840. * @return {Array} The input arr.
  16841. */
  16842. function asc(arr) {
  16843. arr.sort(function (a, b) {
  16844. return a - b;
  16845. });
  16846. return arr;
  16847. }
  16848. /**
  16849. * Get precision
  16850. * @param {number} val
  16851. */
  16852. function getPrecision(val) {
  16853. val = +val;
  16854. if (isNaN(val)) {
  16855. return 0;
  16856. }
  16857. // It is much faster than methods converting number to string as follows
  16858. // var tmp = val.toString();
  16859. // return tmp.length - 1 - tmp.indexOf('.');
  16860. // especially when precision is low
  16861. var e = 1;
  16862. var count = 0;
  16863. while (Math.round(val * e) / e !== val) {
  16864. e *= 10;
  16865. count++;
  16866. }
  16867. return count;
  16868. }
  16869. /**
  16870. * @param {string|number} val
  16871. * @return {number}
  16872. */
  16873. function getPrecisionSafe(val) {
  16874. var str = val.toString();
  16875. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16876. var eIndex = str.indexOf('e');
  16877. if (eIndex > 0) {
  16878. var precision = +str.slice(eIndex + 1);
  16879. return precision < 0 ? -precision : 0;
  16880. }
  16881. else {
  16882. var dotIndex = str.indexOf('.');
  16883. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16884. }
  16885. }
  16886. /**
  16887. * Minimal dicernible data precisioin according to a single pixel.
  16888. *
  16889. * @param {Array.<number>} dataExtent
  16890. * @param {Array.<number>} pixelExtent
  16891. * @return {number} precision
  16892. */
  16893. function getPixelPrecision(dataExtent, pixelExtent) {
  16894. var log = Math.log;
  16895. var LN10 = Math.LN10;
  16896. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16897. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16898. // toFixed() digits argument must be between 0 and 20.
  16899. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16900. return !isFinite(precision) ? 20 : precision;
  16901. }
  16902. /**
  16903. * Get a data of given precision, assuring the sum of percentages
  16904. * in valueList is 1.
  16905. * The largest remainer method is used.
  16906. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16907. *
  16908. * @param {Array.<number>} valueList a list of all data
  16909. * @param {number} idx index of the data to be processed in valueList
  16910. * @param {number} precision integer number showing digits of precision
  16911. * @return {number} percent ranging from 0 to 100
  16912. */
  16913. function getPercentWithPrecision(valueList, idx, precision) {
  16914. if (!valueList[idx]) {
  16915. return 0;
  16916. }
  16917. var sum = reduce(valueList, function (acc, val) {
  16918. return acc + (isNaN(val) ? 0 : val);
  16919. }, 0);
  16920. if (sum === 0) {
  16921. return 0;
  16922. }
  16923. var digits = Math.pow(10, precision);
  16924. var votesPerQuota = map(valueList, function (val) {
  16925. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16926. });
  16927. var targetSeats = digits * 100;
  16928. var seats = map(votesPerQuota, function (votes) {
  16929. // Assign automatic seats.
  16930. return Math.floor(votes);
  16931. });
  16932. var currentSum = reduce(seats, function (acc, val) {
  16933. return acc + val;
  16934. }, 0);
  16935. var remainder = map(votesPerQuota, function (votes, idx) {
  16936. return votes - seats[idx];
  16937. });
  16938. // Has remainding votes.
  16939. while (currentSum < targetSeats) {
  16940. // Find next largest remainder.
  16941. var max = Number.NEGATIVE_INFINITY;
  16942. var maxId = null;
  16943. for (var i = 0, len = remainder.length; i < len; ++i) {
  16944. if (remainder[i] > max) {
  16945. max = remainder[i];
  16946. maxId = i;
  16947. }
  16948. }
  16949. // Add a vote to max remainder.
  16950. ++seats[maxId];
  16951. remainder[maxId] = 0;
  16952. ++currentSum;
  16953. }
  16954. return seats[idx] / digits;
  16955. }
  16956. // Number.MAX_SAFE_INTEGER, ie do not support.
  16957. var MAX_SAFE_INTEGER = 9007199254740991;
  16958. /**
  16959. * To 0 - 2 * PI, considering negative radian.
  16960. * @param {number} radian
  16961. * @return {number}
  16962. */
  16963. function remRadian(radian) {
  16964. var pi2 = Math.PI * 2;
  16965. return (radian % pi2 + pi2) % pi2;
  16966. }
  16967. /**
  16968. * @param {type} radian
  16969. * @return {boolean}
  16970. */
  16971. function isRadianAroundZero(val) {
  16972. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16973. }
  16974. /* eslint-disable */
  16975. 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
  16976. /* eslint-enable */
  16977. /**
  16978. * @param {string|Date|number} value These values can be accepted:
  16979. * + An instance of Date, represent a time in its own time zone.
  16980. * + Or string in a subset of ISO 8601, only including:
  16981. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16982. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16983. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16984. * all of which will be treated as local time if time zone is not specified
  16985. * (see <https://momentjs.com/>).
  16986. * + Or other string format, including (all of which will be treated as loacal time):
  16987. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16988. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16989. * + a timestamp, which represent a time in UTC.
  16990. * @return {Date} date
  16991. */
  16992. function parseDate(value) {
  16993. if (value instanceof Date) {
  16994. return value;
  16995. }
  16996. else if (typeof value === 'string') {
  16997. // Different browsers parse date in different way, so we parse it manually.
  16998. // Some other issues:
  16999. // new Date('1970-01-01') is UTC,
  17000. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  17001. // See issue #3623
  17002. var match = TIME_REG.exec(value);
  17003. if (!match) {
  17004. // return Invalid Date.
  17005. return new Date(NaN);
  17006. }
  17007. // Use local time when no timezone offset specifed.
  17008. if (!match[8]) {
  17009. // match[n] can only be string or undefined.
  17010. // But take care of '12' + 1 => '121'.
  17011. return new Date(
  17012. +match[1],
  17013. +(match[2] || 1) - 1,
  17014. +match[3] || 1,
  17015. +match[4] || 0,
  17016. +(match[5] || 0),
  17017. +match[6] || 0,
  17018. +match[7] || 0
  17019. );
  17020. }
  17021. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  17022. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  17023. // For example, system timezone is set as "Time Zone: America/Toronto",
  17024. // then these code will get different result:
  17025. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  17026. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  17027. // So we should not use `new Date`, but use `Date.UTC`.
  17028. else {
  17029. var hour = +match[4] || 0;
  17030. if (match[8].toUpperCase() !== 'Z') {
  17031. hour -= match[8].slice(0, 3);
  17032. }
  17033. return new Date(Date.UTC(
  17034. +match[1],
  17035. +(match[2] || 1) - 1,
  17036. +match[3] || 1,
  17037. hour,
  17038. +(match[5] || 0),
  17039. +match[6] || 0,
  17040. +match[7] || 0
  17041. ));
  17042. }
  17043. }
  17044. else if (value == null) {
  17045. return new Date(NaN);
  17046. }
  17047. return new Date(Math.round(value));
  17048. }
  17049. /**
  17050. * Quantity of a number. e.g. 0.1, 1, 10, 100
  17051. *
  17052. * @param {number} val
  17053. * @return {number}
  17054. */
  17055. function quantity(val) {
  17056. return Math.pow(10, quantityExponent(val));
  17057. }
  17058. /**
  17059. * Exponent of the quantity of a number
  17060. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  17061. *
  17062. * @param {number} val non-negative value
  17063. * @return {number}
  17064. */
  17065. function quantityExponent(val) {
  17066. if (val === 0) {
  17067. return 0;
  17068. }
  17069. var exp = Math.floor(Math.log(val) / Math.LN10);
  17070. /**
  17071. * exp is expected to be the rounded-down result of the base-10 log of val.
  17072. * But due to the precision loss with Math.log(val), we need to restore it
  17073. * using 10^exp to make sure we can get val back from exp. #11249
  17074. */
  17075. if (val / Math.pow(10, exp) >= 10) {
  17076. exp++;
  17077. }
  17078. return exp;
  17079. }
  17080. /**
  17081. * find a “nice” number approximately equal to x. Round the number if round = true,
  17082. * take ceiling if round = false. The primary observation is that the “nicest”
  17083. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  17084. *
  17085. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  17086. *
  17087. * @param {number} val Non-negative value.
  17088. * @param {boolean} round
  17089. * @return {number}
  17090. */
  17091. function nice(val, round) {
  17092. var exponent = quantityExponent(val);
  17093. var exp10 = Math.pow(10, exponent);
  17094. var f = val / exp10; // 1 <= f < 10
  17095. var nf;
  17096. if (round) {
  17097. if (f < 1.5) {
  17098. nf = 1;
  17099. }
  17100. else if (f < 2.5) {
  17101. nf = 2;
  17102. }
  17103. else if (f < 4) {
  17104. nf = 3;
  17105. }
  17106. else if (f < 7) {
  17107. nf = 5;
  17108. }
  17109. else {
  17110. nf = 10;
  17111. }
  17112. }
  17113. else {
  17114. if (f < 1) {
  17115. nf = 1;
  17116. }
  17117. else if (f < 2) {
  17118. nf = 2;
  17119. }
  17120. else if (f < 3) {
  17121. nf = 3;
  17122. }
  17123. else if (f < 5) {
  17124. nf = 5;
  17125. }
  17126. else {
  17127. nf = 10;
  17128. }
  17129. }
  17130. val = nf * exp10;
  17131. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  17132. // 20 is the uppper bound of toFixed.
  17133. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  17134. }
  17135. /**
  17136. * This code was copied from "d3.js"
  17137. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  17138. * See the license statement at the head of this file.
  17139. * @param {Array.<number>} ascArr
  17140. */
  17141. function quantile(ascArr, p) {
  17142. var H = (ascArr.length - 1) * p + 1;
  17143. var h = Math.floor(H);
  17144. var v = +ascArr[h - 1];
  17145. var e = H - h;
  17146. return e ? v + e * (ascArr[h] - v) : v;
  17147. }
  17148. /**
  17149. * Order intervals asc, and split them when overlap.
  17150. * expect(numberUtil.reformIntervals([
  17151. * {interval: [18, 62], close: [1, 1]},
  17152. * {interval: [-Infinity, -70], close: [0, 0]},
  17153. * {interval: [-70, -26], close: [1, 1]},
  17154. * {interval: [-26, 18], close: [1, 1]},
  17155. * {interval: [62, 150], close: [1, 1]},
  17156. * {interval: [106, 150], close: [1, 1]},
  17157. * {interval: [150, Infinity], close: [0, 0]}
  17158. * ])).toEqual([
  17159. * {interval: [-Infinity, -70], close: [0, 0]},
  17160. * {interval: [-70, -26], close: [1, 1]},
  17161. * {interval: [-26, 18], close: [0, 1]},
  17162. * {interval: [18, 62], close: [0, 1]},
  17163. * {interval: [62, 150], close: [0, 1]},
  17164. * {interval: [150, Infinity], close: [0, 0]}
  17165. * ]);
  17166. * @param {Array.<Object>} list, where `close` mean open or close
  17167. * of the interval, and Infinity can be used.
  17168. * @return {Array.<Object>} The origin list, which has been reformed.
  17169. */
  17170. function reformIntervals(list) {
  17171. list.sort(function (a, b) {
  17172. return littleThan(a, b, 0) ? -1 : 1;
  17173. });
  17174. var curr = -Infinity;
  17175. var currClose = 1;
  17176. for (var i = 0; i < list.length;) {
  17177. var interval = list[i].interval;
  17178. var close = list[i].close;
  17179. for (var lg = 0; lg < 2; lg++) {
  17180. if (interval[lg] <= curr) {
  17181. interval[lg] = curr;
  17182. close[lg] = !lg ? 1 - currClose : 1;
  17183. }
  17184. curr = interval[lg];
  17185. currClose = close[lg];
  17186. }
  17187. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  17188. list.splice(i, 1);
  17189. }
  17190. else {
  17191. i++;
  17192. }
  17193. }
  17194. return list;
  17195. function littleThan(a, b, lg) {
  17196. return a.interval[lg] < b.interval[lg]
  17197. || (
  17198. a.interval[lg] === b.interval[lg]
  17199. && (
  17200. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  17201. || (!lg && littleThan(a, b, 1))
  17202. )
  17203. );
  17204. }
  17205. }
  17206. /**
  17207. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  17208. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  17209. * subtraction forces infinities to NaN
  17210. *
  17211. * @param {*} v
  17212. * @return {boolean}
  17213. */
  17214. function isNumeric(v) {
  17215. return v - parseFloat(v) >= 0;
  17216. }
  17217. var number = (Object.freeze || Object)({
  17218. linearMap: linearMap,
  17219. parsePercent: parsePercent$1,
  17220. round: round$1,
  17221. asc: asc,
  17222. getPrecision: getPrecision,
  17223. getPrecisionSafe: getPrecisionSafe,
  17224. getPixelPrecision: getPixelPrecision,
  17225. getPercentWithPrecision: getPercentWithPrecision,
  17226. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  17227. remRadian: remRadian,
  17228. isRadianAroundZero: isRadianAroundZero,
  17229. parseDate: parseDate,
  17230. quantity: quantity,
  17231. quantityExponent: quantityExponent,
  17232. nice: nice,
  17233. quantile: quantile,
  17234. reformIntervals: reformIntervals,
  17235. isNumeric: isNumeric
  17236. });
  17237. /*
  17238. * Licensed to the Apache Software Foundation (ASF) under one
  17239. * or more contributor license agreements. See the NOTICE file
  17240. * distributed with this work for additional information
  17241. * regarding copyright ownership. The ASF licenses this file
  17242. * to you under the Apache License, Version 2.0 (the
  17243. * "License"); you may not use this file except in compliance
  17244. * with the License. You may obtain a copy of the License at
  17245. *
  17246. * http://www.apache.org/licenses/LICENSE-2.0
  17247. *
  17248. * Unless required by applicable law or agreed to in writing,
  17249. * software distributed under the License is distributed on an
  17250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17251. * KIND, either express or implied. See the License for the
  17252. * specific language governing permissions and limitations
  17253. * under the License.
  17254. */
  17255. // import Text from 'zrender/src/graphic/Text';
  17256. /**
  17257. * add commas after every three numbers
  17258. * @param {string|number} x
  17259. * @return {string}
  17260. */
  17261. function addCommas(x) {
  17262. if (isNaN(x)) {
  17263. return '-';
  17264. }
  17265. x = (x + '').split('.');
  17266. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  17267. + (x.length > 1 ? ('.' + x[1]) : '');
  17268. }
  17269. /**
  17270. * @param {string} str
  17271. * @param {boolean} [upperCaseFirst=false]
  17272. * @return {string} str
  17273. */
  17274. function toCamelCase(str, upperCaseFirst) {
  17275. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  17276. return group1.toUpperCase();
  17277. });
  17278. if (upperCaseFirst && str) {
  17279. str = str.charAt(0).toUpperCase() + str.slice(1);
  17280. }
  17281. return str;
  17282. }
  17283. var normalizeCssArray$1 = normalizeCssArray;
  17284. var replaceReg = /([&<>"'])/g;
  17285. var replaceMap = {
  17286. '&': '&amp;',
  17287. '<': '&lt;',
  17288. '>': '&gt;',
  17289. '"': '&quot;',
  17290. '\'': '&#39;'
  17291. };
  17292. function encodeHTML(source) {
  17293. return source == null
  17294. ? ''
  17295. : (source + '').replace(replaceReg, function (str, c) {
  17296. return replaceMap[c];
  17297. });
  17298. }
  17299. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  17300. var wrapVar = function (varName, seriesIdx) {
  17301. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  17302. };
  17303. /**
  17304. * Template formatter
  17305. * @param {string} tpl
  17306. * @param {Array.<Object>|Object} paramsList
  17307. * @param {boolean} [encode=false]
  17308. * @return {string}
  17309. */
  17310. function formatTpl(tpl, paramsList, encode) {
  17311. if (!isArray(paramsList)) {
  17312. paramsList = [paramsList];
  17313. }
  17314. var seriesLen = paramsList.length;
  17315. if (!seriesLen) {
  17316. return '';
  17317. }
  17318. var $vars = paramsList[0].$vars || [];
  17319. for (var i = 0; i < $vars.length; i++) {
  17320. var alias = TPL_VAR_ALIAS[i];
  17321. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  17322. }
  17323. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  17324. for (var k = 0; k < $vars.length; k++) {
  17325. var val = paramsList[seriesIdx][$vars[k]];
  17326. tpl = tpl.replace(
  17327. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  17328. encode ? encodeHTML(val) : val
  17329. );
  17330. }
  17331. }
  17332. return tpl;
  17333. }
  17334. /**
  17335. * simple Template formatter
  17336. *
  17337. * @param {string} tpl
  17338. * @param {Object} param
  17339. * @param {boolean} [encode=false]
  17340. * @return {string}
  17341. */
  17342. function formatTplSimple(tpl, param, encode) {
  17343. each$1(param, function (value, key) {
  17344. tpl = tpl.replace(
  17345. '{' + key + '}',
  17346. encode ? encodeHTML(value) : value
  17347. );
  17348. });
  17349. return tpl;
  17350. }
  17351. /**
  17352. * @param {Object|string} [opt] If string, means color.
  17353. * @param {string} [opt.color]
  17354. * @param {string} [opt.extraCssText]
  17355. * @param {string} [opt.type='item'] 'item' or 'subItem'
  17356. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  17357. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  17358. * @return {string}
  17359. */
  17360. function getTooltipMarker(opt, extraCssText) {
  17361. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  17362. var color = opt.color;
  17363. var type = opt.type;
  17364. var extraCssText = opt.extraCssText;
  17365. var renderMode = opt.renderMode || 'html';
  17366. var markerId = opt.markerId || 'X';
  17367. if (!color) {
  17368. return '';
  17369. }
  17370. if (renderMode === 'html') {
  17371. return type === 'subItem'
  17372. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  17373. + 'border-radius:4px;width:4px;height:4px;background-color:'
  17374. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  17375. : '<span style="display:inline-block;margin-right:5px;'
  17376. + 'border-radius:10px;width:10px;height:10px;background-color:'
  17377. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  17378. }
  17379. else {
  17380. // Space for rich element marker
  17381. return {
  17382. renderMode: renderMode,
  17383. content: '{marker' + markerId + '|} ',
  17384. style: {
  17385. color: color
  17386. }
  17387. };
  17388. }
  17389. }
  17390. function pad(str, len) {
  17391. str += '';
  17392. return '0000'.substr(0, len - str.length) + str;
  17393. }
  17394. /**
  17395. * ISO Date format
  17396. * @param {string} tpl
  17397. * @param {number} value
  17398. * @param {boolean} [isUTC=false] Default in local time.
  17399. * see `module:echarts/scale/Time`
  17400. * and `module:echarts/util/number#parseDate`.
  17401. * @inner
  17402. */
  17403. function formatTime(tpl, value, isUTC) {
  17404. if (tpl === 'week'
  17405. || tpl === 'month'
  17406. || tpl === 'quarter'
  17407. || tpl === 'half-year'
  17408. || tpl === 'year'
  17409. ) {
  17410. tpl = 'MM-dd\nyyyy';
  17411. }
  17412. var date = parseDate(value);
  17413. var utc = isUTC ? 'UTC' : '';
  17414. var y = date['get' + utc + 'FullYear']();
  17415. var M = date['get' + utc + 'Month']() + 1;
  17416. var d = date['get' + utc + 'Date']();
  17417. var h = date['get' + utc + 'Hours']();
  17418. var m = date['get' + utc + 'Minutes']();
  17419. var s = date['get' + utc + 'Seconds']();
  17420. var S = date['get' + utc + 'Milliseconds']();
  17421. tpl = tpl.replace('MM', pad(M, 2))
  17422. .replace('M', M)
  17423. .replace('yyyy', y)
  17424. .replace('yy', y % 100)
  17425. .replace('dd', pad(d, 2))
  17426. .replace('d', d)
  17427. .replace('hh', pad(h, 2))
  17428. .replace('h', h)
  17429. .replace('mm', pad(m, 2))
  17430. .replace('m', m)
  17431. .replace('ss', pad(s, 2))
  17432. .replace('s', s)
  17433. .replace('SSS', pad(S, 3));
  17434. return tpl;
  17435. }
  17436. /**
  17437. * Capital first
  17438. * @param {string} str
  17439. * @return {string}
  17440. */
  17441. function capitalFirst(str) {
  17442. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  17443. }
  17444. var truncateText$1 = truncateText;
  17445. /**
  17446. * @public
  17447. * @param {Object} opt
  17448. * @param {string} opt.text
  17449. * @param {string} opt.font
  17450. * @param {string} [opt.textAlign='left']
  17451. * @param {string} [opt.textVerticalAlign='top']
  17452. * @param {Array.<number>} [opt.textPadding]
  17453. * @param {number} [opt.textLineHeight]
  17454. * @param {Object} [opt.rich]
  17455. * @param {Object} [opt.truncate]
  17456. * @return {Object} {x, y, width, height, lineHeight}
  17457. */
  17458. function getTextBoundingRect(opt) {
  17459. return getBoundingRect(
  17460. opt.text,
  17461. opt.font,
  17462. opt.textAlign,
  17463. opt.textVerticalAlign,
  17464. opt.textPadding,
  17465. opt.textLineHeight,
  17466. opt.rich,
  17467. opt.truncate
  17468. );
  17469. }
  17470. /**
  17471. * @deprecated
  17472. * the `textLineHeight` was added later.
  17473. * For backward compatiblility, put it as the last parameter.
  17474. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  17475. */
  17476. function getTextRect(
  17477. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  17478. ) {
  17479. return getBoundingRect(
  17480. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  17481. );
  17482. }
  17483. /**
  17484. * open new tab
  17485. * @param {string} link url
  17486. * @param {string} target blank or self
  17487. */
  17488. function windowOpen(link, target) {
  17489. if (target === '_blank' || target === 'blank') {
  17490. var blank = window.open();
  17491. blank.opener = null;
  17492. blank.location = link;
  17493. }
  17494. else {
  17495. window.open(link, target);
  17496. }
  17497. }
  17498. var format = (Object.freeze || Object)({
  17499. addCommas: addCommas,
  17500. toCamelCase: toCamelCase,
  17501. normalizeCssArray: normalizeCssArray$1,
  17502. encodeHTML: encodeHTML,
  17503. formatTpl: formatTpl,
  17504. formatTplSimple: formatTplSimple,
  17505. getTooltipMarker: getTooltipMarker,
  17506. formatTime: formatTime,
  17507. capitalFirst: capitalFirst,
  17508. truncateText: truncateText$1,
  17509. getTextBoundingRect: getTextBoundingRect,
  17510. getTextRect: getTextRect,
  17511. windowOpen: windowOpen
  17512. });
  17513. /*
  17514. * Licensed to the Apache Software Foundation (ASF) under one
  17515. * or more contributor license agreements. See the NOTICE file
  17516. * distributed with this work for additional information
  17517. * regarding copyright ownership. The ASF licenses this file
  17518. * to you under the Apache License, Version 2.0 (the
  17519. * "License"); you may not use this file except in compliance
  17520. * with the License. You may obtain a copy of the License at
  17521. *
  17522. * http://www.apache.org/licenses/LICENSE-2.0
  17523. *
  17524. * Unless required by applicable law or agreed to in writing,
  17525. * software distributed under the License is distributed on an
  17526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17527. * KIND, either express or implied. See the License for the
  17528. * specific language governing permissions and limitations
  17529. * under the License.
  17530. */
  17531. // Layout helpers for each component positioning
  17532. var each$3 = each$1;
  17533. /**
  17534. * @public
  17535. */
  17536. var LOCATION_PARAMS = [
  17537. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17538. ];
  17539. /**
  17540. * @public
  17541. */
  17542. var HV_NAMES = [
  17543. ['width', 'left', 'right'],
  17544. ['height', 'top', 'bottom']
  17545. ];
  17546. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17547. var x = 0;
  17548. var y = 0;
  17549. if (maxWidth == null) {
  17550. maxWidth = Infinity;
  17551. }
  17552. if (maxHeight == null) {
  17553. maxHeight = Infinity;
  17554. }
  17555. var currentLineMaxSize = 0;
  17556. group.eachChild(function (child, idx) {
  17557. var position = child.position;
  17558. var rect = child.getBoundingRect();
  17559. var nextChild = group.childAt(idx + 1);
  17560. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17561. var nextX;
  17562. var nextY;
  17563. if (orient === 'horizontal') {
  17564. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17565. nextX = x + moveX;
  17566. // Wrap when width exceeds maxWidth or meet a `newline` group
  17567. // FIXME compare before adding gap?
  17568. if (nextX > maxWidth || child.newline) {
  17569. x = 0;
  17570. nextX = moveX;
  17571. y += currentLineMaxSize + gap;
  17572. currentLineMaxSize = rect.height;
  17573. }
  17574. else {
  17575. // FIXME: consider rect.y is not `0`?
  17576. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17577. }
  17578. }
  17579. else {
  17580. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17581. nextY = y + moveY;
  17582. // Wrap when width exceeds maxHeight or meet a `newline` group
  17583. if (nextY > maxHeight || child.newline) {
  17584. x += currentLineMaxSize + gap;
  17585. y = 0;
  17586. nextY = moveY;
  17587. currentLineMaxSize = rect.width;
  17588. }
  17589. else {
  17590. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17591. }
  17592. }
  17593. if (child.newline) {
  17594. return;
  17595. }
  17596. position[0] = x;
  17597. position[1] = y;
  17598. orient === 'horizontal'
  17599. ? (x = nextX + gap)
  17600. : (y = nextY + gap);
  17601. });
  17602. }
  17603. /**
  17604. * VBox or HBox layouting
  17605. * @param {string} orient
  17606. * @param {module:zrender/container/Group} group
  17607. * @param {number} gap
  17608. * @param {number} [width=Infinity]
  17609. * @param {number} [height=Infinity]
  17610. */
  17611. var box = boxLayout;
  17612. /**
  17613. * VBox layouting
  17614. * @param {module:zrender/container/Group} group
  17615. * @param {number} gap
  17616. * @param {number} [width=Infinity]
  17617. * @param {number} [height=Infinity]
  17618. */
  17619. var vbox = curry(boxLayout, 'vertical');
  17620. /**
  17621. * HBox layouting
  17622. * @param {module:zrender/container/Group} group
  17623. * @param {number} gap
  17624. * @param {number} [width=Infinity]
  17625. * @param {number} [height=Infinity]
  17626. */
  17627. var hbox = curry(boxLayout, 'horizontal');
  17628. /**
  17629. * If x or x2 is not specified or 'center' 'left' 'right',
  17630. * the width would be as long as possible.
  17631. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17632. * the height would be as long as possible.
  17633. *
  17634. * @param {Object} positionInfo
  17635. * @param {number|string} [positionInfo.x]
  17636. * @param {number|string} [positionInfo.y]
  17637. * @param {number|string} [positionInfo.x2]
  17638. * @param {number|string} [positionInfo.y2]
  17639. * @param {Object} containerRect {width, height}
  17640. * @param {string|number} margin
  17641. * @return {Object} {width, height}
  17642. */
  17643. /**
  17644. * Parse position info.
  17645. *
  17646. * @param {Object} positionInfo
  17647. * @param {number|string} [positionInfo.left]
  17648. * @param {number|string} [positionInfo.top]
  17649. * @param {number|string} [positionInfo.right]
  17650. * @param {number|string} [positionInfo.bottom]
  17651. * @param {number|string} [positionInfo.width]
  17652. * @param {number|string} [positionInfo.height]
  17653. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17654. * @param {Object} containerRect
  17655. * @param {string|number} [margin]
  17656. *
  17657. * @return {module:zrender/core/BoundingRect}
  17658. */
  17659. function getLayoutRect(
  17660. positionInfo, containerRect, margin
  17661. ) {
  17662. margin = normalizeCssArray$1(margin || 0);
  17663. var containerWidth = containerRect.width;
  17664. var containerHeight = containerRect.height;
  17665. var left = parsePercent$1(positionInfo.left, containerWidth);
  17666. var top = parsePercent$1(positionInfo.top, containerHeight);
  17667. var right = parsePercent$1(positionInfo.right, containerWidth);
  17668. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17669. var width = parsePercent$1(positionInfo.width, containerWidth);
  17670. var height = parsePercent$1(positionInfo.height, containerHeight);
  17671. var verticalMargin = margin[2] + margin[0];
  17672. var horizontalMargin = margin[1] + margin[3];
  17673. var aspect = positionInfo.aspect;
  17674. // If width is not specified, calculate width from left and right
  17675. if (isNaN(width)) {
  17676. width = containerWidth - right - horizontalMargin - left;
  17677. }
  17678. if (isNaN(height)) {
  17679. height = containerHeight - bottom - verticalMargin - top;
  17680. }
  17681. if (aspect != null) {
  17682. // If width and height are not given
  17683. // 1. Graph should not exceeds the container
  17684. // 2. Aspect must be keeped
  17685. // 3. Graph should take the space as more as possible
  17686. // FIXME
  17687. // Margin is not considered, because there is no case that both
  17688. // using margin and aspect so far.
  17689. if (isNaN(width) && isNaN(height)) {
  17690. if (aspect > containerWidth / containerHeight) {
  17691. width = containerWidth * 0.8;
  17692. }
  17693. else {
  17694. height = containerHeight * 0.8;
  17695. }
  17696. }
  17697. // Calculate width or height with given aspect
  17698. if (isNaN(width)) {
  17699. width = aspect * height;
  17700. }
  17701. if (isNaN(height)) {
  17702. height = width / aspect;
  17703. }
  17704. }
  17705. // If left is not specified, calculate left from right and width
  17706. if (isNaN(left)) {
  17707. left = containerWidth - right - width - horizontalMargin;
  17708. }
  17709. if (isNaN(top)) {
  17710. top = containerHeight - bottom - height - verticalMargin;
  17711. }
  17712. // Align left and top
  17713. switch (positionInfo.left || positionInfo.right) {
  17714. case 'center':
  17715. left = containerWidth / 2 - width / 2 - margin[3];
  17716. break;
  17717. case 'right':
  17718. left = containerWidth - width - horizontalMargin;
  17719. break;
  17720. }
  17721. switch (positionInfo.top || positionInfo.bottom) {
  17722. case 'middle':
  17723. case 'center':
  17724. top = containerHeight / 2 - height / 2 - margin[0];
  17725. break;
  17726. case 'bottom':
  17727. top = containerHeight - height - verticalMargin;
  17728. break;
  17729. }
  17730. // If something is wrong and left, top, width, height are calculated as NaN
  17731. left = left || 0;
  17732. top = top || 0;
  17733. if (isNaN(width)) {
  17734. // Width may be NaN if only one value is given except width
  17735. width = containerWidth - horizontalMargin - left - (right || 0);
  17736. }
  17737. if (isNaN(height)) {
  17738. // Height may be NaN if only one value is given except height
  17739. height = containerHeight - verticalMargin - top - (bottom || 0);
  17740. }
  17741. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17742. rect.margin = margin;
  17743. return rect;
  17744. }
  17745. /**
  17746. * Position a zr element in viewport
  17747. * Group position is specified by either
  17748. * {left, top}, {right, bottom}
  17749. * If all properties exists, right and bottom will be igonred.
  17750. *
  17751. * Logic:
  17752. * 1. Scale (against origin point in parent coord)
  17753. * 2. Rotate (against origin point in parent coord)
  17754. * 3. Traslate (with el.position by this method)
  17755. * So this method only fixes the last step 'Traslate', which does not affect
  17756. * scaling and rotating.
  17757. *
  17758. * If be called repeatly with the same input el, the same result will be gotten.
  17759. *
  17760. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17761. * @param {Object} positionInfo
  17762. * @param {number|string} [positionInfo.left]
  17763. * @param {number|string} [positionInfo.top]
  17764. * @param {number|string} [positionInfo.right]
  17765. * @param {number|string} [positionInfo.bottom]
  17766. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17767. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17768. * @param {Object} containerRect
  17769. * @param {string|number} margin
  17770. * @param {Object} [opt]
  17771. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17772. * @param {Array.<number>} [opt.boundingMode='all']
  17773. * Specify how to calculate boundingRect when locating.
  17774. * 'all': Position the boundingRect that is transformed and uioned
  17775. * both itself and its descendants.
  17776. * This mode simplies confine the elements in the bounding
  17777. * of their container (e.g., using 'right: 0').
  17778. * 'raw': Position the boundingRect that is not transformed and only itself.
  17779. * This mode is useful when you want a element can overflow its
  17780. * container. (Consider a rotated circle needs to be located in a corner.)
  17781. * In this mode positionInfo.width/height can only be number.
  17782. */
  17783. function positionElement(el, positionInfo, containerRect, margin, opt) {
  17784. var h = !opt || !opt.hv || opt.hv[0];
  17785. var v = !opt || !opt.hv || opt.hv[1];
  17786. var boundingMode = opt && opt.boundingMode || 'all';
  17787. if (!h && !v) {
  17788. return;
  17789. }
  17790. var rect;
  17791. if (boundingMode === 'raw') {
  17792. rect = el.type === 'group'
  17793. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  17794. : el.getBoundingRect();
  17795. }
  17796. else {
  17797. rect = el.getBoundingRect();
  17798. if (el.needLocalTransform()) {
  17799. var transform = el.getLocalTransform();
  17800. // Notice: raw rect may be inner object of el,
  17801. // which should not be modified.
  17802. rect = rect.clone();
  17803. rect.applyTransform(transform);
  17804. }
  17805. }
  17806. // The real width and height can not be specified but calculated by the given el.
  17807. positionInfo = getLayoutRect(
  17808. defaults(
  17809. {width: rect.width, height: rect.height},
  17810. positionInfo
  17811. ),
  17812. containerRect,
  17813. margin
  17814. );
  17815. // Because 'tranlate' is the last step in transform
  17816. // (see zrender/core/Transformable#getLocalTransform),
  17817. // we can just only modify el.position to get final result.
  17818. var elPos = el.position;
  17819. var dx = h ? positionInfo.x - rect.x : 0;
  17820. var dy = v ? positionInfo.y - rect.y : 0;
  17821. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  17822. }
  17823. /**
  17824. * @param {Object} option Contains some of the properties in HV_NAMES.
  17825. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17826. */
  17827. /**
  17828. * Consider Case:
  17829. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17830. * through setOption or media query, using normal zrUtil.merge will cause
  17831. * {right: 0} does not take effect.
  17832. *
  17833. * @example
  17834. * ComponentModel.extend({
  17835. * init: function () {
  17836. * ...
  17837. * var inputPositionParams = layout.getLayoutParams(option);
  17838. * this.mergeOption(inputPositionParams);
  17839. * },
  17840. * mergeOption: function (newOption) {
  17841. * newOption && zrUtil.merge(thisOption, newOption, true);
  17842. * layout.mergeLayoutParam(thisOption, newOption);
  17843. * }
  17844. * });
  17845. *
  17846. * @param {Object} targetOption
  17847. * @param {Object} newOption
  17848. * @param {Object|string} [opt]
  17849. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17850. * that width (or height) should not be calculated by left and right (or top and bottom).
  17851. */
  17852. function mergeLayoutParam(targetOption, newOption, opt) {
  17853. !isObject$1(opt) && (opt = {});
  17854. var ignoreSize = opt.ignoreSize;
  17855. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17856. var hResult = merge$$1(HV_NAMES[0], 0);
  17857. var vResult = merge$$1(HV_NAMES[1], 1);
  17858. copy(HV_NAMES[0], targetOption, hResult);
  17859. copy(HV_NAMES[1], targetOption, vResult);
  17860. function merge$$1(names, hvIdx) {
  17861. var newParams = {};
  17862. var newValueCount = 0;
  17863. var merged = {};
  17864. var mergedValueCount = 0;
  17865. var enoughParamNumber = 2;
  17866. each$3(names, function (name) {
  17867. merged[name] = targetOption[name];
  17868. });
  17869. each$3(names, function (name) {
  17870. // Consider case: newOption.width is null, which is
  17871. // set by user for removing width setting.
  17872. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17873. hasValue(newParams, name) && newValueCount++;
  17874. hasValue(merged, name) && mergedValueCount++;
  17875. });
  17876. if (ignoreSize[hvIdx]) {
  17877. // Only one of left/right is premitted to exist.
  17878. if (hasValue(newOption, names[1])) {
  17879. merged[names[2]] = null;
  17880. }
  17881. else if (hasValue(newOption, names[2])) {
  17882. merged[names[1]] = null;
  17883. }
  17884. return merged;
  17885. }
  17886. // Case: newOption: {width: ..., right: ...},
  17887. // or targetOption: {right: ...} and newOption: {width: ...},
  17888. // There is no conflict when merged only has params count
  17889. // little than enoughParamNumber.
  17890. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17891. return merged;
  17892. }
  17893. // Case: newOption: {width: ..., right: ...},
  17894. // Than we can make sure user only want those two, and ignore
  17895. // all origin params in targetOption.
  17896. else if (newValueCount >= enoughParamNumber) {
  17897. return newParams;
  17898. }
  17899. else {
  17900. // Chose another param from targetOption by priority.
  17901. for (var i = 0; i < names.length; i++) {
  17902. var name = names[i];
  17903. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17904. newParams[name] = targetOption[name];
  17905. break;
  17906. }
  17907. }
  17908. return newParams;
  17909. }
  17910. }
  17911. function hasProp(obj, name) {
  17912. return obj.hasOwnProperty(name);
  17913. }
  17914. function hasValue(obj, name) {
  17915. return obj[name] != null && obj[name] !== 'auto';
  17916. }
  17917. function copy(names, target, source) {
  17918. each$3(names, function (name) {
  17919. target[name] = source[name];
  17920. });
  17921. }
  17922. }
  17923. /**
  17924. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17925. * @param {Object} source
  17926. * @return {Object} Result contains those props.
  17927. */
  17928. function getLayoutParams(source) {
  17929. return copyLayoutParams({}, source);
  17930. }
  17931. /**
  17932. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17933. * @param {Object} source
  17934. * @return {Object} Result contains those props.
  17935. */
  17936. function copyLayoutParams(target, source) {
  17937. source && target && each$3(LOCATION_PARAMS, function (name) {
  17938. source.hasOwnProperty(name) && (target[name] = source[name]);
  17939. });
  17940. return target;
  17941. }
  17942. /*
  17943. * Licensed to the Apache Software Foundation (ASF) under one
  17944. * or more contributor license agreements. See the NOTICE file
  17945. * distributed with this work for additional information
  17946. * regarding copyright ownership. The ASF licenses this file
  17947. * to you under the Apache License, Version 2.0 (the
  17948. * "License"); you may not use this file except in compliance
  17949. * with the License. You may obtain a copy of the License at
  17950. *
  17951. * http://www.apache.org/licenses/LICENSE-2.0
  17952. *
  17953. * Unless required by applicable law or agreed to in writing,
  17954. * software distributed under the License is distributed on an
  17955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17956. * KIND, either express or implied. See the License for the
  17957. * specific language governing permissions and limitations
  17958. * under the License.
  17959. */
  17960. var boxLayoutMixin = {
  17961. getBoxLayoutParams: function () {
  17962. return {
  17963. left: this.get('left'),
  17964. top: this.get('top'),
  17965. right: this.get('right'),
  17966. bottom: this.get('bottom'),
  17967. width: this.get('width'),
  17968. height: this.get('height')
  17969. };
  17970. }
  17971. };
  17972. /*
  17973. * Licensed to the Apache Software Foundation (ASF) under one
  17974. * or more contributor license agreements. See the NOTICE file
  17975. * distributed with this work for additional information
  17976. * regarding copyright ownership. The ASF licenses this file
  17977. * to you under the Apache License, Version 2.0 (the
  17978. * "License"); you may not use this file except in compliance
  17979. * with the License. You may obtain a copy of the License at
  17980. *
  17981. * http://www.apache.org/licenses/LICENSE-2.0
  17982. *
  17983. * Unless required by applicable law or agreed to in writing,
  17984. * software distributed under the License is distributed on an
  17985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17986. * KIND, either express or implied. See the License for the
  17987. * specific language governing permissions and limitations
  17988. * under the License.
  17989. */
  17990. /**
  17991. * Component model
  17992. *
  17993. * @module echarts/model/Component
  17994. */
  17995. var inner$1 = makeInner();
  17996. /**
  17997. * @alias module:echarts/model/Component
  17998. * @constructor
  17999. * @param {Object} option
  18000. * @param {module:echarts/model/Model} parentModel
  18001. * @param {module:echarts/model/Model} ecModel
  18002. */
  18003. var ComponentModel = Model.extend({
  18004. type: 'component',
  18005. /**
  18006. * @readOnly
  18007. * @type {string}
  18008. */
  18009. id: '',
  18010. /**
  18011. * Because simplified concept is probably better, series.name (or component.name)
  18012. * has been having too many resposibilities:
  18013. * (1) Generating id (which requires name in option should not be modified).
  18014. * (2) As an index to mapping series when merging option or calling API (a name
  18015. * can refer to more then one components, which is convinient is some case).
  18016. * (3) Display.
  18017. * @readOnly
  18018. */
  18019. name: '',
  18020. /**
  18021. * @readOnly
  18022. * @type {string}
  18023. */
  18024. mainType: '',
  18025. /**
  18026. * @readOnly
  18027. * @type {string}
  18028. */
  18029. subType: '',
  18030. /**
  18031. * @readOnly
  18032. * @type {number}
  18033. */
  18034. componentIndex: 0,
  18035. /**
  18036. * @type {Object}
  18037. * @protected
  18038. */
  18039. defaultOption: null,
  18040. /**
  18041. * @type {module:echarts/model/Global}
  18042. * @readOnly
  18043. */
  18044. ecModel: null,
  18045. /**
  18046. * key: componentType
  18047. * value: Component model list, can not be null.
  18048. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18049. * @readOnly
  18050. */
  18051. dependentModels: [],
  18052. /**
  18053. * @type {string}
  18054. * @readOnly
  18055. */
  18056. uid: null,
  18057. /**
  18058. * Support merge layout params.
  18059. * Only support 'box' now (left/right/top/bottom/width/height).
  18060. * @type {string|Object} Object can be {ignoreSize: true}
  18061. * @readOnly
  18062. */
  18063. layoutMode: null,
  18064. $constructor: function (option, parentModel, ecModel, extraOpt) {
  18065. Model.call(this, option, parentModel, ecModel, extraOpt);
  18066. this.uid = getUID('ec_cpt_model');
  18067. },
  18068. init: function (option, parentModel, ecModel, extraOpt) {
  18069. this.mergeDefaultAndTheme(option, ecModel);
  18070. },
  18071. mergeDefaultAndTheme: function (option, ecModel) {
  18072. var layoutMode = this.layoutMode;
  18073. var inputPositionParams = layoutMode
  18074. ? getLayoutParams(option) : {};
  18075. var themeModel = ecModel.getTheme();
  18076. merge(option, themeModel.get(this.mainType));
  18077. merge(option, this.getDefaultOption());
  18078. if (layoutMode) {
  18079. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18080. }
  18081. },
  18082. mergeOption: function (option, extraOpt) {
  18083. merge(this.option, option, true);
  18084. var layoutMode = this.layoutMode;
  18085. if (layoutMode) {
  18086. mergeLayoutParam(this.option, option, layoutMode);
  18087. }
  18088. },
  18089. // Hooker after init or mergeOption
  18090. optionUpdated: function (newCptOption, isInit) {},
  18091. getDefaultOption: function () {
  18092. var fields = inner$1(this);
  18093. if (!fields.defaultOption) {
  18094. var optList = [];
  18095. var Class = this.constructor;
  18096. while (Class) {
  18097. var opt = Class.prototype.defaultOption;
  18098. opt && optList.push(opt);
  18099. Class = Class.superClass;
  18100. }
  18101. var defaultOption = {};
  18102. for (var i = optList.length - 1; i >= 0; i--) {
  18103. defaultOption = merge(defaultOption, optList[i], true);
  18104. }
  18105. fields.defaultOption = defaultOption;
  18106. }
  18107. return fields.defaultOption;
  18108. },
  18109. getReferringComponents: function (mainType) {
  18110. return this.ecModel.queryComponents({
  18111. mainType: mainType,
  18112. index: this.get(mainType + 'Index', true),
  18113. id: this.get(mainType + 'Id', true)
  18114. });
  18115. }
  18116. });
  18117. // Reset ComponentModel.extend, add preConstruct.
  18118. // clazzUtil.enableClassExtend(
  18119. // ComponentModel,
  18120. // function (option, parentModel, ecModel, extraOpt) {
  18121. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  18122. // zrUtil.extend(this, extraOpt);
  18123. // this.uid = componentUtil.getUID('componentModel');
  18124. // // this.setReadOnly([
  18125. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  18126. // // 'dependentModels', 'componentIndex'
  18127. // // ]);
  18128. // }
  18129. // );
  18130. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18131. enableClassManagement(
  18132. ComponentModel, {registerWhenExtend: true}
  18133. );
  18134. enableSubTypeDefaulter(ComponentModel);
  18135. // Add capability of ComponentModel.topologicalTravel.
  18136. enableTopologicalTravel(ComponentModel, getDependencies);
  18137. function getDependencies(componentType) {
  18138. var deps = [];
  18139. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  18140. deps = deps.concat(Clazz.prototype.dependencies || []);
  18141. });
  18142. // Ensure main type.
  18143. deps = map(deps, function (type) {
  18144. return parseClassType$1(type).main;
  18145. });
  18146. // Hack dataset for convenience.
  18147. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  18148. deps.unshift('dataset');
  18149. }
  18150. return deps;
  18151. }
  18152. mixin(ComponentModel, boxLayoutMixin);
  18153. /*
  18154. * Licensed to the Apache Software Foundation (ASF) under one
  18155. * or more contributor license agreements. See the NOTICE file
  18156. * distributed with this work for additional information
  18157. * regarding copyright ownership. The ASF licenses this file
  18158. * to you under the Apache License, Version 2.0 (the
  18159. * "License"); you may not use this file except in compliance
  18160. * with the License. You may obtain a copy of the License at
  18161. *
  18162. * http://www.apache.org/licenses/LICENSE-2.0
  18163. *
  18164. * Unless required by applicable law or agreed to in writing,
  18165. * software distributed under the License is distributed on an
  18166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18167. * KIND, either express or implied. See the License for the
  18168. * specific language governing permissions and limitations
  18169. * under the License.
  18170. */
  18171. var platform = '';
  18172. // Navigator not exists in node
  18173. if (typeof navigator !== 'undefined') {
  18174. platform = navigator.platform || '';
  18175. }
  18176. var globalDefault = {
  18177. // backgroundColor: 'rgba(0,0,0,0)',
  18178. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  18179. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  18180. // Light colors:
  18181. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  18182. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  18183. // Dark colors:
  18184. color: [
  18185. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  18186. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  18187. ],
  18188. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  18189. // If xAxis and yAxis declared, grid is created by default.
  18190. // grid: {},
  18191. textStyle: {
  18192. // color: '#000',
  18193. // decoration: 'none',
  18194. // PENDING
  18195. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  18196. // fontFamily: 'Arial, Verdana, sans-serif',
  18197. fontSize: 12,
  18198. fontStyle: 'normal',
  18199. fontWeight: 'normal'
  18200. },
  18201. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  18202. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  18203. // Default is source-over
  18204. blendMode: null,
  18205. animation: 'auto',
  18206. animationDuration: 1000,
  18207. animationDurationUpdate: 300,
  18208. animationEasing: 'exponentialOut',
  18209. animationEasingUpdate: 'cubicOut',
  18210. animationThreshold: 2000,
  18211. // Configuration for progressive/incremental rendering
  18212. progressiveThreshold: 3000,
  18213. progressive: 400,
  18214. // Threshold of if use single hover layer to optimize.
  18215. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  18216. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  18217. // which is unexpected.
  18218. // see example <echarts/test/heatmap-large.html>.
  18219. hoverLayerThreshold: 3000,
  18220. // See: module:echarts/scale/Time
  18221. useUTC: false
  18222. };
  18223. /*
  18224. * Licensed to the Apache Software Foundation (ASF) under one
  18225. * or more contributor license agreements. See the NOTICE file
  18226. * distributed with this work for additional information
  18227. * regarding copyright ownership. The ASF licenses this file
  18228. * to you under the Apache License, Version 2.0 (the
  18229. * "License"); you may not use this file except in compliance
  18230. * with the License. You may obtain a copy of the License at
  18231. *
  18232. * http://www.apache.org/licenses/LICENSE-2.0
  18233. *
  18234. * Unless required by applicable law or agreed to in writing,
  18235. * software distributed under the License is distributed on an
  18236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18237. * KIND, either express or implied. See the License for the
  18238. * specific language governing permissions and limitations
  18239. * under the License.
  18240. */
  18241. var inner$2 = makeInner();
  18242. function getNearestColorPalette(colors, requestColorNum) {
  18243. var paletteNum = colors.length;
  18244. // TODO colors must be in order
  18245. for (var i = 0; i < paletteNum; i++) {
  18246. if (colors[i].length > requestColorNum) {
  18247. return colors[i];
  18248. }
  18249. }
  18250. return colors[paletteNum - 1];
  18251. }
  18252. var colorPaletteMixin = {
  18253. clearColorPalette: function () {
  18254. inner$2(this).colorIdx = 0;
  18255. inner$2(this).colorNameMap = {};
  18256. },
  18257. /**
  18258. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  18259. * twise with the same parameters will get different result.
  18260. * @param {Object} [scope=this]
  18261. * @param {Object} [requestColorNum]
  18262. * @return {string} color string.
  18263. */
  18264. getColorFromPalette: function (name, scope, requestColorNum) {
  18265. scope = scope || this;
  18266. var scopeFields = inner$2(scope);
  18267. var colorIdx = scopeFields.colorIdx || 0;
  18268. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  18269. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  18270. if (colorNameMap.hasOwnProperty(name)) {
  18271. return colorNameMap[name];
  18272. }
  18273. var defaultColorPalette = normalizeToArray(this.get('color', true));
  18274. var layeredColorPalette = this.get('colorLayer', true);
  18275. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  18276. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  18277. // In case can't find in layered color palette.
  18278. colorPalette = colorPalette || defaultColorPalette;
  18279. if (!colorPalette || !colorPalette.length) {
  18280. return;
  18281. }
  18282. var color = colorPalette[colorIdx];
  18283. if (name) {
  18284. colorNameMap[name] = color;
  18285. }
  18286. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  18287. return color;
  18288. }
  18289. };
  18290. /*
  18291. * Licensed to the Apache Software Foundation (ASF) under one
  18292. * or more contributor license agreements. See the NOTICE file
  18293. * distributed with this work for additional information
  18294. * regarding copyright ownership. The ASF licenses this file
  18295. * to you under the Apache License, Version 2.0 (the
  18296. * "License"); you may not use this file except in compliance
  18297. * with the License. You may obtain a copy of the License at
  18298. *
  18299. * http://www.apache.org/licenses/LICENSE-2.0
  18300. *
  18301. * Unless required by applicable law or agreed to in writing,
  18302. * software distributed under the License is distributed on an
  18303. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18304. * KIND, either express or implied. See the License for the
  18305. * specific language governing permissions and limitations
  18306. * under the License.
  18307. */
  18308. // Avoid typo.
  18309. var SOURCE_FORMAT_ORIGINAL = 'original';
  18310. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  18311. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  18312. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  18313. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  18314. // ??? CHANGE A NAME
  18315. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  18316. var SERIES_LAYOUT_BY_COLUMN = 'column';
  18317. var SERIES_LAYOUT_BY_ROW = 'row';
  18318. /*
  18319. * Licensed to the Apache Software Foundation (ASF) under one
  18320. * or more contributor license agreements. See the NOTICE file
  18321. * distributed with this work for additional information
  18322. * regarding copyright ownership. The ASF licenses this file
  18323. * to you under the Apache License, Version 2.0 (the
  18324. * "License"); you may not use this file except in compliance
  18325. * with the License. You may obtain a copy of the License at
  18326. *
  18327. * http://www.apache.org/licenses/LICENSE-2.0
  18328. *
  18329. * Unless required by applicable law or agreed to in writing,
  18330. * software distributed under the License is distributed on an
  18331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18332. * KIND, either express or implied. See the License for the
  18333. * specific language governing permissions and limitations
  18334. * under the License.
  18335. */
  18336. /**
  18337. * [sourceFormat]
  18338. *
  18339. * + "original":
  18340. * This format is only used in series.data, where
  18341. * itemStyle can be specified in data item.
  18342. *
  18343. * + "arrayRows":
  18344. * [
  18345. * ['product', 'score', 'amount'],
  18346. * ['Matcha Latte', 89.3, 95.8],
  18347. * ['Milk Tea', 92.1, 89.4],
  18348. * ['Cheese Cocoa', 94.4, 91.2],
  18349. * ['Walnut Brownie', 85.4, 76.9]
  18350. * ]
  18351. *
  18352. * + "objectRows":
  18353. * [
  18354. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  18355. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  18356. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  18357. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  18358. * ]
  18359. *
  18360. * + "keyedColumns":
  18361. * {
  18362. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  18363. * 'count': [823, 235, 1042, 988],
  18364. * 'score': [95.8, 81.4, 91.2, 76.9]
  18365. * }
  18366. *
  18367. * + "typedArray"
  18368. *
  18369. * + "unknown"
  18370. */
  18371. /**
  18372. * @constructor
  18373. * @param {Object} fields
  18374. * @param {string} fields.sourceFormat
  18375. * @param {Array|Object} fields.fromDataset
  18376. * @param {Array|Object} [fields.data]
  18377. * @param {string} [seriesLayoutBy='column']
  18378. * @param {Array.<Object|string>} [dimensionsDefine]
  18379. * @param {Objet|HashMap} [encodeDefine]
  18380. * @param {number} [startIndex=0]
  18381. * @param {number} [dimensionsDetectCount]
  18382. */
  18383. function Source(fields) {
  18384. /**
  18385. * @type {boolean}
  18386. */
  18387. this.fromDataset = fields.fromDataset;
  18388. /**
  18389. * Not null/undefined.
  18390. * @type {Array|Object}
  18391. */
  18392. this.data = fields.data || (
  18393. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  18394. );
  18395. /**
  18396. * See also "detectSourceFormat".
  18397. * Not null/undefined.
  18398. * @type {string}
  18399. */
  18400. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  18401. /**
  18402. * 'row' or 'column'
  18403. * Not null/undefined.
  18404. * @type {string} seriesLayoutBy
  18405. */
  18406. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18407. /**
  18408. * dimensions definition in option.
  18409. * can be null/undefined.
  18410. * @type {Array.<Object|string>}
  18411. */
  18412. this.dimensionsDefine = fields.dimensionsDefine;
  18413. /**
  18414. * encode definition in option.
  18415. * can be null/undefined.
  18416. * @type {Objet|HashMap}
  18417. */
  18418. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  18419. /**
  18420. * Not null/undefined, uint.
  18421. * @type {number}
  18422. */
  18423. this.startIndex = fields.startIndex || 0;
  18424. /**
  18425. * Can be null/undefined (when unknown), uint.
  18426. * @type {number}
  18427. */
  18428. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  18429. }
  18430. /**
  18431. * Wrap original series data for some compatibility cases.
  18432. */
  18433. Source.seriesDataToSource = function (data) {
  18434. return new Source({
  18435. data: data,
  18436. sourceFormat: isTypedArray(data)
  18437. ? SOURCE_FORMAT_TYPED_ARRAY
  18438. : SOURCE_FORMAT_ORIGINAL,
  18439. fromDataset: false
  18440. });
  18441. };
  18442. enableClassCheck(Source);
  18443. /*
  18444. * Licensed to the Apache Software Foundation (ASF) under one
  18445. * or more contributor license agreements. See the NOTICE file
  18446. * distributed with this work for additional information
  18447. * regarding copyright ownership. The ASF licenses this file
  18448. * to you under the Apache License, Version 2.0 (the
  18449. * "License"); you may not use this file except in compliance
  18450. * with the License. You may obtain a copy of the License at
  18451. *
  18452. * http://www.apache.org/licenses/LICENSE-2.0
  18453. *
  18454. * Unless required by applicable law or agreed to in writing,
  18455. * software distributed under the License is distributed on an
  18456. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18457. * KIND, either express or implied. See the License for the
  18458. * specific language governing permissions and limitations
  18459. * under the License.
  18460. */
  18461. // The result of `guessOrdinal`.
  18462. var BE_ORDINAL = {
  18463. Must: 1, // Encounter string but not '-' and not number-like.
  18464. Might: 2, // Encounter string but number-like.
  18465. Not: 3 // Other cases
  18466. };
  18467. var inner$3 = makeInner();
  18468. /**
  18469. * @see {module:echarts/data/Source}
  18470. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  18471. * @return {string} sourceFormat
  18472. */
  18473. function detectSourceFormat(datasetModel) {
  18474. var data = datasetModel.option.source;
  18475. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18476. if (isTypedArray(data)) {
  18477. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18478. }
  18479. else if (isArray(data)) {
  18480. // FIXME Whether tolerate null in top level array?
  18481. if (data.length === 0) {
  18482. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18483. }
  18484. for (var i = 0, len = data.length; i < len; i++) {
  18485. var item = data[i];
  18486. if (item == null) {
  18487. continue;
  18488. }
  18489. else if (isArray(item)) {
  18490. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18491. break;
  18492. }
  18493. else if (isObject$1(item)) {
  18494. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18495. break;
  18496. }
  18497. }
  18498. }
  18499. else if (isObject$1(data)) {
  18500. for (var key in data) {
  18501. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  18502. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18503. break;
  18504. }
  18505. }
  18506. }
  18507. else if (data != null) {
  18508. throw new Error('Invalid data');
  18509. }
  18510. inner$3(datasetModel).sourceFormat = sourceFormat;
  18511. }
  18512. /**
  18513. * [Scenarios]:
  18514. * (1) Provide source data directly:
  18515. * series: {
  18516. * encode: {...},
  18517. * dimensions: [...]
  18518. * seriesLayoutBy: 'row',
  18519. * data: [[...]]
  18520. * }
  18521. * (2) Refer to datasetModel.
  18522. * series: [{
  18523. * encode: {...}
  18524. * // Ignore datasetIndex means `datasetIndex: 0`
  18525. * // and the dimensions defination in dataset is used
  18526. * }, {
  18527. * encode: {...},
  18528. * seriesLayoutBy: 'column',
  18529. * datasetIndex: 1
  18530. * }]
  18531. *
  18532. * Get data from series itself or datset.
  18533. * @return {module:echarts/data/Source} source
  18534. */
  18535. function getSource(seriesModel) {
  18536. return inner$3(seriesModel).source;
  18537. }
  18538. /**
  18539. * MUST be called before mergeOption of all series.
  18540. * @param {module:echarts/model/Global} ecModel
  18541. */
  18542. function resetSourceDefaulter(ecModel) {
  18543. // `datasetMap` is used to make default encode.
  18544. inner$3(ecModel).datasetMap = createHashMap();
  18545. }
  18546. /**
  18547. * [Caution]:
  18548. * MUST be called after series option merged and
  18549. * before "series.getInitailData()" called.
  18550. *
  18551. * [The rule of making default encode]:
  18552. * Category axis (if exists) alway map to the first dimension.
  18553. * Each other axis occupies a subsequent dimension.
  18554. *
  18555. * [Why make default encode]:
  18556. * Simplify the typing of encode in option, avoiding the case like that:
  18557. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  18558. * where the "y" have to be manually typed as "1, 2, 3, ...".
  18559. *
  18560. * @param {module:echarts/model/Series} seriesModel
  18561. */
  18562. function prepareSource(seriesModel) {
  18563. var seriesOption = seriesModel.option;
  18564. var data = seriesOption.data;
  18565. var sourceFormat = isTypedArray(data)
  18566. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  18567. var fromDataset = false;
  18568. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18569. var sourceHeader = seriesOption.sourceHeader;
  18570. var dimensionsDefine = seriesOption.dimensions;
  18571. var datasetModel = getDatasetModel(seriesModel);
  18572. if (datasetModel) {
  18573. var datasetOption = datasetModel.option;
  18574. data = datasetOption.source;
  18575. sourceFormat = inner$3(datasetModel).sourceFormat;
  18576. fromDataset = true;
  18577. // These settings from series has higher priority.
  18578. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18579. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18580. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18581. }
  18582. var completeResult = completeBySourceData(
  18583. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18584. );
  18585. inner$3(seriesModel).source = new Source({
  18586. data: data,
  18587. fromDataset: fromDataset,
  18588. seriesLayoutBy: seriesLayoutBy,
  18589. sourceFormat: sourceFormat,
  18590. dimensionsDefine: completeResult.dimensionsDefine,
  18591. startIndex: completeResult.startIndex,
  18592. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18593. // Note: dataset option does not have `encode`.
  18594. encodeDefine: seriesOption.encode
  18595. });
  18596. }
  18597. // return {startIndex, dimensionsDefine, dimensionsCount}
  18598. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18599. if (!data) {
  18600. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18601. }
  18602. var dimensionsDetectCount;
  18603. var startIndex;
  18604. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18605. // Rule: Most of the first line are string: it is header.
  18606. // Caution: consider a line with 5 string and 1 number,
  18607. // it still can not be sure it is a head, because the
  18608. // 5 string may be 5 values of category columns.
  18609. if (sourceHeader === 'auto' || sourceHeader == null) {
  18610. arrayRowsTravelFirst(function (val) {
  18611. // '-' is regarded as null/undefined.
  18612. if (val != null && val !== '-') {
  18613. if (isString(val)) {
  18614. startIndex == null && (startIndex = 1);
  18615. }
  18616. else {
  18617. startIndex = 0;
  18618. }
  18619. }
  18620. // 10 is an experience number, avoid long loop.
  18621. }, seriesLayoutBy, data, 10);
  18622. }
  18623. else {
  18624. startIndex = sourceHeader ? 1 : 0;
  18625. }
  18626. if (!dimensionsDefine && startIndex === 1) {
  18627. dimensionsDefine = [];
  18628. arrayRowsTravelFirst(function (val, index) {
  18629. dimensionsDefine[index] = val != null ? val : '';
  18630. }, seriesLayoutBy, data);
  18631. }
  18632. dimensionsDetectCount = dimensionsDefine
  18633. ? dimensionsDefine.length
  18634. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18635. ? data.length
  18636. : data[0]
  18637. ? data[0].length
  18638. : null;
  18639. }
  18640. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18641. if (!dimensionsDefine) {
  18642. dimensionsDefine = objectRowsCollectDimensions(data);
  18643. }
  18644. }
  18645. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18646. if (!dimensionsDefine) {
  18647. dimensionsDefine = [];
  18648. each$1(data, function (colArr, key) {
  18649. dimensionsDefine.push(key);
  18650. });
  18651. }
  18652. }
  18653. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18654. var value0 = getDataItemValue(data[0]);
  18655. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18656. }
  18657. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18658. if (__DEV__) {
  18659. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18660. }
  18661. }
  18662. return {
  18663. startIndex: startIndex,
  18664. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18665. dimensionsDetectCount: dimensionsDetectCount
  18666. };
  18667. }
  18668. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18669. // which is reasonable. But dimension name is duplicated.
  18670. // Returns undefined or an array contains only object without null/undefiend or string.
  18671. function normalizeDimensionsDefine(dimensionsDefine) {
  18672. if (!dimensionsDefine) {
  18673. // The meaning of null/undefined is different from empty array.
  18674. return;
  18675. }
  18676. var nameMap = createHashMap();
  18677. return map(dimensionsDefine, function (item, index) {
  18678. item = extend({}, isObject$1(item) ? item : {name: item});
  18679. // User can set null in dimensions.
  18680. // We dont auto specify name, othewise a given name may
  18681. // cause it be refered unexpectedly.
  18682. if (item.name == null) {
  18683. return item;
  18684. }
  18685. // Also consider number form like 2012.
  18686. item.name += '';
  18687. // User may also specify displayName.
  18688. // displayName will always exists except user not
  18689. // specified or dim name is not specified or detected.
  18690. // (A auto generated dim name will not be used as
  18691. // displayName).
  18692. if (item.displayName == null) {
  18693. item.displayName = item.name;
  18694. }
  18695. var exist = nameMap.get(item.name);
  18696. if (!exist) {
  18697. nameMap.set(item.name, {count: 1});
  18698. }
  18699. else {
  18700. item.name += '-' + exist.count++;
  18701. }
  18702. return item;
  18703. });
  18704. }
  18705. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18706. maxLoop == null && (maxLoop = Infinity);
  18707. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18708. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18709. cb(data[i] ? data[i][0] : null, i);
  18710. }
  18711. }
  18712. else {
  18713. var value0 = data[0] || [];
  18714. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18715. cb(value0[i], i);
  18716. }
  18717. }
  18718. }
  18719. function objectRowsCollectDimensions(data) {
  18720. var firstIndex = 0;
  18721. var obj;
  18722. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18723. if (obj) {
  18724. var dimensions = [];
  18725. each$1(obj, function (value, key) {
  18726. dimensions.push(key);
  18727. });
  18728. return dimensions;
  18729. }
  18730. }
  18731. /**
  18732. * [The strategy of the arrengment of data dimensions for dataset]:
  18733. * "value way": all axes are non-category axes. So series one by one take
  18734. * several (the number is coordSysDims.length) dimensions from dataset.
  18735. * The result of data arrengment of data dimensions like:
  18736. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18737. * "category way": at least one axis is category axis. So the the first data
  18738. * dimension is always mapped to the first category axis and shared by
  18739. * all of the series. The other data dimensions are taken by series like
  18740. * "value way" does.
  18741. * The result of data arrengment of data dimensions like:
  18742. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18743. *
  18744. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18745. * @param {module:model/Series} seriesModel
  18746. * @param {module:data/Source} source
  18747. * @return {Object} encode Never be `null/undefined`.
  18748. */
  18749. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18750. var encode = {};
  18751. var datasetModel = getDatasetModel(seriesModel);
  18752. // Currently only make default when using dataset, util more reqirements occur.
  18753. if (!datasetModel || !coordDimensions) {
  18754. return encode;
  18755. }
  18756. var encodeItemName = [];
  18757. var encodeSeriesName = [];
  18758. var ecModel = seriesModel.ecModel;
  18759. var datasetMap = inner$3(ecModel).datasetMap;
  18760. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18761. var baseCategoryDimIndex;
  18762. var categoryWayValueDimStart;
  18763. coordDimensions = coordDimensions.slice();
  18764. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18765. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18766. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18767. baseCategoryDimIndex = coordDimIdx;
  18768. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18769. }
  18770. encode[coordDimInfo.name] = [];
  18771. });
  18772. var datasetRecord = datasetMap.get(key)
  18773. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18774. // TODO
  18775. // Auto detect first time axis and do arrangement.
  18776. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18777. var coordDimName = coordDimInfo.name;
  18778. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18779. // In value way.
  18780. if (baseCategoryDimIndex == null) {
  18781. var start = datasetRecord.valueWayDim;
  18782. pushDim(encode[coordDimName], start, count);
  18783. pushDim(encodeSeriesName, start, count);
  18784. datasetRecord.valueWayDim += count;
  18785. // ??? TODO give a better default series name rule?
  18786. // especially when encode x y specified.
  18787. // consider: when mutiple series share one dimension
  18788. // category axis, series name should better use
  18789. // the other dimsion name. On the other hand, use
  18790. // both dimensions name.
  18791. }
  18792. // In category way, the first category axis.
  18793. else if (baseCategoryDimIndex === coordDimIdx) {
  18794. pushDim(encode[coordDimName], 0, count);
  18795. pushDim(encodeItemName, 0, count);
  18796. }
  18797. // In category way, the other axis.
  18798. else {
  18799. var start = datasetRecord.categoryWayDim;
  18800. pushDim(encode[coordDimName], start, count);
  18801. pushDim(encodeSeriesName, start, count);
  18802. datasetRecord.categoryWayDim += count;
  18803. }
  18804. });
  18805. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18806. for (var i = 0; i < idxCount; i++) {
  18807. dimIdxArr.push(idxFrom + i);
  18808. }
  18809. }
  18810. function getDataDimCountOnCoordDim(coordDimInfo) {
  18811. var dimsDef = coordDimInfo.dimsDef;
  18812. return dimsDef ? dimsDef.length : 1;
  18813. }
  18814. encodeItemName.length && (encode.itemName = encodeItemName);
  18815. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18816. return encode;
  18817. }
  18818. /**
  18819. * Work for data like [{name: ..., value: ...}, ...].
  18820. *
  18821. * @param {module:model/Series} seriesModel
  18822. * @param {module:data/Source} source
  18823. * @return {Object} encode Never be `null/undefined`.
  18824. */
  18825. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18826. var encode = {};
  18827. var datasetModel = getDatasetModel(seriesModel);
  18828. // Currently only make default when using dataset, util more reqirements occur.
  18829. if (!datasetModel) {
  18830. return encode;
  18831. }
  18832. var sourceFormat = source.sourceFormat;
  18833. var dimensionsDefine = source.dimensionsDefine;
  18834. var potentialNameDimIndex;
  18835. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18836. each$1(dimensionsDefine, function (dim, idx) {
  18837. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18838. potentialNameDimIndex = idx;
  18839. }
  18840. });
  18841. }
  18842. // idxResult: {v, n}.
  18843. var idxResult = (function () {
  18844. var idxRes0 = {};
  18845. var idxRes1 = {};
  18846. var guessRecords = [];
  18847. // 5 is an experience value.
  18848. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18849. var guessResult = doGuessOrdinal(
  18850. source.data, sourceFormat, source.seriesLayoutBy,
  18851. dimensionsDefine, source.startIndex, i
  18852. );
  18853. guessRecords.push(guessResult);
  18854. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18855. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18856. // and then find a name dim with the priority:
  18857. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18858. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18859. idxRes0.v = i;
  18860. }
  18861. if (idxRes0.n == null
  18862. || (idxRes0.n === idxRes0.v)
  18863. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18864. ) {
  18865. idxRes0.n = i;
  18866. }
  18867. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18868. return idxRes0;
  18869. }
  18870. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18871. // find the first BE_ORDINAL.Might as the value dim,
  18872. // and then find a name dim with the priority:
  18873. // "other dim" > "the value dim itself".
  18874. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18875. // treated as number.
  18876. if (!isPureNumber) {
  18877. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18878. idxRes1.v = i;
  18879. }
  18880. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18881. idxRes1.n = i;
  18882. }
  18883. }
  18884. }
  18885. function fulfilled(idxResult) {
  18886. return idxResult.v != null && idxResult.n != null;
  18887. }
  18888. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18889. })();
  18890. if (idxResult) {
  18891. encode.value = idxResult.v;
  18892. // `potentialNameDimIndex` has highest priority.
  18893. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18894. // By default, label use itemName in charts.
  18895. // So we dont set encodeLabel here.
  18896. encode.itemName = [nameDimIndex];
  18897. encode.seriesName = [nameDimIndex];
  18898. }
  18899. return encode;
  18900. }
  18901. /**
  18902. * If return null/undefined, indicate that should not use datasetModel.
  18903. */
  18904. function getDatasetModel(seriesModel) {
  18905. var option = seriesModel.option;
  18906. // Caution: consider the scenario:
  18907. // A dataset is declared and a series is not expected to use the dataset,
  18908. // and at the beginning `setOption({series: { noData })` (just prepare other
  18909. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18910. // the user should set an empty array to avoid that dataset is used by default.
  18911. var thisData = option.data;
  18912. if (!thisData) {
  18913. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18914. }
  18915. }
  18916. /**
  18917. * The rule should not be complex, otherwise user might not
  18918. * be able to known where the data is wrong.
  18919. * The code is ugly, but how to make it neat?
  18920. *
  18921. * @param {module:echars/data/Source} source
  18922. * @param {number} dimIndex
  18923. * @return {BE_ORDINAL} guess result.
  18924. */
  18925. function guessOrdinal(source, dimIndex) {
  18926. return doGuessOrdinal(
  18927. source.data,
  18928. source.sourceFormat,
  18929. source.seriesLayoutBy,
  18930. source.dimensionsDefine,
  18931. source.startIndex,
  18932. dimIndex
  18933. );
  18934. }
  18935. // dimIndex may be overflow source data.
  18936. // return {BE_ORDINAL}
  18937. function doGuessOrdinal(
  18938. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18939. ) {
  18940. var result;
  18941. // Experience value.
  18942. var maxLoop = 5;
  18943. if (isTypedArray(data)) {
  18944. return BE_ORDINAL.Not;
  18945. }
  18946. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18947. // always exists in source.
  18948. var dimName;
  18949. var dimType;
  18950. if (dimensionsDefine) {
  18951. var dimDefItem = dimensionsDefine[dimIndex];
  18952. if (isObject$1(dimDefItem)) {
  18953. dimName = dimDefItem.name;
  18954. dimType = dimDefItem.type;
  18955. }
  18956. else if (isString(dimDefItem)) {
  18957. dimName = dimDefItem;
  18958. }
  18959. }
  18960. if (dimType != null) {
  18961. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18962. }
  18963. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18964. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18965. var sample = data[dimIndex];
  18966. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18967. if ((result = detectValue(sample[startIndex + i])) != null) {
  18968. return result;
  18969. }
  18970. }
  18971. }
  18972. else {
  18973. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18974. var row = data[startIndex + i];
  18975. if (row && (result = detectValue(row[dimIndex])) != null) {
  18976. return result;
  18977. }
  18978. }
  18979. }
  18980. }
  18981. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18982. if (!dimName) {
  18983. return BE_ORDINAL.Not;
  18984. }
  18985. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18986. var item = data[i];
  18987. if (item && (result = detectValue(item[dimName])) != null) {
  18988. return result;
  18989. }
  18990. }
  18991. }
  18992. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18993. if (!dimName) {
  18994. return BE_ORDINAL.Not;
  18995. }
  18996. var sample = data[dimName];
  18997. if (!sample || isTypedArray(sample)) {
  18998. return BE_ORDINAL.Not;
  18999. }
  19000. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  19001. if ((result = detectValue(sample[i])) != null) {
  19002. return result;
  19003. }
  19004. }
  19005. }
  19006. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19007. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19008. var item = data[i];
  19009. var val = getDataItemValue(item);
  19010. if (!isArray(val)) {
  19011. return BE_ORDINAL.Not;
  19012. }
  19013. if ((result = detectValue(val[dimIndex])) != null) {
  19014. return result;
  19015. }
  19016. }
  19017. }
  19018. function detectValue(val) {
  19019. var beStr = isString(val);
  19020. // Consider usage convenience, '1', '2' will be treated as "number".
  19021. // `isFinit('')` get `true`.
  19022. if (val != null && isFinite(val) && val !== '') {
  19023. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  19024. }
  19025. else if (beStr && val !== '-') {
  19026. return BE_ORDINAL.Must;
  19027. }
  19028. }
  19029. return BE_ORDINAL.Not;
  19030. }
  19031. /*
  19032. * Licensed to the Apache Software Foundation (ASF) under one
  19033. * or more contributor license agreements. See the NOTICE file
  19034. * distributed with this work for additional information
  19035. * regarding copyright ownership. The ASF licenses this file
  19036. * to you under the Apache License, Version 2.0 (the
  19037. * "License"); you may not use this file except in compliance
  19038. * with the License. You may obtain a copy of the License at
  19039. *
  19040. * http://www.apache.org/licenses/LICENSE-2.0
  19041. *
  19042. * Unless required by applicable law or agreed to in writing,
  19043. * software distributed under the License is distributed on an
  19044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19045. * KIND, either express or implied. See the License for the
  19046. * specific language governing permissions and limitations
  19047. * under the License.
  19048. */
  19049. /**
  19050. * ECharts global model
  19051. *
  19052. * @module {echarts/model/Global}
  19053. */
  19054. /**
  19055. * Caution: If the mechanism should be changed some day, these cases
  19056. * should be considered:
  19057. *
  19058. * (1) In `merge option` mode, if using the same option to call `setOption`
  19059. * many times, the result should be the same (try our best to ensure that).
  19060. * (2) In `merge option` mode, if a component has no id/name specified, it
  19061. * will be merged by index, and the result sequence of the components is
  19062. * consistent to the original sequence.
  19063. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  19064. * `mergeOption` in module:echarts/model/OptionManager.
  19065. */
  19066. var OPTION_INNER_KEY = '\0_ec_inner';
  19067. /**
  19068. * @alias module:echarts/model/Global
  19069. *
  19070. * @param {Object} option
  19071. * @param {module:echarts/model/Model} parentModel
  19072. * @param {Object} theme
  19073. */
  19074. var GlobalModel = Model.extend({
  19075. init: function (option, parentModel, theme, optionManager) {
  19076. theme = theme || {};
  19077. this.option = null; // Mark as not initialized.
  19078. /**
  19079. * @type {module:echarts/model/Model}
  19080. * @private
  19081. */
  19082. this._theme = new Model(theme);
  19083. /**
  19084. * @type {module:echarts/model/OptionManager}
  19085. */
  19086. this._optionManager = optionManager;
  19087. },
  19088. setOption: function (option, optionPreprocessorFuncs) {
  19089. assert$1(
  19090. !(OPTION_INNER_KEY in option),
  19091. 'please use chart.getOption()'
  19092. );
  19093. this._optionManager.setOption(option, optionPreprocessorFuncs);
  19094. this.resetOption(null);
  19095. },
  19096. /**
  19097. * @param {string} type null/undefined: reset all.
  19098. * 'recreate': force recreate all.
  19099. * 'timeline': only reset timeline option
  19100. * 'media': only reset media query option
  19101. * @return {boolean} Whether option changed.
  19102. */
  19103. resetOption: function (type) {
  19104. var optionChanged = false;
  19105. var optionManager = this._optionManager;
  19106. if (!type || type === 'recreate') {
  19107. var baseOption = optionManager.mountOption(type === 'recreate');
  19108. if (!this.option || type === 'recreate') {
  19109. initBase.call(this, baseOption);
  19110. }
  19111. else {
  19112. this.restoreData();
  19113. this.mergeOption(baseOption);
  19114. }
  19115. optionChanged = true;
  19116. }
  19117. if (type === 'timeline' || type === 'media') {
  19118. this.restoreData();
  19119. }
  19120. if (!type || type === 'recreate' || type === 'timeline') {
  19121. var timelineOption = optionManager.getTimelineOption(this);
  19122. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  19123. }
  19124. if (!type || type === 'recreate' || type === 'media') {
  19125. var mediaOptions = optionManager.getMediaOption(this, this._api);
  19126. if (mediaOptions.length) {
  19127. each$1(mediaOptions, function (mediaOption) {
  19128. this.mergeOption(mediaOption, optionChanged = true);
  19129. }, this);
  19130. }
  19131. }
  19132. return optionChanged;
  19133. },
  19134. /**
  19135. * @protected
  19136. */
  19137. mergeOption: function (newOption) {
  19138. var option = this.option;
  19139. var componentsMap = this._componentsMap;
  19140. var newCptTypes = [];
  19141. resetSourceDefaulter(this);
  19142. // If no component class, merge directly.
  19143. // For example: color, animaiton options, etc.
  19144. each$1(newOption, function (componentOption, mainType) {
  19145. if (componentOption == null) {
  19146. return;
  19147. }
  19148. if (!ComponentModel.hasClass(mainType)) {
  19149. // globalSettingTask.dirty();
  19150. option[mainType] = option[mainType] == null
  19151. ? clone(componentOption)
  19152. : merge(option[mainType], componentOption, true);
  19153. }
  19154. else if (mainType) {
  19155. newCptTypes.push(mainType);
  19156. }
  19157. });
  19158. ComponentModel.topologicalTravel(
  19159. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  19160. );
  19161. function visitComponent(mainType, dependencies) {
  19162. var newCptOptionList = normalizeToArray(newOption[mainType]);
  19163. var mapResult = mappingToExists(
  19164. componentsMap.get(mainType), newCptOptionList
  19165. );
  19166. makeIdAndName(mapResult);
  19167. // Set mainType and complete subType.
  19168. each$1(mapResult, function (item, index) {
  19169. var opt = item.option;
  19170. if (isObject$1(opt)) {
  19171. item.keyInfo.mainType = mainType;
  19172. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  19173. }
  19174. });
  19175. var dependentModels = getComponentsByTypes(
  19176. componentsMap, dependencies
  19177. );
  19178. option[mainType] = [];
  19179. componentsMap.set(mainType, []);
  19180. each$1(mapResult, function (resultItem, index) {
  19181. var componentModel = resultItem.exist;
  19182. var newCptOption = resultItem.option;
  19183. assert$1(
  19184. isObject$1(newCptOption) || componentModel,
  19185. 'Empty component definition'
  19186. );
  19187. // Consider where is no new option and should be merged using {},
  19188. // see removeEdgeAndAdd in topologicalTravel and
  19189. // ComponentModel.getAllClassMainTypes.
  19190. if (!newCptOption) {
  19191. componentModel.mergeOption({}, this);
  19192. componentModel.optionUpdated({}, false);
  19193. }
  19194. else {
  19195. var ComponentModelClass = ComponentModel.getClass(
  19196. mainType, resultItem.keyInfo.subType, true
  19197. );
  19198. if (componentModel && componentModel.constructor === ComponentModelClass) {
  19199. componentModel.name = resultItem.keyInfo.name;
  19200. // componentModel.settingTask && componentModel.settingTask.dirty();
  19201. componentModel.mergeOption(newCptOption, this);
  19202. componentModel.optionUpdated(newCptOption, false);
  19203. }
  19204. else {
  19205. // PENDING Global as parent ?
  19206. var extraOpt = extend(
  19207. {
  19208. dependentModels: dependentModels,
  19209. componentIndex: index
  19210. },
  19211. resultItem.keyInfo
  19212. );
  19213. componentModel = new ComponentModelClass(
  19214. newCptOption, this, this, extraOpt
  19215. );
  19216. extend(componentModel, extraOpt);
  19217. componentModel.init(newCptOption, this, this, extraOpt);
  19218. // Call optionUpdated after init.
  19219. // newCptOption has been used as componentModel.option
  19220. // and may be merged with theme and default, so pass null
  19221. // to avoid confusion.
  19222. componentModel.optionUpdated(null, true);
  19223. }
  19224. }
  19225. componentsMap.get(mainType)[index] = componentModel;
  19226. option[mainType][index] = componentModel.option;
  19227. }, this);
  19228. // Backup series for filtering.
  19229. if (mainType === 'series') {
  19230. createSeriesIndices(this, componentsMap.get('series'));
  19231. }
  19232. }
  19233. this._seriesIndicesMap = createHashMap(
  19234. this._seriesIndices = this._seriesIndices || []
  19235. );
  19236. },
  19237. /**
  19238. * Get option for output (cloned option and inner info removed)
  19239. * @public
  19240. * @return {Object}
  19241. */
  19242. getOption: function () {
  19243. var option = clone(this.option);
  19244. each$1(option, function (opts, mainType) {
  19245. if (ComponentModel.hasClass(mainType)) {
  19246. var opts = normalizeToArray(opts);
  19247. for (var i = opts.length - 1; i >= 0; i--) {
  19248. // Remove options with inner id.
  19249. if (isIdInner(opts[i])) {
  19250. opts.splice(i, 1);
  19251. }
  19252. }
  19253. option[mainType] = opts;
  19254. }
  19255. });
  19256. delete option[OPTION_INNER_KEY];
  19257. return option;
  19258. },
  19259. /**
  19260. * @return {module:echarts/model/Model}
  19261. */
  19262. getTheme: function () {
  19263. return this._theme;
  19264. },
  19265. /**
  19266. * @param {string} mainType
  19267. * @param {number} [idx=0]
  19268. * @return {module:echarts/model/Component}
  19269. */
  19270. getComponent: function (mainType, idx) {
  19271. var list = this._componentsMap.get(mainType);
  19272. if (list) {
  19273. return list[idx || 0];
  19274. }
  19275. },
  19276. /**
  19277. * If none of index and id and name used, return all components with mainType.
  19278. * @param {Object} condition
  19279. * @param {string} condition.mainType
  19280. * @param {string} [condition.subType] If ignore, only query by mainType
  19281. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  19282. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  19283. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  19284. * @return {Array.<module:echarts/model/Component>}
  19285. */
  19286. queryComponents: function (condition) {
  19287. var mainType = condition.mainType;
  19288. if (!mainType) {
  19289. return [];
  19290. }
  19291. var index = condition.index;
  19292. var id = condition.id;
  19293. var name = condition.name;
  19294. var cpts = this._componentsMap.get(mainType);
  19295. if (!cpts || !cpts.length) {
  19296. return [];
  19297. }
  19298. var result;
  19299. if (index != null) {
  19300. if (!isArray(index)) {
  19301. index = [index];
  19302. }
  19303. result = filter(map(index, function (idx) {
  19304. return cpts[idx];
  19305. }), function (val) {
  19306. return !!val;
  19307. });
  19308. }
  19309. else if (id != null) {
  19310. var isIdArray = isArray(id);
  19311. result = filter(cpts, function (cpt) {
  19312. return (isIdArray && indexOf(id, cpt.id) >= 0)
  19313. || (!isIdArray && cpt.id === id);
  19314. });
  19315. }
  19316. else if (name != null) {
  19317. var isNameArray = isArray(name);
  19318. result = filter(cpts, function (cpt) {
  19319. return (isNameArray && indexOf(name, cpt.name) >= 0)
  19320. || (!isNameArray && cpt.name === name);
  19321. });
  19322. }
  19323. else {
  19324. // Return all components with mainType
  19325. result = cpts.slice();
  19326. }
  19327. return filterBySubType(result, condition);
  19328. },
  19329. /**
  19330. * The interface is different from queryComponents,
  19331. * which is convenient for inner usage.
  19332. *
  19333. * @usage
  19334. * var result = findComponents(
  19335. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  19336. * );
  19337. * var result = findComponents(
  19338. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  19339. * );
  19340. * var result = findComponents(
  19341. * {mainType: 'series',
  19342. * filter: function (model, index) {...}}
  19343. * );
  19344. * // result like [component0, componnet1, ...]
  19345. *
  19346. * @param {Object} condition
  19347. * @param {string} condition.mainType Mandatory.
  19348. * @param {string} [condition.subType] Optional.
  19349. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  19350. * where xxx is mainType.
  19351. * If query attribute is null/undefined or has no index/id/name,
  19352. * do not filtering by query conditions, which is convenient for
  19353. * no-payload situations or when target of action is global.
  19354. * @param {Function} [condition.filter] parameter: component, return boolean.
  19355. * @return {Array.<module:echarts/model/Component>}
  19356. */
  19357. findComponents: function (condition) {
  19358. var query = condition.query;
  19359. var mainType = condition.mainType;
  19360. var queryCond = getQueryCond(query);
  19361. var result = queryCond
  19362. ? this.queryComponents(queryCond)
  19363. : this._componentsMap.get(mainType);
  19364. return doFilter(filterBySubType(result, condition));
  19365. function getQueryCond(q) {
  19366. var indexAttr = mainType + 'Index';
  19367. var idAttr = mainType + 'Id';
  19368. var nameAttr = mainType + 'Name';
  19369. return q && (
  19370. q[indexAttr] != null
  19371. || q[idAttr] != null
  19372. || q[nameAttr] != null
  19373. )
  19374. ? {
  19375. mainType: mainType,
  19376. // subType will be filtered finally.
  19377. index: q[indexAttr],
  19378. id: q[idAttr],
  19379. name: q[nameAttr]
  19380. }
  19381. : null;
  19382. }
  19383. function doFilter(res) {
  19384. return condition.filter
  19385. ? filter(res, condition.filter)
  19386. : res;
  19387. }
  19388. },
  19389. /**
  19390. * @usage
  19391. * eachComponent('legend', function (legendModel, index) {
  19392. * ...
  19393. * });
  19394. * eachComponent(function (componentType, model, index) {
  19395. * // componentType does not include subType
  19396. * // (componentType is 'xxx' but not 'xxx.aa')
  19397. * });
  19398. * eachComponent(
  19399. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  19400. * function (model, index) {...}
  19401. * );
  19402. * eachComponent(
  19403. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  19404. * function (model, index) {...}
  19405. * );
  19406. *
  19407. * @param {string|Object=} mainType When mainType is object, the definition
  19408. * is the same as the method 'findComponents'.
  19409. * @param {Function} cb
  19410. * @param {*} context
  19411. */
  19412. eachComponent: function (mainType, cb, context) {
  19413. var componentsMap = this._componentsMap;
  19414. if (typeof mainType === 'function') {
  19415. context = cb;
  19416. cb = mainType;
  19417. componentsMap.each(function (components, componentType) {
  19418. each$1(components, function (component, index) {
  19419. cb.call(context, componentType, component, index);
  19420. });
  19421. });
  19422. }
  19423. else if (isString(mainType)) {
  19424. each$1(componentsMap.get(mainType), cb, context);
  19425. }
  19426. else if (isObject$1(mainType)) {
  19427. var queryResult = this.findComponents(mainType);
  19428. each$1(queryResult, cb, context);
  19429. }
  19430. },
  19431. /**
  19432. * @param {string} name
  19433. * @return {Array.<module:echarts/model/Series>}
  19434. */
  19435. getSeriesByName: function (name) {
  19436. var series = this._componentsMap.get('series');
  19437. return filter(series, function (oneSeries) {
  19438. return oneSeries.name === name;
  19439. });
  19440. },
  19441. /**
  19442. * @param {number} seriesIndex
  19443. * @return {module:echarts/model/Series}
  19444. */
  19445. getSeriesByIndex: function (seriesIndex) {
  19446. return this._componentsMap.get('series')[seriesIndex];
  19447. },
  19448. /**
  19449. * Get series list before filtered by type.
  19450. * FIXME: rename to getRawSeriesByType?
  19451. *
  19452. * @param {string} subType
  19453. * @return {Array.<module:echarts/model/Series>}
  19454. */
  19455. getSeriesByType: function (subType) {
  19456. var series = this._componentsMap.get('series');
  19457. return filter(series, function (oneSeries) {
  19458. return oneSeries.subType === subType;
  19459. });
  19460. },
  19461. /**
  19462. * @return {Array.<module:echarts/model/Series>}
  19463. */
  19464. getSeries: function () {
  19465. return this._componentsMap.get('series').slice();
  19466. },
  19467. /**
  19468. * @return {number}
  19469. */
  19470. getSeriesCount: function () {
  19471. return this._componentsMap.get('series').length;
  19472. },
  19473. /**
  19474. * After filtering, series may be different
  19475. * frome raw series.
  19476. *
  19477. * @param {Function} cb
  19478. * @param {*} context
  19479. */
  19480. eachSeries: function (cb, context) {
  19481. assertSeriesInitialized(this);
  19482. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19483. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19484. cb.call(context, series, rawSeriesIndex);
  19485. }, this);
  19486. },
  19487. /**
  19488. * Iterate raw series before filtered.
  19489. *
  19490. * @param {Function} cb
  19491. * @param {*} context
  19492. */
  19493. eachRawSeries: function (cb, context) {
  19494. each$1(this._componentsMap.get('series'), cb, context);
  19495. },
  19496. /**
  19497. * After filtering, series may be different.
  19498. * frome raw series.
  19499. *
  19500. * @param {string} subType.
  19501. * @param {Function} cb
  19502. * @param {*} context
  19503. */
  19504. eachSeriesByType: function (subType, cb, context) {
  19505. assertSeriesInitialized(this);
  19506. each$1(this._seriesIndices, function (rawSeriesIndex) {
  19507. var series = this._componentsMap.get('series')[rawSeriesIndex];
  19508. if (series.subType === subType) {
  19509. cb.call(context, series, rawSeriesIndex);
  19510. }
  19511. }, this);
  19512. },
  19513. /**
  19514. * Iterate raw series before filtered of given type.
  19515. *
  19516. * @parma {string} subType
  19517. * @param {Function} cb
  19518. * @param {*} context
  19519. */
  19520. eachRawSeriesByType: function (subType, cb, context) {
  19521. return each$1(this.getSeriesByType(subType), cb, context);
  19522. },
  19523. /**
  19524. * @param {module:echarts/model/Series} seriesModel
  19525. */
  19526. isSeriesFiltered: function (seriesModel) {
  19527. assertSeriesInitialized(this);
  19528. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  19529. },
  19530. /**
  19531. * @return {Array.<number>}
  19532. */
  19533. getCurrentSeriesIndices: function () {
  19534. return (this._seriesIndices || []).slice();
  19535. },
  19536. /**
  19537. * @param {Function} cb
  19538. * @param {*} context
  19539. */
  19540. filterSeries: function (cb, context) {
  19541. assertSeriesInitialized(this);
  19542. var filteredSeries = filter(
  19543. this._componentsMap.get('series'), cb, context
  19544. );
  19545. createSeriesIndices(this, filteredSeries);
  19546. },
  19547. restoreData: function (payload) {
  19548. var componentsMap = this._componentsMap;
  19549. createSeriesIndices(this, componentsMap.get('series'));
  19550. var componentTypes = [];
  19551. componentsMap.each(function (components, componentType) {
  19552. componentTypes.push(componentType);
  19553. });
  19554. ComponentModel.topologicalTravel(
  19555. componentTypes,
  19556. ComponentModel.getAllClassMainTypes(),
  19557. function (componentType, dependencies) {
  19558. each$1(componentsMap.get(componentType), function (component) {
  19559. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  19560. && component.restoreData();
  19561. });
  19562. }
  19563. );
  19564. }
  19565. });
  19566. function isNotTargetSeries(seriesModel, payload) {
  19567. if (payload) {
  19568. var index = payload.seiresIndex;
  19569. var id = payload.seriesId;
  19570. var name = payload.seriesName;
  19571. return (index != null && seriesModel.componentIndex !== index)
  19572. || (id != null && seriesModel.id !== id)
  19573. || (name != null && seriesModel.name !== name);
  19574. }
  19575. }
  19576. /**
  19577. * @inner
  19578. */
  19579. function mergeTheme(option, theme) {
  19580. // PENDING
  19581. // NOT use `colorLayer` in theme if option has `color`
  19582. var notMergeColorLayer = option.color && !option.colorLayer;
  19583. each$1(theme, function (themeItem, name) {
  19584. if (name === 'colorLayer' && notMergeColorLayer) {
  19585. return;
  19586. }
  19587. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19588. if (!ComponentModel.hasClass(name)) {
  19589. if (typeof themeItem === 'object') {
  19590. option[name] = !option[name]
  19591. ? clone(themeItem)
  19592. : merge(option[name], themeItem, false);
  19593. }
  19594. else {
  19595. if (option[name] == null) {
  19596. option[name] = themeItem;
  19597. }
  19598. }
  19599. }
  19600. });
  19601. }
  19602. function initBase(baseOption) {
  19603. baseOption = baseOption;
  19604. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19605. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19606. this.option = {};
  19607. this.option[OPTION_INNER_KEY] = 1;
  19608. /**
  19609. * Init with series: [], in case of calling findSeries method
  19610. * before series initialized.
  19611. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19612. * @private
  19613. */
  19614. this._componentsMap = createHashMap({series: []});
  19615. /**
  19616. * Mapping between filtered series list and raw series list.
  19617. * key: filtered series indices, value: raw series indices.
  19618. * @type {Array.<nubmer>}
  19619. * @private
  19620. */
  19621. this._seriesIndices;
  19622. this._seriesIndicesMap;
  19623. mergeTheme(baseOption, this._theme.option);
  19624. // TODO Needs clone when merging to the unexisted property
  19625. merge(baseOption, globalDefault, false);
  19626. this.mergeOption(baseOption);
  19627. }
  19628. /**
  19629. * @inner
  19630. * @param {Array.<string>|string} types model types
  19631. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19632. */
  19633. function getComponentsByTypes(componentsMap, types) {
  19634. if (!isArray(types)) {
  19635. types = types ? [types] : [];
  19636. }
  19637. var ret = {};
  19638. each$1(types, function (type) {
  19639. ret[type] = (componentsMap.get(type) || []).slice();
  19640. });
  19641. return ret;
  19642. }
  19643. /**
  19644. * @inner
  19645. */
  19646. function determineSubType(mainType, newCptOption, existComponent) {
  19647. var subType = newCptOption.type
  19648. ? newCptOption.type
  19649. : existComponent
  19650. ? existComponent.subType
  19651. // Use determineSubType only when there is no existComponent.
  19652. : ComponentModel.determineSubType(mainType, newCptOption);
  19653. // tooltip, markline, markpoint may always has no subType
  19654. return subType;
  19655. }
  19656. /**
  19657. * @inner
  19658. */
  19659. function createSeriesIndices(ecModel, seriesModels) {
  19660. ecModel._seriesIndicesMap = createHashMap(
  19661. ecModel._seriesIndices = map(seriesModels, function (series) {
  19662. return series.componentIndex;
  19663. }) || []
  19664. );
  19665. }
  19666. /**
  19667. * @inner
  19668. */
  19669. function filterBySubType(components, condition) {
  19670. // Using hasOwnProperty for restrict. Consider
  19671. // subType is undefined in user payload.
  19672. return condition.hasOwnProperty('subType')
  19673. ? filter(components, function (cpt) {
  19674. return cpt.subType === condition.subType;
  19675. })
  19676. : components;
  19677. }
  19678. /**
  19679. * @inner
  19680. */
  19681. function assertSeriesInitialized(ecModel) {
  19682. // Components that use _seriesIndices should depends on series component,
  19683. // which make sure that their initialization is after series.
  19684. if (__DEV__) {
  19685. if (!ecModel._seriesIndices) {
  19686. throw new Error('Option should contains series.');
  19687. }
  19688. }
  19689. }
  19690. mixin(GlobalModel, colorPaletteMixin);
  19691. /*
  19692. * Licensed to the Apache Software Foundation (ASF) under one
  19693. * or more contributor license agreements. See the NOTICE file
  19694. * distributed with this work for additional information
  19695. * regarding copyright ownership. The ASF licenses this file
  19696. * to you under the Apache License, Version 2.0 (the
  19697. * "License"); you may not use this file except in compliance
  19698. * with the License. You may obtain a copy of the License at
  19699. *
  19700. * http://www.apache.org/licenses/LICENSE-2.0
  19701. *
  19702. * Unless required by applicable law or agreed to in writing,
  19703. * software distributed under the License is distributed on an
  19704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19705. * KIND, either express or implied. See the License for the
  19706. * specific language governing permissions and limitations
  19707. * under the License.
  19708. */
  19709. var echartsAPIList = [
  19710. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19711. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19712. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19713. ];
  19714. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19715. function ExtensionAPI(chartInstance) {
  19716. each$1(echartsAPIList, function (name) {
  19717. this[name] = bind(chartInstance[name], chartInstance);
  19718. }, this);
  19719. }
  19720. /*
  19721. * Licensed to the Apache Software Foundation (ASF) under one
  19722. * or more contributor license agreements. See the NOTICE file
  19723. * distributed with this work for additional information
  19724. * regarding copyright ownership. The ASF licenses this file
  19725. * to you under the Apache License, Version 2.0 (the
  19726. * "License"); you may not use this file except in compliance
  19727. * with the License. You may obtain a copy of the License at
  19728. *
  19729. * http://www.apache.org/licenses/LICENSE-2.0
  19730. *
  19731. * Unless required by applicable law or agreed to in writing,
  19732. * software distributed under the License is distributed on an
  19733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19734. * KIND, either express or implied. See the License for the
  19735. * specific language governing permissions and limitations
  19736. * under the License.
  19737. */
  19738. var coordinateSystemCreators = {};
  19739. function CoordinateSystemManager() {
  19740. this._coordinateSystems = [];
  19741. }
  19742. CoordinateSystemManager.prototype = {
  19743. constructor: CoordinateSystemManager,
  19744. create: function (ecModel, api) {
  19745. var coordinateSystems = [];
  19746. each$1(coordinateSystemCreators, function (creater, type) {
  19747. var list = creater.create(ecModel, api);
  19748. coordinateSystems = coordinateSystems.concat(list || []);
  19749. });
  19750. this._coordinateSystems = coordinateSystems;
  19751. },
  19752. update: function (ecModel, api) {
  19753. each$1(this._coordinateSystems, function (coordSys) {
  19754. coordSys.update && coordSys.update(ecModel, api);
  19755. });
  19756. },
  19757. getCoordinateSystems: function () {
  19758. return this._coordinateSystems.slice();
  19759. }
  19760. };
  19761. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19762. coordinateSystemCreators[type] = coordinateSystemCreator;
  19763. };
  19764. CoordinateSystemManager.get = function (type) {
  19765. return coordinateSystemCreators[type];
  19766. };
  19767. /*
  19768. * Licensed to the Apache Software Foundation (ASF) under one
  19769. * or more contributor license agreements. See the NOTICE file
  19770. * distributed with this work for additional information
  19771. * regarding copyright ownership. The ASF licenses this file
  19772. * to you under the Apache License, Version 2.0 (the
  19773. * "License"); you may not use this file except in compliance
  19774. * with the License. You may obtain a copy of the License at
  19775. *
  19776. * http://www.apache.org/licenses/LICENSE-2.0
  19777. *
  19778. * Unless required by applicable law or agreed to in writing,
  19779. * software distributed under the License is distributed on an
  19780. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19781. * KIND, either express or implied. See the License for the
  19782. * specific language governing permissions and limitations
  19783. * under the License.
  19784. */
  19785. /**
  19786. * ECharts option manager
  19787. *
  19788. * @module {echarts/model/OptionManager}
  19789. */
  19790. var each$4 = each$1;
  19791. var clone$3 = clone;
  19792. var map$1 = map;
  19793. var merge$1 = merge;
  19794. var QUERY_REG = /^(min|max)?(.+)$/;
  19795. /**
  19796. * TERM EXPLANATIONS:
  19797. *
  19798. * [option]:
  19799. *
  19800. * An object that contains definitions of components. For example:
  19801. * var option = {
  19802. * title: {...},
  19803. * legend: {...},
  19804. * visualMap: {...},
  19805. * series: [
  19806. * {data: [...]},
  19807. * {data: [...]},
  19808. * ...
  19809. * ]
  19810. * };
  19811. *
  19812. * [rawOption]:
  19813. *
  19814. * An object input to echarts.setOption. 'rawOption' may be an
  19815. * 'option', or may be an object contains multi-options. For example:
  19816. * var option = {
  19817. * baseOption: {
  19818. * title: {...},
  19819. * legend: {...},
  19820. * series: [
  19821. * {data: [...]},
  19822. * {data: [...]},
  19823. * ...
  19824. * ]
  19825. * },
  19826. * timeline: {...},
  19827. * options: [
  19828. * {title: {...}, series: {data: [...]}},
  19829. * {title: {...}, series: {data: [...]}},
  19830. * ...
  19831. * ],
  19832. * media: [
  19833. * {
  19834. * query: {maxWidth: 320},
  19835. * option: {series: {x: 20}, visualMap: {show: false}}
  19836. * },
  19837. * {
  19838. * query: {minWidth: 320, maxWidth: 720},
  19839. * option: {series: {x: 500}, visualMap: {show: true}}
  19840. * },
  19841. * {
  19842. * option: {series: {x: 1200}, visualMap: {show: true}}
  19843. * }
  19844. * ]
  19845. * };
  19846. *
  19847. * @alias module:echarts/model/OptionManager
  19848. * @param {module:echarts/ExtensionAPI} api
  19849. */
  19850. function OptionManager(api) {
  19851. /**
  19852. * @private
  19853. * @type {module:echarts/ExtensionAPI}
  19854. */
  19855. this._api = api;
  19856. /**
  19857. * @private
  19858. * @type {Array.<number>}
  19859. */
  19860. this._timelineOptions = [];
  19861. /**
  19862. * @private
  19863. * @type {Array.<Object>}
  19864. */
  19865. this._mediaList = [];
  19866. /**
  19867. * @private
  19868. * @type {Object}
  19869. */
  19870. this._mediaDefault;
  19871. /**
  19872. * -1, means default.
  19873. * empty means no media.
  19874. * @private
  19875. * @type {Array.<number>}
  19876. */
  19877. this._currentMediaIndices = [];
  19878. /**
  19879. * @private
  19880. * @type {Object}
  19881. */
  19882. this._optionBackup;
  19883. /**
  19884. * @private
  19885. * @type {Object}
  19886. */
  19887. this._newBaseOption;
  19888. }
  19889. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19890. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19891. // rawOption cloned and backuped when timeline changed, which does no
  19892. // good to performance. What's more, that both timeline and setOption
  19893. // method supply 'notMerge' brings complex and some problems.
  19894. // Consider this case:
  19895. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19896. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19897. OptionManager.prototype = {
  19898. constructor: OptionManager,
  19899. /**
  19900. * @public
  19901. * @param {Object} rawOption Raw option.
  19902. * @param {module:echarts/model/Global} ecModel
  19903. * @param {Array.<Function>} optionPreprocessorFuncs
  19904. * @return {Object} Init option
  19905. */
  19906. setOption: function (rawOption, optionPreprocessorFuncs) {
  19907. if (rawOption) {
  19908. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19909. each$1(normalizeToArray(rawOption.series), function (series) {
  19910. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19911. });
  19912. }
  19913. // Caution: some series modify option data, if do not clone,
  19914. // it should ensure that the repeat modify correctly
  19915. // (create a new object when modify itself).
  19916. rawOption = clone$3(rawOption);
  19917. // FIXME
  19918. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19919. var oldOptionBackup = this._optionBackup;
  19920. var newParsedOption = parseRawOption.call(
  19921. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19922. );
  19923. this._newBaseOption = newParsedOption.baseOption;
  19924. // For setOption at second time (using merge mode);
  19925. if (oldOptionBackup) {
  19926. // Only baseOption can be merged.
  19927. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19928. // For simplicity, timeline options and media options do not support merge,
  19929. // that is, if you `setOption` twice and both has timeline options, the latter
  19930. // timeline opitons will not be merged to the formers, but just substitude them.
  19931. if (newParsedOption.timelineOptions.length) {
  19932. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19933. }
  19934. if (newParsedOption.mediaList.length) {
  19935. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19936. }
  19937. if (newParsedOption.mediaDefault) {
  19938. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19939. }
  19940. }
  19941. else {
  19942. this._optionBackup = newParsedOption;
  19943. }
  19944. },
  19945. /**
  19946. * @param {boolean} isRecreate
  19947. * @return {Object}
  19948. */
  19949. mountOption: function (isRecreate) {
  19950. var optionBackup = this._optionBackup;
  19951. // TODO
  19952. // 如果没有reset功能则不clone。
  19953. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19954. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19955. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19956. this._currentMediaIndices = [];
  19957. return clone$3(isRecreate
  19958. // this._optionBackup.baseOption, which is created at the first `setOption`
  19959. // called, and is merged into every new option by inner method `mergeOption`
  19960. // each time `setOption` called, can be only used in `isRecreate`, because
  19961. // its reliability is under suspicion. In other cases option merge is
  19962. // performed by `model.mergeOption`.
  19963. ? optionBackup.baseOption : this._newBaseOption
  19964. );
  19965. },
  19966. /**
  19967. * @param {module:echarts/model/Global} ecModel
  19968. * @return {Object}
  19969. */
  19970. getTimelineOption: function (ecModel) {
  19971. var option;
  19972. var timelineOptions = this._timelineOptions;
  19973. if (timelineOptions.length) {
  19974. // getTimelineOption can only be called after ecModel inited,
  19975. // so we can get currentIndex from timelineModel.
  19976. var timelineModel = ecModel.getComponent('timeline');
  19977. if (timelineModel) {
  19978. option = clone$3(
  19979. timelineOptions[timelineModel.getCurrentIndex()],
  19980. true
  19981. );
  19982. }
  19983. }
  19984. return option;
  19985. },
  19986. /**
  19987. * @param {module:echarts/model/Global} ecModel
  19988. * @return {Array.<Object>}
  19989. */
  19990. getMediaOption: function (ecModel) {
  19991. var ecWidth = this._api.getWidth();
  19992. var ecHeight = this._api.getHeight();
  19993. var mediaList = this._mediaList;
  19994. var mediaDefault = this._mediaDefault;
  19995. var indices = [];
  19996. var result = [];
  19997. // No media defined.
  19998. if (!mediaList.length && !mediaDefault) {
  19999. return result;
  20000. }
  20001. // Multi media may be applied, the latter defined media has higher priority.
  20002. for (var i = 0, len = mediaList.length; i < len; i++) {
  20003. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  20004. indices.push(i);
  20005. }
  20006. }
  20007. // FIXME
  20008. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  20009. if (!indices.length && mediaDefault) {
  20010. indices = [-1];
  20011. }
  20012. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  20013. result = map$1(indices, function (index) {
  20014. return clone$3(
  20015. index === -1 ? mediaDefault.option : mediaList[index].option
  20016. );
  20017. });
  20018. }
  20019. // Otherwise return nothing.
  20020. this._currentMediaIndices = indices;
  20021. return result;
  20022. }
  20023. };
  20024. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  20025. var timelineOptions = [];
  20026. var mediaList = [];
  20027. var mediaDefault;
  20028. var baseOption;
  20029. // Compatible with ec2.
  20030. var timelineOpt = rawOption.timeline;
  20031. if (rawOption.baseOption) {
  20032. baseOption = rawOption.baseOption;
  20033. }
  20034. // For timeline
  20035. if (timelineOpt || rawOption.options) {
  20036. baseOption = baseOption || {};
  20037. timelineOptions = (rawOption.options || []).slice();
  20038. }
  20039. // For media query
  20040. if (rawOption.media) {
  20041. baseOption = baseOption || {};
  20042. var media = rawOption.media;
  20043. each$4(media, function (singleMedia) {
  20044. if (singleMedia && singleMedia.option) {
  20045. if (singleMedia.query) {
  20046. mediaList.push(singleMedia);
  20047. }
  20048. else if (!mediaDefault) {
  20049. // Use the first media default.
  20050. mediaDefault = singleMedia;
  20051. }
  20052. }
  20053. });
  20054. }
  20055. // For normal option
  20056. if (!baseOption) {
  20057. baseOption = rawOption;
  20058. }
  20059. // Set timelineOpt to baseOption in ec3,
  20060. // which is convenient for merge option.
  20061. if (!baseOption.timeline) {
  20062. baseOption.timeline = timelineOpt;
  20063. }
  20064. // Preprocess.
  20065. each$4([baseOption].concat(timelineOptions)
  20066. .concat(map(mediaList, function (media) {
  20067. return media.option;
  20068. })),
  20069. function (option) {
  20070. each$4(optionPreprocessorFuncs, function (preProcess) {
  20071. preProcess(option, isNew);
  20072. });
  20073. }
  20074. );
  20075. return {
  20076. baseOption: baseOption,
  20077. timelineOptions: timelineOptions,
  20078. mediaDefault: mediaDefault,
  20079. mediaList: mediaList
  20080. };
  20081. }
  20082. /**
  20083. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  20084. * Support: width, height, aspectRatio
  20085. * Can use max or min as prefix.
  20086. */
  20087. function applyMediaQuery(query, ecWidth, ecHeight) {
  20088. var realMap = {
  20089. width: ecWidth,
  20090. height: ecHeight,
  20091. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  20092. };
  20093. var applicatable = true;
  20094. each$1(query, function (value, attr) {
  20095. var matched = attr.match(QUERY_REG);
  20096. if (!matched || !matched[1] || !matched[2]) {
  20097. return;
  20098. }
  20099. var operator = matched[1];
  20100. var realAttr = matched[2].toLowerCase();
  20101. if (!compare(realMap[realAttr], value, operator)) {
  20102. applicatable = false;
  20103. }
  20104. });
  20105. return applicatable;
  20106. }
  20107. function compare(real, expect, operator) {
  20108. if (operator === 'min') {
  20109. return real >= expect;
  20110. }
  20111. else if (operator === 'max') {
  20112. return real <= expect;
  20113. }
  20114. else { // Equals
  20115. return real === expect;
  20116. }
  20117. }
  20118. function indicesEquals(indices1, indices2) {
  20119. // indices is always order by asc and has only finite number.
  20120. return indices1.join(',') === indices2.join(',');
  20121. }
  20122. /**
  20123. * Consider case:
  20124. * `chart.setOption(opt1);`
  20125. * Then user do some interaction like dataZoom, dataView changing.
  20126. * `chart.setOption(opt2);`
  20127. * Then user press 'reset button' in toolbox.
  20128. *
  20129. * After doing that all of the interaction effects should be reset, the
  20130. * chart should be the same as the result of invoke
  20131. * `chart.setOption(opt1); chart.setOption(opt2);`.
  20132. *
  20133. * Although it is not able ensure that
  20134. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  20135. * `chart.setOption(merge(opt1, opt2));` exactly,
  20136. * this might be the only simple way to implement that feature.
  20137. *
  20138. * MEMO: We've considered some other approaches:
  20139. * 1. Each model handle its self restoration but not uniform treatment.
  20140. * (Too complex in logic and error-prone)
  20141. * 2. Use a shadow ecModel. (Performace expensive)
  20142. */
  20143. function mergeOption(oldOption, newOption) {
  20144. newOption = newOption || {};
  20145. each$4(newOption, function (newCptOpt, mainType) {
  20146. if (newCptOpt == null) {
  20147. return;
  20148. }
  20149. var oldCptOpt = oldOption[mainType];
  20150. if (!ComponentModel.hasClass(mainType)) {
  20151. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  20152. }
  20153. else {
  20154. newCptOpt = normalizeToArray(newCptOpt);
  20155. oldCptOpt = normalizeToArray(oldCptOpt);
  20156. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  20157. oldOption[mainType] = map$1(mapResult, function (item) {
  20158. return (item.option && item.exist)
  20159. ? merge$1(item.exist, item.option, true)
  20160. : (item.exist || item.option);
  20161. });
  20162. }
  20163. });
  20164. }
  20165. /*
  20166. * Licensed to the Apache Software Foundation (ASF) under one
  20167. * or more contributor license agreements. See the NOTICE file
  20168. * distributed with this work for additional information
  20169. * regarding copyright ownership. The ASF licenses this file
  20170. * to you under the Apache License, Version 2.0 (the
  20171. * "License"); you may not use this file except in compliance
  20172. * with the License. You may obtain a copy of the License at
  20173. *
  20174. * http://www.apache.org/licenses/LICENSE-2.0
  20175. *
  20176. * Unless required by applicable law or agreed to in writing,
  20177. * software distributed under the License is distributed on an
  20178. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20179. * KIND, either express or implied. See the License for the
  20180. * specific language governing permissions and limitations
  20181. * under the License.
  20182. */
  20183. var each$5 = each$1;
  20184. var isObject$3 = isObject$1;
  20185. var POSSIBLE_STYLES = [
  20186. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  20187. 'chordStyle', 'label', 'labelLine'
  20188. ];
  20189. function compatEC2ItemStyle(opt) {
  20190. var itemStyleOpt = opt && opt.itemStyle;
  20191. if (!itemStyleOpt) {
  20192. return;
  20193. }
  20194. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  20195. var styleName = POSSIBLE_STYLES[i];
  20196. var normalItemStyleOpt = itemStyleOpt.normal;
  20197. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  20198. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  20199. opt[styleName] = opt[styleName] || {};
  20200. if (!opt[styleName].normal) {
  20201. opt[styleName].normal = normalItemStyleOpt[styleName];
  20202. }
  20203. else {
  20204. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  20205. }
  20206. normalItemStyleOpt[styleName] = null;
  20207. }
  20208. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  20209. opt[styleName] = opt[styleName] || {};
  20210. if (!opt[styleName].emphasis) {
  20211. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  20212. }
  20213. else {
  20214. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  20215. }
  20216. emphasisItemStyleOpt[styleName] = null;
  20217. }
  20218. }
  20219. }
  20220. function convertNormalEmphasis(opt, optType, useExtend) {
  20221. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  20222. var normalOpt = opt[optType].normal;
  20223. var emphasisOpt = opt[optType].emphasis;
  20224. if (normalOpt) {
  20225. // Timeline controlStyle has other properties besides normal and emphasis
  20226. if (useExtend) {
  20227. opt[optType].normal = opt[optType].emphasis = null;
  20228. defaults(opt[optType], normalOpt);
  20229. }
  20230. else {
  20231. opt[optType] = normalOpt;
  20232. }
  20233. }
  20234. if (emphasisOpt) {
  20235. opt.emphasis = opt.emphasis || {};
  20236. opt.emphasis[optType] = emphasisOpt;
  20237. }
  20238. }
  20239. }
  20240. function removeEC3NormalStatus(opt) {
  20241. convertNormalEmphasis(opt, 'itemStyle');
  20242. convertNormalEmphasis(opt, 'lineStyle');
  20243. convertNormalEmphasis(opt, 'areaStyle');
  20244. convertNormalEmphasis(opt, 'label');
  20245. convertNormalEmphasis(opt, 'labelLine');
  20246. // treemap
  20247. convertNormalEmphasis(opt, 'upperLabel');
  20248. // graph
  20249. convertNormalEmphasis(opt, 'edgeLabel');
  20250. }
  20251. function compatTextStyle(opt, propName) {
  20252. // Check whether is not object (string\null\undefined ...)
  20253. var labelOptSingle = isObject$3(opt) && opt[propName];
  20254. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  20255. if (textStyle) {
  20256. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  20257. var propName = TEXT_STYLE_OPTIONS[i];
  20258. if (textStyle.hasOwnProperty(propName)) {
  20259. labelOptSingle[propName] = textStyle[propName];
  20260. }
  20261. }
  20262. }
  20263. }
  20264. function compatEC3CommonStyles(opt) {
  20265. if (opt) {
  20266. removeEC3NormalStatus(opt);
  20267. compatTextStyle(opt, 'label');
  20268. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  20269. }
  20270. }
  20271. function processSeries(seriesOpt) {
  20272. if (!isObject$3(seriesOpt)) {
  20273. return;
  20274. }
  20275. compatEC2ItemStyle(seriesOpt);
  20276. removeEC3NormalStatus(seriesOpt);
  20277. compatTextStyle(seriesOpt, 'label');
  20278. // treemap
  20279. compatTextStyle(seriesOpt, 'upperLabel');
  20280. // graph
  20281. compatTextStyle(seriesOpt, 'edgeLabel');
  20282. if (seriesOpt.emphasis) {
  20283. compatTextStyle(seriesOpt.emphasis, 'label');
  20284. // treemap
  20285. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  20286. // graph
  20287. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  20288. }
  20289. var markPoint = seriesOpt.markPoint;
  20290. if (markPoint) {
  20291. compatEC2ItemStyle(markPoint);
  20292. compatEC3CommonStyles(markPoint);
  20293. }
  20294. var markLine = seriesOpt.markLine;
  20295. if (markLine) {
  20296. compatEC2ItemStyle(markLine);
  20297. compatEC3CommonStyles(markLine);
  20298. }
  20299. var markArea = seriesOpt.markArea;
  20300. if (markArea) {
  20301. compatEC3CommonStyles(markArea);
  20302. }
  20303. var data = seriesOpt.data;
  20304. // Break with ec3: if `setOption` again, there may be no `type` in option,
  20305. // then the backward compat based on option type will not be performed.
  20306. if (seriesOpt.type === 'graph') {
  20307. data = data || seriesOpt.nodes;
  20308. var edgeData = seriesOpt.links || seriesOpt.edges;
  20309. if (edgeData && !isTypedArray(edgeData)) {
  20310. for (var i = 0; i < edgeData.length; i++) {
  20311. compatEC3CommonStyles(edgeData[i]);
  20312. }
  20313. }
  20314. each$1(seriesOpt.categories, function (opt) {
  20315. removeEC3NormalStatus(opt);
  20316. });
  20317. }
  20318. if (data && !isTypedArray(data)) {
  20319. for (var i = 0; i < data.length; i++) {
  20320. compatEC3CommonStyles(data[i]);
  20321. }
  20322. }
  20323. // mark point data
  20324. var markPoint = seriesOpt.markPoint;
  20325. if (markPoint && markPoint.data) {
  20326. var mpData = markPoint.data;
  20327. for (var i = 0; i < mpData.length; i++) {
  20328. compatEC3CommonStyles(mpData[i]);
  20329. }
  20330. }
  20331. // mark line data
  20332. var markLine = seriesOpt.markLine;
  20333. if (markLine && markLine.data) {
  20334. var mlData = markLine.data;
  20335. for (var i = 0; i < mlData.length; i++) {
  20336. if (isArray(mlData[i])) {
  20337. compatEC3CommonStyles(mlData[i][0]);
  20338. compatEC3CommonStyles(mlData[i][1]);
  20339. }
  20340. else {
  20341. compatEC3CommonStyles(mlData[i]);
  20342. }
  20343. }
  20344. }
  20345. // Series
  20346. if (seriesOpt.type === 'gauge') {
  20347. compatTextStyle(seriesOpt, 'axisLabel');
  20348. compatTextStyle(seriesOpt, 'title');
  20349. compatTextStyle(seriesOpt, 'detail');
  20350. }
  20351. else if (seriesOpt.type === 'treemap') {
  20352. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  20353. each$1(seriesOpt.levels, function (opt) {
  20354. removeEC3NormalStatus(opt);
  20355. });
  20356. }
  20357. else if (seriesOpt.type === 'tree') {
  20358. removeEC3NormalStatus(seriesOpt.leaves);
  20359. }
  20360. // sunburst starts from ec4, so it does not need to compat levels.
  20361. }
  20362. function toArr(o) {
  20363. return isArray(o) ? o : o ? [o] : [];
  20364. }
  20365. function toObj(o) {
  20366. return (isArray(o) ? o[0] : o) || {};
  20367. }
  20368. var compatStyle = function (option, isTheme) {
  20369. each$5(toArr(option.series), function (seriesOpt) {
  20370. isObject$3(seriesOpt) && processSeries(seriesOpt);
  20371. });
  20372. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  20373. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  20374. each$5(
  20375. axes,
  20376. function (axisName) {
  20377. each$5(toArr(option[axisName]), function (axisOpt) {
  20378. if (axisOpt) {
  20379. compatTextStyle(axisOpt, 'axisLabel');
  20380. compatTextStyle(axisOpt.axisPointer, 'label');
  20381. }
  20382. });
  20383. }
  20384. );
  20385. each$5(toArr(option.parallel), function (parallelOpt) {
  20386. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  20387. compatTextStyle(parallelAxisDefault, 'axisLabel');
  20388. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  20389. });
  20390. each$5(toArr(option.calendar), function (calendarOpt) {
  20391. convertNormalEmphasis(calendarOpt, 'itemStyle');
  20392. compatTextStyle(calendarOpt, 'dayLabel');
  20393. compatTextStyle(calendarOpt, 'monthLabel');
  20394. compatTextStyle(calendarOpt, 'yearLabel');
  20395. });
  20396. // radar.name.textStyle
  20397. each$5(toArr(option.radar), function (radarOpt) {
  20398. compatTextStyle(radarOpt, 'name');
  20399. });
  20400. each$5(toArr(option.geo), function (geoOpt) {
  20401. if (isObject$3(geoOpt)) {
  20402. compatEC3CommonStyles(geoOpt);
  20403. each$5(toArr(geoOpt.regions), function (regionObj) {
  20404. compatEC3CommonStyles(regionObj);
  20405. });
  20406. }
  20407. });
  20408. each$5(toArr(option.timeline), function (timelineOpt) {
  20409. compatEC3CommonStyles(timelineOpt);
  20410. convertNormalEmphasis(timelineOpt, 'label');
  20411. convertNormalEmphasis(timelineOpt, 'itemStyle');
  20412. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  20413. var data = timelineOpt.data;
  20414. isArray(data) && each$1(data, function (item) {
  20415. if (isObject$1(item)) {
  20416. convertNormalEmphasis(item, 'label');
  20417. convertNormalEmphasis(item, 'itemStyle');
  20418. }
  20419. });
  20420. });
  20421. each$5(toArr(option.toolbox), function (toolboxOpt) {
  20422. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  20423. each$5(toolboxOpt.feature, function (featureOpt) {
  20424. convertNormalEmphasis(featureOpt, 'iconStyle');
  20425. });
  20426. });
  20427. compatTextStyle(toObj(option.axisPointer), 'label');
  20428. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  20429. };
  20430. /*
  20431. * Licensed to the Apache Software Foundation (ASF) under one
  20432. * or more contributor license agreements. See the NOTICE file
  20433. * distributed with this work for additional information
  20434. * regarding copyright ownership. The ASF licenses this file
  20435. * to you under the Apache License, Version 2.0 (the
  20436. * "License"); you may not use this file except in compliance
  20437. * with the License. You may obtain a copy of the License at
  20438. *
  20439. * http://www.apache.org/licenses/LICENSE-2.0
  20440. *
  20441. * Unless required by applicable law or agreed to in writing,
  20442. * software distributed under the License is distributed on an
  20443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20444. * KIND, either express or implied. See the License for the
  20445. * specific language governing permissions and limitations
  20446. * under the License.
  20447. */
  20448. // Compatitable with 2.0
  20449. function get(opt, path) {
  20450. path = path.split(',');
  20451. var obj = opt;
  20452. for (var i = 0; i < path.length; i++) {
  20453. obj = obj && obj[path[i]];
  20454. if (obj == null) {
  20455. break;
  20456. }
  20457. }
  20458. return obj;
  20459. }
  20460. function set$1(opt, path, val, overwrite) {
  20461. path = path.split(',');
  20462. var obj = opt;
  20463. var key;
  20464. for (var i = 0; i < path.length - 1; i++) {
  20465. key = path[i];
  20466. if (obj[key] == null) {
  20467. obj[key] = {};
  20468. }
  20469. obj = obj[key];
  20470. }
  20471. if (overwrite || obj[path[i]] == null) {
  20472. obj[path[i]] = val;
  20473. }
  20474. }
  20475. function compatLayoutProperties(option) {
  20476. each$1(LAYOUT_PROPERTIES, function (prop) {
  20477. if (prop[0] in option && !(prop[1] in option)) {
  20478. option[prop[1]] = option[prop[0]];
  20479. }
  20480. });
  20481. }
  20482. var LAYOUT_PROPERTIES = [
  20483. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  20484. ];
  20485. var COMPATITABLE_COMPONENTS = [
  20486. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  20487. ];
  20488. var backwardCompat = function (option, isTheme) {
  20489. compatStyle(option, isTheme);
  20490. // Make sure series array for model initialization.
  20491. option.series = normalizeToArray(option.series);
  20492. each$1(option.series, function (seriesOpt) {
  20493. if (!isObject$1(seriesOpt)) {
  20494. return;
  20495. }
  20496. var seriesType = seriesOpt.type;
  20497. if (seriesType === 'line') {
  20498. if (seriesOpt.clipOverflow != null) {
  20499. seriesOpt.clip = seriesOpt.clipOverflow;
  20500. }
  20501. }
  20502. else if (seriesType === 'pie' || seriesType === 'gauge') {
  20503. if (seriesOpt.clockWise != null) {
  20504. seriesOpt.clockwise = seriesOpt.clockWise;
  20505. }
  20506. }
  20507. else if (seriesType === 'gauge') {
  20508. var pointerColor = get(seriesOpt, 'pointer.color');
  20509. pointerColor != null
  20510. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  20511. }
  20512. compatLayoutProperties(seriesOpt);
  20513. });
  20514. // dataRange has changed to visualMap
  20515. if (option.dataRange) {
  20516. option.visualMap = option.dataRange;
  20517. }
  20518. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  20519. var options = option[componentName];
  20520. if (options) {
  20521. if (!isArray(options)) {
  20522. options = [options];
  20523. }
  20524. each$1(options, function (option) {
  20525. compatLayoutProperties(option);
  20526. });
  20527. }
  20528. });
  20529. };
  20530. /*
  20531. * Licensed to the Apache Software Foundation (ASF) under one
  20532. * or more contributor license agreements. See the NOTICE file
  20533. * distributed with this work for additional information
  20534. * regarding copyright ownership. The ASF licenses this file
  20535. * to you under the Apache License, Version 2.0 (the
  20536. * "License"); you may not use this file except in compliance
  20537. * with the License. You may obtain a copy of the License at
  20538. *
  20539. * http://www.apache.org/licenses/LICENSE-2.0
  20540. *
  20541. * Unless required by applicable law or agreed to in writing,
  20542. * software distributed under the License is distributed on an
  20543. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20544. * KIND, either express or implied. See the License for the
  20545. * specific language governing permissions and limitations
  20546. * under the License.
  20547. */
  20548. // (1) [Caution]: the logic is correct based on the premises:
  20549. // data processing stage is blocked in stream.
  20550. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  20551. // (2) Only register once when import repeatly.
  20552. // Should be executed after series filtered and before stack calculation.
  20553. var dataStack = function (ecModel) {
  20554. var stackInfoMap = createHashMap();
  20555. ecModel.eachSeries(function (seriesModel) {
  20556. var stack = seriesModel.get('stack');
  20557. // Compatibal: when `stack` is set as '', do not stack.
  20558. if (stack) {
  20559. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  20560. var data = seriesModel.getData();
  20561. var stackInfo = {
  20562. // Used for calculate axis extent automatically.
  20563. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  20564. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  20565. stackedDimension: data.getCalculationInfo('stackedDimension'),
  20566. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  20567. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20568. data: data,
  20569. seriesModel: seriesModel
  20570. };
  20571. // If stacked on axis that do not support data stack.
  20572. if (!stackInfo.stackedDimension
  20573. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20574. ) {
  20575. return;
  20576. }
  20577. stackInfoList.length && data.setCalculationInfo(
  20578. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20579. );
  20580. stackInfoList.push(stackInfo);
  20581. }
  20582. });
  20583. stackInfoMap.each(calculateStack);
  20584. };
  20585. function calculateStack(stackInfoList) {
  20586. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20587. var resultVal = [];
  20588. var resultNaN = [NaN, NaN];
  20589. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20590. var targetData = targetStackInfo.data;
  20591. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20592. // Should not write on raw data, because stack series model list changes
  20593. // depending on legend selection.
  20594. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20595. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20596. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20597. // should also be NaN, to draw a appropriate belt area.
  20598. if (isNaN(sum)) {
  20599. return resultNaN;
  20600. }
  20601. var byValue;
  20602. var stackedDataRawIndex;
  20603. if (isStackedByIndex) {
  20604. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20605. }
  20606. else {
  20607. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20608. }
  20609. // If stackOver is NaN, chart view will render point on value start.
  20610. var stackedOver = NaN;
  20611. for (var j = idxInStack - 1; j >= 0; j--) {
  20612. var stackInfo = stackInfoList[j];
  20613. // Has been optimized by inverted indices on `stackedByDimension`.
  20614. if (!isStackedByIndex) {
  20615. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20616. }
  20617. if (stackedDataRawIndex >= 0) {
  20618. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20619. // Considering positive stack, negative stack and empty data
  20620. if ((sum >= 0 && val > 0) // Positive stack
  20621. || (sum <= 0 && val < 0) // Negative stack
  20622. ) {
  20623. sum += val;
  20624. stackedOver = val;
  20625. break;
  20626. }
  20627. }
  20628. }
  20629. resultVal[0] = sum;
  20630. resultVal[1] = stackedOver;
  20631. return resultVal;
  20632. });
  20633. targetData.hostModel.setData(newData);
  20634. // Update for consequent calculation
  20635. targetStackInfo.data = newData;
  20636. });
  20637. }
  20638. /*
  20639. * Licensed to the Apache Software Foundation (ASF) under one
  20640. * or more contributor license agreements. See the NOTICE file
  20641. * distributed with this work for additional information
  20642. * regarding copyright ownership. The ASF licenses this file
  20643. * to you under the Apache License, Version 2.0 (the
  20644. * "License"); you may not use this file except in compliance
  20645. * with the License. You may obtain a copy of the License at
  20646. *
  20647. * http://www.apache.org/licenses/LICENSE-2.0
  20648. *
  20649. * Unless required by applicable law or agreed to in writing,
  20650. * software distributed under the License is distributed on an
  20651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20652. * KIND, either express or implied. See the License for the
  20653. * specific language governing permissions and limitations
  20654. * under the License.
  20655. */
  20656. // TODO
  20657. // ??? refactor? check the outer usage of data provider.
  20658. // merge with defaultDimValueGetter?
  20659. /**
  20660. * If normal array used, mutable chunk size is supported.
  20661. * If typed array used, chunk size must be fixed.
  20662. */
  20663. function DefaultDataProvider(source, dimSize) {
  20664. if (!Source.isInstance(source)) {
  20665. source = Source.seriesDataToSource(source);
  20666. }
  20667. this._source = source;
  20668. var data = this._data = source.data;
  20669. var sourceFormat = source.sourceFormat;
  20670. // Typed array. TODO IE10+?
  20671. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20672. if (__DEV__) {
  20673. if (dimSize == null) {
  20674. throw new Error('Typed array data must specify dimension size');
  20675. }
  20676. }
  20677. this._offset = 0;
  20678. this._dimSize = dimSize;
  20679. this._data = data;
  20680. }
  20681. var methods = providerMethods[
  20682. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20683. ? sourceFormat + '_' + source.seriesLayoutBy
  20684. : sourceFormat
  20685. ];
  20686. if (__DEV__) {
  20687. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20688. }
  20689. extend(this, methods);
  20690. }
  20691. var providerProto = DefaultDataProvider.prototype;
  20692. // If data is pure without style configuration
  20693. providerProto.pure = false;
  20694. // If data is persistent and will not be released after use.
  20695. providerProto.persistent = true;
  20696. // ???! FIXME legacy data provider do not has method getSource
  20697. providerProto.getSource = function () {
  20698. return this._source;
  20699. };
  20700. var providerMethods = {
  20701. 'arrayRows_column': {
  20702. pure: true,
  20703. count: function () {
  20704. return Math.max(0, this._data.length - this._source.startIndex);
  20705. },
  20706. getItem: function (idx) {
  20707. return this._data[idx + this._source.startIndex];
  20708. },
  20709. appendData: appendDataSimply
  20710. },
  20711. 'arrayRows_row': {
  20712. pure: true,
  20713. count: function () {
  20714. var row = this._data[0];
  20715. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20716. },
  20717. getItem: function (idx) {
  20718. idx += this._source.startIndex;
  20719. var item = [];
  20720. var data = this._data;
  20721. for (var i = 0; i < data.length; i++) {
  20722. var row = data[i];
  20723. item.push(row ? row[idx] : null);
  20724. }
  20725. return item;
  20726. },
  20727. appendData: function () {
  20728. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20729. }
  20730. },
  20731. 'objectRows': {
  20732. pure: true,
  20733. count: countSimply,
  20734. getItem: getItemSimply,
  20735. appendData: appendDataSimply
  20736. },
  20737. 'keyedColumns': {
  20738. pure: true,
  20739. count: function () {
  20740. var dimName = this._source.dimensionsDefine[0].name;
  20741. var col = this._data[dimName];
  20742. return col ? col.length : 0;
  20743. },
  20744. getItem: function (idx) {
  20745. var item = [];
  20746. var dims = this._source.dimensionsDefine;
  20747. for (var i = 0; i < dims.length; i++) {
  20748. var col = this._data[dims[i].name];
  20749. item.push(col ? col[idx] : null);
  20750. }
  20751. return item;
  20752. },
  20753. appendData: function (newData) {
  20754. var data = this._data;
  20755. each$1(newData, function (newCol, key) {
  20756. var oldCol = data[key] || (data[key] = []);
  20757. for (var i = 0; i < (newCol || []).length; i++) {
  20758. oldCol.push(newCol[i]);
  20759. }
  20760. });
  20761. }
  20762. },
  20763. 'original': {
  20764. count: countSimply,
  20765. getItem: getItemSimply,
  20766. appendData: appendDataSimply
  20767. },
  20768. 'typedArray': {
  20769. persistent: false,
  20770. pure: true,
  20771. count: function () {
  20772. return this._data ? (this._data.length / this._dimSize) : 0;
  20773. },
  20774. getItem: function (idx, out) {
  20775. idx = idx - this._offset;
  20776. out = out || [];
  20777. var offset = this._dimSize * idx;
  20778. for (var i = 0; i < this._dimSize; i++) {
  20779. out[i] = this._data[offset + i];
  20780. }
  20781. return out;
  20782. },
  20783. appendData: function (newData) {
  20784. if (__DEV__) {
  20785. assert$1(
  20786. isTypedArray(newData),
  20787. 'Added data must be TypedArray if data in initialization is TypedArray'
  20788. );
  20789. }
  20790. this._data = newData;
  20791. },
  20792. // Clean self if data is already used.
  20793. clean: function () {
  20794. // PENDING
  20795. this._offset += this.count();
  20796. this._data = null;
  20797. }
  20798. }
  20799. };
  20800. function countSimply() {
  20801. return this._data.length;
  20802. }
  20803. function getItemSimply(idx) {
  20804. return this._data[idx];
  20805. }
  20806. function appendDataSimply(newData) {
  20807. for (var i = 0; i < newData.length; i++) {
  20808. this._data.push(newData[i]);
  20809. }
  20810. }
  20811. var rawValueGetters = {
  20812. arrayRows: getRawValueSimply,
  20813. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20814. return dimIndex != null ? dataItem[dimName] : dataItem;
  20815. },
  20816. keyedColumns: getRawValueSimply,
  20817. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20818. // FIXME
  20819. // In some case (markpoint in geo (geo-map.html)), dataItem
  20820. // is {coord: [...]}
  20821. var value = getDataItemValue(dataItem);
  20822. return (dimIndex == null || !(value instanceof Array))
  20823. ? value
  20824. : value[dimIndex];
  20825. },
  20826. typedArray: getRawValueSimply
  20827. };
  20828. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20829. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20830. }
  20831. var defaultDimValueGetters = {
  20832. arrayRows: getDimValueSimply,
  20833. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20834. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20835. },
  20836. keyedColumns: getDimValueSimply,
  20837. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20838. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20839. // If dataItem is an plain object with no value field, the var `value`
  20840. // will be assigned with the object, but it will be tread correctly
  20841. // in the `convertDataValue`.
  20842. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20843. // If any dataItem is like { value: 10 }
  20844. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20845. this.hasItemOption = true;
  20846. }
  20847. return converDataValue(
  20848. (value instanceof Array)
  20849. ? value[dimIndex]
  20850. // If value is a single number or something else not array.
  20851. : value,
  20852. this._dimensionInfos[dimName]
  20853. );
  20854. },
  20855. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20856. return dataItem[dimIndex];
  20857. }
  20858. };
  20859. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20860. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20861. }
  20862. /**
  20863. * This helper method convert value in data.
  20864. * @param {string|number|Date} value
  20865. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20866. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20867. */
  20868. function converDataValue(value, dimInfo) {
  20869. // Performance sensitive.
  20870. var dimType = dimInfo && dimInfo.type;
  20871. if (dimType === 'ordinal') {
  20872. // If given value is a category string
  20873. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20874. return ordinalMeta
  20875. ? ordinalMeta.parseAndCollect(value)
  20876. : value;
  20877. }
  20878. if (dimType === 'time'
  20879. // spead up when using timestamp
  20880. && typeof value !== 'number'
  20881. && value != null
  20882. && value !== '-'
  20883. ) {
  20884. value = +parseDate(value);
  20885. }
  20886. // dimType defaults 'number'.
  20887. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20888. // parse to NaN.
  20889. return (value == null || value === '')
  20890. ? NaN
  20891. // If string (like '-'), using '+' parse to NaN
  20892. // If object, also parse to NaN
  20893. : +value;
  20894. }
  20895. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20896. // Consider persistent.
  20897. // Caution: why use raw value to display on label or tooltip?
  20898. // A reason is to avoid format. For example time value we do not know
  20899. // how to format is expected. More over, if stack is used, calculated
  20900. // value may be 0.91000000001, which have brings trouble to display.
  20901. // TODO: consider how to treat null/undefined/NaN when display?
  20902. /**
  20903. * @param {module:echarts/data/List} data
  20904. * @param {number} dataIndex
  20905. * @param {string|number} [dim] dimName or dimIndex
  20906. * @return {Array.<number>|string|number} can be null/undefined.
  20907. */
  20908. function retrieveRawValue(data, dataIndex, dim) {
  20909. if (!data) {
  20910. return;
  20911. }
  20912. // Consider data may be not persistent.
  20913. var dataItem = data.getRawDataItem(dataIndex);
  20914. if (dataItem == null) {
  20915. return;
  20916. }
  20917. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20918. var dimName;
  20919. var dimIndex;
  20920. var dimInfo = data.getDimensionInfo(dim);
  20921. if (dimInfo) {
  20922. dimName = dimInfo.name;
  20923. dimIndex = dimInfo.index;
  20924. }
  20925. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20926. }
  20927. /**
  20928. * Compatible with some cases (in pie, map) like:
  20929. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20930. * where only sourceFormat is 'original' and 'objectRows' supported.
  20931. *
  20932. * ??? TODO
  20933. * Supported detail options in data item when using 'arrayRows'.
  20934. *
  20935. * @param {module:echarts/data/List} data
  20936. * @param {number} dataIndex
  20937. * @param {string} attr like 'selected'
  20938. */
  20939. function retrieveRawAttr(data, dataIndex, attr) {
  20940. if (!data) {
  20941. return;
  20942. }
  20943. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20944. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20945. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20946. ) {
  20947. return;
  20948. }
  20949. var dataItem = data.getRawDataItem(dataIndex);
  20950. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20951. dataItem = null;
  20952. }
  20953. if (dataItem) {
  20954. return dataItem[attr];
  20955. }
  20956. }
  20957. /*
  20958. * Licensed to the Apache Software Foundation (ASF) under one
  20959. * or more contributor license agreements. See the NOTICE file
  20960. * distributed with this work for additional information
  20961. * regarding copyright ownership. The ASF licenses this file
  20962. * to you under the Apache License, Version 2.0 (the
  20963. * "License"); you may not use this file except in compliance
  20964. * with the License. You may obtain a copy of the License at
  20965. *
  20966. * http://www.apache.org/licenses/LICENSE-2.0
  20967. *
  20968. * Unless required by applicable law or agreed to in writing,
  20969. * software distributed under the License is distributed on an
  20970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20971. * KIND, either express or implied. See the License for the
  20972. * specific language governing permissions and limitations
  20973. * under the License.
  20974. */
  20975. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20976. // PENDING A little ugly
  20977. var dataFormatMixin = {
  20978. /**
  20979. * Get params for formatter
  20980. * @param {number} dataIndex
  20981. * @param {string} [dataType]
  20982. * @return {Object}
  20983. */
  20984. getDataParams: function (dataIndex, dataType) {
  20985. var data = this.getData(dataType);
  20986. var rawValue = this.getRawValue(dataIndex, dataType);
  20987. var rawDataIndex = data.getRawIndex(dataIndex);
  20988. var name = data.getName(dataIndex);
  20989. var itemOpt = data.getRawDataItem(dataIndex);
  20990. var color = data.getItemVisual(dataIndex, 'color');
  20991. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20992. var tooltipModel = this.ecModel.getComponent('tooltip');
  20993. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20994. var renderMode = getTooltipRenderMode(renderModeOption);
  20995. var mainType = this.mainType;
  20996. var isSeries = mainType === 'series';
  20997. var userOutput = data.userOutput;
  20998. return {
  20999. componentType: mainType,
  21000. componentSubType: this.subType,
  21001. componentIndex: this.componentIndex,
  21002. seriesType: isSeries ? this.subType : null,
  21003. seriesIndex: this.seriesIndex,
  21004. seriesId: isSeries ? this.id : null,
  21005. seriesName: isSeries ? this.name : null,
  21006. name: name,
  21007. dataIndex: rawDataIndex,
  21008. data: itemOpt,
  21009. dataType: dataType,
  21010. value: rawValue,
  21011. color: color,
  21012. borderColor: borderColor,
  21013. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  21014. encode: userOutput ? userOutput.encode : null,
  21015. marker: getTooltipMarker({
  21016. color: color,
  21017. renderMode: renderMode
  21018. }),
  21019. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  21020. $vars: ['seriesName', 'name', 'value']
  21021. };
  21022. },
  21023. /**
  21024. * Format label
  21025. * @param {number} dataIndex
  21026. * @param {string} [status='normal'] 'normal' or 'emphasis'
  21027. * @param {string} [dataType]
  21028. * @param {number} [dimIndex] Only used in some chart that
  21029. * use formatter in different dimensions, like radar.
  21030. * @param {string} [labelProp='label']
  21031. * @return {string} If not formatter, return null/undefined
  21032. */
  21033. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  21034. status = status || 'normal';
  21035. var data = this.getData(dataType);
  21036. var itemModel = data.getItemModel(dataIndex);
  21037. var params = this.getDataParams(dataIndex, dataType);
  21038. if (dimIndex != null && (params.value instanceof Array)) {
  21039. params.value = params.value[dimIndex];
  21040. }
  21041. var formatter = itemModel.get(
  21042. status === 'normal'
  21043. ? [labelProp || 'label', 'formatter']
  21044. : [status, labelProp || 'label', 'formatter']
  21045. );
  21046. if (typeof formatter === 'function') {
  21047. params.status = status;
  21048. params.dimensionIndex = dimIndex;
  21049. return formatter(params);
  21050. }
  21051. else if (typeof formatter === 'string') {
  21052. var str = formatTpl(formatter, params);
  21053. // Support 'aaa{@[3]}bbb{@product}ccc'.
  21054. // Do not support '}' in dim name util have to.
  21055. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  21056. var len = dim.length;
  21057. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  21058. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  21059. }
  21060. return retrieveRawValue(data, dataIndex, dim);
  21061. });
  21062. }
  21063. },
  21064. /**
  21065. * Get raw value in option
  21066. * @param {number} idx
  21067. * @param {string} [dataType]
  21068. * @return {Array|number|string}
  21069. */
  21070. getRawValue: function (idx, dataType) {
  21071. return retrieveRawValue(this.getData(dataType), idx);
  21072. },
  21073. /**
  21074. * Should be implemented.
  21075. * @param {number} dataIndex
  21076. * @param {boolean} [multipleSeries=false]
  21077. * @param {number} [dataType]
  21078. * @return {string} tooltip string
  21079. */
  21080. formatTooltip: function () {
  21081. // Empty function
  21082. }
  21083. };
  21084. /*
  21085. * Licensed to the Apache Software Foundation (ASF) under one
  21086. * or more contributor license agreements. See the NOTICE file
  21087. * distributed with this work for additional information
  21088. * regarding copyright ownership. The ASF licenses this file
  21089. * to you under the Apache License, Version 2.0 (the
  21090. * "License"); you may not use this file except in compliance
  21091. * with the License. You may obtain a copy of the License at
  21092. *
  21093. * http://www.apache.org/licenses/LICENSE-2.0
  21094. *
  21095. * Unless required by applicable law or agreed to in writing,
  21096. * software distributed under the License is distributed on an
  21097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21098. * KIND, either express or implied. See the License for the
  21099. * specific language governing permissions and limitations
  21100. * under the License.
  21101. */
  21102. /**
  21103. * @param {Object} define
  21104. * @return See the return of `createTask`.
  21105. */
  21106. function createTask(define) {
  21107. return new Task(define);
  21108. }
  21109. /**
  21110. * @constructor
  21111. * @param {Object} define
  21112. * @param {Function} define.reset Custom reset
  21113. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  21114. * @param {Function} [define.count] count is used to determin data task.
  21115. * @param {Function} [define.onDirty] count is used to determin data task.
  21116. */
  21117. function Task(define) {
  21118. define = define || {};
  21119. this._reset = define.reset;
  21120. this._plan = define.plan;
  21121. this._count = define.count;
  21122. this._onDirty = define.onDirty;
  21123. this._dirty = true;
  21124. // Context must be specified implicitly, to
  21125. // avoid miss update context when model changed.
  21126. this.context;
  21127. }
  21128. var taskProto = Task.prototype;
  21129. /**
  21130. * @param {Object} performArgs
  21131. * @param {number} [performArgs.step] Specified step.
  21132. * @param {number} [performArgs.skip] Skip customer perform call.
  21133. * @param {number} [performArgs.modBy] Sampling window size.
  21134. * @param {number} [performArgs.modDataCount] Sampling count.
  21135. */
  21136. taskProto.perform = function (performArgs) {
  21137. var upTask = this._upstream;
  21138. var skip = performArgs && performArgs.skip;
  21139. // TODO some refactor.
  21140. // Pull data. Must pull data each time, because context.data
  21141. // may be updated by Series.setData.
  21142. if (this._dirty && upTask) {
  21143. var context = this.context;
  21144. context.data = context.outputData = upTask.context.outputData;
  21145. }
  21146. if (this.__pipeline) {
  21147. this.__pipeline.currentTask = this;
  21148. }
  21149. var planResult;
  21150. if (this._plan && !skip) {
  21151. planResult = this._plan(this.context);
  21152. }
  21153. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  21154. // elements uniformed distributed when progress, especially when moving or zooming.
  21155. var lastModBy = normalizeModBy(this._modBy);
  21156. var lastModDataCount = this._modDataCount || 0;
  21157. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  21158. var modDataCount = performArgs && performArgs.modDataCount || 0;
  21159. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  21160. planResult = 'reset';
  21161. }
  21162. function normalizeModBy(val) {
  21163. !(val >= 1) && (val = 1); // jshint ignore:line
  21164. return val;
  21165. }
  21166. var forceFirstProgress;
  21167. if (this._dirty || planResult === 'reset') {
  21168. this._dirty = false;
  21169. forceFirstProgress = reset(this, skip);
  21170. }
  21171. this._modBy = modBy;
  21172. this._modDataCount = modDataCount;
  21173. var step = performArgs && performArgs.step;
  21174. if (upTask) {
  21175. if (__DEV__) {
  21176. assert$1(upTask._outputDueEnd != null);
  21177. }
  21178. this._dueEnd = upTask._outputDueEnd;
  21179. }
  21180. // DataTask or overallTask
  21181. else {
  21182. if (__DEV__) {
  21183. assert$1(!this._progress || this._count);
  21184. }
  21185. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  21186. }
  21187. // Note: Stubs, that its host overall task let it has progress, has progress.
  21188. // If no progress, pass index from upstream to downstream each time plan called.
  21189. if (this._progress) {
  21190. var start = this._dueIndex;
  21191. var end = Math.min(
  21192. step != null ? this._dueIndex + step : Infinity,
  21193. this._dueEnd
  21194. );
  21195. if (!skip && (forceFirstProgress || start < end)) {
  21196. var progress = this._progress;
  21197. if (isArray(progress)) {
  21198. for (var i = 0; i < progress.length; i++) {
  21199. doProgress(this, progress[i], start, end, modBy, modDataCount);
  21200. }
  21201. }
  21202. else {
  21203. doProgress(this, progress, start, end, modBy, modDataCount);
  21204. }
  21205. }
  21206. this._dueIndex = end;
  21207. // If no `outputDueEnd`, assume that output data and
  21208. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  21209. var outputDueEnd = this._settedOutputEnd != null
  21210. ? this._settedOutputEnd : end;
  21211. if (__DEV__) {
  21212. // ??? Can not rollback.
  21213. assert$1(outputDueEnd >= this._outputDueEnd);
  21214. }
  21215. this._outputDueEnd = outputDueEnd;
  21216. }
  21217. else {
  21218. // (1) Some overall task has no progress.
  21219. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  21220. // This should always be performed so it can be passed to downstream.
  21221. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  21222. ? this._settedOutputEnd : this._dueEnd;
  21223. }
  21224. return this.unfinished();
  21225. };
  21226. var iterator = (function () {
  21227. var end;
  21228. var current;
  21229. var modBy;
  21230. var modDataCount;
  21231. var winCount;
  21232. var it = {
  21233. reset: function (s, e, sStep, sCount) {
  21234. current = s;
  21235. end = e;
  21236. modBy = sStep;
  21237. modDataCount = sCount;
  21238. winCount = Math.ceil(modDataCount / modBy);
  21239. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  21240. }
  21241. };
  21242. return it;
  21243. function sequentialNext() {
  21244. return current < end ? current++ : null;
  21245. }
  21246. function modNext() {
  21247. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  21248. var result = current >= end
  21249. ? null
  21250. : dataIndex < modDataCount
  21251. ? dataIndex
  21252. // If modDataCount is smaller than data.count() (consider `appendData` case),
  21253. // Use normal linear rendering mode.
  21254. : current;
  21255. current++;
  21256. return result;
  21257. }
  21258. })();
  21259. taskProto.dirty = function () {
  21260. this._dirty = true;
  21261. this._onDirty && this._onDirty(this.context);
  21262. };
  21263. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  21264. iterator.reset(start, end, modBy, modDataCount);
  21265. taskIns._callingProgress = progress;
  21266. taskIns._callingProgress({
  21267. start: start, end: end, count: end - start, next: iterator.next
  21268. }, taskIns.context);
  21269. }
  21270. function reset(taskIns, skip) {
  21271. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  21272. taskIns._settedOutputEnd = null;
  21273. var progress;
  21274. var forceFirstProgress;
  21275. if (!skip && taskIns._reset) {
  21276. progress = taskIns._reset(taskIns.context);
  21277. if (progress && progress.progress) {
  21278. forceFirstProgress = progress.forceFirstProgress;
  21279. progress = progress.progress;
  21280. }
  21281. // To simplify no progress checking, array must has item.
  21282. if (isArray(progress) && !progress.length) {
  21283. progress = null;
  21284. }
  21285. }
  21286. taskIns._progress = progress;
  21287. taskIns._modBy = taskIns._modDataCount = null;
  21288. var downstream = taskIns._downstream;
  21289. downstream && downstream.dirty();
  21290. return forceFirstProgress;
  21291. }
  21292. /**
  21293. * @return {boolean}
  21294. */
  21295. taskProto.unfinished = function () {
  21296. return this._progress && this._dueIndex < this._dueEnd;
  21297. };
  21298. /**
  21299. * @param {Object} downTask The downstream task.
  21300. * @return {Object} The downstream task.
  21301. */
  21302. taskProto.pipe = function (downTask) {
  21303. if (__DEV__) {
  21304. assert$1(downTask && !downTask._disposed && downTask !== this);
  21305. }
  21306. // If already downstream, do not dirty downTask.
  21307. if (this._downstream !== downTask || this._dirty) {
  21308. this._downstream = downTask;
  21309. downTask._upstream = this;
  21310. downTask.dirty();
  21311. }
  21312. };
  21313. taskProto.dispose = function () {
  21314. if (this._disposed) {
  21315. return;
  21316. }
  21317. this._upstream && (this._upstream._downstream = null);
  21318. this._downstream && (this._downstream._upstream = null);
  21319. this._dirty = false;
  21320. this._disposed = true;
  21321. };
  21322. taskProto.getUpstream = function () {
  21323. return this._upstream;
  21324. };
  21325. taskProto.getDownstream = function () {
  21326. return this._downstream;
  21327. };
  21328. taskProto.setOutputEnd = function (end) {
  21329. // This only happend in dataTask, dataZoom, map, currently.
  21330. // where dataZoom do not set end each time, but only set
  21331. // when reset. So we should record the setted end, in case
  21332. // that the stub of dataZoom perform again and earse the
  21333. // setted end by upstream.
  21334. this._outputDueEnd = this._settedOutputEnd = end;
  21335. };
  21336. ///////////////////////////////////////////////////////////
  21337. // For stream debug (Should be commented out after used!)
  21338. // Usage: printTask(this, 'begin');
  21339. // Usage: printTask(this, null, {someExtraProp});
  21340. // function printTask(task, prefix, extra) {
  21341. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  21342. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  21343. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  21344. // var props = [];
  21345. // if (task.__pipeline) {
  21346. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  21347. // props.push({text: 'idx', value: val});
  21348. // } else {
  21349. // var stubCount = 0;
  21350. // task.agentStubMap.each(() => stubCount++);
  21351. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  21352. // }
  21353. // props.push({text: 'uid', value: task.uidDebug});
  21354. // if (task.__pipeline) {
  21355. // props.push({text: 'pid', value: task.__pipeline.id});
  21356. // task.agent && props.push(
  21357. // {text: 'stubFor', value: task.agent.uidDebug}
  21358. // );
  21359. // }
  21360. // props.push(
  21361. // {text: 'dirty', value: task._dirty},
  21362. // {text: 'dueIndex', value: task._dueIndex},
  21363. // {text: 'dueEnd', value: task._dueEnd},
  21364. // {text: 'outputDueEnd', value: task._outputDueEnd}
  21365. // );
  21366. // if (extra) {
  21367. // Object.keys(extra).forEach(key => {
  21368. // props.push({text: key, value: extra[key]});
  21369. // });
  21370. // }
  21371. // var args = ['color: blue'];
  21372. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  21373. // args.push('color: black', 'color: red'),
  21374. // `${item.text}: %c${item.value}`
  21375. // )).join('%c, ');
  21376. // console.log.apply(console, [msg].concat(args));
  21377. // // console.log(this);
  21378. // }
  21379. /*
  21380. * Licensed to the Apache Software Foundation (ASF) under one
  21381. * or more contributor license agreements. See the NOTICE file
  21382. * distributed with this work for additional information
  21383. * regarding copyright ownership. The ASF licenses this file
  21384. * to you under the Apache License, Version 2.0 (the
  21385. * "License"); you may not use this file except in compliance
  21386. * with the License. You may obtain a copy of the License at
  21387. *
  21388. * http://www.apache.org/licenses/LICENSE-2.0
  21389. *
  21390. * Unless required by applicable law or agreed to in writing,
  21391. * software distributed under the License is distributed on an
  21392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21393. * KIND, either express or implied. See the License for the
  21394. * specific language governing permissions and limitations
  21395. * under the License.
  21396. */
  21397. var inner$4 = makeInner();
  21398. var SeriesModel = ComponentModel.extend({
  21399. type: 'series.__base__',
  21400. /**
  21401. * @readOnly
  21402. */
  21403. seriesIndex: 0,
  21404. // coodinateSystem will be injected in the echarts/CoordinateSystem
  21405. coordinateSystem: null,
  21406. /**
  21407. * @type {Object}
  21408. * @protected
  21409. */
  21410. defaultOption: null,
  21411. /**
  21412. * legend visual provider to the legend component
  21413. * @type {Object}
  21414. */
  21415. // PENDING
  21416. legendVisualProvider: null,
  21417. /**
  21418. * Access path of color for visual
  21419. */
  21420. visualColorAccessPath: 'itemStyle.color',
  21421. /**
  21422. * Access path of borderColor for visual
  21423. */
  21424. visualBorderColorAccessPath: 'itemStyle.borderColor',
  21425. /**
  21426. * Support merge layout params.
  21427. * Only support 'box' now (left/right/top/bottom/width/height).
  21428. * @type {string|Object} Object can be {ignoreSize: true}
  21429. * @readOnly
  21430. */
  21431. layoutMode: null,
  21432. init: function (option, parentModel, ecModel, extraOpt) {
  21433. /**
  21434. * @type {number}
  21435. * @readOnly
  21436. */
  21437. this.seriesIndex = this.componentIndex;
  21438. this.dataTask = createTask({
  21439. count: dataTaskCount,
  21440. reset: dataTaskReset
  21441. });
  21442. this.dataTask.context = {model: this};
  21443. this.mergeDefaultAndTheme(option, ecModel);
  21444. prepareSource(this);
  21445. var data = this.getInitialData(option, ecModel);
  21446. wrapData(data, this);
  21447. this.dataTask.context.data = data;
  21448. if (__DEV__) {
  21449. assert$1(data, 'getInitialData returned invalid data.');
  21450. }
  21451. /**
  21452. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  21453. * @private
  21454. */
  21455. inner$4(this).dataBeforeProcessed = data;
  21456. // If we reverse the order (make data firstly, and then make
  21457. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21458. // cause data.graph.data !== data when using
  21459. // module:echarts/data/Graph or module:echarts/data/Tree.
  21460. // See module:echarts/data/helper/linkList
  21461. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21462. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21463. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21464. // Call `seriesModel.getRawData()` instead.
  21465. // this.restoreData();
  21466. autoSeriesName(this);
  21467. },
  21468. /**
  21469. * Util for merge default and theme to option
  21470. * @param {Object} option
  21471. * @param {module:echarts/model/Global} ecModel
  21472. */
  21473. mergeDefaultAndTheme: function (option, ecModel) {
  21474. var layoutMode = this.layoutMode;
  21475. var inputPositionParams = layoutMode
  21476. ? getLayoutParams(option) : {};
  21477. // Backward compat: using subType on theme.
  21478. // But if name duplicate between series subType
  21479. // (for example: parallel) add component mainType,
  21480. // add suffix 'Series'.
  21481. var themeSubType = this.subType;
  21482. if (ComponentModel.hasClass(themeSubType)) {
  21483. themeSubType += 'Series';
  21484. }
  21485. merge(
  21486. option,
  21487. ecModel.getTheme().get(this.subType)
  21488. );
  21489. merge(option, this.getDefaultOption());
  21490. // Default label emphasis `show`
  21491. defaultEmphasis(option, 'label', ['show']);
  21492. this.fillDataTextStyle(option.data);
  21493. if (layoutMode) {
  21494. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21495. }
  21496. },
  21497. mergeOption: function (newSeriesOption, ecModel) {
  21498. // this.settingTask.dirty();
  21499. newSeriesOption = merge(this.option, newSeriesOption, true);
  21500. this.fillDataTextStyle(newSeriesOption.data);
  21501. var layoutMode = this.layoutMode;
  21502. if (layoutMode) {
  21503. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21504. }
  21505. prepareSource(this);
  21506. var data = this.getInitialData(newSeriesOption, ecModel);
  21507. wrapData(data, this);
  21508. this.dataTask.dirty();
  21509. this.dataTask.context.data = data;
  21510. inner$4(this).dataBeforeProcessed = data;
  21511. autoSeriesName(this);
  21512. },
  21513. fillDataTextStyle: function (data) {
  21514. // Default data label emphasis `show`
  21515. // FIXME Tree structure data ?
  21516. // FIXME Performance ?
  21517. if (data && !isTypedArray(data)) {
  21518. var props = ['show'];
  21519. for (var i = 0; i < data.length; i++) {
  21520. if (data[i] && data[i].label) {
  21521. defaultEmphasis(data[i], 'label', props);
  21522. }
  21523. }
  21524. }
  21525. },
  21526. /**
  21527. * Init a data structure from data related option in series
  21528. * Must be overwritten
  21529. */
  21530. getInitialData: function () {},
  21531. /**
  21532. * Append data to list
  21533. * @param {Object} params
  21534. * @param {Array|TypedArray} params.data
  21535. */
  21536. appendData: function (params) {
  21537. // FIXME ???
  21538. // (1) If data from dataset, forbidden append.
  21539. // (2) support append data of dataset.
  21540. var data = this.getRawData();
  21541. data.appendData(params.data);
  21542. },
  21543. /**
  21544. * Consider some method like `filter`, `map` need make new data,
  21545. * We should make sure that `seriesModel.getData()` get correct
  21546. * data in the stream procedure. So we fetch data from upstream
  21547. * each time `task.perform` called.
  21548. * @param {string} [dataType]
  21549. * @return {module:echarts/data/List}
  21550. */
  21551. getData: function (dataType) {
  21552. var task = getCurrentTask(this);
  21553. if (task) {
  21554. var data = task.context.data;
  21555. return dataType == null ? data : data.getLinkedData(dataType);
  21556. }
  21557. else {
  21558. // When series is not alive (that may happen when click toolbox
  21559. // restore or setOption with not merge mode), series data may
  21560. // be still need to judge animation or something when graphic
  21561. // elements want to know whether fade out.
  21562. return inner$4(this).data;
  21563. }
  21564. },
  21565. /**
  21566. * @param {module:echarts/data/List} data
  21567. */
  21568. setData: function (data) {
  21569. var task = getCurrentTask(this);
  21570. if (task) {
  21571. var context = task.context;
  21572. // Consider case: filter, data sample.
  21573. if (context.data !== data && task.modifyOutputEnd) {
  21574. task.setOutputEnd(data.count());
  21575. }
  21576. context.outputData = data;
  21577. // Caution: setData should update context.data,
  21578. // Because getData may be called multiply in a
  21579. // single stage and expect to get the data just
  21580. // set. (For example, AxisProxy, x y both call
  21581. // getData and setDate sequentially).
  21582. // So the context.data should be fetched from
  21583. // upstream each time when a stage starts to be
  21584. // performed.
  21585. if (task !== this.dataTask) {
  21586. context.data = data;
  21587. }
  21588. }
  21589. inner$4(this).data = data;
  21590. },
  21591. /**
  21592. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21593. * @return {module:echarts/data/Source} source
  21594. */
  21595. getSource: function () {
  21596. return getSource(this);
  21597. },
  21598. /**
  21599. * Get data before processed
  21600. * @return {module:echarts/data/List}
  21601. */
  21602. getRawData: function () {
  21603. return inner$4(this).dataBeforeProcessed;
  21604. },
  21605. /**
  21606. * Get base axis if has coordinate system and has axis.
  21607. * By default use coordSys.getBaseAxis();
  21608. * Can be overrided for some chart.
  21609. * @return {type} description
  21610. */
  21611. getBaseAxis: function () {
  21612. var coordSys = this.coordinateSystem;
  21613. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21614. },
  21615. // FIXME
  21616. /**
  21617. * Default tooltip formatter
  21618. *
  21619. * @param {number} dataIndex
  21620. * @param {boolean} [multipleSeries=false]
  21621. * @param {number} [dataType]
  21622. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21623. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21624. * string is used as DOM HTML content.
  21625. * 'richText' is used for rendering tooltip in rich text form, for those where
  21626. * DOM operation is not supported.
  21627. * @return {Object} formatted tooltip with `html` and `markers`
  21628. */
  21629. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21630. var series = this;
  21631. renderMode = renderMode || 'html';
  21632. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21633. var isRichText = renderMode === 'richText';
  21634. var markers = {};
  21635. var markerId = 0;
  21636. function formatArrayValue(value) {
  21637. // ??? TODO refactor these logic.
  21638. // check: category-no-encode-has-axis-data in dataset.html
  21639. var vertially = reduce(value, function (vertially, val, idx) {
  21640. var dimItem = data.getDimensionInfo(idx);
  21641. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21642. }, 0);
  21643. var result = [];
  21644. tooltipDims.length
  21645. ? each$1(tooltipDims, function (dim) {
  21646. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21647. })
  21648. // By default, all dims is used on tooltip.
  21649. : each$1(value, setEachItem);
  21650. function setEachItem(val, dim) {
  21651. var dimInfo = data.getDimensionInfo(dim);
  21652. // If `dimInfo.tooltip` is not set, show tooltip.
  21653. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21654. return;
  21655. }
  21656. var dimType = dimInfo.type;
  21657. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21658. var dimHead = getTooltipMarker({
  21659. color: color,
  21660. type: 'subItem',
  21661. renderMode: renderMode,
  21662. markerId: markName
  21663. });
  21664. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21665. var valStr = (vertially
  21666. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21667. : ''
  21668. )
  21669. // FIXME should not format time for raw data?
  21670. + encodeHTML(dimType === 'ordinal'
  21671. ? val + ''
  21672. : dimType === 'time'
  21673. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21674. : addCommas(val)
  21675. );
  21676. valStr && result.push(valStr);
  21677. if (isRichText) {
  21678. markers[markName] = color;
  21679. ++markerId;
  21680. }
  21681. }
  21682. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21683. var content = newLine + result.join(newLine || ', ');
  21684. return {
  21685. renderMode: renderMode,
  21686. content: content,
  21687. style: markers
  21688. };
  21689. }
  21690. function formatSingleValue(val) {
  21691. // return encodeHTML(addCommas(val));
  21692. return {
  21693. renderMode: renderMode,
  21694. content: encodeHTML(addCommas(val)),
  21695. style: markers
  21696. };
  21697. }
  21698. var data = this.getData();
  21699. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21700. var tooltipDimLen = tooltipDims.length;
  21701. var value = this.getRawValue(dataIndex);
  21702. var isValueArr = isArray(value);
  21703. var color = data.getItemVisual(dataIndex, 'color');
  21704. if (isObject$1(color) && color.colorStops) {
  21705. color = (color.colorStops[0] || {}).color;
  21706. }
  21707. color = color || 'transparent';
  21708. // Complicated rule for pretty tooltip.
  21709. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21710. ? formatArrayValue(value)
  21711. : tooltipDimLen
  21712. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21713. : formatSingleValue(isValueArr ? value[0] : value);
  21714. var content = formattedValue.content;
  21715. var markName = series.seriesIndex + 'at' + markerId;
  21716. var colorEl = getTooltipMarker({
  21717. color: color,
  21718. type: 'item',
  21719. renderMode: renderMode,
  21720. markerId: markName
  21721. });
  21722. markers[markName] = color;
  21723. ++markerId;
  21724. var name = data.getName(dataIndex);
  21725. var seriesName = this.name;
  21726. if (!isNameSpecified(this)) {
  21727. seriesName = '';
  21728. }
  21729. seriesName = seriesName
  21730. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21731. : '';
  21732. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21733. var html = !multipleSeries
  21734. ? seriesName + colorStr
  21735. + (name
  21736. ? encodeHTML(name) + ': ' + content
  21737. : content
  21738. )
  21739. : colorStr + seriesName + content;
  21740. return {
  21741. html: html,
  21742. markers: markers
  21743. };
  21744. },
  21745. /**
  21746. * @return {boolean}
  21747. */
  21748. isAnimationEnabled: function () {
  21749. if (env$1.node) {
  21750. return false;
  21751. }
  21752. var animationEnabled = this.getShallow('animation');
  21753. if (animationEnabled) {
  21754. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21755. animationEnabled = false;
  21756. }
  21757. }
  21758. return animationEnabled;
  21759. },
  21760. restoreData: function () {
  21761. this.dataTask.dirty();
  21762. },
  21763. getColorFromPalette: function (name, scope, requestColorNum) {
  21764. var ecModel = this.ecModel;
  21765. // PENDING
  21766. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21767. if (!color) {
  21768. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21769. }
  21770. return color;
  21771. },
  21772. /**
  21773. * Use `data.mapDimension(coordDim, true)` instead.
  21774. * @deprecated
  21775. */
  21776. coordDimToDataDim: function (coordDim) {
  21777. return this.getRawData().mapDimension(coordDim, true);
  21778. },
  21779. /**
  21780. * Get progressive rendering count each step
  21781. * @return {number}
  21782. */
  21783. getProgressive: function () {
  21784. return this.get('progressive');
  21785. },
  21786. /**
  21787. * Get progressive rendering count each step
  21788. * @return {number}
  21789. */
  21790. getProgressiveThreshold: function () {
  21791. return this.get('progressiveThreshold');
  21792. },
  21793. /**
  21794. * Get data indices for show tooltip content. See tooltip.
  21795. * @abstract
  21796. * @param {Array.<string>|string} dim
  21797. * @param {Array.<number>} value
  21798. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21799. * @return {Object} {dataIndices, nestestValue}.
  21800. */
  21801. getAxisTooltipData: null,
  21802. /**
  21803. * See tooltip.
  21804. * @abstract
  21805. * @param {number} dataIndex
  21806. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21807. */
  21808. getTooltipPosition: null,
  21809. /**
  21810. * @see {module:echarts/stream/Scheduler}
  21811. */
  21812. pipeTask: null,
  21813. /**
  21814. * Convinient for override in extended class.
  21815. * @protected
  21816. * @type {Function}
  21817. */
  21818. preventIncremental: null,
  21819. /**
  21820. * @public
  21821. * @readOnly
  21822. * @type {Object}
  21823. */
  21824. pipelineContext: null
  21825. });
  21826. mixin(SeriesModel, dataFormatMixin);
  21827. mixin(SeriesModel, colorPaletteMixin);
  21828. /**
  21829. * MUST be called after `prepareSource` called
  21830. * Here we need to make auto series, especially for auto legend. But we
  21831. * do not modify series.name in option to avoid side effects.
  21832. */
  21833. function autoSeriesName(seriesModel) {
  21834. // User specified name has higher priority, otherwise it may cause
  21835. // series can not be queried unexpectedly.
  21836. var name = seriesModel.name;
  21837. if (!isNameSpecified(seriesModel)) {
  21838. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21839. }
  21840. }
  21841. function getSeriesAutoName(seriesModel) {
  21842. var data = seriesModel.getRawData();
  21843. var dataDims = data.mapDimension('seriesName', true);
  21844. var nameArr = [];
  21845. each$1(dataDims, function (dataDim) {
  21846. var dimInfo = data.getDimensionInfo(dataDim);
  21847. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21848. });
  21849. return nameArr.join(' ');
  21850. }
  21851. function dataTaskCount(context) {
  21852. return context.model.getRawData().count();
  21853. }
  21854. function dataTaskReset(context) {
  21855. var seriesModel = context.model;
  21856. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21857. return dataTaskProgress;
  21858. }
  21859. function dataTaskProgress(param, context) {
  21860. // Avoid repead cloneShallow when data just created in reset.
  21861. if (context.outputData && param.end > context.outputData.count()) {
  21862. context.model.getRawData().cloneShallow(context.outputData);
  21863. }
  21864. }
  21865. // TODO refactor
  21866. function wrapData(data, seriesModel) {
  21867. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21868. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21869. });
  21870. }
  21871. function onDataSelfChange(seriesModel) {
  21872. var task = getCurrentTask(seriesModel);
  21873. if (task) {
  21874. // Consider case: filter, selectRange
  21875. task.setOutputEnd(this.count());
  21876. }
  21877. }
  21878. function getCurrentTask(seriesModel) {
  21879. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21880. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21881. if (pipeline) {
  21882. // When pipline finished, the currrentTask keep the last
  21883. // task (renderTask).
  21884. var task = pipeline.currentTask;
  21885. if (task) {
  21886. var agentStubMap = task.agentStubMap;
  21887. if (agentStubMap) {
  21888. task = agentStubMap.get(seriesModel.uid);
  21889. }
  21890. }
  21891. return task;
  21892. }
  21893. }
  21894. /*
  21895. * Licensed to the Apache Software Foundation (ASF) under one
  21896. * or more contributor license agreements. See the NOTICE file
  21897. * distributed with this work for additional information
  21898. * regarding copyright ownership. The ASF licenses this file
  21899. * to you under the Apache License, Version 2.0 (the
  21900. * "License"); you may not use this file except in compliance
  21901. * with the License. You may obtain a copy of the License at
  21902. *
  21903. * http://www.apache.org/licenses/LICENSE-2.0
  21904. *
  21905. * Unless required by applicable law or agreed to in writing,
  21906. * software distributed under the License is distributed on an
  21907. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21908. * KIND, either express or implied. See the License for the
  21909. * specific language governing permissions and limitations
  21910. * under the License.
  21911. */
  21912. var Component$1 = function () {
  21913. /**
  21914. * @type {module:zrender/container/Group}
  21915. * @readOnly
  21916. */
  21917. this.group = new Group();
  21918. /**
  21919. * @type {string}
  21920. * @readOnly
  21921. */
  21922. this.uid = getUID('viewComponent');
  21923. };
  21924. Component$1.prototype = {
  21925. constructor: Component$1,
  21926. init: function (ecModel, api) {},
  21927. render: function (componentModel, ecModel, api, payload) {},
  21928. dispose: function () {},
  21929. /**
  21930. * @param {string} eventType
  21931. * @param {Object} query
  21932. * @param {module:zrender/Element} targetEl
  21933. * @param {Object} packedEvent
  21934. * @return {boolen} Pass only when return `true`.
  21935. */
  21936. filterForExposedEvent: null
  21937. };
  21938. var componentProto = Component$1.prototype;
  21939. componentProto.updateView =
  21940. componentProto.updateLayout =
  21941. componentProto.updateVisual =
  21942. function (seriesModel, ecModel, api, payload) {
  21943. // Do nothing;
  21944. };
  21945. // Enable Component.extend.
  21946. enableClassExtend(Component$1);
  21947. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21948. enableClassManagement(Component$1, {registerWhenExtend: true});
  21949. /*
  21950. * Licensed to the Apache Software Foundation (ASF) under one
  21951. * or more contributor license agreements. See the NOTICE file
  21952. * distributed with this work for additional information
  21953. * regarding copyright ownership. The ASF licenses this file
  21954. * to you under the Apache License, Version 2.0 (the
  21955. * "License"); you may not use this file except in compliance
  21956. * with the License. You may obtain a copy of the License at
  21957. *
  21958. * http://www.apache.org/licenses/LICENSE-2.0
  21959. *
  21960. * Unless required by applicable law or agreed to in writing,
  21961. * software distributed under the License is distributed on an
  21962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21963. * KIND, either express or implied. See the License for the
  21964. * specific language governing permissions and limitations
  21965. * under the License.
  21966. */
  21967. /**
  21968. * @return {string} If large mode changed, return string 'reset';
  21969. */
  21970. var createRenderPlanner = function () {
  21971. var inner = makeInner();
  21972. return function (seriesModel) {
  21973. var fields = inner(seriesModel);
  21974. var pipelineContext = seriesModel.pipelineContext;
  21975. var originalLarge = fields.large;
  21976. var originalProgressive = fields.progressiveRender;
  21977. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  21978. // exists. See #11611 . Probably we need to modify this structure, see the comment
  21979. // on `performRawSeries` in `Schedular.js`.
  21980. var large = fields.large = pipelineContext && pipelineContext.large;
  21981. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  21982. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21983. };
  21984. };
  21985. /*
  21986. * Licensed to the Apache Software Foundation (ASF) under one
  21987. * or more contributor license agreements. See the NOTICE file
  21988. * distributed with this work for additional information
  21989. * regarding copyright ownership. The ASF licenses this file
  21990. * to you under the Apache License, Version 2.0 (the
  21991. * "License"); you may not use this file except in compliance
  21992. * with the License. You may obtain a copy of the License at
  21993. *
  21994. * http://www.apache.org/licenses/LICENSE-2.0
  21995. *
  21996. * Unless required by applicable law or agreed to in writing,
  21997. * software distributed under the License is distributed on an
  21998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21999. * KIND, either express or implied. See the License for the
  22000. * specific language governing permissions and limitations
  22001. * under the License.
  22002. */
  22003. var inner$5 = makeInner();
  22004. var renderPlanner = createRenderPlanner();
  22005. function Chart() {
  22006. /**
  22007. * @type {module:zrender/container/Group}
  22008. * @readOnly
  22009. */
  22010. this.group = new Group();
  22011. /**
  22012. * @type {string}
  22013. * @readOnly
  22014. */
  22015. this.uid = getUID('viewChart');
  22016. this.renderTask = createTask({
  22017. plan: renderTaskPlan,
  22018. reset: renderTaskReset
  22019. });
  22020. this.renderTask.context = {view: this};
  22021. }
  22022. Chart.prototype = {
  22023. type: 'chart',
  22024. /**
  22025. * Init the chart.
  22026. * @param {module:echarts/model/Global} ecModel
  22027. * @param {module:echarts/ExtensionAPI} api
  22028. */
  22029. init: function (ecModel, api) {},
  22030. /**
  22031. * Render the chart.
  22032. * @param {module:echarts/model/Series} seriesModel
  22033. * @param {module:echarts/model/Global} ecModel
  22034. * @param {module:echarts/ExtensionAPI} api
  22035. * @param {Object} payload
  22036. */
  22037. render: function (seriesModel, ecModel, api, payload) {},
  22038. /**
  22039. * Highlight series or specified data item.
  22040. * @param {module:echarts/model/Series} seriesModel
  22041. * @param {module:echarts/model/Global} ecModel
  22042. * @param {module:echarts/ExtensionAPI} api
  22043. * @param {Object} payload
  22044. */
  22045. highlight: function (seriesModel, ecModel, api, payload) {
  22046. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  22047. },
  22048. /**
  22049. * Downplay series or specified data item.
  22050. * @param {module:echarts/model/Series} seriesModel
  22051. * @param {module:echarts/model/Global} ecModel
  22052. * @param {module:echarts/ExtensionAPI} api
  22053. * @param {Object} payload
  22054. */
  22055. downplay: function (seriesModel, ecModel, api, payload) {
  22056. toggleHighlight(seriesModel.getData(), payload, 'normal');
  22057. },
  22058. /**
  22059. * Remove self.
  22060. * @param {module:echarts/model/Global} ecModel
  22061. * @param {module:echarts/ExtensionAPI} api
  22062. */
  22063. remove: function (ecModel, api) {
  22064. this.group.removeAll();
  22065. },
  22066. /**
  22067. * Dispose self.
  22068. * @param {module:echarts/model/Global} ecModel
  22069. * @param {module:echarts/ExtensionAPI} api
  22070. */
  22071. dispose: function () {},
  22072. /**
  22073. * Rendering preparation in progressive mode.
  22074. * @param {module:echarts/model/Series} seriesModel
  22075. * @param {module:echarts/model/Global} ecModel
  22076. * @param {module:echarts/ExtensionAPI} api
  22077. * @param {Object} payload
  22078. */
  22079. incrementalPrepareRender: null,
  22080. /**
  22081. * Render in progressive mode.
  22082. * @param {Object} params See taskParams in `stream/task.js`
  22083. * @param {module:echarts/model/Series} seriesModel
  22084. * @param {module:echarts/model/Global} ecModel
  22085. * @param {module:echarts/ExtensionAPI} api
  22086. * @param {Object} payload
  22087. */
  22088. incrementalRender: null,
  22089. /**
  22090. * Update transform directly.
  22091. * @param {module:echarts/model/Series} seriesModel
  22092. * @param {module:echarts/model/Global} ecModel
  22093. * @param {module:echarts/ExtensionAPI} api
  22094. * @param {Object} payload
  22095. * @return {Object} {update: true}
  22096. */
  22097. updateTransform: null,
  22098. /**
  22099. * The view contains the given point.
  22100. * @interface
  22101. * @param {Array.<number>} point
  22102. * @return {boolean}
  22103. */
  22104. // containPoint: function () {}
  22105. /**
  22106. * @param {string} eventType
  22107. * @param {Object} query
  22108. * @param {module:zrender/Element} targetEl
  22109. * @param {Object} packedEvent
  22110. * @return {boolen} Pass only when return `true`.
  22111. */
  22112. filterForExposedEvent: null
  22113. };
  22114. var chartProto = Chart.prototype;
  22115. chartProto.updateView =
  22116. chartProto.updateLayout =
  22117. chartProto.updateVisual =
  22118. function (seriesModel, ecModel, api, payload) {
  22119. this.render(seriesModel, ecModel, api, payload);
  22120. };
  22121. /**
  22122. * Set state of single element
  22123. * @param {module:zrender/Element} el
  22124. * @param {string} state 'normal'|'emphasis'
  22125. * @param {number} highlightDigit
  22126. */
  22127. function elSetState(el, state, highlightDigit) {
  22128. if (el) {
  22129. el.trigger(state, highlightDigit);
  22130. if (el.isGroup
  22131. // Simple optimize.
  22132. && !isHighDownDispatcher(el)
  22133. ) {
  22134. for (var i = 0, len = el.childCount(); i < len; i++) {
  22135. elSetState(el.childAt(i), state, highlightDigit);
  22136. }
  22137. }
  22138. }
  22139. }
  22140. /**
  22141. * @param {module:echarts/data/List} data
  22142. * @param {Object} payload
  22143. * @param {string} state 'normal'|'emphasis'
  22144. */
  22145. function toggleHighlight(data, payload, state) {
  22146. var dataIndex = queryDataIndex(data, payload);
  22147. var highlightDigit = (payload && payload.highlightKey != null)
  22148. ? getHighlightDigit(payload.highlightKey)
  22149. : null;
  22150. if (dataIndex != null) {
  22151. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  22152. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22153. });
  22154. }
  22155. else {
  22156. data.eachItemGraphicEl(function (el) {
  22157. elSetState(el, state, highlightDigit);
  22158. });
  22159. }
  22160. }
  22161. // Enable Chart.extend.
  22162. enableClassExtend(Chart, ['dispose']);
  22163. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  22164. enableClassManagement(Chart, {registerWhenExtend: true});
  22165. Chart.markUpdateMethod = function (payload, methodName) {
  22166. inner$5(payload).updateMethod = methodName;
  22167. };
  22168. function renderTaskPlan(context) {
  22169. return renderPlanner(context.model);
  22170. }
  22171. function renderTaskReset(context) {
  22172. var seriesModel = context.model;
  22173. var ecModel = context.ecModel;
  22174. var api = context.api;
  22175. var payload = context.payload;
  22176. // ???! remove updateView updateVisual
  22177. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22178. var view = context.view;
  22179. var updateMethod = payload && inner$5(payload).updateMethod;
  22180. var methodName = progressiveRender
  22181. ? 'incrementalPrepareRender'
  22182. : (updateMethod && view[updateMethod])
  22183. ? updateMethod
  22184. // `appendData` is also supported when data amount
  22185. // is less than progressive threshold.
  22186. : 'render';
  22187. if (methodName !== 'render') {
  22188. view[methodName](seriesModel, ecModel, api, payload);
  22189. }
  22190. return progressMethodMap[methodName];
  22191. }
  22192. var progressMethodMap = {
  22193. incrementalPrepareRender: {
  22194. progress: function (params, context) {
  22195. context.view.incrementalRender(
  22196. params, context.model, context.ecModel, context.api, context.payload
  22197. );
  22198. }
  22199. },
  22200. render: {
  22201. // Put view.render in `progress` to support appendData. But in this case
  22202. // view.render should not be called in reset, otherwise it will be called
  22203. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22204. // in any cases.
  22205. forceFirstProgress: true,
  22206. progress: function (params, context) {
  22207. context.view.render(
  22208. context.model, context.ecModel, context.api, context.payload
  22209. );
  22210. }
  22211. }
  22212. };
  22213. /*
  22214. * Licensed to the Apache Software Foundation (ASF) under one
  22215. * or more contributor license agreements. See the NOTICE file
  22216. * distributed with this work for additional information
  22217. * regarding copyright ownership. The ASF licenses this file
  22218. * to you under the Apache License, Version 2.0 (the
  22219. * "License"); you may not use this file except in compliance
  22220. * with the License. You may obtain a copy of the License at
  22221. *
  22222. * http://www.apache.org/licenses/LICENSE-2.0
  22223. *
  22224. * Unless required by applicable law or agreed to in writing,
  22225. * software distributed under the License is distributed on an
  22226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22227. * KIND, either express or implied. See the License for the
  22228. * specific language governing permissions and limitations
  22229. * under the License.
  22230. */
  22231. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22232. var RATE = '\0__throttleRate';
  22233. var THROTTLE_TYPE = '\0__throttleType';
  22234. /**
  22235. * @public
  22236. * @param {(Function)} fn
  22237. * @param {number} [delay=0] Unit: ms.
  22238. * @param {boolean} [debounce=false]
  22239. * true: If call interval less than `delay`, only the last call works.
  22240. * false: If call interval less than `delay, call works on fixed rate.
  22241. * @return {(Function)} throttled fn.
  22242. */
  22243. function throttle(fn, delay, debounce) {
  22244. var currCall;
  22245. var lastCall = 0;
  22246. var lastExec = 0;
  22247. var timer = null;
  22248. var diff;
  22249. var scope;
  22250. var args;
  22251. var debounceNextCall;
  22252. delay = delay || 0;
  22253. function exec() {
  22254. lastExec = (new Date()).getTime();
  22255. timer = null;
  22256. fn.apply(scope, args || []);
  22257. }
  22258. var cb = function () {
  22259. currCall = (new Date()).getTime();
  22260. scope = this;
  22261. args = arguments;
  22262. var thisDelay = debounceNextCall || delay;
  22263. var thisDebounce = debounceNextCall || debounce;
  22264. debounceNextCall = null;
  22265. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22266. clearTimeout(timer);
  22267. // Here we should make sure that: the `exec` SHOULD NOT be called later
  22268. // than a new call of `cb`, that is, preserving the command order. Consider
  22269. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22270. // happens, either the `exec` is called dierectly, or the call is delayed.
  22271. // But the delayed call should never be later than next call of `cb`. Under
  22272. // this assurance, we can simply update view state each time `dispatchAction`
  22273. // triggered by user roaming, but not need to add extra code to avoid the
  22274. // state being "rolled-back".
  22275. if (thisDebounce) {
  22276. timer = setTimeout(exec, thisDelay);
  22277. }
  22278. else {
  22279. if (diff >= 0) {
  22280. exec();
  22281. }
  22282. else {
  22283. timer = setTimeout(exec, -diff);
  22284. }
  22285. }
  22286. lastCall = currCall;
  22287. };
  22288. /**
  22289. * Clear throttle.
  22290. * @public
  22291. */
  22292. cb.clear = function () {
  22293. if (timer) {
  22294. clearTimeout(timer);
  22295. timer = null;
  22296. }
  22297. };
  22298. /**
  22299. * Enable debounce once.
  22300. */
  22301. cb.debounceNextCall = function (debounceDelay) {
  22302. debounceNextCall = debounceDelay;
  22303. };
  22304. return cb;
  22305. }
  22306. /**
  22307. * Create throttle method or update throttle rate.
  22308. *
  22309. * @example
  22310. * ComponentView.prototype.render = function () {
  22311. * ...
  22312. * throttle.createOrUpdate(
  22313. * this,
  22314. * '_dispatchAction',
  22315. * this.model.get('throttle'),
  22316. * 'fixRate'
  22317. * );
  22318. * };
  22319. * ComponentView.prototype.remove = function () {
  22320. * throttle.clear(this, '_dispatchAction');
  22321. * };
  22322. * ComponentView.prototype.dispose = function () {
  22323. * throttle.clear(this, '_dispatchAction');
  22324. * };
  22325. *
  22326. * @public
  22327. * @param {Object} obj
  22328. * @param {string} fnAttr
  22329. * @param {number} [rate]
  22330. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  22331. * @return {Function} throttled function.
  22332. */
  22333. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22334. var fn = obj[fnAttr];
  22335. if (!fn) {
  22336. return;
  22337. }
  22338. var originFn = fn[ORIGIN_METHOD] || fn;
  22339. var lastThrottleType = fn[THROTTLE_TYPE];
  22340. var lastRate = fn[RATE];
  22341. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22342. if (rate == null || !throttleType) {
  22343. return (obj[fnAttr] = originFn);
  22344. }
  22345. fn = obj[fnAttr] = throttle(
  22346. originFn, rate, throttleType === 'debounce'
  22347. );
  22348. fn[ORIGIN_METHOD] = originFn;
  22349. fn[THROTTLE_TYPE] = throttleType;
  22350. fn[RATE] = rate;
  22351. }
  22352. return fn;
  22353. }
  22354. /**
  22355. * Clear throttle. Example see throttle.createOrUpdate.
  22356. *
  22357. * @public
  22358. * @param {Object} obj
  22359. * @param {string} fnAttr
  22360. */
  22361. function clear(obj, fnAttr) {
  22362. var fn = obj[fnAttr];
  22363. if (fn && fn[ORIGIN_METHOD]) {
  22364. obj[fnAttr] = fn[ORIGIN_METHOD];
  22365. }
  22366. }
  22367. /*
  22368. * Licensed to the Apache Software Foundation (ASF) under one
  22369. * or more contributor license agreements. See the NOTICE file
  22370. * distributed with this work for additional information
  22371. * regarding copyright ownership. The ASF licenses this file
  22372. * to you under the Apache License, Version 2.0 (the
  22373. * "License"); you may not use this file except in compliance
  22374. * with the License. You may obtain a copy of the License at
  22375. *
  22376. * http://www.apache.org/licenses/LICENSE-2.0
  22377. *
  22378. * Unless required by applicable law or agreed to in writing,
  22379. * software distributed under the License is distributed on an
  22380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22381. * KIND, either express or implied. See the License for the
  22382. * specific language governing permissions and limitations
  22383. * under the License.
  22384. */
  22385. var seriesColor = {
  22386. createOnAllSeries: true,
  22387. performRawSeries: true,
  22388. reset: function (seriesModel, ecModel) {
  22389. var data = seriesModel.getData();
  22390. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  22391. // Set in itemStyle
  22392. var color = seriesModel.get(colorAccessPath);
  22393. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  22394. ? color : null;
  22395. // Default color
  22396. if (!color || colorCallback) {
  22397. color = seriesModel.getColorFromPalette(
  22398. // TODO series count changed.
  22399. seriesModel.name, null, ecModel.getSeriesCount()
  22400. );
  22401. }
  22402. data.setVisual('color', color);
  22403. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  22404. var borderColor = seriesModel.get(borderColorAccessPath);
  22405. data.setVisual('borderColor', borderColor);
  22406. // Only visible series has each data be visual encoded
  22407. if (!ecModel.isSeriesFiltered(seriesModel)) {
  22408. if (colorCallback) {
  22409. data.each(function (idx) {
  22410. data.setItemVisual(
  22411. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  22412. );
  22413. });
  22414. }
  22415. // itemStyle in each data item
  22416. var dataEach = function (data, idx) {
  22417. var itemModel = data.getItemModel(idx);
  22418. var color = itemModel.get(colorAccessPath, true);
  22419. var borderColor = itemModel.get(borderColorAccessPath, true);
  22420. if (color != null) {
  22421. data.setItemVisual(idx, 'color', color);
  22422. }
  22423. if (borderColor != null) {
  22424. data.setItemVisual(idx, 'borderColor', borderColor);
  22425. }
  22426. };
  22427. return { dataEach: data.hasItemOption ? dataEach : null };
  22428. }
  22429. }
  22430. };
  22431. /*
  22432. * Licensed to the Apache Software Foundation (ASF) under one
  22433. * or more contributor license agreements. See the NOTICE file
  22434. * distributed with this work for additional information
  22435. * regarding copyright ownership. The ASF licenses this file
  22436. * to you under the Apache License, Version 2.0 (the
  22437. * "License"); you may not use this file except in compliance
  22438. * with the License. You may obtain a copy of the License at
  22439. *
  22440. * http://www.apache.org/licenses/LICENSE-2.0
  22441. *
  22442. * Unless required by applicable law or agreed to in writing,
  22443. * software distributed under the License is distributed on an
  22444. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22445. * KIND, either express or implied. See the License for the
  22446. * specific language governing permissions and limitations
  22447. * under the License.
  22448. */
  22449. /**
  22450. * Language: English.
  22451. */
  22452. var lang = {
  22453. legend: {
  22454. selector: {
  22455. all: 'All',
  22456. inverse: 'Inv'
  22457. }
  22458. },
  22459. toolbox: {
  22460. brush: {
  22461. title: {
  22462. rect: 'Box Select',
  22463. polygon: 'Lasso Select',
  22464. lineX: 'Horizontally Select',
  22465. lineY: 'Vertically Select',
  22466. keep: 'Keep Selections',
  22467. clear: 'Clear Selections'
  22468. }
  22469. },
  22470. dataView: {
  22471. title: 'Data View',
  22472. lang: ['Data View', 'Close', 'Refresh']
  22473. },
  22474. dataZoom: {
  22475. title: {
  22476. zoom: 'Zoom',
  22477. back: 'Zoom Reset'
  22478. }
  22479. },
  22480. magicType: {
  22481. title: {
  22482. line: 'Switch to Line Chart',
  22483. bar: 'Switch to Bar Chart',
  22484. stack: 'Stack',
  22485. tiled: 'Tile'
  22486. }
  22487. },
  22488. restore: {
  22489. title: 'Restore'
  22490. },
  22491. saveAsImage: {
  22492. title: 'Save as Image',
  22493. lang: ['Right Click to Save Image']
  22494. }
  22495. },
  22496. series: {
  22497. typeNames: {
  22498. pie: 'Pie chart',
  22499. bar: 'Bar chart',
  22500. line: 'Line chart',
  22501. scatter: 'Scatter plot',
  22502. effectScatter: 'Ripple scatter plot',
  22503. radar: 'Radar chart',
  22504. tree: 'Tree',
  22505. treemap: 'Treemap',
  22506. boxplot: 'Boxplot',
  22507. candlestick: 'Candlestick',
  22508. k: 'K line chart',
  22509. heatmap: 'Heat map',
  22510. map: 'Map',
  22511. parallel: 'Parallel coordinate map',
  22512. lines: 'Line graph',
  22513. graph: 'Relationship graph',
  22514. sankey: 'Sankey diagram',
  22515. funnel: 'Funnel chart',
  22516. gauge: 'Guage',
  22517. pictorialBar: 'Pictorial bar',
  22518. themeRiver: 'Theme River Map',
  22519. sunburst: 'Sunburst'
  22520. }
  22521. },
  22522. aria: {
  22523. general: {
  22524. withTitle: 'This is a chart about "{title}"',
  22525. withoutTitle: 'This is a chart'
  22526. },
  22527. series: {
  22528. single: {
  22529. prefix: '',
  22530. withName: ' with type {seriesType} named {seriesName}.',
  22531. withoutName: ' with type {seriesType}.'
  22532. },
  22533. multiple: {
  22534. prefix: '. It consists of {seriesCount} series count.',
  22535. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  22536. withoutName: ' The {seriesId} series is a {seriesType}.',
  22537. separator: {
  22538. middle: '',
  22539. end: ''
  22540. }
  22541. }
  22542. },
  22543. data: {
  22544. allData: 'The data is as follows: ',
  22545. partialData: 'The first {displayCnt} items are: ',
  22546. withName: 'the data for {name} is {value}',
  22547. withoutName: '{value}',
  22548. separator: {
  22549. middle: ',',
  22550. end: '.'
  22551. }
  22552. }
  22553. }
  22554. };
  22555. /*
  22556. * Licensed to the Apache Software Foundation (ASF) under one
  22557. * or more contributor license agreements. See the NOTICE file
  22558. * distributed with this work for additional information
  22559. * regarding copyright ownership. The ASF licenses this file
  22560. * to you under the Apache License, Version 2.0 (the
  22561. * "License"); you may not use this file except in compliance
  22562. * with the License. You may obtain a copy of the License at
  22563. *
  22564. * http://www.apache.org/licenses/LICENSE-2.0
  22565. *
  22566. * Unless required by applicable law or agreed to in writing,
  22567. * software distributed under the License is distributed on an
  22568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22569. * KIND, either express or implied. See the License for the
  22570. * specific language governing permissions and limitations
  22571. * under the License.
  22572. */
  22573. var aria = function (dom, ecModel) {
  22574. var ariaModel = ecModel.getModel('aria');
  22575. if (!ariaModel.get('show')) {
  22576. return;
  22577. }
  22578. else if (ariaModel.get('description')) {
  22579. dom.setAttribute('aria-label', ariaModel.get('description'));
  22580. return;
  22581. }
  22582. var seriesCnt = 0;
  22583. ecModel.eachSeries(function (seriesModel, idx) {
  22584. ++seriesCnt;
  22585. }, this);
  22586. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  22587. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  22588. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  22589. var ariaLabel;
  22590. if (seriesCnt < 1) {
  22591. // No series, no aria label
  22592. return;
  22593. }
  22594. else {
  22595. var title = getTitle();
  22596. if (title) {
  22597. ariaLabel = replace(getConfig('general.withTitle'), {
  22598. title: title
  22599. });
  22600. }
  22601. else {
  22602. ariaLabel = getConfig('general.withoutTitle');
  22603. }
  22604. var seriesLabels = [];
  22605. var prefix = seriesCnt > 1
  22606. ? 'series.multiple.prefix'
  22607. : 'series.single.prefix';
  22608. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22609. ecModel.eachSeries(function (seriesModel, idx) {
  22610. if (idx < displaySeriesCnt) {
  22611. var seriesLabel;
  22612. var seriesName = seriesModel.get('name');
  22613. var seriesTpl = 'series.'
  22614. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22615. seriesLabel = getConfig(seriesName
  22616. ? seriesTpl + 'withName'
  22617. : seriesTpl + 'withoutName');
  22618. seriesLabel = replace(seriesLabel, {
  22619. seriesId: seriesModel.seriesIndex,
  22620. seriesName: seriesModel.get('name'),
  22621. seriesType: getSeriesTypeName(seriesModel.subType)
  22622. });
  22623. var data = seriesModel.getData();
  22624. window.data = data;
  22625. if (data.count() > maxDataCnt) {
  22626. // Show part of data
  22627. seriesLabel += replace(getConfig('data.partialData'), {
  22628. displayCnt: maxDataCnt
  22629. });
  22630. }
  22631. else {
  22632. seriesLabel += getConfig('data.allData');
  22633. }
  22634. var dataLabels = [];
  22635. for (var i = 0; i < data.count(); i++) {
  22636. if (i < maxDataCnt) {
  22637. var name = data.getName(i);
  22638. var value = retrieveRawValue(data, i);
  22639. dataLabels.push(
  22640. replace(
  22641. name
  22642. ? getConfig('data.withName')
  22643. : getConfig('data.withoutName'),
  22644. {
  22645. name: name,
  22646. value: value
  22647. }
  22648. )
  22649. );
  22650. }
  22651. }
  22652. seriesLabel += dataLabels
  22653. .join(getConfig('data.separator.middle'))
  22654. + getConfig('data.separator.end');
  22655. seriesLabels.push(seriesLabel);
  22656. }
  22657. });
  22658. ariaLabel += seriesLabels
  22659. .join(getConfig('series.multiple.separator.middle'))
  22660. + getConfig('series.multiple.separator.end');
  22661. dom.setAttribute('aria-label', ariaLabel);
  22662. }
  22663. function replace(str, keyValues) {
  22664. if (typeof str !== 'string') {
  22665. return str;
  22666. }
  22667. var result = str;
  22668. each$1(keyValues, function (value, key) {
  22669. result = result.replace(
  22670. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22671. value
  22672. );
  22673. });
  22674. return result;
  22675. }
  22676. function getConfig(path) {
  22677. var userConfig = ariaModel.get(path);
  22678. if (userConfig == null) {
  22679. var pathArr = path.split('.');
  22680. var result = lang.aria;
  22681. for (var i = 0; i < pathArr.length; ++i) {
  22682. result = result[pathArr[i]];
  22683. }
  22684. return result;
  22685. }
  22686. else {
  22687. return userConfig;
  22688. }
  22689. }
  22690. function getTitle() {
  22691. var title = ecModel.getModel('title').option;
  22692. if (title && title.length) {
  22693. title = title[0];
  22694. }
  22695. return title && title.text;
  22696. }
  22697. function getSeriesTypeName(type) {
  22698. return lang.series.typeNames[type] || '自定义图';
  22699. }
  22700. };
  22701. /*
  22702. * Licensed to the Apache Software Foundation (ASF) under one
  22703. * or more contributor license agreements. See the NOTICE file
  22704. * distributed with this work for additional information
  22705. * regarding copyright ownership. The ASF licenses this file
  22706. * to you under the Apache License, Version 2.0 (the
  22707. * "License"); you may not use this file except in compliance
  22708. * with the License. You may obtain a copy of the License at
  22709. *
  22710. * http://www.apache.org/licenses/LICENSE-2.0
  22711. *
  22712. * Unless required by applicable law or agreed to in writing,
  22713. * software distributed under the License is distributed on an
  22714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22715. * KIND, either express or implied. See the License for the
  22716. * specific language governing permissions and limitations
  22717. * under the License.
  22718. */
  22719. var PI$1 = Math.PI;
  22720. /**
  22721. * @param {module:echarts/ExtensionAPI} api
  22722. * @param {Object} [opts]
  22723. * @param {string} [opts.text]
  22724. * @param {string} [opts.color]
  22725. * @param {string} [opts.textColor]
  22726. * @return {module:zrender/Element}
  22727. */
  22728. var loadingDefault = function (api, opts) {
  22729. opts = opts || {};
  22730. defaults(opts, {
  22731. text: 'loading',
  22732. textColor: '#000',
  22733. fontSize: '12px',
  22734. maskColor: 'rgba(255, 255, 255, 0.8)',
  22735. showSpinner: true,
  22736. color: '#c23531',
  22737. spinnerRadius: 10,
  22738. lineWidth: 5,
  22739. zlevel: 0
  22740. });
  22741. var group = new Group();
  22742. var mask = new Rect({
  22743. style: {
  22744. fill: opts.maskColor
  22745. },
  22746. zlevel: opts.zlevel,
  22747. z: 10000
  22748. });
  22749. group.add(mask);
  22750. var font = opts.fontSize + ' sans-serif';
  22751. var labelRect = new Rect({
  22752. style: {
  22753. fill: 'none',
  22754. text: opts.text,
  22755. font: font,
  22756. textPosition: 'right',
  22757. textDistance: 10,
  22758. textFill: opts.textColor
  22759. },
  22760. zlevel: opts.zlevel,
  22761. z: 10001
  22762. });
  22763. group.add(labelRect);
  22764. if (opts.showSpinner) {
  22765. var arc = new Arc({
  22766. shape: {
  22767. startAngle: -PI$1 / 2,
  22768. endAngle: -PI$1 / 2 + 0.1,
  22769. r: opts.spinnerRadius
  22770. },
  22771. style: {
  22772. stroke: opts.color,
  22773. lineCap: 'round',
  22774. lineWidth: opts.lineWidth
  22775. },
  22776. zlevel: opts.zlevel,
  22777. z: 10001
  22778. });
  22779. arc.animateShape(true)
  22780. .when(1000, {
  22781. endAngle: PI$1 * 3 / 2
  22782. })
  22783. .start('circularInOut');
  22784. arc.animateShape(true)
  22785. .when(1000, {
  22786. startAngle: PI$1 * 3 / 2
  22787. })
  22788. .delay(300)
  22789. .start('circularInOut');
  22790. group.add(arc);
  22791. }
  22792. // Inject resize
  22793. group.resize = function () {
  22794. var textWidth = getWidth(opts.text, font);
  22795. var r = opts.showSpinner ? opts.spinnerRadius : 0;
  22796. // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22797. // textDistance needs to be calculated when both animation and text exist
  22798. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2
  22799. // only show the text
  22800. - (opts.showSpinner ? 0 : textWidth / 2);
  22801. var cy = api.getHeight() / 2;
  22802. opts.showSpinner && arc.setShape({
  22803. cx: cx,
  22804. cy: cy
  22805. });
  22806. labelRect.setShape({
  22807. x: cx - r,
  22808. y: cy - r,
  22809. width: r * 2,
  22810. height: r * 2
  22811. });
  22812. mask.setShape({
  22813. x: 0,
  22814. y: 0,
  22815. width: api.getWidth(),
  22816. height: api.getHeight()
  22817. });
  22818. };
  22819. group.resize();
  22820. return group;
  22821. };
  22822. /*
  22823. * Licensed to the Apache Software Foundation (ASF) under one
  22824. * or more contributor license agreements. See the NOTICE file
  22825. * distributed with this work for additional information
  22826. * regarding copyright ownership. The ASF licenses this file
  22827. * to you under the Apache License, Version 2.0 (the
  22828. * "License"); you may not use this file except in compliance
  22829. * with the License. You may obtain a copy of the License at
  22830. *
  22831. * http://www.apache.org/licenses/LICENSE-2.0
  22832. *
  22833. * Unless required by applicable law or agreed to in writing,
  22834. * software distributed under the License is distributed on an
  22835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22836. * KIND, either express or implied. See the License for the
  22837. * specific language governing permissions and limitations
  22838. * under the License.
  22839. */
  22840. /**
  22841. * @module echarts/stream/Scheduler
  22842. */
  22843. /**
  22844. * @constructor
  22845. */
  22846. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22847. this.ecInstance = ecInstance;
  22848. this.api = api;
  22849. this.unfinished;
  22850. // Fix current processors in case that in some rear cases that
  22851. // processors might be registered after echarts instance created.
  22852. // Register processors incrementally for a echarts instance is
  22853. // not supported by this stream architecture.
  22854. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22855. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22856. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22857. /**
  22858. * @private
  22859. * @type {
  22860. * [handlerUID: string]: {
  22861. * seriesTaskMap?: {
  22862. * [seriesUID: string]: Task
  22863. * },
  22864. * overallTask?: Task
  22865. * }
  22866. * }
  22867. */
  22868. this._stageTaskMap = createHashMap();
  22869. }
  22870. var proto = Scheduler.prototype;
  22871. /**
  22872. * @param {module:echarts/model/Global} ecModel
  22873. * @param {Object} payload
  22874. */
  22875. proto.restoreData = function (ecModel, payload) {
  22876. // TODO: Only restroe needed series and components, but not all components.
  22877. // Currently `restoreData` of all of the series and component will be called.
  22878. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22879. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22880. // and some components like coordinate system, axes, dataZoom, visualMap only
  22881. // need their target series refresh.
  22882. // (1) If we are implementing this feature some day, we should consider these cases:
  22883. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22884. // on the settings of `dataZoom`), it should be re-performed if the component
  22885. // is modified by `setOption`.
  22886. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22887. // it should be re-performed when the result array of `getTargetSeries` changed.
  22888. // We use `dependencies` to cover these issues.
  22889. // (3) How to update target series when coordinate system related components modified.
  22890. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22891. // and this case all of the tasks will be set as dirty.
  22892. ecModel.restoreData(payload);
  22893. // Theoretically an overall task not only depends on each of its target series, but also
  22894. // depends on all of the series.
  22895. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22896. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22897. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22898. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22899. // probably cause state chaos (consider `dataZoomProcessor`).
  22900. this._stageTaskMap.each(function (taskRecord) {
  22901. var overallTask = taskRecord.overallTask;
  22902. overallTask && overallTask.dirty();
  22903. });
  22904. };
  22905. // If seriesModel provided, incremental threshold is check by series data.
  22906. proto.getPerformArgs = function (task, isBlock) {
  22907. // For overall task
  22908. if (!task.__pipeline) {
  22909. return;
  22910. }
  22911. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22912. var pCtx = pipeline.context;
  22913. var incremental = !isBlock
  22914. && pipeline.progressiveEnabled
  22915. && (!pCtx || pCtx.progressiveRender)
  22916. && task.__idxInPipeline > pipeline.blockIndex;
  22917. var step = incremental ? pipeline.step : null;
  22918. var modDataCount = pCtx && pCtx.modDataCount;
  22919. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22920. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22921. };
  22922. proto.getPipeline = function (pipelineId) {
  22923. return this._pipelineMap.get(pipelineId);
  22924. };
  22925. /**
  22926. * Current, progressive rendering starts from visual and layout.
  22927. * Always detect render mode in the same stage, avoiding that incorrect
  22928. * detection caused by data filtering.
  22929. * Caution:
  22930. * `updateStreamModes` use `seriesModel.getData()`.
  22931. */
  22932. proto.updateStreamModes = function (seriesModel, view) {
  22933. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22934. var data = seriesModel.getData();
  22935. var dataLen = data.count();
  22936. // `progressiveRender` means that can render progressively in each
  22937. // animation frame. Note that some types of series do not provide
  22938. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22939. // use the term `incremental` but not `progressive` to describe the
  22940. // case that `chart.appendData`.
  22941. var progressiveRender = pipeline.progressiveEnabled
  22942. && view.incrementalPrepareRender
  22943. && dataLen >= pipeline.threshold;
  22944. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22945. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22946. // see `test/candlestick-large3.html`
  22947. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22948. seriesModel.pipelineContext = pipeline.context = {
  22949. progressiveRender: progressiveRender,
  22950. modDataCount: modDataCount,
  22951. large: large
  22952. };
  22953. };
  22954. proto.restorePipelines = function (ecModel) {
  22955. var scheduler = this;
  22956. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22957. ecModel.eachSeries(function (seriesModel) {
  22958. var progressive = seriesModel.getProgressive();
  22959. var pipelineId = seriesModel.uid;
  22960. pipelineMap.set(pipelineId, {
  22961. id: pipelineId,
  22962. head: null,
  22963. tail: null,
  22964. threshold: seriesModel.getProgressiveThreshold(),
  22965. progressiveEnabled: progressive
  22966. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22967. blockIndex: -1,
  22968. step: Math.round(progressive || 700),
  22969. count: 0
  22970. });
  22971. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22972. });
  22973. };
  22974. proto.prepareStageTasks = function () {
  22975. var stageTaskMap = this._stageTaskMap;
  22976. var ecModel = this.ecInstance.getModel();
  22977. var api = this.api;
  22978. each$1(this._allHandlers, function (handler) {
  22979. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22980. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22981. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22982. }, this);
  22983. };
  22984. proto.prepareView = function (view, model, ecModel, api) {
  22985. var renderTask = view.renderTask;
  22986. var context = renderTask.context;
  22987. context.model = model;
  22988. context.ecModel = ecModel;
  22989. context.api = api;
  22990. renderTask.__block = !view.incrementalPrepareRender;
  22991. pipe(this, model, renderTask);
  22992. };
  22993. proto.performDataProcessorTasks = function (ecModel, payload) {
  22994. // If we do not use `block` here, it should be considered when to update modes.
  22995. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22996. };
  22997. // opt
  22998. // opt.visualType: 'visual' or 'layout'
  22999. // opt.setDirty
  23000. proto.performVisualTasks = function (ecModel, payload, opt) {
  23001. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  23002. };
  23003. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  23004. opt = opt || {};
  23005. var unfinished;
  23006. each$1(stageHandlers, function (stageHandler, idx) {
  23007. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23008. return;
  23009. }
  23010. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23011. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23012. var overallTask = stageHandlerRecord.overallTask;
  23013. if (overallTask) {
  23014. var overallNeedDirty;
  23015. var agentStubMap = overallTask.agentStubMap;
  23016. agentStubMap.each(function (stub) {
  23017. if (needSetDirty(opt, stub)) {
  23018. stub.dirty();
  23019. overallNeedDirty = true;
  23020. }
  23021. });
  23022. overallNeedDirty && overallTask.dirty();
  23023. updatePayload(overallTask, payload);
  23024. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  23025. // Execute stubs firstly, which may set the overall task dirty,
  23026. // then execute the overall task. And stub will call seriesModel.setData,
  23027. // which ensures that in the overallTask seriesModel.getData() will not
  23028. // return incorrect data.
  23029. agentStubMap.each(function (stub) {
  23030. stub.perform(performArgs);
  23031. });
  23032. unfinished |= overallTask.perform(performArgs);
  23033. }
  23034. else if (seriesTaskMap) {
  23035. seriesTaskMap.each(function (task, pipelineId) {
  23036. if (needSetDirty(opt, task)) {
  23037. task.dirty();
  23038. }
  23039. var performArgs = scheduler.getPerformArgs(task, opt.block);
  23040. // FIXME
  23041. // if intending to decalare `performRawSeries` in handlers, only
  23042. // stream-independent (specifically, data item independent) operations can be
  23043. // performed. Because is a series is filtered, most of the tasks will not
  23044. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23045. // Perhaps we should not provide a separate callback for this case instead
  23046. // of providing the config `performRawSeries`. The stream-dependent operaions
  23047. // and stream-independent operations should better not be mixed.
  23048. performArgs.skip = !stageHandler.performRawSeries
  23049. && ecModel.isSeriesFiltered(task.context.model);
  23050. updatePayload(task, payload);
  23051. unfinished |= task.perform(performArgs);
  23052. });
  23053. }
  23054. });
  23055. function needSetDirty(opt, task) {
  23056. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23057. }
  23058. scheduler.unfinished |= unfinished;
  23059. }
  23060. proto.performSeriesTasks = function (ecModel) {
  23061. var unfinished;
  23062. ecModel.eachSeries(function (seriesModel) {
  23063. // Progress to the end for dataInit and dataRestore.
  23064. unfinished |= seriesModel.dataTask.perform();
  23065. });
  23066. this.unfinished |= unfinished;
  23067. };
  23068. proto.plan = function () {
  23069. // Travel pipelines, check block.
  23070. this._pipelineMap.each(function (pipeline) {
  23071. var task = pipeline.tail;
  23072. do {
  23073. if (task.__block) {
  23074. pipeline.blockIndex = task.__idxInPipeline;
  23075. break;
  23076. }
  23077. task = task.getUpstream();
  23078. }
  23079. while (task);
  23080. });
  23081. };
  23082. var updatePayload = proto.updatePayload = function (task, payload) {
  23083. payload !== 'remain' && (task.context.payload = payload);
  23084. };
  23085. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23086. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  23087. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  23088. var seriesType = stageHandler.seriesType;
  23089. var getTargetSeries = stageHandler.getTargetSeries;
  23090. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23091. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23092. // it works but it may cause other irrelevant charts blocked.
  23093. if (stageHandler.createOnAllSeries) {
  23094. ecModel.eachRawSeries(create);
  23095. }
  23096. else if (seriesType) {
  23097. ecModel.eachRawSeriesByType(seriesType, create);
  23098. }
  23099. else if (getTargetSeries) {
  23100. getTargetSeries(ecModel, api).each(create);
  23101. }
  23102. function create(seriesModel) {
  23103. var pipelineId = seriesModel.uid;
  23104. // Init tasks for each seriesModel only once.
  23105. // Reuse original task instance.
  23106. var task = seriesTaskMap.get(pipelineId)
  23107. || seriesTaskMap.set(pipelineId, createTask({
  23108. plan: seriesTaskPlan,
  23109. reset: seriesTaskReset,
  23110. count: seriesTaskCount
  23111. }));
  23112. task.context = {
  23113. model: seriesModel,
  23114. ecModel: ecModel,
  23115. api: api,
  23116. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23117. plan: stageHandler.plan,
  23118. reset: stageHandler.reset,
  23119. scheduler: scheduler
  23120. };
  23121. pipe(scheduler, seriesModel, task);
  23122. }
  23123. // Clear unused series tasks.
  23124. var pipelineMap = scheduler._pipelineMap;
  23125. seriesTaskMap.each(function (task, pipelineId) {
  23126. if (!pipelineMap.get(pipelineId)) {
  23127. task.dispose();
  23128. seriesTaskMap.removeKey(pipelineId);
  23129. }
  23130. });
  23131. }
  23132. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  23133. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  23134. // For overall task, the function only be called on reset stage.
  23135. || createTask({reset: overallTaskReset});
  23136. overallTask.context = {
  23137. ecModel: ecModel,
  23138. api: api,
  23139. overallReset: stageHandler.overallReset,
  23140. scheduler: scheduler
  23141. };
  23142. // Reuse orignal stubs.
  23143. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  23144. var seriesType = stageHandler.seriesType;
  23145. var getTargetSeries = stageHandler.getTargetSeries;
  23146. var overallProgress = true;
  23147. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  23148. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23149. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23150. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23151. // we set the pipeline block.
  23152. if (seriesType) {
  23153. ecModel.eachRawSeriesByType(seriesType, createStub);
  23154. }
  23155. else if (getTargetSeries) {
  23156. getTargetSeries(ecModel, api).each(createStub);
  23157. }
  23158. // Otherwise, (usually it is legancy case), the overall task will only be
  23159. // executed when upstream dirty. Otherwise the progressive rendering of all
  23160. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23161. // dirty info from upsteam.
  23162. else {
  23163. overallProgress = false;
  23164. each$1(ecModel.getSeries(), createStub);
  23165. }
  23166. function createStub(seriesModel) {
  23167. var pipelineId = seriesModel.uid;
  23168. var stub = agentStubMap.get(pipelineId);
  23169. if (!stub) {
  23170. stub = agentStubMap.set(pipelineId, createTask(
  23171. {reset: stubReset, onDirty: stubOnDirty}
  23172. ));
  23173. // When the result of `getTargetSeries` changed, the overallTask
  23174. // should be set as dirty and re-performed.
  23175. overallTask.dirty();
  23176. }
  23177. stub.context = {
  23178. model: seriesModel,
  23179. overallProgress: overallProgress,
  23180. modifyOutputEnd: modifyOutputEnd
  23181. };
  23182. stub.agent = overallTask;
  23183. stub.__block = overallProgress;
  23184. pipe(scheduler, seriesModel, stub);
  23185. }
  23186. // Clear unused stubs.
  23187. var pipelineMap = scheduler._pipelineMap;
  23188. agentStubMap.each(function (stub, pipelineId) {
  23189. if (!pipelineMap.get(pipelineId)) {
  23190. stub.dispose();
  23191. // When the result of `getTargetSeries` changed, the overallTask
  23192. // should be set as dirty and re-performed.
  23193. overallTask.dirty();
  23194. agentStubMap.removeKey(pipelineId);
  23195. }
  23196. });
  23197. }
  23198. function overallTaskReset(context) {
  23199. context.overallReset(
  23200. context.ecModel, context.api, context.payload
  23201. );
  23202. }
  23203. function stubReset(context, upstreamContext) {
  23204. return context.overallProgress && stubProgress;
  23205. }
  23206. function stubProgress() {
  23207. this.agent.dirty();
  23208. this.getDownstream().dirty();
  23209. }
  23210. function stubOnDirty() {
  23211. this.agent && this.agent.dirty();
  23212. }
  23213. function seriesTaskPlan(context) {
  23214. return context.plan && context.plan(
  23215. context.model, context.ecModel, context.api, context.payload
  23216. );
  23217. }
  23218. function seriesTaskReset(context) {
  23219. if (context.useClearVisual) {
  23220. context.data.clearAllVisual();
  23221. }
  23222. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  23223. context.model, context.ecModel, context.api, context.payload
  23224. ));
  23225. return resetDefines.length > 1
  23226. ? map(resetDefines, function (v, idx) {
  23227. return makeSeriesTaskProgress(idx);
  23228. })
  23229. : singleSeriesTaskProgress;
  23230. }
  23231. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23232. function makeSeriesTaskProgress(resetDefineIdx) {
  23233. return function (params, context) {
  23234. var data = context.data;
  23235. var resetDefine = context.resetDefines[resetDefineIdx];
  23236. if (resetDefine && resetDefine.dataEach) {
  23237. for (var i = params.start; i < params.end; i++) {
  23238. resetDefine.dataEach(data, i);
  23239. }
  23240. }
  23241. else if (resetDefine && resetDefine.progress) {
  23242. resetDefine.progress(params, data);
  23243. }
  23244. };
  23245. }
  23246. function seriesTaskCount(context) {
  23247. return context.data.count();
  23248. }
  23249. function pipe(scheduler, seriesModel, task) {
  23250. var pipelineId = seriesModel.uid;
  23251. var pipeline = scheduler._pipelineMap.get(pipelineId);
  23252. !pipeline.head && (pipeline.head = task);
  23253. pipeline.tail && pipeline.tail.pipe(task);
  23254. pipeline.tail = task;
  23255. task.__idxInPipeline = pipeline.count++;
  23256. task.__pipeline = pipeline;
  23257. }
  23258. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23259. if (isFunction$1(stageHandler)) {
  23260. stageHandler = {
  23261. overallReset: stageHandler,
  23262. seriesType: detectSeriseType(stageHandler)
  23263. };
  23264. }
  23265. stageHandler.uid = getUID('stageHandler');
  23266. visualType && (stageHandler.visualType = visualType);
  23267. return stageHandler;
  23268. };
  23269. /**
  23270. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23271. * To ensure that they can work normally, they should work in block mode, that is,
  23272. * they should not be started util the previous tasks finished. So they cause the
  23273. * progressive rendering disabled. We try to detect the series type, to narrow down
  23274. * the block range to only the series type they concern, but not all series.
  23275. */
  23276. function detectSeriseType(legacyFunc) {
  23277. seriesType = null;
  23278. try {
  23279. // Assume there is no async when calling `eachSeriesByType`.
  23280. legacyFunc(ecModelMock, apiMock);
  23281. }
  23282. catch (e) {
  23283. }
  23284. return seriesType;
  23285. }
  23286. var ecModelMock = {};
  23287. var apiMock = {};
  23288. var seriesType;
  23289. mockMethods(ecModelMock, GlobalModel);
  23290. mockMethods(apiMock, ExtensionAPI);
  23291. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23292. seriesType = type;
  23293. };
  23294. ecModelMock.eachComponent = function (cond) {
  23295. if (cond.mainType === 'series' && cond.subType) {
  23296. seriesType = cond.subType;
  23297. }
  23298. };
  23299. function mockMethods(target, Clz) {
  23300. /* eslint-disable */
  23301. for (var name in Clz.prototype) {
  23302. // Do not use hasOwnProperty
  23303. target[name] = noop;
  23304. }
  23305. /* eslint-enable */
  23306. }
  23307. /*
  23308. * Licensed to the Apache Software Foundation (ASF) under one
  23309. * or more contributor license agreements. See the NOTICE file
  23310. * distributed with this work for additional information
  23311. * regarding copyright ownership. The ASF licenses this file
  23312. * to you under the Apache License, Version 2.0 (the
  23313. * "License"); you may not use this file except in compliance
  23314. * with the License. You may obtain a copy of the License at
  23315. *
  23316. * http://www.apache.org/licenses/LICENSE-2.0
  23317. *
  23318. * Unless required by applicable law or agreed to in writing,
  23319. * software distributed under the License is distributed on an
  23320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23321. * KIND, either express or implied. See the License for the
  23322. * specific language governing permissions and limitations
  23323. * under the License.
  23324. */
  23325. var colorAll = [
  23326. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  23327. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  23328. ];
  23329. var lightTheme = {
  23330. color: colorAll,
  23331. colorLayer: [
  23332. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  23333. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  23334. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  23335. colorAll
  23336. ]
  23337. };
  23338. /*
  23339. * Licensed to the Apache Software Foundation (ASF) under one
  23340. * or more contributor license agreements. See the NOTICE file
  23341. * distributed with this work for additional information
  23342. * regarding copyright ownership. The ASF licenses this file
  23343. * to you under the Apache License, Version 2.0 (the
  23344. * "License"); you may not use this file except in compliance
  23345. * with the License. You may obtain a copy of the License at
  23346. *
  23347. * http://www.apache.org/licenses/LICENSE-2.0
  23348. *
  23349. * Unless required by applicable law or agreed to in writing,
  23350. * software distributed under the License is distributed on an
  23351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23352. * KIND, either express or implied. See the License for the
  23353. * specific language governing permissions and limitations
  23354. * under the License.
  23355. */
  23356. var contrastColor = '#eee';
  23357. var axisCommon = function () {
  23358. return {
  23359. axisLine: {
  23360. lineStyle: {
  23361. color: contrastColor
  23362. }
  23363. },
  23364. axisTick: {
  23365. lineStyle: {
  23366. color: contrastColor
  23367. }
  23368. },
  23369. axisLabel: {
  23370. textStyle: {
  23371. color: contrastColor
  23372. }
  23373. },
  23374. splitLine: {
  23375. lineStyle: {
  23376. type: 'dashed',
  23377. color: '#aaa'
  23378. }
  23379. },
  23380. splitArea: {
  23381. areaStyle: {
  23382. color: contrastColor
  23383. }
  23384. }
  23385. };
  23386. };
  23387. var colorPalette = [
  23388. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  23389. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  23390. ];
  23391. var theme = {
  23392. color: colorPalette,
  23393. backgroundColor: '#333',
  23394. tooltip: {
  23395. axisPointer: {
  23396. lineStyle: {
  23397. color: contrastColor
  23398. },
  23399. crossStyle: {
  23400. color: contrastColor
  23401. },
  23402. label: {
  23403. color: '#000'
  23404. }
  23405. }
  23406. },
  23407. legend: {
  23408. textStyle: {
  23409. color: contrastColor
  23410. }
  23411. },
  23412. textStyle: {
  23413. color: contrastColor
  23414. },
  23415. title: {
  23416. textStyle: {
  23417. color: contrastColor
  23418. }
  23419. },
  23420. toolbox: {
  23421. iconStyle: {
  23422. normal: {
  23423. borderColor: contrastColor
  23424. }
  23425. }
  23426. },
  23427. dataZoom: {
  23428. textStyle: {
  23429. color: contrastColor
  23430. }
  23431. },
  23432. visualMap: {
  23433. textStyle: {
  23434. color: contrastColor
  23435. }
  23436. },
  23437. timeline: {
  23438. lineStyle: {
  23439. color: contrastColor
  23440. },
  23441. itemStyle: {
  23442. normal: {
  23443. color: colorPalette[1]
  23444. }
  23445. },
  23446. label: {
  23447. normal: {
  23448. textStyle: {
  23449. color: contrastColor
  23450. }
  23451. }
  23452. },
  23453. controlStyle: {
  23454. normal: {
  23455. color: contrastColor,
  23456. borderColor: contrastColor
  23457. }
  23458. }
  23459. },
  23460. timeAxis: axisCommon(),
  23461. logAxis: axisCommon(),
  23462. valueAxis: axisCommon(),
  23463. categoryAxis: axisCommon(),
  23464. line: {
  23465. symbol: 'circle'
  23466. },
  23467. graph: {
  23468. color: colorPalette
  23469. },
  23470. gauge: {
  23471. title: {
  23472. textStyle: {
  23473. color: contrastColor
  23474. }
  23475. }
  23476. },
  23477. candlestick: {
  23478. itemStyle: {
  23479. normal: {
  23480. color: '#FD1050',
  23481. color0: '#0CF49B',
  23482. borderColor: '#FD1050',
  23483. borderColor0: '#0CF49B'
  23484. }
  23485. }
  23486. }
  23487. };
  23488. theme.categoryAxis.splitLine.show = false;
  23489. /*
  23490. * Licensed to the Apache Software Foundation (ASF) under one
  23491. * or more contributor license agreements. See the NOTICE file
  23492. * distributed with this work for additional information
  23493. * regarding copyright ownership. The ASF licenses this file
  23494. * to you under the Apache License, Version 2.0 (the
  23495. * "License"); you may not use this file except in compliance
  23496. * with the License. You may obtain a copy of the License at
  23497. *
  23498. * http://www.apache.org/licenses/LICENSE-2.0
  23499. *
  23500. * Unless required by applicable law or agreed to in writing,
  23501. * software distributed under the License is distributed on an
  23502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23503. * KIND, either express or implied. See the License for the
  23504. * specific language governing permissions and limitations
  23505. * under the License.
  23506. */
  23507. /**
  23508. * This module is imported by echarts directly.
  23509. *
  23510. * Notice:
  23511. * Always keep this file exists for backward compatibility.
  23512. * Because before 4.1.0, dataset is an optional component,
  23513. * some users may import this module manually.
  23514. */
  23515. ComponentModel.extend({
  23516. type: 'dataset',
  23517. /**
  23518. * @protected
  23519. */
  23520. defaultOption: {
  23521. // 'row', 'column'
  23522. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  23523. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  23524. sourceHeader: null,
  23525. dimensions: null,
  23526. source: null
  23527. },
  23528. optionUpdated: function () {
  23529. detectSourceFormat(this);
  23530. }
  23531. });
  23532. Component$1.extend({
  23533. type: 'dataset'
  23534. });
  23535. /**
  23536. * 椭圆形状
  23537. * @module zrender/graphic/shape/Ellipse
  23538. */
  23539. var Ellipse = Path.extend({
  23540. type: 'ellipse',
  23541. shape: {
  23542. cx: 0, cy: 0,
  23543. rx: 0, ry: 0
  23544. },
  23545. buildPath: function (ctx, shape) {
  23546. var k = 0.5522848;
  23547. var x = shape.cx;
  23548. var y = shape.cy;
  23549. var a = shape.rx;
  23550. var b = shape.ry;
  23551. var ox = a * k; // 水平控制点偏移量
  23552. var oy = b * k; // 垂直控制点偏移量
  23553. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  23554. ctx.moveTo(x - a, y);
  23555. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  23556. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  23557. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  23558. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  23559. ctx.closePath();
  23560. }
  23561. });
  23562. // import RadialGradient from '../graphic/RadialGradient';
  23563. // import Pattern from '../graphic/Pattern';
  23564. // import * as vector from '../core/vector';
  23565. // Most of the values can be separated by comma and/or white space.
  23566. var DILIMITER_REG = /[\s,]+/;
  23567. /**
  23568. * For big svg string, this method might be time consuming.
  23569. *
  23570. * @param {string} svg xml string
  23571. * @return {Object} xml root.
  23572. */
  23573. function parseXML(svg) {
  23574. if (isString(svg)) {
  23575. var parser = new DOMParser();
  23576. svg = parser.parseFromString(svg, 'text/xml');
  23577. }
  23578. // Document node. If using $.get, doc node may be input.
  23579. if (svg.nodeType === 9) {
  23580. svg = svg.firstChild;
  23581. }
  23582. // nodeName of <!DOCTYPE svg> is also 'svg'.
  23583. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  23584. svg = svg.nextSibling;
  23585. }
  23586. return svg;
  23587. }
  23588. function SVGParser() {
  23589. this._defs = {};
  23590. this._root = null;
  23591. this._isDefine = false;
  23592. this._isText = false;
  23593. }
  23594. SVGParser.prototype.parse = function (xml, opt) {
  23595. opt = opt || {};
  23596. var svg = parseXML(xml);
  23597. if (!svg) {
  23598. throw new Error('Illegal svg');
  23599. }
  23600. var root = new Group();
  23601. this._root = root;
  23602. // parse view port
  23603. var viewBox = svg.getAttribute('viewBox') || '';
  23604. // If width/height not specified, means "100%" of `opt.width/height`.
  23605. // TODO: Other percent value not supported yet.
  23606. var width = parseFloat(svg.getAttribute('width') || opt.width);
  23607. var height = parseFloat(svg.getAttribute('height') || opt.height);
  23608. // If width/height not specified, set as null for output.
  23609. isNaN(width) && (width = null);
  23610. isNaN(height) && (height = null);
  23611. // Apply inline style on svg element.
  23612. parseAttributes(svg, root, null, true);
  23613. var child = svg.firstChild;
  23614. while (child) {
  23615. this._parseNode(child, root);
  23616. child = child.nextSibling;
  23617. }
  23618. var viewBoxRect;
  23619. var viewBoxTransform;
  23620. if (viewBox) {
  23621. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23622. // Some invalid case like viewBox: 'none'.
  23623. if (viewBoxArr.length >= 4) {
  23624. viewBoxRect = {
  23625. x: parseFloat(viewBoxArr[0] || 0),
  23626. y: parseFloat(viewBoxArr[1] || 0),
  23627. width: parseFloat(viewBoxArr[2]),
  23628. height: parseFloat(viewBoxArr[3])
  23629. };
  23630. }
  23631. }
  23632. if (viewBoxRect && width != null && height != null) {
  23633. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23634. if (!opt.ignoreViewBox) {
  23635. // If set transform on the output group, it probably bring trouble when
  23636. // some users only intend to show the clipped content inside the viewBox,
  23637. // but not intend to transform the output group. So we keep the output
  23638. // group no transform. If the user intend to use the viewBox as a
  23639. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23640. // manually according to the viewBox info in the output of this method.
  23641. var elRoot = root;
  23642. root = new Group();
  23643. root.add(elRoot);
  23644. elRoot.scale = viewBoxTransform.scale.slice();
  23645. elRoot.position = viewBoxTransform.position.slice();
  23646. }
  23647. }
  23648. // Some shapes might be overflow the viewport, which should be
  23649. // clipped despite whether the viewBox is used, as the SVG does.
  23650. if (!opt.ignoreRootClip && width != null && height != null) {
  23651. root.setClipPath(new Rect({
  23652. shape: {x: 0, y: 0, width: width, height: height}
  23653. }));
  23654. }
  23655. // Set width/height on group just for output the viewport size.
  23656. return {
  23657. root: root,
  23658. width: width,
  23659. height: height,
  23660. viewBoxRect: viewBoxRect,
  23661. viewBoxTransform: viewBoxTransform
  23662. };
  23663. };
  23664. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23665. var nodeName = xmlNode.nodeName.toLowerCase();
  23666. // TODO
  23667. // support <style>...</style> in svg, where nodeName is 'style',
  23668. // CSS classes is defined globally wherever the style tags are declared.
  23669. if (nodeName === 'defs') {
  23670. // define flag
  23671. this._isDefine = true;
  23672. }
  23673. else if (nodeName === 'text') {
  23674. this._isText = true;
  23675. }
  23676. var el;
  23677. if (this._isDefine) {
  23678. var parser = defineParsers[nodeName];
  23679. if (parser) {
  23680. var def = parser.call(this, xmlNode);
  23681. var id = xmlNode.getAttribute('id');
  23682. if (id) {
  23683. this._defs[id] = def;
  23684. }
  23685. }
  23686. }
  23687. else {
  23688. var parser = nodeParsers[nodeName];
  23689. if (parser) {
  23690. el = parser.call(this, xmlNode, parentGroup);
  23691. parentGroup.add(el);
  23692. }
  23693. }
  23694. var child = xmlNode.firstChild;
  23695. while (child) {
  23696. if (child.nodeType === 1) {
  23697. this._parseNode(child, el);
  23698. }
  23699. // Is text
  23700. if (child.nodeType === 3 && this._isText) {
  23701. this._parseText(child, el);
  23702. }
  23703. child = child.nextSibling;
  23704. }
  23705. // Quit define
  23706. if (nodeName === 'defs') {
  23707. this._isDefine = false;
  23708. }
  23709. else if (nodeName === 'text') {
  23710. this._isText = false;
  23711. }
  23712. };
  23713. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23714. if (xmlNode.nodeType === 1) {
  23715. var dx = xmlNode.getAttribute('dx') || 0;
  23716. var dy = xmlNode.getAttribute('dy') || 0;
  23717. this._textX += parseFloat(dx);
  23718. this._textY += parseFloat(dy);
  23719. }
  23720. var text = new Text({
  23721. style: {
  23722. text: xmlNode.textContent,
  23723. transformText: true
  23724. },
  23725. position: [this._textX || 0, this._textY || 0]
  23726. });
  23727. inheritStyle(parentGroup, text);
  23728. parseAttributes(xmlNode, text, this._defs);
  23729. var fontSize = text.style.fontSize;
  23730. if (fontSize && fontSize < 9) {
  23731. // PENDING
  23732. text.style.fontSize = 9;
  23733. text.scale = text.scale || [1, 1];
  23734. text.scale[0] *= fontSize / 9;
  23735. text.scale[1] *= fontSize / 9;
  23736. }
  23737. var rect = text.getBoundingRect();
  23738. this._textX += rect.width;
  23739. parentGroup.add(text);
  23740. return text;
  23741. };
  23742. var nodeParsers = {
  23743. 'g': function (xmlNode, parentGroup) {
  23744. var g = new Group();
  23745. inheritStyle(parentGroup, g);
  23746. parseAttributes(xmlNode, g, this._defs);
  23747. return g;
  23748. },
  23749. 'rect': function (xmlNode, parentGroup) {
  23750. var rect = new Rect();
  23751. inheritStyle(parentGroup, rect);
  23752. parseAttributes(xmlNode, rect, this._defs);
  23753. rect.setShape({
  23754. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23755. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23756. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23757. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23758. });
  23759. // console.log(xmlNode.getAttribute('transform'));
  23760. // console.log(rect.transform);
  23761. return rect;
  23762. },
  23763. 'circle': function (xmlNode, parentGroup) {
  23764. var circle = new Circle();
  23765. inheritStyle(parentGroup, circle);
  23766. parseAttributes(xmlNode, circle, this._defs);
  23767. circle.setShape({
  23768. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23769. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23770. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23771. });
  23772. return circle;
  23773. },
  23774. 'line': function (xmlNode, parentGroup) {
  23775. var line = new Line();
  23776. inheritStyle(parentGroup, line);
  23777. parseAttributes(xmlNode, line, this._defs);
  23778. line.setShape({
  23779. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23780. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23781. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23782. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23783. });
  23784. return line;
  23785. },
  23786. 'ellipse': function (xmlNode, parentGroup) {
  23787. var ellipse = new Ellipse();
  23788. inheritStyle(parentGroup, ellipse);
  23789. parseAttributes(xmlNode, ellipse, this._defs);
  23790. ellipse.setShape({
  23791. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23792. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23793. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23794. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23795. });
  23796. return ellipse;
  23797. },
  23798. 'polygon': function (xmlNode, parentGroup) {
  23799. var points = xmlNode.getAttribute('points');
  23800. if (points) {
  23801. points = parsePoints(points);
  23802. }
  23803. var polygon = new Polygon({
  23804. shape: {
  23805. points: points || []
  23806. }
  23807. });
  23808. inheritStyle(parentGroup, polygon);
  23809. parseAttributes(xmlNode, polygon, this._defs);
  23810. return polygon;
  23811. },
  23812. 'polyline': function (xmlNode, parentGroup) {
  23813. var path = new Path();
  23814. inheritStyle(parentGroup, path);
  23815. parseAttributes(xmlNode, path, this._defs);
  23816. var points = xmlNode.getAttribute('points');
  23817. if (points) {
  23818. points = parsePoints(points);
  23819. }
  23820. var polyline = new Polyline({
  23821. shape: {
  23822. points: points || []
  23823. }
  23824. });
  23825. return polyline;
  23826. },
  23827. 'image': function (xmlNode, parentGroup) {
  23828. var img = new ZImage();
  23829. inheritStyle(parentGroup, img);
  23830. parseAttributes(xmlNode, img, this._defs);
  23831. img.setStyle({
  23832. image: xmlNode.getAttribute('xlink:href'),
  23833. x: xmlNode.getAttribute('x'),
  23834. y: xmlNode.getAttribute('y'),
  23835. width: xmlNode.getAttribute('width'),
  23836. height: xmlNode.getAttribute('height')
  23837. });
  23838. return img;
  23839. },
  23840. 'text': function (xmlNode, parentGroup) {
  23841. var x = xmlNode.getAttribute('x') || 0;
  23842. var y = xmlNode.getAttribute('y') || 0;
  23843. var dx = xmlNode.getAttribute('dx') || 0;
  23844. var dy = xmlNode.getAttribute('dy') || 0;
  23845. this._textX = parseFloat(x) + parseFloat(dx);
  23846. this._textY = parseFloat(y) + parseFloat(dy);
  23847. var g = new Group();
  23848. inheritStyle(parentGroup, g);
  23849. parseAttributes(xmlNode, g, this._defs);
  23850. return g;
  23851. },
  23852. 'tspan': function (xmlNode, parentGroup) {
  23853. var x = xmlNode.getAttribute('x');
  23854. var y = xmlNode.getAttribute('y');
  23855. if (x != null) {
  23856. // new offset x
  23857. this._textX = parseFloat(x);
  23858. }
  23859. if (y != null) {
  23860. // new offset y
  23861. this._textY = parseFloat(y);
  23862. }
  23863. var dx = xmlNode.getAttribute('dx') || 0;
  23864. var dy = xmlNode.getAttribute('dy') || 0;
  23865. var g = new Group();
  23866. inheritStyle(parentGroup, g);
  23867. parseAttributes(xmlNode, g, this._defs);
  23868. this._textX += dx;
  23869. this._textY += dy;
  23870. return g;
  23871. },
  23872. 'path': function (xmlNode, parentGroup) {
  23873. // TODO svg fill rule
  23874. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23875. // path.style.globalCompositeOperation = 'xor';
  23876. var d = xmlNode.getAttribute('d') || '';
  23877. // Performance sensitive.
  23878. var path = createFromString(d);
  23879. inheritStyle(parentGroup, path);
  23880. parseAttributes(xmlNode, path, this._defs);
  23881. return path;
  23882. }
  23883. };
  23884. var defineParsers = {
  23885. 'lineargradient': function (xmlNode) {
  23886. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23887. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23888. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23889. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23890. var gradient = new LinearGradient(x1, y1, x2, y2);
  23891. _parseGradientColorStops(xmlNode, gradient);
  23892. return gradient;
  23893. },
  23894. 'radialgradient': function (xmlNode) {
  23895. }
  23896. };
  23897. function _parseGradientColorStops(xmlNode, gradient) {
  23898. var stop = xmlNode.firstChild;
  23899. while (stop) {
  23900. if (stop.nodeType === 1) {
  23901. var offset = stop.getAttribute('offset');
  23902. if (offset.indexOf('%') > 0) { // percentage
  23903. offset = parseInt(offset, 10) / 100;
  23904. }
  23905. else if (offset) { // number from 0 to 1
  23906. offset = parseFloat(offset);
  23907. }
  23908. else {
  23909. offset = 0;
  23910. }
  23911. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23912. gradient.addColorStop(offset, stopColor);
  23913. }
  23914. stop = stop.nextSibling;
  23915. }
  23916. }
  23917. function inheritStyle(parent, child) {
  23918. if (parent && parent.__inheritedStyle) {
  23919. if (!child.__inheritedStyle) {
  23920. child.__inheritedStyle = {};
  23921. }
  23922. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23923. }
  23924. }
  23925. function parsePoints(pointsString) {
  23926. var list = trim(pointsString).split(DILIMITER_REG);
  23927. var points = [];
  23928. for (var i = 0; i < list.length; i += 2) {
  23929. var x = parseFloat(list[i]);
  23930. var y = parseFloat(list[i + 1]);
  23931. points.push([x, y]);
  23932. }
  23933. return points;
  23934. }
  23935. var attributesMap = {
  23936. 'fill': 'fill',
  23937. 'stroke': 'stroke',
  23938. 'stroke-width': 'lineWidth',
  23939. 'opacity': 'opacity',
  23940. 'fill-opacity': 'fillOpacity',
  23941. 'stroke-opacity': 'strokeOpacity',
  23942. 'stroke-dasharray': 'lineDash',
  23943. 'stroke-dashoffset': 'lineDashOffset',
  23944. 'stroke-linecap': 'lineCap',
  23945. 'stroke-linejoin': 'lineJoin',
  23946. 'stroke-miterlimit': 'miterLimit',
  23947. 'font-family': 'fontFamily',
  23948. 'font-size': 'fontSize',
  23949. 'font-style': 'fontStyle',
  23950. 'font-weight': 'fontWeight',
  23951. 'text-align': 'textAlign',
  23952. 'alignment-baseline': 'textBaseline'
  23953. };
  23954. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23955. var zrStyle = el.__inheritedStyle || {};
  23956. var isTextEl = el.type === 'text';
  23957. // TODO Shadow
  23958. if (xmlNode.nodeType === 1) {
  23959. parseTransformAttribute(xmlNode, el);
  23960. extend(zrStyle, parseStyleAttribute(xmlNode));
  23961. if (!onlyInlineStyle) {
  23962. for (var svgAttrName in attributesMap) {
  23963. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23964. var attrValue = xmlNode.getAttribute(svgAttrName);
  23965. if (attrValue != null) {
  23966. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23967. }
  23968. }
  23969. }
  23970. }
  23971. }
  23972. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23973. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23974. el.style = el.style || new Style();
  23975. var elStyle = el.style;
  23976. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23977. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23978. each$1([
  23979. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23980. ], function (propName) {
  23981. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23982. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23983. });
  23984. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23985. zrStyle.textBaseline = 'alphabetic';
  23986. }
  23987. if (zrStyle.textBaseline === 'alphabetic') {
  23988. zrStyle.textBaseline = 'bottom';
  23989. }
  23990. if (zrStyle.textAlign === 'start') {
  23991. zrStyle.textAlign = 'left';
  23992. }
  23993. if (zrStyle.textAlign === 'end') {
  23994. zrStyle.textAlign = 'right';
  23995. }
  23996. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23997. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23998. ], function (propName) {
  23999. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  24000. });
  24001. if (zrStyle.lineDash) {
  24002. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  24003. }
  24004. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  24005. // enable stroke
  24006. el[elStrokeProp] = true;
  24007. }
  24008. el.__inheritedStyle = zrStyle;
  24009. }
  24010. var urlRegex = /url\(\s*#(.*?)\)/;
  24011. function getPaint(str, defs) {
  24012. // if (str === 'none') {
  24013. // return;
  24014. // }
  24015. var urlMatch = defs && str && str.match(urlRegex);
  24016. if (urlMatch) {
  24017. var url = trim(urlMatch[1]);
  24018. var def = defs[url];
  24019. return def;
  24020. }
  24021. return str;
  24022. }
  24023. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  24024. function parseTransformAttribute(xmlNode, node) {
  24025. var transform = xmlNode.getAttribute('transform');
  24026. if (transform) {
  24027. transform = transform.replace(/,/g, ' ');
  24028. var m = null;
  24029. var transformOps = [];
  24030. transform.replace(transformRegex, function (str, type, value) {
  24031. transformOps.push(type, value);
  24032. });
  24033. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  24034. var value = transformOps[i];
  24035. var type = transformOps[i - 1];
  24036. m = m || create$1();
  24037. switch (type) {
  24038. case 'translate':
  24039. value = trim(value).split(DILIMITER_REG);
  24040. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  24041. break;
  24042. case 'scale':
  24043. value = trim(value).split(DILIMITER_REG);
  24044. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  24045. break;
  24046. case 'rotate':
  24047. value = trim(value).split(DILIMITER_REG);
  24048. rotate(m, m, parseFloat(value[0]));
  24049. break;
  24050. case 'skew':
  24051. value = trim(value).split(DILIMITER_REG);
  24052. console.warn('Skew transform is not supported yet');
  24053. break;
  24054. case 'matrix':
  24055. var value = trim(value).split(DILIMITER_REG);
  24056. m[0] = parseFloat(value[0]);
  24057. m[1] = parseFloat(value[1]);
  24058. m[2] = parseFloat(value[2]);
  24059. m[3] = parseFloat(value[3]);
  24060. m[4] = parseFloat(value[4]);
  24061. m[5] = parseFloat(value[5]);
  24062. break;
  24063. }
  24064. }
  24065. node.setLocalTransform(m);
  24066. }
  24067. }
  24068. // Value may contain space.
  24069. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  24070. function parseStyleAttribute(xmlNode) {
  24071. var style = xmlNode.getAttribute('style');
  24072. var result = {};
  24073. if (!style) {
  24074. return result;
  24075. }
  24076. var styleList = {};
  24077. styleRegex.lastIndex = 0;
  24078. var styleRegResult;
  24079. while ((styleRegResult = styleRegex.exec(style)) != null) {
  24080. styleList[styleRegResult[1]] = styleRegResult[2];
  24081. }
  24082. for (var svgAttrName in attributesMap) {
  24083. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  24084. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  24085. }
  24086. }
  24087. return result;
  24088. }
  24089. /**
  24090. * @param {Array.<number>} viewBoxRect
  24091. * @param {number} width
  24092. * @param {number} height
  24093. * @return {Object} {scale, position}
  24094. */
  24095. function makeViewBoxTransform(viewBoxRect, width, height) {
  24096. var scaleX = width / viewBoxRect.width;
  24097. var scaleY = height / viewBoxRect.height;
  24098. var scale = Math.min(scaleX, scaleY);
  24099. // preserveAspectRatio 'xMidYMid'
  24100. var viewBoxScale = [scale, scale];
  24101. var viewBoxPosition = [
  24102. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  24103. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  24104. ];
  24105. return {
  24106. scale: viewBoxScale,
  24107. position: viewBoxPosition
  24108. };
  24109. }
  24110. /**
  24111. * @param {string|XMLElement} xml
  24112. * @param {Object} [opt]
  24113. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  24114. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  24115. * @param {boolean} [opt.ignoreViewBox]
  24116. * @param {boolean} [opt.ignoreRootClip]
  24117. * @return {Object} result:
  24118. * {
  24119. * root: Group, The root of the the result tree of zrender shapes,
  24120. * width: number, the viewport width of the SVG,
  24121. * height: number, the viewport height of the SVG,
  24122. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  24123. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  24124. * }
  24125. */
  24126. /*
  24127. * Licensed to the Apache Software Foundation (ASF) under one
  24128. * or more contributor license agreements. See the NOTICE file
  24129. * distributed with this work for additional information
  24130. * regarding copyright ownership. The ASF licenses this file
  24131. * to you under the Apache License, Version 2.0 (the
  24132. * "License"); you may not use this file except in compliance
  24133. * with the License. You may obtain a copy of the License at
  24134. *
  24135. * http://www.apache.org/licenses/LICENSE-2.0
  24136. *
  24137. * Unless required by applicable law or agreed to in writing,
  24138. * software distributed under the License is distributed on an
  24139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24140. * KIND, either express or implied. See the License for the
  24141. * specific language governing permissions and limitations
  24142. * under the License.
  24143. */
  24144. var storage = createHashMap();
  24145. // For minimize the code size of common echarts package,
  24146. // do not put too much logic in this module.
  24147. var mapDataStorage = {
  24148. // The format of record: see `echarts.registerMap`.
  24149. // Compatible with previous `echarts.registerMap`.
  24150. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  24151. var records;
  24152. if (isArray(rawGeoJson)) {
  24153. records = rawGeoJson;
  24154. }
  24155. else if (rawGeoJson.svg) {
  24156. records = [{
  24157. type: 'svg',
  24158. source: rawGeoJson.svg,
  24159. specialAreas: rawGeoJson.specialAreas
  24160. }];
  24161. }
  24162. else {
  24163. // Backward compatibility.
  24164. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  24165. rawSpecialAreas = rawGeoJson.specialAreas;
  24166. rawGeoJson = rawGeoJson.geoJson;
  24167. }
  24168. records = [{
  24169. type: 'geoJSON',
  24170. source: rawGeoJson,
  24171. specialAreas: rawSpecialAreas
  24172. }];
  24173. }
  24174. each$1(records, function (record) {
  24175. var type = record.type;
  24176. type === 'geoJson' && (type = record.type = 'geoJSON');
  24177. var parse = parsers[type];
  24178. if (__DEV__) {
  24179. assert$1(parse, 'Illegal map type: ' + type);
  24180. }
  24181. parse(record);
  24182. });
  24183. return storage.set(mapName, records);
  24184. },
  24185. retrieveMap: function (mapName) {
  24186. return storage.get(mapName);
  24187. }
  24188. };
  24189. var parsers = {
  24190. geoJSON: function (record) {
  24191. var source = record.source;
  24192. record.geoJSON = !isString(source)
  24193. ? source
  24194. : (typeof JSON !== 'undefined' && JSON.parse)
  24195. ? JSON.parse(source)
  24196. : (new Function('return (' + source + ');'))();
  24197. },
  24198. // Only perform parse to XML object here, which might be time
  24199. // consiming for large SVG.
  24200. // Although convert XML to zrender element is also time consiming,
  24201. // if we do it here, the clone of zrender elements has to be
  24202. // required. So we do it once for each geo instance, util real
  24203. // performance issues call for optimizing it.
  24204. svg: function (record) {
  24205. record.svgXML = parseXML(record.source);
  24206. }
  24207. };
  24208. /*
  24209. * Licensed to the Apache Software Foundation (ASF) under one
  24210. * or more contributor license agreements. See the NOTICE file
  24211. * distributed with this work for additional information
  24212. * regarding copyright ownership. The ASF licenses this file
  24213. * to you under the Apache License, Version 2.0 (the
  24214. * "License"); you may not use this file except in compliance
  24215. * with the License. You may obtain a copy of the License at
  24216. *
  24217. * http://www.apache.org/licenses/LICENSE-2.0
  24218. *
  24219. * Unless required by applicable law or agreed to in writing,
  24220. * software distributed under the License is distributed on an
  24221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24222. * KIND, either express or implied. See the License for the
  24223. * specific language governing permissions and limitations
  24224. * under the License.
  24225. */
  24226. var assert = assert$1;
  24227. var each = each$1;
  24228. var isFunction = isFunction$1;
  24229. var isObject = isObject$1;
  24230. var parseClassType = ComponentModel.parseClassType;
  24231. var version = '4.8.0';
  24232. var dependencies = {
  24233. zrender: '4.3.1'
  24234. };
  24235. var TEST_FRAME_REMAIN_TIME = 1;
  24236. var PRIORITY_PROCESSOR_FILTER = 1000;
  24237. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  24238. var PRIORITY_PROCESSOR_DATASTACK = 900;
  24239. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24240. var PRIORITY_VISUAL_LAYOUT = 1000;
  24241. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24242. var PRIORITY_VISUAL_GLOBAL = 2000;
  24243. var PRIORITY_VISUAL_CHART = 3000;
  24244. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  24245. var PRIORITY_VISUAL_COMPONENT = 4000;
  24246. // FIXME
  24247. // necessary?
  24248. var PRIORITY_VISUAL_BRUSH = 5000;
  24249. var PRIORITY = {
  24250. PROCESSOR: {
  24251. FILTER: PRIORITY_PROCESSOR_FILTER,
  24252. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  24253. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  24254. },
  24255. VISUAL: {
  24256. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  24257. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  24258. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  24259. CHART: PRIORITY_VISUAL_CHART,
  24260. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  24261. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  24262. BRUSH: PRIORITY_VISUAL_BRUSH
  24263. }
  24264. };
  24265. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  24266. // where they must not be invoked nestedly, except the only case: invoke
  24267. // dispatchAction with updateMethod "none" in main process.
  24268. // This flag is used to carry out this rule.
  24269. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  24270. var IN_MAIN_PROCESS = '__flagInMainProcess';
  24271. var OPTION_UPDATED = '__optionUpdated';
  24272. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  24273. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  24274. return function (eventName, handler, context) {
  24275. if (!ignoreDisposed && this._disposed) {
  24276. disposedWarning(this.id);
  24277. return;
  24278. }
  24279. // Event name is all lowercase
  24280. eventName = eventName && eventName.toLowerCase();
  24281. Eventful.prototype[method].call(this, eventName, handler, context);
  24282. };
  24283. }
  24284. /**
  24285. * @module echarts~MessageCenter
  24286. */
  24287. function MessageCenter() {
  24288. Eventful.call(this);
  24289. }
  24290. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  24291. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  24292. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  24293. mixin(MessageCenter, Eventful);
  24294. /**
  24295. * @module echarts~ECharts
  24296. */
  24297. function ECharts(dom, theme$$1, opts) {
  24298. opts = opts || {};
  24299. // Get theme by name
  24300. if (typeof theme$$1 === 'string') {
  24301. theme$$1 = themeStorage[theme$$1];
  24302. }
  24303. /**
  24304. * @type {string}
  24305. */
  24306. this.id;
  24307. /**
  24308. * Group id
  24309. * @type {string}
  24310. */
  24311. this.group;
  24312. /**
  24313. * @type {HTMLElement}
  24314. * @private
  24315. */
  24316. this._dom = dom;
  24317. var defaultRenderer = 'canvas';
  24318. if (__DEV__) {
  24319. defaultRenderer = (
  24320. typeof window === 'undefined' ? global : window
  24321. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  24322. }
  24323. /**
  24324. * @type {module:zrender/ZRender}
  24325. * @private
  24326. */
  24327. var zr = this._zr = init$1(dom, {
  24328. renderer: opts.renderer || defaultRenderer,
  24329. devicePixelRatio: opts.devicePixelRatio,
  24330. width: opts.width,
  24331. height: opts.height
  24332. });
  24333. /**
  24334. * Expect 60 fps.
  24335. * @type {Function}
  24336. * @private
  24337. */
  24338. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  24339. var theme$$1 = clone(theme$$1);
  24340. theme$$1 && backwardCompat(theme$$1, true);
  24341. /**
  24342. * @type {Object}
  24343. * @private
  24344. */
  24345. this._theme = theme$$1;
  24346. /**
  24347. * @type {Array.<module:echarts/view/Chart>}
  24348. * @private
  24349. */
  24350. this._chartsViews = [];
  24351. /**
  24352. * @type {Object.<string, module:echarts/view/Chart>}
  24353. * @private
  24354. */
  24355. this._chartsMap = {};
  24356. /**
  24357. * @type {Array.<module:echarts/view/Component>}
  24358. * @private
  24359. */
  24360. this._componentsViews = [];
  24361. /**
  24362. * @type {Object.<string, module:echarts/view/Component>}
  24363. * @private
  24364. */
  24365. this._componentsMap = {};
  24366. /**
  24367. * @type {module:echarts/CoordinateSystem}
  24368. * @private
  24369. */
  24370. this._coordSysMgr = new CoordinateSystemManager();
  24371. /**
  24372. * @type {module:echarts/ExtensionAPI}
  24373. * @private
  24374. */
  24375. var api = this._api = createExtensionAPI(this);
  24376. // Sort on demand
  24377. function prioritySortFunc(a, b) {
  24378. return a.__prio - b.__prio;
  24379. }
  24380. sort(visualFuncs, prioritySortFunc);
  24381. sort(dataProcessorFuncs, prioritySortFunc);
  24382. /**
  24383. * @type {module:echarts/stream/Scheduler}
  24384. */
  24385. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  24386. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  24387. /**
  24388. * @type {module:echarts~MessageCenter}
  24389. * @private
  24390. */
  24391. this._messageCenter = new MessageCenter();
  24392. // Init mouse events
  24393. this._initEvents();
  24394. // In case some people write `window.onresize = chart.resize`
  24395. this.resize = bind(this.resize, this);
  24396. // Can't dispatch action during rendering procedure
  24397. this._pendingActions = [];
  24398. zr.animation.on('frame', this._onframe, this);
  24399. bindRenderedEvent(zr, this);
  24400. // ECharts instance can be used as value.
  24401. setAsPrimitive(this);
  24402. }
  24403. var echartsProto = ECharts.prototype;
  24404. echartsProto._onframe = function () {
  24405. if (this._disposed) {
  24406. return;
  24407. }
  24408. var scheduler = this._scheduler;
  24409. // Lazy update
  24410. if (this[OPTION_UPDATED]) {
  24411. var silent = this[OPTION_UPDATED].silent;
  24412. this[IN_MAIN_PROCESS] = true;
  24413. prepare(this);
  24414. updateMethods.update.call(this);
  24415. this[IN_MAIN_PROCESS] = false;
  24416. this[OPTION_UPDATED] = false;
  24417. flushPendingActions.call(this, silent);
  24418. triggerUpdatedEvent.call(this, silent);
  24419. }
  24420. // Avoid do both lazy update and progress in one frame.
  24421. else if (scheduler.unfinished) {
  24422. // Stream progress.
  24423. var remainTime = TEST_FRAME_REMAIN_TIME;
  24424. var ecModel = this._model;
  24425. var api = this._api;
  24426. scheduler.unfinished = false;
  24427. do {
  24428. var startTime = +new Date();
  24429. scheduler.performSeriesTasks(ecModel);
  24430. // Currently dataProcessorFuncs do not check threshold.
  24431. scheduler.performDataProcessorTasks(ecModel);
  24432. updateStreamModes(this, ecModel);
  24433. // Do not update coordinate system here. Because that coord system update in
  24434. // each frame is not a good user experience. So we follow the rule that
  24435. // the extent of the coordinate system is determin in the first frame (the
  24436. // frame is executed immedietely after task reset.
  24437. // this._coordSysMgr.update(ecModel, api);
  24438. // console.log('--- ec frame visual ---', remainTime);
  24439. scheduler.performVisualTasks(ecModel);
  24440. renderSeries(this, this._model, api, 'remain');
  24441. remainTime -= (+new Date() - startTime);
  24442. }
  24443. while (remainTime > 0 && scheduler.unfinished);
  24444. // Call flush explicitly for trigger finished event.
  24445. if (!scheduler.unfinished) {
  24446. this._zr.flush();
  24447. }
  24448. // Else, zr flushing be ensue within the same frame,
  24449. // because zr flushing is after onframe event.
  24450. }
  24451. };
  24452. /**
  24453. * @return {HTMLElement}
  24454. */
  24455. echartsProto.getDom = function () {
  24456. return this._dom;
  24457. };
  24458. /**
  24459. * @return {module:zrender~ZRender}
  24460. */
  24461. echartsProto.getZr = function () {
  24462. return this._zr;
  24463. };
  24464. /**
  24465. * Usage:
  24466. * chart.setOption(option, notMerge, lazyUpdate);
  24467. * chart.setOption(option, {
  24468. * notMerge: ...,
  24469. * lazyUpdate: ...,
  24470. * silent: ...
  24471. * });
  24472. *
  24473. * @param {Object} option
  24474. * @param {Object|boolean} [opts] opts or notMerge.
  24475. * @param {boolean} [opts.notMerge=false]
  24476. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  24477. */
  24478. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  24479. if (__DEV__) {
  24480. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  24481. }
  24482. if (this._disposed) {
  24483. disposedWarning(this.id);
  24484. return;
  24485. }
  24486. var silent;
  24487. if (isObject(notMerge)) {
  24488. lazyUpdate = notMerge.lazyUpdate;
  24489. silent = notMerge.silent;
  24490. notMerge = notMerge.notMerge;
  24491. }
  24492. this[IN_MAIN_PROCESS] = true;
  24493. if (!this._model || notMerge) {
  24494. var optionManager = new OptionManager(this._api);
  24495. var theme$$1 = this._theme;
  24496. var ecModel = this._model = new GlobalModel();
  24497. ecModel.scheduler = this._scheduler;
  24498. ecModel.init(null, null, theme$$1, optionManager);
  24499. }
  24500. this._model.setOption(option, optionPreprocessorFuncs);
  24501. if (lazyUpdate) {
  24502. this[OPTION_UPDATED] = {silent: silent};
  24503. this[IN_MAIN_PROCESS] = false;
  24504. }
  24505. else {
  24506. prepare(this);
  24507. updateMethods.update.call(this);
  24508. // Ensure zr refresh sychronously, and then pixel in canvas can be
  24509. // fetched after `setOption`.
  24510. this._zr.flush();
  24511. this[OPTION_UPDATED] = false;
  24512. this[IN_MAIN_PROCESS] = false;
  24513. flushPendingActions.call(this, silent);
  24514. triggerUpdatedEvent.call(this, silent);
  24515. }
  24516. };
  24517. /**
  24518. * @DEPRECATED
  24519. */
  24520. echartsProto.setTheme = function () {
  24521. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  24522. };
  24523. /**
  24524. * @return {module:echarts/model/Global}
  24525. */
  24526. echartsProto.getModel = function () {
  24527. return this._model;
  24528. };
  24529. /**
  24530. * @return {Object}
  24531. */
  24532. echartsProto.getOption = function () {
  24533. return this._model && this._model.getOption();
  24534. };
  24535. /**
  24536. * @return {number}
  24537. */
  24538. echartsProto.getWidth = function () {
  24539. return this._zr.getWidth();
  24540. };
  24541. /**
  24542. * @return {number}
  24543. */
  24544. echartsProto.getHeight = function () {
  24545. return this._zr.getHeight();
  24546. };
  24547. /**
  24548. * @return {number}
  24549. */
  24550. echartsProto.getDevicePixelRatio = function () {
  24551. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  24552. };
  24553. /**
  24554. * Get canvas which has all thing rendered
  24555. * @param {Object} opts
  24556. * @param {string} [opts.backgroundColor]
  24557. * @return {string}
  24558. */
  24559. echartsProto.getRenderedCanvas = function (opts) {
  24560. if (!env$1.canvasSupported) {
  24561. return;
  24562. }
  24563. opts = opts || {};
  24564. opts.pixelRatio = opts.pixelRatio || 1;
  24565. opts.backgroundColor = opts.backgroundColor
  24566. || this._model.get('backgroundColor');
  24567. var zr = this._zr;
  24568. // var list = zr.storage.getDisplayList();
  24569. // Stop animations
  24570. // Never works before in init animation, so remove it.
  24571. // zrUtil.each(list, function (el) {
  24572. // el.stopAnimation(true);
  24573. // });
  24574. return zr.painter.getRenderedCanvas(opts);
  24575. };
  24576. /**
  24577. * Get svg data url
  24578. * @return {string}
  24579. */
  24580. echartsProto.getSvgDataURL = function () {
  24581. if (!env$1.svgSupported) {
  24582. return;
  24583. }
  24584. var zr = this._zr;
  24585. var list = zr.storage.getDisplayList();
  24586. // Stop animations
  24587. each$1(list, function (el) {
  24588. el.stopAnimation(true);
  24589. });
  24590. return zr.painter.toDataURL();
  24591. };
  24592. /**
  24593. * @return {string}
  24594. * @param {Object} opts
  24595. * @param {string} [opts.type='png']
  24596. * @param {string} [opts.pixelRatio=1]
  24597. * @param {string} [opts.backgroundColor]
  24598. * @param {string} [opts.excludeComponents]
  24599. */
  24600. echartsProto.getDataURL = function (opts) {
  24601. if (this._disposed) {
  24602. disposedWarning(this.id);
  24603. return;
  24604. }
  24605. opts = opts || {};
  24606. var excludeComponents = opts.excludeComponents;
  24607. var ecModel = this._model;
  24608. var excludesComponentViews = [];
  24609. var self = this;
  24610. each(excludeComponents, function (componentType) {
  24611. ecModel.eachComponent({
  24612. mainType: componentType
  24613. }, function (component) {
  24614. var view = self._componentsMap[component.__viewId];
  24615. if (!view.group.ignore) {
  24616. excludesComponentViews.push(view);
  24617. view.group.ignore = true;
  24618. }
  24619. });
  24620. });
  24621. var url = this._zr.painter.getType() === 'svg'
  24622. ? this.getSvgDataURL()
  24623. : this.getRenderedCanvas(opts).toDataURL(
  24624. 'image/' + (opts && opts.type || 'png')
  24625. );
  24626. each(excludesComponentViews, function (view) {
  24627. view.group.ignore = false;
  24628. });
  24629. return url;
  24630. };
  24631. /**
  24632. * @return {string}
  24633. * @param {Object} opts
  24634. * @param {string} [opts.type='png']
  24635. * @param {string} [opts.pixelRatio=1]
  24636. * @param {string} [opts.backgroundColor]
  24637. */
  24638. echartsProto.getConnectedDataURL = function (opts) {
  24639. if (this._disposed) {
  24640. disposedWarning(this.id);
  24641. return;
  24642. }
  24643. if (!env$1.canvasSupported) {
  24644. return;
  24645. }
  24646. var isSvg = opts.type === 'svg';
  24647. var groupId = this.group;
  24648. var mathMin = Math.min;
  24649. var mathMax = Math.max;
  24650. var MAX_NUMBER = Infinity;
  24651. if (connectedGroups[groupId]) {
  24652. var left = MAX_NUMBER;
  24653. var top = MAX_NUMBER;
  24654. var right = -MAX_NUMBER;
  24655. var bottom = -MAX_NUMBER;
  24656. var canvasList = [];
  24657. var dpr = (opts && opts.pixelRatio) || 1;
  24658. each$1(instances, function (chart, id) {
  24659. if (chart.group === groupId) {
  24660. var canvas = isSvg
  24661. ? chart.getZr().painter.getSvgDom().innerHTML
  24662. : chart.getRenderedCanvas(clone(opts));
  24663. var boundingRect = chart.getDom().getBoundingClientRect();
  24664. left = mathMin(boundingRect.left, left);
  24665. top = mathMin(boundingRect.top, top);
  24666. right = mathMax(boundingRect.right, right);
  24667. bottom = mathMax(boundingRect.bottom, bottom);
  24668. canvasList.push({
  24669. dom: canvas,
  24670. left: boundingRect.left,
  24671. top: boundingRect.top
  24672. });
  24673. }
  24674. });
  24675. left *= dpr;
  24676. top *= dpr;
  24677. right *= dpr;
  24678. bottom *= dpr;
  24679. var width = right - left;
  24680. var height = bottom - top;
  24681. var targetCanvas = createCanvas();
  24682. var zr = init$1(targetCanvas, {
  24683. renderer: isSvg ? 'svg' : 'canvas'
  24684. });
  24685. zr.resize({
  24686. width: width,
  24687. height: height
  24688. });
  24689. if (isSvg) {
  24690. var content = '';
  24691. each(canvasList, function (item) {
  24692. var x = item.left - left;
  24693. var y = item.top - top;
  24694. content += '<g transform="translate(' + x + ','
  24695. + y + ')">' + item.dom + '</g>';
  24696. });
  24697. zr.painter.getSvgRoot().innerHTML = content;
  24698. if (opts.connectedBackgroundColor) {
  24699. zr.painter.setBackgroundColor(opts.connectedBackgroundColor);
  24700. }
  24701. zr.refreshImmediately();
  24702. return zr.painter.toDataURL();
  24703. }
  24704. else {
  24705. // Background between the charts
  24706. if (opts.connectedBackgroundColor) {
  24707. zr.add(new Rect({
  24708. shape: {
  24709. x: 0,
  24710. y: 0,
  24711. width: width,
  24712. height: height
  24713. },
  24714. style: {
  24715. fill: opts.connectedBackgroundColor
  24716. }
  24717. }));
  24718. }
  24719. each(canvasList, function (item) {
  24720. var img = new ZImage({
  24721. style: {
  24722. x: item.left * dpr - left,
  24723. y: item.top * dpr - top,
  24724. image: item.dom
  24725. }
  24726. });
  24727. zr.add(img);
  24728. });
  24729. zr.refreshImmediately();
  24730. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24731. }
  24732. }
  24733. else {
  24734. return this.getDataURL(opts);
  24735. }
  24736. };
  24737. /**
  24738. * Convert from logical coordinate system to pixel coordinate system.
  24739. * See CoordinateSystem#convertToPixel.
  24740. * @param {string|Object} finder
  24741. * If string, e.g., 'geo', means {geoIndex: 0}.
  24742. * If Object, could contain some of these properties below:
  24743. * {
  24744. * seriesIndex / seriesId / seriesName,
  24745. * geoIndex / geoId, geoName,
  24746. * bmapIndex / bmapId / bmapName,
  24747. * xAxisIndex / xAxisId / xAxisName,
  24748. * yAxisIndex / yAxisId / yAxisName,
  24749. * gridIndex / gridId / gridName,
  24750. * ... (can be extended)
  24751. * }
  24752. * @param {Array|number} value
  24753. * @return {Array|number} result
  24754. */
  24755. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24756. /**
  24757. * Convert from pixel coordinate system to logical coordinate system.
  24758. * See CoordinateSystem#convertFromPixel.
  24759. * @param {string|Object} finder
  24760. * If string, e.g., 'geo', means {geoIndex: 0}.
  24761. * If Object, could contain some of these properties below:
  24762. * {
  24763. * seriesIndex / seriesId / seriesName,
  24764. * geoIndex / geoId / geoName,
  24765. * bmapIndex / bmapId / bmapName,
  24766. * xAxisIndex / xAxisId / xAxisName,
  24767. * yAxisIndex / yAxisId / yAxisName
  24768. * gridIndex / gridId / gridName,
  24769. * ... (can be extended)
  24770. * }
  24771. * @param {Array|number} value
  24772. * @return {Array|number} result
  24773. */
  24774. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24775. function doConvertPixel(methodName, finder, value) {
  24776. if (this._disposed) {
  24777. disposedWarning(this.id);
  24778. return;
  24779. }
  24780. var ecModel = this._model;
  24781. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24782. var result;
  24783. finder = parseFinder(ecModel, finder);
  24784. for (var i = 0; i < coordSysList.length; i++) {
  24785. var coordSys = coordSysList[i];
  24786. if (coordSys[methodName]
  24787. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24788. ) {
  24789. return result;
  24790. }
  24791. }
  24792. if (__DEV__) {
  24793. console.warn(
  24794. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24795. );
  24796. }
  24797. }
  24798. /**
  24799. * Is the specified coordinate systems or components contain the given pixel point.
  24800. * @param {string|Object} finder
  24801. * If string, e.g., 'geo', means {geoIndex: 0}.
  24802. * If Object, could contain some of these properties below:
  24803. * {
  24804. * seriesIndex / seriesId / seriesName,
  24805. * geoIndex / geoId / geoName,
  24806. * bmapIndex / bmapId / bmapName,
  24807. * xAxisIndex / xAxisId / xAxisName,
  24808. * yAxisIndex / yAxisId / yAxisName,
  24809. * gridIndex / gridId / gridName,
  24810. * ... (can be extended)
  24811. * }
  24812. * @param {Array|number} value
  24813. * @return {boolean} result
  24814. */
  24815. echartsProto.containPixel = function (finder, value) {
  24816. if (this._disposed) {
  24817. disposedWarning(this.id);
  24818. return;
  24819. }
  24820. var ecModel = this._model;
  24821. var result;
  24822. finder = parseFinder(ecModel, finder);
  24823. each$1(finder, function (models, key) {
  24824. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24825. var coordSys = model.coordinateSystem;
  24826. if (coordSys && coordSys.containPoint) {
  24827. result |= !!coordSys.containPoint(value);
  24828. }
  24829. else if (key === 'seriesModels') {
  24830. var view = this._chartsMap[model.__viewId];
  24831. if (view && view.containPoint) {
  24832. result |= view.containPoint(value, model);
  24833. }
  24834. else {
  24835. if (__DEV__) {
  24836. console.warn(key + ': ' + (view
  24837. ? 'The found component do not support containPoint.'
  24838. : 'No view mapping to the found component.'
  24839. ));
  24840. }
  24841. }
  24842. }
  24843. else {
  24844. if (__DEV__) {
  24845. console.warn(key + ': containPoint is not supported');
  24846. }
  24847. }
  24848. }, this);
  24849. }, this);
  24850. return !!result;
  24851. };
  24852. /**
  24853. * Get visual from series or data.
  24854. * @param {string|Object} finder
  24855. * If string, e.g., 'series', means {seriesIndex: 0}.
  24856. * If Object, could contain some of these properties below:
  24857. * {
  24858. * seriesIndex / seriesId / seriesName,
  24859. * dataIndex / dataIndexInside
  24860. * }
  24861. * If dataIndex is not specified, series visual will be fetched,
  24862. * but not data item visual.
  24863. * If all of seriesIndex, seriesId, seriesName are not specified,
  24864. * visual will be fetched from first series.
  24865. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24866. */
  24867. echartsProto.getVisual = function (finder, visualType) {
  24868. var ecModel = this._model;
  24869. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24870. var seriesModel = finder.seriesModel;
  24871. if (__DEV__) {
  24872. if (!seriesModel) {
  24873. console.warn('There is no specified seires model');
  24874. }
  24875. }
  24876. var data = seriesModel.getData();
  24877. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24878. ? finder.dataIndexInside
  24879. : finder.hasOwnProperty('dataIndex')
  24880. ? data.indexOfRawIndex(finder.dataIndex)
  24881. : null;
  24882. return dataIndexInside != null
  24883. ? data.getItemVisual(dataIndexInside, visualType)
  24884. : data.getVisual(visualType);
  24885. };
  24886. /**
  24887. * Get view of corresponding component model
  24888. * @param {module:echarts/model/Component} componentModel
  24889. * @return {module:echarts/view/Component}
  24890. */
  24891. echartsProto.getViewOfComponentModel = function (componentModel) {
  24892. return this._componentsMap[componentModel.__viewId];
  24893. };
  24894. /**
  24895. * Get view of corresponding series model
  24896. * @param {module:echarts/model/Series} seriesModel
  24897. * @return {module:echarts/view/Chart}
  24898. */
  24899. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24900. return this._chartsMap[seriesModel.__viewId];
  24901. };
  24902. var updateMethods = {
  24903. prepareAndUpdate: function (payload) {
  24904. prepare(this);
  24905. updateMethods.update.call(this, payload);
  24906. },
  24907. /**
  24908. * @param {Object} payload
  24909. * @private
  24910. */
  24911. update: function (payload) {
  24912. // console.profile && console.profile('update');
  24913. var ecModel = this._model;
  24914. var api = this._api;
  24915. var zr = this._zr;
  24916. var coordSysMgr = this._coordSysMgr;
  24917. var scheduler = this._scheduler;
  24918. // update before setOption
  24919. if (!ecModel) {
  24920. return;
  24921. }
  24922. scheduler.restoreData(ecModel, payload);
  24923. scheduler.performSeriesTasks(ecModel);
  24924. // TODO
  24925. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24926. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24927. // Create new coordinate system each update
  24928. // In LineView may save the old coordinate system and use it to get the orignal point
  24929. coordSysMgr.create(ecModel, api);
  24930. scheduler.performDataProcessorTasks(ecModel, payload);
  24931. // Current stream render is not supported in data process. So we can update
  24932. // stream modes after data processing, where the filtered data is used to
  24933. // deteming whether use progressive rendering.
  24934. updateStreamModes(this, ecModel);
  24935. // We update stream modes before coordinate system updated, then the modes info
  24936. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24937. // the drawback is the full coord info can not be fetched. Fortunately this full
  24938. // coord is not requied in stream mode updater currently.
  24939. coordSysMgr.update(ecModel, api);
  24940. clearColorPalette(ecModel);
  24941. scheduler.performVisualTasks(ecModel, payload);
  24942. render(this, ecModel, api, payload);
  24943. // Set background
  24944. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24945. // In IE8
  24946. if (!env$1.canvasSupported) {
  24947. var colorArr = parse(backgroundColor);
  24948. backgroundColor = stringify(colorArr, 'rgb');
  24949. if (colorArr[3] === 0) {
  24950. backgroundColor = 'transparent';
  24951. }
  24952. }
  24953. else {
  24954. zr.setBackgroundColor(backgroundColor);
  24955. }
  24956. performPostUpdateFuncs(ecModel, api);
  24957. // console.profile && console.profileEnd('update');
  24958. },
  24959. /**
  24960. * @param {Object} payload
  24961. * @private
  24962. */
  24963. updateTransform: function (payload) {
  24964. var ecModel = this._model;
  24965. var ecIns = this;
  24966. var api = this._api;
  24967. // update before setOption
  24968. if (!ecModel) {
  24969. return;
  24970. }
  24971. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24972. var componentDirtyList = [];
  24973. ecModel.eachComponent(function (componentType, componentModel) {
  24974. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24975. if (componentView && componentView.__alive) {
  24976. if (componentView.updateTransform) {
  24977. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24978. result && result.update && componentDirtyList.push(componentView);
  24979. }
  24980. else {
  24981. componentDirtyList.push(componentView);
  24982. }
  24983. }
  24984. });
  24985. var seriesDirtyMap = createHashMap();
  24986. ecModel.eachSeries(function (seriesModel) {
  24987. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24988. if (chartView.updateTransform) {
  24989. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24990. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24991. }
  24992. else {
  24993. seriesDirtyMap.set(seriesModel.uid, 1);
  24994. }
  24995. });
  24996. clearColorPalette(ecModel);
  24997. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24998. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24999. this._scheduler.performVisualTasks(
  25000. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  25001. );
  25002. // Currently, not call render of components. Geo render cost a lot.
  25003. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25004. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  25005. performPostUpdateFuncs(ecModel, this._api);
  25006. },
  25007. /**
  25008. * @param {Object} payload
  25009. * @private
  25010. */
  25011. updateView: function (payload) {
  25012. var ecModel = this._model;
  25013. // update before setOption
  25014. if (!ecModel) {
  25015. return;
  25016. }
  25017. Chart.markUpdateMethod(payload, 'updateView');
  25018. clearColorPalette(ecModel);
  25019. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25020. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25021. render(this, this._model, this._api, payload);
  25022. performPostUpdateFuncs(ecModel, this._api);
  25023. },
  25024. /**
  25025. * @param {Object} payload
  25026. * @private
  25027. */
  25028. updateVisual: function (payload) {
  25029. updateMethods.update.call(this, payload);
  25030. // var ecModel = this._model;
  25031. // // update before setOption
  25032. // if (!ecModel) {
  25033. // return;
  25034. // }
  25035. // ChartView.markUpdateMethod(payload, 'updateVisual');
  25036. // clearColorPalette(ecModel);
  25037. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25038. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  25039. // render(this, this._model, this._api, payload);
  25040. // performPostUpdateFuncs(ecModel, this._api);
  25041. },
  25042. /**
  25043. * @param {Object} payload
  25044. * @private
  25045. */
  25046. updateLayout: function (payload) {
  25047. updateMethods.update.call(this, payload);
  25048. // var ecModel = this._model;
  25049. // // update before setOption
  25050. // if (!ecModel) {
  25051. // return;
  25052. // }
  25053. // ChartView.markUpdateMethod(payload, 'updateLayout');
  25054. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25055. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25056. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  25057. // render(this, this._model, this._api, payload);
  25058. // performPostUpdateFuncs(ecModel, this._api);
  25059. }
  25060. };
  25061. function prepare(ecIns) {
  25062. var ecModel = ecIns._model;
  25063. var scheduler = ecIns._scheduler;
  25064. scheduler.restorePipelines(ecModel);
  25065. scheduler.prepareStageTasks();
  25066. prepareView(ecIns, 'component', ecModel, scheduler);
  25067. prepareView(ecIns, 'chart', ecModel, scheduler);
  25068. scheduler.plan();
  25069. }
  25070. /**
  25071. * @private
  25072. */
  25073. function updateDirectly(ecIns, method, payload, mainType, subType) {
  25074. var ecModel = ecIns._model;
  25075. // broadcast
  25076. if (!mainType) {
  25077. // FIXME
  25078. // Chart will not be update directly here, except set dirty.
  25079. // But there is no such scenario now.
  25080. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  25081. return;
  25082. }
  25083. var query = {};
  25084. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25085. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25086. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25087. var condition = {mainType: mainType, query: query};
  25088. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25089. var excludeSeriesId = payload.excludeSeriesId;
  25090. if (excludeSeriesId != null) {
  25091. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  25092. }
  25093. // If dispatchAction before setOption, do nothing.
  25094. ecModel && ecModel.eachComponent(condition, function (model) {
  25095. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  25096. callView(ecIns[
  25097. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25098. ][model.__viewId]);
  25099. }
  25100. }, ecIns);
  25101. function callView(view) {
  25102. view && view.__alive && view[method] && view[method](
  25103. view.__model, ecModel, ecIns._api, payload
  25104. );
  25105. }
  25106. }
  25107. /**
  25108. * Resize the chart
  25109. * @param {Object} opts
  25110. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  25111. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  25112. * @param {boolean} [opts.silent=false]
  25113. */
  25114. echartsProto.resize = function (opts) {
  25115. if (__DEV__) {
  25116. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  25117. }
  25118. if (this._disposed) {
  25119. disposedWarning(this.id);
  25120. return;
  25121. }
  25122. this._zr.resize(opts);
  25123. var ecModel = this._model;
  25124. // Resize loading effect
  25125. this._loadingFX && this._loadingFX.resize();
  25126. if (!ecModel) {
  25127. return;
  25128. }
  25129. var optionChanged = ecModel.resetOption('media');
  25130. var silent = opts && opts.silent;
  25131. this[IN_MAIN_PROCESS] = true;
  25132. optionChanged && prepare(this);
  25133. updateMethods.update.call(this);
  25134. this[IN_MAIN_PROCESS] = false;
  25135. flushPendingActions.call(this, silent);
  25136. triggerUpdatedEvent.call(this, silent);
  25137. };
  25138. function updateStreamModes(ecIns, ecModel) {
  25139. var chartsMap = ecIns._chartsMap;
  25140. var scheduler = ecIns._scheduler;
  25141. ecModel.eachSeries(function (seriesModel) {
  25142. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  25143. });
  25144. }
  25145. /**
  25146. * Show loading effect
  25147. * @param {string} [name='default']
  25148. * @param {Object} [cfg]
  25149. */
  25150. echartsProto.showLoading = function (name, cfg) {
  25151. if (this._disposed) {
  25152. disposedWarning(this.id);
  25153. return;
  25154. }
  25155. if (isObject(name)) {
  25156. cfg = name;
  25157. name = '';
  25158. }
  25159. name = name || 'default';
  25160. this.hideLoading();
  25161. if (!loadingEffects[name]) {
  25162. if (__DEV__) {
  25163. console.warn('Loading effects ' + name + ' not exists.');
  25164. }
  25165. return;
  25166. }
  25167. var el = loadingEffects[name](this._api, cfg);
  25168. var zr = this._zr;
  25169. this._loadingFX = el;
  25170. zr.add(el);
  25171. };
  25172. /**
  25173. * Hide loading effect
  25174. */
  25175. echartsProto.hideLoading = function () {
  25176. if (this._disposed) {
  25177. disposedWarning(this.id);
  25178. return;
  25179. }
  25180. this._loadingFX && this._zr.remove(this._loadingFX);
  25181. this._loadingFX = null;
  25182. };
  25183. /**
  25184. * @param {Object} eventObj
  25185. * @return {Object}
  25186. */
  25187. echartsProto.makeActionFromEvent = function (eventObj) {
  25188. var payload = extend({}, eventObj);
  25189. payload.type = eventActionMap[eventObj.type];
  25190. return payload;
  25191. };
  25192. /**
  25193. * @pubilc
  25194. * @param {Object} payload
  25195. * @param {string} [payload.type] Action type
  25196. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  25197. * @param {boolean} [opt.silent=false] Whether trigger events.
  25198. * @param {boolean} [opt.flush=undefined]
  25199. * true: Flush immediately, and then pixel in canvas can be fetched
  25200. * immediately. Caution: it might affect performance.
  25201. * false: Not flush.
  25202. * undefined: Auto decide whether perform flush.
  25203. */
  25204. echartsProto.dispatchAction = function (payload, opt) {
  25205. if (this._disposed) {
  25206. disposedWarning(this.id);
  25207. return;
  25208. }
  25209. if (!isObject(opt)) {
  25210. opt = {silent: !!opt};
  25211. }
  25212. if (!actions[payload.type]) {
  25213. return;
  25214. }
  25215. // Avoid dispatch action before setOption. Especially in `connect`.
  25216. if (!this._model) {
  25217. return;
  25218. }
  25219. // May dispatchAction in rendering procedure
  25220. if (this[IN_MAIN_PROCESS]) {
  25221. this._pendingActions.push(payload);
  25222. return;
  25223. }
  25224. doDispatchAction.call(this, payload, opt.silent);
  25225. if (opt.flush) {
  25226. this._zr.flush(true);
  25227. }
  25228. else if (opt.flush !== false && env$1.browser.weChat) {
  25229. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25230. // hang when sliding page (on touch event), which cause that zr does not
  25231. // refresh util user interaction finished, which is not expected.
  25232. // But `dispatchAction` may be called too frequently when pan on touch
  25233. // screen, which impacts performance if do not throttle them.
  25234. this._throttledZrFlush();
  25235. }
  25236. flushPendingActions.call(this, opt.silent);
  25237. triggerUpdatedEvent.call(this, opt.silent);
  25238. };
  25239. function doDispatchAction(payload, silent) {
  25240. var payloadType = payload.type;
  25241. var escapeConnect = payload.escapeConnect;
  25242. var actionWrap = actions[payloadType];
  25243. var actionInfo = actionWrap.actionInfo;
  25244. var cptType = (actionInfo.update || 'update').split(':');
  25245. var updateMethod = cptType.pop();
  25246. cptType = cptType[0] != null && parseClassType(cptType[0]);
  25247. this[IN_MAIN_PROCESS] = true;
  25248. var payloads = [payload];
  25249. var batched = false;
  25250. // Batch action
  25251. if (payload.batch) {
  25252. batched = true;
  25253. payloads = map(payload.batch, function (item) {
  25254. item = defaults(extend({}, item), payload);
  25255. item.batch = null;
  25256. return item;
  25257. });
  25258. }
  25259. var eventObjBatch = [];
  25260. var eventObj;
  25261. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  25262. each(payloads, function (batchItem) {
  25263. // Action can specify the event by return it.
  25264. eventObj = actionWrap.action(batchItem, this._model, this._api);
  25265. // Emit event outside
  25266. eventObj = eventObj || extend({}, batchItem);
  25267. // Convert type to eventType
  25268. eventObj.type = actionInfo.event || eventObj.type;
  25269. eventObjBatch.push(eventObj);
  25270. // light update does not perform data process, layout and visual.
  25271. if (isHighDown) {
  25272. // method, payload, mainType, subType
  25273. updateDirectly(this, updateMethod, batchItem, 'series');
  25274. }
  25275. else if (cptType) {
  25276. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  25277. }
  25278. }, this);
  25279. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  25280. // Still dirty
  25281. if (this[OPTION_UPDATED]) {
  25282. // FIXME Pass payload ?
  25283. prepare(this);
  25284. updateMethods.update.call(this, payload);
  25285. this[OPTION_UPDATED] = false;
  25286. }
  25287. else {
  25288. updateMethods[updateMethod].call(this, payload);
  25289. }
  25290. }
  25291. // Follow the rule of action batch
  25292. if (batched) {
  25293. eventObj = {
  25294. type: actionInfo.event || payloadType,
  25295. escapeConnect: escapeConnect,
  25296. batch: eventObjBatch
  25297. };
  25298. }
  25299. else {
  25300. eventObj = eventObjBatch[0];
  25301. }
  25302. this[IN_MAIN_PROCESS] = false;
  25303. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  25304. }
  25305. function flushPendingActions(silent) {
  25306. var pendingActions = this._pendingActions;
  25307. while (pendingActions.length) {
  25308. var payload = pendingActions.shift();
  25309. doDispatchAction.call(this, payload, silent);
  25310. }
  25311. }
  25312. function triggerUpdatedEvent(silent) {
  25313. !silent && this.trigger('updated');
  25314. }
  25315. /**
  25316. * Event `rendered` is triggered when zr
  25317. * rendered. It is useful for realtime
  25318. * snapshot (reflect animation).
  25319. *
  25320. * Event `finished` is triggered when:
  25321. * (1) zrender rendering finished.
  25322. * (2) initial animation finished.
  25323. * (3) progressive rendering finished.
  25324. * (4) no pending action.
  25325. * (5) no delayed setOption needs to be processed.
  25326. */
  25327. function bindRenderedEvent(zr, ecIns) {
  25328. zr.on('rendered', function () {
  25329. ecIns.trigger('rendered');
  25330. // The `finished` event should not be triggered repeatly,
  25331. // so it should only be triggered when rendering indeed happend
  25332. // in zrender. (Consider the case that dipatchAction is keep
  25333. // triggering when mouse move).
  25334. if (
  25335. // Although zr is dirty if initial animation is not finished
  25336. // and this checking is called on frame, we also check
  25337. // animation finished for robustness.
  25338. zr.animation.isFinished()
  25339. && !ecIns[OPTION_UPDATED]
  25340. && !ecIns._scheduler.unfinished
  25341. && !ecIns._pendingActions.length
  25342. ) {
  25343. ecIns.trigger('finished');
  25344. }
  25345. });
  25346. }
  25347. /**
  25348. * @param {Object} params
  25349. * @param {number} params.seriesIndex
  25350. * @param {Array|TypedArray} params.data
  25351. */
  25352. echartsProto.appendData = function (params) {
  25353. if (this._disposed) {
  25354. disposedWarning(this.id);
  25355. return;
  25356. }
  25357. var seriesIndex = params.seriesIndex;
  25358. var ecModel = this.getModel();
  25359. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25360. if (__DEV__) {
  25361. assert(params.data && seriesModel);
  25362. }
  25363. seriesModel.appendData(params);
  25364. // Note: `appendData` does not support that update extent of coordinate
  25365. // system, util some scenario require that. In the expected usage of
  25366. // `appendData`, the initial extent of coordinate system should better
  25367. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25368. // the extent changed while `appendData`, the location of the painted
  25369. // graphic elements have to be changed, which make the usage of
  25370. // `appendData` meaningless.
  25371. this._scheduler.unfinished = true;
  25372. };
  25373. /**
  25374. * Register event
  25375. * @method
  25376. */
  25377. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  25378. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  25379. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  25380. /**
  25381. * Prepare view instances of charts and components
  25382. * @param {module:echarts/model/Global} ecModel
  25383. * @private
  25384. */
  25385. function prepareView(ecIns, type, ecModel, scheduler) {
  25386. var isComponent = type === 'component';
  25387. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25388. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25389. var zr = ecIns._zr;
  25390. var api = ecIns._api;
  25391. for (var i = 0; i < viewList.length; i++) {
  25392. viewList[i].__alive = false;
  25393. }
  25394. isComponent
  25395. ? ecModel.eachComponent(function (componentType, model) {
  25396. componentType !== 'series' && doPrepare(model);
  25397. })
  25398. : ecModel.eachSeries(doPrepare);
  25399. function doPrepare(model) {
  25400. // Consider: id same and type changed.
  25401. var viewId = '_ec_' + model.id + '_' + model.type;
  25402. var view = viewMap[viewId];
  25403. if (!view) {
  25404. var classType = parseClassType(model.type);
  25405. var Clazz = isComponent
  25406. ? Component$1.getClass(classType.main, classType.sub)
  25407. : Chart.getClass(classType.sub);
  25408. if (__DEV__) {
  25409. assert(Clazz, classType.sub + ' does not exist.');
  25410. }
  25411. view = new Clazz();
  25412. view.init(ecModel, api);
  25413. viewMap[viewId] = view;
  25414. viewList.push(view);
  25415. zr.add(view.group);
  25416. }
  25417. model.__viewId = view.__id = viewId;
  25418. view.__alive = true;
  25419. view.__model = model;
  25420. view.group.__ecComponentInfo = {
  25421. mainType: model.mainType,
  25422. index: model.componentIndex
  25423. };
  25424. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25425. }
  25426. for (var i = 0; i < viewList.length;) {
  25427. var view = viewList[i];
  25428. if (!view.__alive) {
  25429. !isComponent && view.renderTask.dispose();
  25430. zr.remove(view.group);
  25431. view.dispose(ecModel, api);
  25432. viewList.splice(i, 1);
  25433. delete viewMap[view.__id];
  25434. view.__id = view.group.__ecComponentInfo = null;
  25435. }
  25436. else {
  25437. i++;
  25438. }
  25439. }
  25440. }
  25441. // /**
  25442. // * Encode visual infomation from data after data processing
  25443. // *
  25444. // * @param {module:echarts/model/Global} ecModel
  25445. // * @param {object} layout
  25446. // * @param {boolean} [layoutFilter] `true`: only layout,
  25447. // * `false`: only not layout,
  25448. // * `null`/`undefined`: all.
  25449. // * @param {string} taskBaseTag
  25450. // * @private
  25451. // */
  25452. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  25453. // each(visualFuncs, function (visual, index) {
  25454. // var isLayout = visual.isLayout;
  25455. // if (layoutFilter == null
  25456. // || (layoutFilter === false && !isLayout)
  25457. // || (layoutFilter === true && isLayout)
  25458. // ) {
  25459. // visual.func(ecModel, api, payload);
  25460. // }
  25461. // });
  25462. // }
  25463. function clearColorPalette(ecModel) {
  25464. ecModel.clearColorPalette();
  25465. ecModel.eachSeries(function (seriesModel) {
  25466. seriesModel.clearColorPalette();
  25467. });
  25468. }
  25469. function render(ecIns, ecModel, api, payload) {
  25470. renderComponents(ecIns, ecModel, api, payload);
  25471. each(ecIns._chartsViews, function (chart) {
  25472. chart.__alive = false;
  25473. });
  25474. renderSeries(ecIns, ecModel, api, payload);
  25475. // Remove groups of unrendered charts
  25476. each(ecIns._chartsViews, function (chart) {
  25477. if (!chart.__alive) {
  25478. chart.remove(ecModel, api);
  25479. }
  25480. });
  25481. }
  25482. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  25483. each(dirtyList || ecIns._componentsViews, function (componentView) {
  25484. var componentModel = componentView.__model;
  25485. componentView.render(componentModel, ecModel, api, payload);
  25486. updateZ(componentModel, componentView);
  25487. });
  25488. }
  25489. /**
  25490. * Render each chart and component
  25491. * @private
  25492. */
  25493. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  25494. // Render all charts
  25495. var scheduler = ecIns._scheduler;
  25496. var unfinished;
  25497. ecModel.eachSeries(function (seriesModel) {
  25498. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25499. chartView.__alive = true;
  25500. var renderTask = chartView.renderTask;
  25501. scheduler.updatePayload(renderTask, payload);
  25502. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  25503. renderTask.dirty();
  25504. }
  25505. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  25506. chartView.group.silent = !!seriesModel.get('silent');
  25507. updateZ(seriesModel, chartView);
  25508. updateBlend(seriesModel, chartView);
  25509. });
  25510. scheduler.unfinished |= unfinished;
  25511. // If use hover layer
  25512. updateHoverLayerStatus(ecIns, ecModel);
  25513. // Add aria
  25514. aria(ecIns._zr.dom, ecModel);
  25515. }
  25516. function performPostUpdateFuncs(ecModel, api) {
  25517. each(postUpdateFuncs, function (func) {
  25518. func(ecModel, api);
  25519. });
  25520. }
  25521. var MOUSE_EVENT_NAMES = [
  25522. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  25523. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  25524. ];
  25525. /**
  25526. * @private
  25527. */
  25528. echartsProto._initEvents = function () {
  25529. each(MOUSE_EVENT_NAMES, function (eveName) {
  25530. var handler = function (e) {
  25531. var ecModel = this.getModel();
  25532. var el = e.target;
  25533. var params;
  25534. var isGlobalOut = eveName === 'globalout';
  25535. // no e.target when 'globalout'.
  25536. if (isGlobalOut) {
  25537. params = {};
  25538. }
  25539. else if (el && el.dataIndex != null) {
  25540. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  25541. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  25542. }
  25543. // If element has custom eventData of components
  25544. else if (el && el.eventData) {
  25545. params = extend({}, el.eventData);
  25546. }
  25547. // Contract: if params prepared in mouse event,
  25548. // these properties must be specified:
  25549. // {
  25550. // componentType: string (component main type)
  25551. // componentIndex: number
  25552. // }
  25553. // Otherwise event query can not work.
  25554. if (params) {
  25555. var componentType = params.componentType;
  25556. var componentIndex = params.componentIndex;
  25557. // Special handling for historic reason: when trigger by
  25558. // markLine/markPoint/markArea, the componentType is
  25559. // 'markLine'/'markPoint'/'markArea', but we should better
  25560. // enable them to be queried by seriesIndex, since their
  25561. // option is set in each series.
  25562. if (componentType === 'markLine'
  25563. || componentType === 'markPoint'
  25564. || componentType === 'markArea'
  25565. ) {
  25566. componentType = 'series';
  25567. componentIndex = params.seriesIndex;
  25568. }
  25569. var model = componentType && componentIndex != null
  25570. && ecModel.getComponent(componentType, componentIndex);
  25571. var view = model && this[
  25572. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  25573. ][model.__viewId];
  25574. if (__DEV__) {
  25575. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25576. // be missed, otherwise there is no way to distinguish source component.
  25577. // See `dataFormat.getDataParams`.
  25578. if (!isGlobalOut && !(model && view)) {
  25579. console.warn('model or view can not be found by params');
  25580. }
  25581. }
  25582. params.event = e;
  25583. params.type = eveName;
  25584. this._ecEventProcessor.eventInfo = {
  25585. targetEl: el,
  25586. packedEvent: params,
  25587. model: model,
  25588. view: view
  25589. };
  25590. this.trigger(eveName, params);
  25591. }
  25592. };
  25593. // Consider that some component (like tooltip, brush, ...)
  25594. // register zr event handler, but user event handler might
  25595. // do anything, such as call `setOption` or `dispatchAction`,
  25596. // which probably update any of the content and probably
  25597. // cause problem if it is called previous other inner handlers.
  25598. handler.zrEventfulCallAtLast = true;
  25599. this._zr.on(eveName, handler, this);
  25600. }, this);
  25601. each(eventActionMap, function (actionType, eventType) {
  25602. this._messageCenter.on(eventType, function (event) {
  25603. this.trigger(eventType, event);
  25604. }, this);
  25605. }, this);
  25606. };
  25607. /**
  25608. * @return {boolean}
  25609. */
  25610. echartsProto.isDisposed = function () {
  25611. return this._disposed;
  25612. };
  25613. /**
  25614. * Clear
  25615. */
  25616. echartsProto.clear = function () {
  25617. if (this._disposed) {
  25618. disposedWarning(this.id);
  25619. return;
  25620. }
  25621. this.setOption({ series: [] }, true);
  25622. };
  25623. /**
  25624. * Dispose instance
  25625. */
  25626. echartsProto.dispose = function () {
  25627. if (this._disposed) {
  25628. disposedWarning(this.id);
  25629. return;
  25630. }
  25631. this._disposed = true;
  25632. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25633. var api = this._api;
  25634. var ecModel = this._model;
  25635. each(this._componentsViews, function (component) {
  25636. component.dispose(ecModel, api);
  25637. });
  25638. each(this._chartsViews, function (chart) {
  25639. chart.dispose(ecModel, api);
  25640. });
  25641. // Dispose after all views disposed
  25642. this._zr.dispose();
  25643. delete instances[this.id];
  25644. };
  25645. mixin(ECharts, Eventful);
  25646. function disposedWarning(id) {
  25647. if (__DEV__) {
  25648. console.warn('Instance ' + id + ' has been disposed');
  25649. }
  25650. }
  25651. function updateHoverLayerStatus(ecIns, ecModel) {
  25652. var zr = ecIns._zr;
  25653. var storage = zr.storage;
  25654. var elCount = 0;
  25655. storage.traverse(function (el) {
  25656. elCount++;
  25657. });
  25658. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25659. ecModel.eachSeries(function (seriesModel) {
  25660. if (seriesModel.preventUsingHoverLayer) {
  25661. return;
  25662. }
  25663. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25664. if (chartView.__alive) {
  25665. chartView.group.traverse(function (el) {
  25666. // Don't switch back.
  25667. el.useHoverLayer = true;
  25668. });
  25669. }
  25670. });
  25671. }
  25672. }
  25673. /**
  25674. * Update chart progressive and blend.
  25675. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25676. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25677. */
  25678. function updateBlend(seriesModel, chartView) {
  25679. var blendMode = seriesModel.get('blendMode') || null;
  25680. if (__DEV__) {
  25681. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25682. console.warn('Only canvas support blendMode');
  25683. }
  25684. }
  25685. chartView.group.traverse(function (el) {
  25686. // FIXME marker and other components
  25687. if (!el.isGroup) {
  25688. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25689. if (el.style.blend !== blendMode) {
  25690. el.setStyle('blend', blendMode);
  25691. }
  25692. }
  25693. if (el.eachPendingDisplayable) {
  25694. el.eachPendingDisplayable(function (displayable) {
  25695. displayable.setStyle('blend', blendMode);
  25696. });
  25697. }
  25698. });
  25699. }
  25700. /**
  25701. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25702. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25703. */
  25704. function updateZ(model, view) {
  25705. var z = model.get('z');
  25706. var zlevel = model.get('zlevel');
  25707. // Set z and zlevel
  25708. view.group.traverse(function (el) {
  25709. if (el.type !== 'group') {
  25710. z != null && (el.z = z);
  25711. zlevel != null && (el.zlevel = zlevel);
  25712. }
  25713. });
  25714. }
  25715. function createExtensionAPI(ecInstance) {
  25716. var coordSysMgr = ecInstance._coordSysMgr;
  25717. return extend(new ExtensionAPI(ecInstance), {
  25718. // Inject methods
  25719. getCoordinateSystems: bind(
  25720. coordSysMgr.getCoordinateSystems, coordSysMgr
  25721. ),
  25722. getComponentByElement: function (el) {
  25723. while (el) {
  25724. var modelInfo = el.__ecComponentInfo;
  25725. if (modelInfo != null) {
  25726. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25727. }
  25728. el = el.parent;
  25729. }
  25730. }
  25731. });
  25732. }
  25733. /**
  25734. * @class
  25735. * Usage of query:
  25736. * `chart.on('click', query, handler);`
  25737. * The `query` can be:
  25738. * + The component type query string, only `mainType` or `mainType.subType`,
  25739. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25740. * + The component query object, like:
  25741. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25742. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25743. * + The data query object, like:
  25744. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25745. * + The other query object (cmponent customized query), like:
  25746. * `{element: 'some'}` (only available in custom series).
  25747. *
  25748. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25749. * same as there is no such prop in the `query` object.
  25750. */
  25751. function EventProcessor() {
  25752. // These info required: targetEl, packedEvent, model, view
  25753. this.eventInfo;
  25754. }
  25755. EventProcessor.prototype = {
  25756. constructor: EventProcessor,
  25757. normalizeQuery: function (query) {
  25758. var cptQuery = {};
  25759. var dataQuery = {};
  25760. var otherQuery = {};
  25761. // `query` is `mainType` or `mainType.subType` of component.
  25762. if (isString(query)) {
  25763. var condCptType = parseClassType(query);
  25764. // `.main` and `.sub` may be ''.
  25765. cptQuery.mainType = condCptType.main || null;
  25766. cptQuery.subType = condCptType.sub || null;
  25767. }
  25768. // `query` is an object, convert to {mainType, index, name, id}.
  25769. else {
  25770. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25771. // can not be used in `compomentModel.filterForExposedEvent`.
  25772. var suffixes = ['Index', 'Name', 'Id'];
  25773. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25774. each$1(query, function (val, key) {
  25775. var reserved = false;
  25776. for (var i = 0; i < suffixes.length; i++) {
  25777. var propSuffix = suffixes[i];
  25778. var suffixPos = key.lastIndexOf(propSuffix);
  25779. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25780. var mainType = key.slice(0, suffixPos);
  25781. // Consider `dataIndex`.
  25782. if (mainType !== 'data') {
  25783. cptQuery.mainType = mainType;
  25784. cptQuery[propSuffix.toLowerCase()] = val;
  25785. reserved = true;
  25786. }
  25787. }
  25788. }
  25789. if (dataKeys.hasOwnProperty(key)) {
  25790. dataQuery[key] = val;
  25791. reserved = true;
  25792. }
  25793. if (!reserved) {
  25794. otherQuery[key] = val;
  25795. }
  25796. });
  25797. }
  25798. return {
  25799. cptQuery: cptQuery,
  25800. dataQuery: dataQuery,
  25801. otherQuery: otherQuery
  25802. };
  25803. },
  25804. filter: function (eventType, query, args) {
  25805. // They should be assigned before each trigger call.
  25806. var eventInfo = this.eventInfo;
  25807. if (!eventInfo) {
  25808. return true;
  25809. }
  25810. var targetEl = eventInfo.targetEl;
  25811. var packedEvent = eventInfo.packedEvent;
  25812. var model = eventInfo.model;
  25813. var view = eventInfo.view;
  25814. // For event like 'globalout'.
  25815. if (!model || !view) {
  25816. return true;
  25817. }
  25818. var cptQuery = query.cptQuery;
  25819. var dataQuery = query.dataQuery;
  25820. return check(cptQuery, model, 'mainType')
  25821. && check(cptQuery, model, 'subType')
  25822. && check(cptQuery, model, 'index', 'componentIndex')
  25823. && check(cptQuery, model, 'name')
  25824. && check(cptQuery, model, 'id')
  25825. && check(dataQuery, packedEvent, 'name')
  25826. && check(dataQuery, packedEvent, 'dataIndex')
  25827. && check(dataQuery, packedEvent, 'dataType')
  25828. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25829. eventType, query.otherQuery, targetEl, packedEvent
  25830. ));
  25831. function check(query, host, prop, propOnHost) {
  25832. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25833. }
  25834. },
  25835. afterTrigger: function () {
  25836. // Make sure the eventInfo wont be used in next trigger.
  25837. this.eventInfo = null;
  25838. }
  25839. };
  25840. /**
  25841. * @type {Object} key: actionType.
  25842. * @inner
  25843. */
  25844. var actions = {};
  25845. /**
  25846. * Map eventType to actionType
  25847. * @type {Object}
  25848. */
  25849. var eventActionMap = {};
  25850. /**
  25851. * Data processor functions of each stage
  25852. * @type {Array.<Object.<string, Function>>}
  25853. * @inner
  25854. */
  25855. var dataProcessorFuncs = [];
  25856. /**
  25857. * @type {Array.<Function>}
  25858. * @inner
  25859. */
  25860. var optionPreprocessorFuncs = [];
  25861. /**
  25862. * @type {Array.<Function>}
  25863. * @inner
  25864. */
  25865. var postUpdateFuncs = [];
  25866. /**
  25867. * Visual encoding functions of each stage
  25868. * @type {Array.<Object.<string, Function>>}
  25869. */
  25870. var visualFuncs = [];
  25871. /**
  25872. * Theme storage
  25873. * @type {Object.<key, Object>}
  25874. */
  25875. var themeStorage = {};
  25876. /**
  25877. * Loading effects
  25878. */
  25879. var loadingEffects = {};
  25880. var instances = {};
  25881. var connectedGroups = {};
  25882. var idBase = new Date() - 0;
  25883. var groupIdBase = new Date() - 0;
  25884. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25885. function enableConnect(chart) {
  25886. var STATUS_PENDING = 0;
  25887. var STATUS_UPDATING = 1;
  25888. var STATUS_UPDATED = 2;
  25889. var STATUS_KEY = '__connectUpdateStatus';
  25890. function updateConnectedChartsStatus(charts, status) {
  25891. for (var i = 0; i < charts.length; i++) {
  25892. var otherChart = charts[i];
  25893. otherChart[STATUS_KEY] = status;
  25894. }
  25895. }
  25896. each(eventActionMap, function (actionType, eventType) {
  25897. chart._messageCenter.on(eventType, function (event) {
  25898. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25899. if (event && event.escapeConnect) {
  25900. return;
  25901. }
  25902. var action = chart.makeActionFromEvent(event);
  25903. var otherCharts = [];
  25904. each(instances, function (otherChart) {
  25905. if (otherChart !== chart && otherChart.group === chart.group) {
  25906. otherCharts.push(otherChart);
  25907. }
  25908. });
  25909. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25910. each(otherCharts, function (otherChart) {
  25911. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25912. otherChart.dispatchAction(action);
  25913. }
  25914. });
  25915. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25916. }
  25917. });
  25918. });
  25919. }
  25920. /**
  25921. * @param {HTMLElement} dom
  25922. * @param {Object} [theme]
  25923. * @param {Object} opts
  25924. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25925. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25926. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25927. * Can be 'auto' (the same as null/undefined)
  25928. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25929. * Can be 'auto' (the same as null/undefined)
  25930. */
  25931. function init(dom, theme$$1, opts) {
  25932. if (__DEV__) {
  25933. // Check version
  25934. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25935. throw new Error(
  25936. 'zrender/src ' + version$1
  25937. + ' is too old for ECharts ' + version
  25938. + '. Current version need ZRender '
  25939. + dependencies.zrender + '+'
  25940. );
  25941. }
  25942. if (!dom) {
  25943. throw new Error('Initialize failed: invalid dom.');
  25944. }
  25945. }
  25946. var existInstance = getInstanceByDom(dom);
  25947. if (existInstance) {
  25948. if (__DEV__) {
  25949. console.warn('There is a chart instance already initialized on the dom.');
  25950. }
  25951. return existInstance;
  25952. }
  25953. if (__DEV__) {
  25954. if (isDom(dom)
  25955. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25956. && (
  25957. (!dom.clientWidth && (!opts || opts.width == null))
  25958. || (!dom.clientHeight && (!opts || opts.height == null))
  25959. )
  25960. ) {
  25961. console.warn('Can\'t get DOM width or height. Please check '
  25962. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25963. + 'For example, you may need to call this in the callback '
  25964. + 'of window.onload.');
  25965. }
  25966. }
  25967. var chart = new ECharts(dom, theme$$1, opts);
  25968. chart.id = 'ec_' + idBase++;
  25969. instances[chart.id] = chart;
  25970. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25971. enableConnect(chart);
  25972. return chart;
  25973. }
  25974. /**
  25975. * @return {string|Array.<module:echarts~ECharts>} groupId
  25976. */
  25977. function connect(groupId) {
  25978. // Is array of charts
  25979. if (isArray(groupId)) {
  25980. var charts = groupId;
  25981. groupId = null;
  25982. // If any chart has group
  25983. each(charts, function (chart) {
  25984. if (chart.group != null) {
  25985. groupId = chart.group;
  25986. }
  25987. });
  25988. groupId = groupId || ('g_' + groupIdBase++);
  25989. each(charts, function (chart) {
  25990. chart.group = groupId;
  25991. });
  25992. }
  25993. connectedGroups[groupId] = true;
  25994. return groupId;
  25995. }
  25996. /**
  25997. * @DEPRECATED
  25998. * @return {string} groupId
  25999. */
  26000. function disConnect(groupId) {
  26001. connectedGroups[groupId] = false;
  26002. }
  26003. /**
  26004. * @return {string} groupId
  26005. */
  26006. var disconnect = disConnect;
  26007. /**
  26008. * Dispose a chart instance
  26009. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  26010. */
  26011. function dispose(chart) {
  26012. if (typeof chart === 'string') {
  26013. chart = instances[chart];
  26014. }
  26015. else if (!(chart instanceof ECharts)) {
  26016. // Try to treat as dom
  26017. chart = getInstanceByDom(chart);
  26018. }
  26019. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  26020. chart.dispose();
  26021. }
  26022. }
  26023. /**
  26024. * @param {HTMLElement} dom
  26025. * @return {echarts~ECharts}
  26026. */
  26027. function getInstanceByDom(dom) {
  26028. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26029. }
  26030. /**
  26031. * @param {string} key
  26032. * @return {echarts~ECharts}
  26033. */
  26034. function getInstanceById(key) {
  26035. return instances[key];
  26036. }
  26037. /**
  26038. * Register theme
  26039. */
  26040. function registerTheme(name, theme$$1) {
  26041. themeStorage[name] = theme$$1;
  26042. }
  26043. /**
  26044. * Register option preprocessor
  26045. * @param {Function} preprocessorFunc
  26046. */
  26047. function registerPreprocessor(preprocessorFunc) {
  26048. optionPreprocessorFuncs.push(preprocessorFunc);
  26049. }
  26050. /**
  26051. * @param {number} [priority=1000]
  26052. * @param {Object|Function} processor
  26053. */
  26054. function registerProcessor(priority, processor) {
  26055. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  26056. }
  26057. /**
  26058. * Register postUpdater
  26059. * @param {Function} postUpdateFunc
  26060. */
  26061. function registerPostUpdate(postUpdateFunc) {
  26062. postUpdateFuncs.push(postUpdateFunc);
  26063. }
  26064. /**
  26065. * Usage:
  26066. * registerAction('someAction', 'someEvent', function () { ... });
  26067. * registerAction('someAction', function () { ... });
  26068. * registerAction(
  26069. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  26070. * function () { ... }
  26071. * );
  26072. *
  26073. * @param {(string|Object)} actionInfo
  26074. * @param {string} actionInfo.type
  26075. * @param {string} [actionInfo.event]
  26076. * @param {string} [actionInfo.update]
  26077. * @param {string} [eventName]
  26078. * @param {Function} action
  26079. */
  26080. function registerAction(actionInfo, eventName, action) {
  26081. if (typeof eventName === 'function') {
  26082. action = eventName;
  26083. eventName = '';
  26084. }
  26085. var actionType = isObject(actionInfo)
  26086. ? actionInfo.type
  26087. : ([actionInfo, actionInfo = {
  26088. event: eventName
  26089. }][0]);
  26090. // Event name is all lowercase
  26091. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26092. eventName = actionInfo.event;
  26093. // Validate action type and event name.
  26094. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26095. if (!actions[actionType]) {
  26096. actions[actionType] = {action: action, actionInfo: actionInfo};
  26097. }
  26098. eventActionMap[eventName] = actionType;
  26099. }
  26100. /**
  26101. * @param {string} type
  26102. * @param {*} CoordinateSystem
  26103. */
  26104. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  26105. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  26106. }
  26107. /**
  26108. * Get dimensions of specified coordinate system.
  26109. * @param {string} type
  26110. * @return {Array.<string|Object>}
  26111. */
  26112. function getCoordinateSystemDimensions(type) {
  26113. var coordSysCreator = CoordinateSystemManager.get(type);
  26114. if (coordSysCreator) {
  26115. return coordSysCreator.getDimensionsInfo
  26116. ? coordSysCreator.getDimensionsInfo()
  26117. : coordSysCreator.dimensions.slice();
  26118. }
  26119. }
  26120. /**
  26121. * Layout is a special stage of visual encoding
  26122. * Most visual encoding like color are common for different chart
  26123. * But each chart has it's own layout algorithm
  26124. *
  26125. * @param {number} [priority=1000]
  26126. * @param {Function} layoutTask
  26127. */
  26128. function registerLayout(priority, layoutTask) {
  26129. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26130. }
  26131. /**
  26132. * @param {number} [priority=3000]
  26133. * @param {module:echarts/stream/Task} visualTask
  26134. */
  26135. function registerVisual(priority, visualTask) {
  26136. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26137. }
  26138. /**
  26139. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  26140. */
  26141. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26142. if (isFunction(priority) || isObject(priority)) {
  26143. fn = priority;
  26144. priority = defaultPriority;
  26145. }
  26146. if (__DEV__) {
  26147. if (isNaN(priority) || priority == null) {
  26148. throw new Error('Illegal priority');
  26149. }
  26150. // Check duplicate
  26151. each(targetList, function (wrap) {
  26152. assert(wrap.__raw !== fn);
  26153. });
  26154. }
  26155. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26156. stageHandler.__prio = priority;
  26157. stageHandler.__raw = fn;
  26158. targetList.push(stageHandler);
  26159. return stageHandler;
  26160. }
  26161. /**
  26162. * @param {string} name
  26163. */
  26164. function registerLoading(name, loadingFx) {
  26165. loadingEffects[name] = loadingFx;
  26166. }
  26167. /**
  26168. * @param {Object} opts
  26169. * @param {string} [superClass]
  26170. */
  26171. function extendComponentModel(opts/*, superClass*/) {
  26172. // var Clazz = ComponentModel;
  26173. // if (superClass) {
  26174. // var classType = parseClassType(superClass);
  26175. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26176. // }
  26177. return ComponentModel.extend(opts);
  26178. }
  26179. /**
  26180. * @param {Object} opts
  26181. * @param {string} [superClass]
  26182. */
  26183. function extendComponentView(opts/*, superClass*/) {
  26184. // var Clazz = ComponentView;
  26185. // if (superClass) {
  26186. // var classType = parseClassType(superClass);
  26187. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  26188. // }
  26189. return Component$1.extend(opts);
  26190. }
  26191. /**
  26192. * @param {Object} opts
  26193. * @param {string} [superClass]
  26194. */
  26195. function extendSeriesModel(opts/*, superClass*/) {
  26196. // var Clazz = SeriesModel;
  26197. // if (superClass) {
  26198. // superClass = 'series.' + superClass.replace('series.', '');
  26199. // var classType = parseClassType(superClass);
  26200. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  26201. // }
  26202. return SeriesModel.extend(opts);
  26203. }
  26204. /**
  26205. * @param {Object} opts
  26206. * @param {string} [superClass]
  26207. */
  26208. function extendChartView(opts/*, superClass*/) {
  26209. // var Clazz = ChartView;
  26210. // if (superClass) {
  26211. // superClass = superClass.replace('series.', '');
  26212. // var classType = parseClassType(superClass);
  26213. // Clazz = ChartView.getClass(classType.main, true);
  26214. // }
  26215. return Chart.extend(opts);
  26216. }
  26217. /**
  26218. * ZRender need a canvas context to do measureText.
  26219. * But in node environment canvas may be created by node-canvas.
  26220. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26221. *
  26222. * Be careful of using it in the browser.
  26223. *
  26224. * @param {Function} creator
  26225. * @example
  26226. * var Canvas = require('canvas');
  26227. * var echarts = require('echarts');
  26228. * echarts.setCanvasCreator(function () {
  26229. * // Small size is enough.
  26230. * return new Canvas(32, 32);
  26231. * });
  26232. */
  26233. function setCanvasCreator(creator) {
  26234. $override('createCanvas', creator);
  26235. }
  26236. /**
  26237. * @param {string} mapName
  26238. * @param {Array.<Object>|Object|string} geoJson
  26239. * @param {Object} [specialAreas]
  26240. *
  26241. * @example GeoJSON
  26242. * $.get('USA.json', function (geoJson) {
  26243. * echarts.registerMap('USA', geoJson);
  26244. * // Or
  26245. * echarts.registerMap('USA', {
  26246. * geoJson: geoJson,
  26247. * specialAreas: {}
  26248. * })
  26249. * });
  26250. *
  26251. * $.get('airport.svg', function (svg) {
  26252. * echarts.registerMap('airport', {
  26253. * svg: svg
  26254. * }
  26255. * });
  26256. *
  26257. * echarts.registerMap('eu', [
  26258. * {svg: eu-topographic.svg},
  26259. * {geoJSON: eu.json}
  26260. * ])
  26261. */
  26262. function registerMap(mapName, geoJson, specialAreas) {
  26263. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26264. }
  26265. /**
  26266. * @param {string} mapName
  26267. * @return {Object}
  26268. */
  26269. function getMap(mapName) {
  26270. // For backward compatibility, only return the first one.
  26271. var records = mapDataStorage.retrieveMap(mapName);
  26272. return records && records[0] && {
  26273. geoJson: records[0].geoJSON,
  26274. specialAreas: records[0].specialAreas
  26275. };
  26276. }
  26277. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  26278. registerPreprocessor(backwardCompat);
  26279. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26280. registerLoading('default', loadingDefault);
  26281. // Default actions
  26282. registerAction({
  26283. type: 'highlight',
  26284. event: 'highlight',
  26285. update: 'highlight'
  26286. }, noop);
  26287. registerAction({
  26288. type: 'downplay',
  26289. event: 'downplay',
  26290. update: 'downplay'
  26291. }, noop);
  26292. // Default theme
  26293. registerTheme('light', lightTheme);
  26294. registerTheme('dark', theme);
  26295. // For backward compatibility, where the namespace `dataTool` will
  26296. // be mounted on `echarts` is the extension `dataTool` is imported.
  26297. var dataTool = {};
  26298. /*
  26299. * Licensed to the Apache Software Foundation (ASF) under one
  26300. * or more contributor license agreements. See the NOTICE file
  26301. * distributed with this work for additional information
  26302. * regarding copyright ownership. The ASF licenses this file
  26303. * to you under the Apache License, Version 2.0 (the
  26304. * "License"); you may not use this file except in compliance
  26305. * with the License. You may obtain a copy of the License at
  26306. *
  26307. * http://www.apache.org/licenses/LICENSE-2.0
  26308. *
  26309. * Unless required by applicable law or agreed to in writing,
  26310. * software distributed under the License is distributed on an
  26311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26312. * KIND, either express or implied. See the License for the
  26313. * specific language governing permissions and limitations
  26314. * under the License.
  26315. */
  26316. function defaultKeyGetter(item) {
  26317. return item;
  26318. }
  26319. /**
  26320. * @param {Array} oldArr
  26321. * @param {Array} newArr
  26322. * @param {Function} oldKeyGetter
  26323. * @param {Function} newKeyGetter
  26324. * @param {Object} [context] Can be visited by this.context in callback.
  26325. */
  26326. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  26327. this._old = oldArr;
  26328. this._new = newArr;
  26329. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  26330. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  26331. this.context = context;
  26332. }
  26333. DataDiffer.prototype = {
  26334. constructor: DataDiffer,
  26335. /**
  26336. * Callback function when add a data
  26337. */
  26338. add: function (func) {
  26339. this._add = func;
  26340. return this;
  26341. },
  26342. /**
  26343. * Callback function when update a data
  26344. */
  26345. update: function (func) {
  26346. this._update = func;
  26347. return this;
  26348. },
  26349. /**
  26350. * Callback function when remove a data
  26351. */
  26352. remove: function (func) {
  26353. this._remove = func;
  26354. return this;
  26355. },
  26356. execute: function () {
  26357. var oldArr = this._old;
  26358. var newArr = this._new;
  26359. var oldDataIndexMap = {};
  26360. var newDataIndexMap = {};
  26361. var oldDataKeyArr = [];
  26362. var newDataKeyArr = [];
  26363. var i;
  26364. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  26365. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  26366. for (i = 0; i < oldArr.length; i++) {
  26367. var key = oldDataKeyArr[i];
  26368. var idx = newDataIndexMap[key];
  26369. // idx can never be empty array here. see 'set null' logic below.
  26370. if (idx != null) {
  26371. // Consider there is duplicate key (for example, use dataItem.name as key).
  26372. // We should make sure every item in newArr and oldArr can be visited.
  26373. var len = idx.length;
  26374. if (len) {
  26375. len === 1 && (newDataIndexMap[key] = null);
  26376. idx = idx.shift();
  26377. }
  26378. else {
  26379. newDataIndexMap[key] = null;
  26380. }
  26381. this._update && this._update(idx, i);
  26382. }
  26383. else {
  26384. this._remove && this._remove(i);
  26385. }
  26386. }
  26387. for (var i = 0; i < newDataKeyArr.length; i++) {
  26388. var key = newDataKeyArr[i];
  26389. if (newDataIndexMap.hasOwnProperty(key)) {
  26390. var idx = newDataIndexMap[key];
  26391. if (idx == null) {
  26392. continue;
  26393. }
  26394. // idx can never be empty array here. see 'set null' logic above.
  26395. if (!idx.length) {
  26396. this._add && this._add(idx);
  26397. }
  26398. else {
  26399. for (var j = 0, len = idx.length; j < len; j++) {
  26400. this._add && this._add(idx[j]);
  26401. }
  26402. }
  26403. }
  26404. }
  26405. }
  26406. };
  26407. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  26408. for (var i = 0; i < arr.length; i++) {
  26409. // Add prefix to avoid conflict with Object.prototype.
  26410. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  26411. var existence = map[key];
  26412. if (existence == null) {
  26413. keyArr.push(key);
  26414. map[key] = i;
  26415. }
  26416. else {
  26417. if (!existence.length) {
  26418. map[key] = existence = [existence];
  26419. }
  26420. existence.push(i);
  26421. }
  26422. }
  26423. }
  26424. /*
  26425. * Licensed to the Apache Software Foundation (ASF) under one
  26426. * or more contributor license agreements. See the NOTICE file
  26427. * distributed with this work for additional information
  26428. * regarding copyright ownership. The ASF licenses this file
  26429. * to you under the Apache License, Version 2.0 (the
  26430. * "License"); you may not use this file except in compliance
  26431. * with the License. You may obtain a copy of the License at
  26432. *
  26433. * http://www.apache.org/licenses/LICENSE-2.0
  26434. *
  26435. * Unless required by applicable law or agreed to in writing,
  26436. * software distributed under the License is distributed on an
  26437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26438. * KIND, either express or implied. See the License for the
  26439. * specific language governing permissions and limitations
  26440. * under the License.
  26441. */
  26442. var OTHER_DIMENSIONS = createHashMap([
  26443. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  26444. ]);
  26445. function summarizeDimensions(data) {
  26446. var summary = {};
  26447. var encode = summary.encode = {};
  26448. var notExtraCoordDimMap = createHashMap();
  26449. var defaultedLabel = [];
  26450. var defaultedTooltip = [];
  26451. // See the comment of `List.js#userOutput`.
  26452. var userOutput = summary.userOutput = {
  26453. dimensionNames: data.dimensions.slice(),
  26454. encode: {}
  26455. };
  26456. each$1(data.dimensions, function (dimName) {
  26457. var dimItem = data.getDimensionInfo(dimName);
  26458. var coordDim = dimItem.coordDim;
  26459. if (coordDim) {
  26460. if (__DEV__) {
  26461. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  26462. }
  26463. var coordDimIndex = dimItem.coordDimIndex;
  26464. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  26465. if (!dimItem.isExtraCoord) {
  26466. notExtraCoordDimMap.set(coordDim, 1);
  26467. // Use the last coord dim (and label friendly) as default label,
  26468. // because when dataset is used, it is hard to guess which dimension
  26469. // can be value dimension. If both show x, y on label is not look good,
  26470. // and conventionally y axis is focused more.
  26471. if (mayLabelDimType(dimItem.type)) {
  26472. defaultedLabel[0] = dimName;
  26473. }
  26474. // User output encode do not contain generated coords.
  26475. // And it only has index. User can use index to retrieve value from the raw item array.
  26476. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  26477. }
  26478. if (dimItem.defaultTooltip) {
  26479. defaultedTooltip.push(dimName);
  26480. }
  26481. }
  26482. OTHER_DIMENSIONS.each(function (v, otherDim) {
  26483. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  26484. var dimIndex = dimItem.otherDims[otherDim];
  26485. if (dimIndex != null && dimIndex !== false) {
  26486. encodeArr[dimIndex] = dimItem.name;
  26487. }
  26488. });
  26489. });
  26490. var dataDimsOnCoord = [];
  26491. var encodeFirstDimNotExtra = {};
  26492. notExtraCoordDimMap.each(function (v, coordDim) {
  26493. var dimArr = encode[coordDim];
  26494. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  26495. // But should fix the case that radar axes: simplify the logic
  26496. // of `completeDimension`, remove `extraPrefix`.
  26497. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  26498. // Not necessary to remove duplicate, because a data
  26499. // dim canot on more than one coordDim.
  26500. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  26501. });
  26502. summary.dataDimsOnCoord = dataDimsOnCoord;
  26503. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  26504. var encodeLabel = encode.label;
  26505. // FIXME `encode.label` is not recommanded, because formatter can not be set
  26506. // in this way. Use label.formatter instead. May be remove this approach someday.
  26507. if (encodeLabel && encodeLabel.length) {
  26508. defaultedLabel = encodeLabel.slice();
  26509. }
  26510. var encodeTooltip = encode.tooltip;
  26511. if (encodeTooltip && encodeTooltip.length) {
  26512. defaultedTooltip = encodeTooltip.slice();
  26513. }
  26514. else if (!defaultedTooltip.length) {
  26515. defaultedTooltip = defaultedLabel.slice();
  26516. }
  26517. encode.defaultedLabel = defaultedLabel;
  26518. encode.defaultedTooltip = defaultedTooltip;
  26519. return summary;
  26520. }
  26521. function getOrCreateEncodeArr(encode, dim) {
  26522. if (!encode.hasOwnProperty(dim)) {
  26523. encode[dim] = [];
  26524. }
  26525. return encode[dim];
  26526. }
  26527. function getDimensionTypeByAxis(axisType) {
  26528. return axisType === 'category'
  26529. ? 'ordinal'
  26530. : axisType === 'time'
  26531. ? 'time'
  26532. : 'float';
  26533. }
  26534. function mayLabelDimType(dimType) {
  26535. // In most cases, ordinal and time do not suitable for label.
  26536. // Ordinal info can be displayed on axis. Time is too long.
  26537. return !(dimType === 'ordinal' || dimType === 'time');
  26538. }
  26539. // function findTheLastDimMayLabel(data) {
  26540. // // Get last value dim
  26541. // var dimensions = data.dimensions.slice();
  26542. // var valueType;
  26543. // var valueDim;
  26544. // while (dimensions.length && (
  26545. // valueDim = dimensions.pop(),
  26546. // valueType = data.getDimensionInfo(valueDim).type,
  26547. // valueType === 'ordinal' || valueType === 'time'
  26548. // )) {} // jshint ignore:line
  26549. // return valueDim;
  26550. // }
  26551. /*
  26552. * Licensed to the Apache Software Foundation (ASF) under one
  26553. * or more contributor license agreements. See the NOTICE file
  26554. * distributed with this work for additional information
  26555. * regarding copyright ownership. The ASF licenses this file
  26556. * to you under the Apache License, Version 2.0 (the
  26557. * "License"); you may not use this file except in compliance
  26558. * with the License. You may obtain a copy of the License at
  26559. *
  26560. * http://www.apache.org/licenses/LICENSE-2.0
  26561. *
  26562. * Unless required by applicable law or agreed to in writing,
  26563. * software distributed under the License is distributed on an
  26564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26565. * KIND, either express or implied. See the License for the
  26566. * specific language governing permissions and limitations
  26567. * under the License.
  26568. */
  26569. /**
  26570. * @class
  26571. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  26572. */
  26573. function DataDimensionInfo(opt) {
  26574. if (opt != null) {
  26575. extend(this, opt);
  26576. }
  26577. /**
  26578. * Dimension name.
  26579. * Mandatory.
  26580. * @type {string}
  26581. */
  26582. // this.name;
  26583. /**
  26584. * The origin name in dimsDef, see source helper.
  26585. * If displayName given, the tooltip will displayed vertically.
  26586. * Optional.
  26587. * @type {string}
  26588. */
  26589. // this.displayName;
  26590. /**
  26591. * Which coordSys dimension this dimension mapped to.
  26592. * A `coordDim` can be a "coordSysDim" that the coordSys required
  26593. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  26594. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  26595. * (That is determined by whether `isExtraCoord` is `true`).
  26596. * Mandatory.
  26597. * @type {string}
  26598. */
  26599. // this.coordDim;
  26600. /**
  26601. * The index of this dimension in `series.encode[coordDim]`.
  26602. * Mandatory.
  26603. * @type {number}
  26604. */
  26605. // this.coordDimIndex;
  26606. /**
  26607. * Dimension type. The enumerable values are the key of
  26608. * `dataCtors` of `data/List`.
  26609. * Optional.
  26610. * @type {string}
  26611. */
  26612. // this.type;
  26613. /**
  26614. * This index of this dimension info in `data/List#_dimensionInfos`.
  26615. * Mandatory after added to `data/List`.
  26616. * @type {number}
  26617. */
  26618. // this.index;
  26619. /**
  26620. * The format of `otherDims` is:
  26621. * ```js
  26622. * {
  26623. * tooltip: number optional,
  26624. * label: number optional,
  26625. * itemName: number optional,
  26626. * seriesName: number optional,
  26627. * }
  26628. * ```
  26629. *
  26630. * A `series.encode` can specified these fields:
  26631. * ```js
  26632. * encode: {
  26633. * // "3, 1, 5" is the index of data dimension.
  26634. * tooltip: [3, 1, 5],
  26635. * label: [0, 3],
  26636. * ...
  26637. * }
  26638. * ```
  26639. * `otherDims` is the parse result of the `series.encode` above, like:
  26640. * ```js
  26641. * // Suppose the index of this data dimension is `3`.
  26642. * this.otherDims = {
  26643. * // `3` is at the index `0` of the `encode.tooltip`
  26644. * tooltip: 0,
  26645. * // `3` is at the index `1` of the `encode.tooltip`
  26646. * label: 1
  26647. * };
  26648. * ```
  26649. *
  26650. * This prop should never be `null`/`undefined` after initialized.
  26651. * @type {Object}
  26652. */
  26653. this.otherDims = {};
  26654. /**
  26655. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26656. * "coordSys" required.
  26657. * Mandatory.
  26658. * @type {boolean}
  26659. */
  26660. // this.isExtraCoord;
  26661. /**
  26662. * @type {module:data/OrdinalMeta}
  26663. */
  26664. // this.ordinalMeta;
  26665. /**
  26666. * Whether to create inverted indices.
  26667. * @type {boolean}
  26668. */
  26669. // this.createInvertedIndices;
  26670. }
  26671. /*
  26672. * Licensed to the Apache Software Foundation (ASF) under one
  26673. * or more contributor license agreements. See the NOTICE file
  26674. * distributed with this work for additional information
  26675. * regarding copyright ownership. The ASF licenses this file
  26676. * to you under the Apache License, Version 2.0 (the
  26677. * "License"); you may not use this file except in compliance
  26678. * with the License. You may obtain a copy of the License at
  26679. *
  26680. * http://www.apache.org/licenses/LICENSE-2.0
  26681. *
  26682. * Unless required by applicable law or agreed to in writing,
  26683. * software distributed under the License is distributed on an
  26684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26685. * KIND, either express or implied. See the License for the
  26686. * specific language governing permissions and limitations
  26687. * under the License.
  26688. */
  26689. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26690. /**
  26691. * List for data storage
  26692. * @module echarts/data/List
  26693. */
  26694. var isObject$4 = isObject$1;
  26695. var UNDEFINED = 'undefined';
  26696. var INDEX_NOT_FOUND = -1;
  26697. // Use prefix to avoid index to be the same as otherIdList[idx],
  26698. // which will cause weird udpate animation.
  26699. var ID_PREFIX = 'e\0\0';
  26700. var dataCtors = {
  26701. 'float': typeof Float64Array === UNDEFINED
  26702. ? Array : Float64Array,
  26703. 'int': typeof Int32Array === UNDEFINED
  26704. ? Array : Int32Array,
  26705. // Ordinal data type can be string or int
  26706. 'ordinal': Array,
  26707. 'number': Array,
  26708. 'time': Array
  26709. };
  26710. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26711. // different from the Ctor of typed array.
  26712. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26713. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26714. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26715. function getIndicesCtor(list) {
  26716. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26717. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26718. }
  26719. function cloneChunk(originalChunk) {
  26720. var Ctor = originalChunk.constructor;
  26721. // Only shallow clone is enough when Array.
  26722. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26723. }
  26724. var TRANSFERABLE_PROPERTIES = [
  26725. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26726. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26727. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26728. ];
  26729. var CLONE_PROPERTIES = [
  26730. '_extent', '_approximateExtent', '_rawExtent'
  26731. ];
  26732. function transferProperties(target, source) {
  26733. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26734. if (source.hasOwnProperty(propName)) {
  26735. target[propName] = source[propName];
  26736. }
  26737. });
  26738. target.__wrappedMethods = source.__wrappedMethods;
  26739. each$1(CLONE_PROPERTIES, function (propName) {
  26740. target[propName] = clone(source[propName]);
  26741. });
  26742. target._calculationInfo = extend(source._calculationInfo);
  26743. }
  26744. /**
  26745. * @constructor
  26746. * @alias module:echarts/data/List
  26747. *
  26748. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26749. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26750. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26751. * @param {module:echarts/model/Model} hostModel
  26752. */
  26753. var List = function (dimensions, hostModel) {
  26754. dimensions = dimensions || ['x', 'y'];
  26755. var dimensionInfos = {};
  26756. var dimensionNames = [];
  26757. var invertedIndicesMap = {};
  26758. for (var i = 0; i < dimensions.length; i++) {
  26759. // Use the original dimensions[i], where other flag props may exists.
  26760. var dimensionInfo = dimensions[i];
  26761. if (isString(dimensionInfo)) {
  26762. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26763. }
  26764. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26765. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26766. }
  26767. var dimensionName = dimensionInfo.name;
  26768. dimensionInfo.type = dimensionInfo.type || 'float';
  26769. if (!dimensionInfo.coordDim) {
  26770. dimensionInfo.coordDim = dimensionName;
  26771. dimensionInfo.coordDimIndex = 0;
  26772. }
  26773. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26774. dimensionNames.push(dimensionName);
  26775. dimensionInfos[dimensionName] = dimensionInfo;
  26776. dimensionInfo.index = i;
  26777. if (dimensionInfo.createInvertedIndices) {
  26778. invertedIndicesMap[dimensionName] = [];
  26779. }
  26780. }
  26781. /**
  26782. * @readOnly
  26783. * @type {Array.<string>}
  26784. */
  26785. this.dimensions = dimensionNames;
  26786. /**
  26787. * Infomation of each data dimension, like data type.
  26788. * @type {Object}
  26789. */
  26790. this._dimensionInfos = dimensionInfos;
  26791. /**
  26792. * @type {module:echarts/model/Model}
  26793. */
  26794. this.hostModel = hostModel;
  26795. /**
  26796. * @type {module:echarts/model/Model}
  26797. */
  26798. this.dataType;
  26799. /**
  26800. * Indices stores the indices of data subset after filtered.
  26801. * This data subset will be used in chart.
  26802. * @type {Array.<number>}
  26803. * @readOnly
  26804. */
  26805. this._indices = null;
  26806. this._count = 0;
  26807. this._rawCount = 0;
  26808. /**
  26809. * Data storage
  26810. * @type {Object.<key, Array.<TypedArray|Array>>}
  26811. * @private
  26812. */
  26813. this._storage = {};
  26814. /**
  26815. * @type {Array.<string>}
  26816. */
  26817. this._nameList = [];
  26818. /**
  26819. * @type {Array.<string>}
  26820. */
  26821. this._idList = [];
  26822. /**
  26823. * Models of data option is stored sparse for optimizing memory cost
  26824. * @type {Array.<module:echarts/model/Model>}
  26825. * @private
  26826. */
  26827. this._optionModels = [];
  26828. /**
  26829. * Global visual properties after visual coding
  26830. * @type {Object}
  26831. * @private
  26832. */
  26833. this._visual = {};
  26834. /**
  26835. * Globel layout properties.
  26836. * @type {Object}
  26837. * @private
  26838. */
  26839. this._layout = {};
  26840. /**
  26841. * Item visual properties after visual coding
  26842. * @type {Array.<Object>}
  26843. * @private
  26844. */
  26845. this._itemVisuals = [];
  26846. /**
  26847. * Key: visual type, Value: boolean
  26848. * @type {Object}
  26849. * @readOnly
  26850. */
  26851. this.hasItemVisual = {};
  26852. /**
  26853. * Item layout properties after layout
  26854. * @type {Array.<Object>}
  26855. * @private
  26856. */
  26857. this._itemLayouts = [];
  26858. /**
  26859. * Graphic elemnents
  26860. * @type {Array.<module:zrender/Element>}
  26861. * @private
  26862. */
  26863. this._graphicEls = [];
  26864. /**
  26865. * Max size of each chunk.
  26866. * @type {number}
  26867. * @private
  26868. */
  26869. this._chunkSize = 1e5;
  26870. /**
  26871. * @type {number}
  26872. * @private
  26873. */
  26874. this._chunkCount = 0;
  26875. /**
  26876. * @type {Array.<Array|Object>}
  26877. * @private
  26878. */
  26879. this._rawData;
  26880. /**
  26881. * Raw extent will not be cloned, but only transfered.
  26882. * It will not be calculated util needed.
  26883. * key: dim,
  26884. * value: {end: number, extent: Array.<number>}
  26885. * @type {Object}
  26886. * @private
  26887. */
  26888. this._rawExtent = {};
  26889. /**
  26890. * @type {Object}
  26891. * @private
  26892. */
  26893. this._extent = {};
  26894. /**
  26895. * key: dim
  26896. * value: extent
  26897. * @type {Object}
  26898. * @private
  26899. */
  26900. this._approximateExtent = {};
  26901. /**
  26902. * Cache summary info for fast visit. See "dimensionHelper".
  26903. * @type {Object}
  26904. * @private
  26905. */
  26906. this._dimensionsSummary = summarizeDimensions(this);
  26907. /**
  26908. * @type {Object.<Array|TypedArray>}
  26909. * @private
  26910. */
  26911. this._invertedIndicesMap = invertedIndicesMap;
  26912. /**
  26913. * @type {Object}
  26914. * @private
  26915. */
  26916. this._calculationInfo = {};
  26917. /**
  26918. * User output info of this data.
  26919. * DO NOT use it in other places!
  26920. *
  26921. * When preparing user params for user callbacks, we have
  26922. * to clone these inner data structures to prevent users
  26923. * from modifying them to effect built-in logic. And for
  26924. * performance consideration we make this `userOutput` to
  26925. * avoid clone them too many times.
  26926. *
  26927. * @type {Object}
  26928. * @readOnly
  26929. */
  26930. this.userOutput = this._dimensionsSummary.userOutput;
  26931. };
  26932. var listProto = List.prototype;
  26933. listProto.type = 'list';
  26934. /**
  26935. * If each data item has it's own option
  26936. * @type {boolean}
  26937. */
  26938. listProto.hasItemOption = true;
  26939. /**
  26940. * The meanings of the input parameter `dim`:
  26941. *
  26942. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26943. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26944. * + If dim is a number-like string (e.g., `"1"`):
  26945. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26946. * + If not, it will be converted to a number, which means the index of the dimension.
  26947. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26948. * dimension setting, although now it seems that it is not a good idea.)
  26949. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26950. * if no dimension name is defined as `"1"`.
  26951. * + If dim is a not-number-like string, it means the concrete dim name.
  26952. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26953. * or customized in `dimensions` property of option like `"age"`.
  26954. *
  26955. * Get dimension name
  26956. * @param {string|number} dim See above.
  26957. * @return {string} Concrete dim name.
  26958. */
  26959. listProto.getDimension = function (dim) {
  26960. if (typeof dim === 'number'
  26961. // If being a number-like string but not being defined a dimension name.
  26962. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26963. ) {
  26964. dim = this.dimensions[dim];
  26965. }
  26966. return dim;
  26967. };
  26968. /**
  26969. * Get type and calculation info of particular dimension
  26970. * @param {string|number} dim
  26971. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26972. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26973. */
  26974. listProto.getDimensionInfo = function (dim) {
  26975. // Do not clone, because there may be categories in dimInfo.
  26976. return this._dimensionInfos[this.getDimension(dim)];
  26977. };
  26978. /**
  26979. * @return {Array.<string>} concrete dimension name list on coord.
  26980. */
  26981. listProto.getDimensionsOnCoord = function () {
  26982. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26983. };
  26984. /**
  26985. * @param {string} coordDim
  26986. * @param {number} [idx] A coordDim may map to more than one data dim.
  26987. * If idx is `true`, return a array of all mapped dims.
  26988. * If idx is not specified, return the first dim not extra.
  26989. * @return {string|Array.<string>} concrete data dim.
  26990. * If idx is number, and not found, return null/undefined.
  26991. * If idx is `true`, and not found, return empty array (always return array).
  26992. */
  26993. listProto.mapDimension = function (coordDim, idx) {
  26994. var dimensionsSummary = this._dimensionsSummary;
  26995. if (idx == null) {
  26996. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26997. }
  26998. var dims = dimensionsSummary.encode[coordDim];
  26999. return idx === true
  27000. // always return array if idx is `true`
  27001. ? (dims || []).slice()
  27002. : (dims && dims[idx]);
  27003. };
  27004. /**
  27005. * Initialize from data
  27006. * @param {Array.<Object|number|Array>} data source or data or data provider.
  27007. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  27008. * defualt label/tooltip.
  27009. * A name can be specified in encode.itemName,
  27010. * or dataItem.name (only for series option data),
  27011. * or provided in nameList from outside.
  27012. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  27013. */
  27014. listProto.initData = function (data, nameList, dimValueGetter) {
  27015. var notProvider = Source.isInstance(data) || isArrayLike(data);
  27016. if (notProvider) {
  27017. data = new DefaultDataProvider(data, this.dimensions.length);
  27018. }
  27019. if (__DEV__) {
  27020. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  27021. throw new Error('Inavlid data provider.');
  27022. }
  27023. }
  27024. this._rawData = data;
  27025. // Clear
  27026. this._storage = {};
  27027. this._indices = null;
  27028. this._nameList = nameList || [];
  27029. this._idList = [];
  27030. this._nameRepeatCount = {};
  27031. if (!dimValueGetter) {
  27032. this.hasItemOption = false;
  27033. }
  27034. /**
  27035. * @readOnly
  27036. */
  27037. this.defaultDimValueGetter = defaultDimValueGetters[
  27038. this._rawData.getSource().sourceFormat
  27039. ];
  27040. // Default dim value getter
  27041. this._dimValueGetter = dimValueGetter = dimValueGetter
  27042. || this.defaultDimValueGetter;
  27043. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  27044. // Reset raw extent.
  27045. this._rawExtent = {};
  27046. this._initDataFromProvider(0, data.count());
  27047. // If data has no item option.
  27048. if (data.pure) {
  27049. this.hasItemOption = false;
  27050. }
  27051. };
  27052. listProto.getProvider = function () {
  27053. return this._rawData;
  27054. };
  27055. /**
  27056. * Caution: Can be only called on raw data (before `this._indices` created).
  27057. */
  27058. listProto.appendData = function (data) {
  27059. if (__DEV__) {
  27060. assert$1(!this._indices, 'appendData can only be called on raw data.');
  27061. }
  27062. var rawData = this._rawData;
  27063. var start = this.count();
  27064. rawData.appendData(data);
  27065. var end = rawData.count();
  27066. if (!rawData.persistent) {
  27067. end += start;
  27068. }
  27069. this._initDataFromProvider(start, end);
  27070. };
  27071. /**
  27072. * Caution: Can be only called on raw data (before `this._indices` created).
  27073. * This method does not modify `rawData` (`dataProvider`), but only
  27074. * add values to storage.
  27075. *
  27076. * The final count will be increased by `Math.max(values.length, names.length)`.
  27077. *
  27078. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  27079. * [
  27080. * [12, 33, 44],
  27081. * [NaN, 43, 1],
  27082. * ['-', 'asdf', 0]
  27083. * ]
  27084. * Each item is exaclty cooresponding to a dimension.
  27085. * @param {Array.<string>} [names]
  27086. */
  27087. listProto.appendValues = function (values, names) {
  27088. var chunkSize = this._chunkSize;
  27089. var storage = this._storage;
  27090. var dimensions = this.dimensions;
  27091. var dimLen = dimensions.length;
  27092. var rawExtent = this._rawExtent;
  27093. var start = this.count();
  27094. var end = start + Math.max(values.length, names ? names.length : 0);
  27095. var originalChunkCount = this._chunkCount;
  27096. for (var i = 0; i < dimLen; i++) {
  27097. var dim = dimensions[i];
  27098. if (!rawExtent[dim]) {
  27099. rawExtent[dim] = getInitialExtent();
  27100. }
  27101. if (!storage[dim]) {
  27102. storage[dim] = [];
  27103. }
  27104. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  27105. this._chunkCount = storage[dim].length;
  27106. }
  27107. var emptyDataItem = new Array(dimLen);
  27108. for (var idx = start; idx < end; idx++) {
  27109. var sourceIdx = idx - start;
  27110. var chunkIndex = Math.floor(idx / chunkSize);
  27111. var chunkOffset = idx % chunkSize;
  27112. // Store the data by dimensions
  27113. for (var k = 0; k < dimLen; k++) {
  27114. var dim = dimensions[k];
  27115. var val = this._dimValueGetterArrayRows(
  27116. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  27117. );
  27118. storage[dim][chunkIndex][chunkOffset] = val;
  27119. var dimRawExtent = rawExtent[dim];
  27120. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27121. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27122. }
  27123. if (names) {
  27124. this._nameList[idx] = names[sourceIdx];
  27125. }
  27126. }
  27127. this._rawCount = this._count = end;
  27128. // Reset data extent
  27129. this._extent = {};
  27130. prepareInvertedIndex(this);
  27131. };
  27132. listProto._initDataFromProvider = function (start, end) {
  27133. // Optimize.
  27134. if (start >= end) {
  27135. return;
  27136. }
  27137. var chunkSize = this._chunkSize;
  27138. var rawData = this._rawData;
  27139. var storage = this._storage;
  27140. var dimensions = this.dimensions;
  27141. var dimLen = dimensions.length;
  27142. var dimensionInfoMap = this._dimensionInfos;
  27143. var nameList = this._nameList;
  27144. var idList = this._idList;
  27145. var rawExtent = this._rawExtent;
  27146. var nameRepeatCount = this._nameRepeatCount = {};
  27147. var nameDimIdx;
  27148. var originalChunkCount = this._chunkCount;
  27149. for (var i = 0; i < dimLen; i++) {
  27150. var dim = dimensions[i];
  27151. if (!rawExtent[dim]) {
  27152. rawExtent[dim] = getInitialExtent();
  27153. }
  27154. var dimInfo = dimensionInfoMap[dim];
  27155. if (dimInfo.otherDims.itemName === 0) {
  27156. nameDimIdx = this._nameDimIdx = i;
  27157. }
  27158. if (dimInfo.otherDims.itemId === 0) {
  27159. this._idDimIdx = i;
  27160. }
  27161. if (!storage[dim]) {
  27162. storage[dim] = [];
  27163. }
  27164. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  27165. this._chunkCount = storage[dim].length;
  27166. }
  27167. var dataItem = new Array(dimLen);
  27168. for (var idx = start; idx < end; idx++) {
  27169. // NOTICE: Try not to write things into dataItem
  27170. dataItem = rawData.getItem(idx, dataItem);
  27171. // Each data item is value
  27172. // [1, 2]
  27173. // 2
  27174. // Bar chart, line chart which uses category axis
  27175. // only gives the 'y' value. 'x' value is the indices of category
  27176. // Use a tempValue to normalize the value to be a (x, y) value
  27177. var chunkIndex = Math.floor(idx / chunkSize);
  27178. var chunkOffset = idx % chunkSize;
  27179. // Store the data by dimensions
  27180. for (var k = 0; k < dimLen; k++) {
  27181. var dim = dimensions[k];
  27182. var dimStorage = storage[dim][chunkIndex];
  27183. // PENDING NULL is empty or zero
  27184. var val = this._dimValueGetter(dataItem, dim, idx, k);
  27185. dimStorage[chunkOffset] = val;
  27186. var dimRawExtent = rawExtent[dim];
  27187. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27188. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27189. }
  27190. // ??? FIXME not check by pure but sourceFormat?
  27191. // TODO refactor these logic.
  27192. if (!rawData.pure) {
  27193. var name = nameList[idx];
  27194. if (dataItem && name == null) {
  27195. // If dataItem is {name: ...}, it has highest priority.
  27196. // That is appropriate for many common cases.
  27197. if (dataItem.name != null) {
  27198. // There is no other place to persistent dataItem.name,
  27199. // so save it to nameList.
  27200. nameList[idx] = name = dataItem.name;
  27201. }
  27202. else if (nameDimIdx != null) {
  27203. var nameDim = dimensions[nameDimIdx];
  27204. var nameDimChunk = storage[nameDim][chunkIndex];
  27205. if (nameDimChunk) {
  27206. name = nameDimChunk[chunkOffset];
  27207. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  27208. if (ordinalMeta && ordinalMeta.categories.length) {
  27209. name = ordinalMeta.categories[name];
  27210. }
  27211. }
  27212. }
  27213. }
  27214. // Try using the id in option
  27215. // id or name is used on dynamical data, mapping old and new items.
  27216. var id = dataItem == null ? null : dataItem.id;
  27217. if (id == null && name != null) {
  27218. // Use name as id and add counter to avoid same name
  27219. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  27220. id = name;
  27221. if (nameRepeatCount[name] > 0) {
  27222. id += '__ec__' + nameRepeatCount[name];
  27223. }
  27224. nameRepeatCount[name]++;
  27225. }
  27226. id != null && (idList[idx] = id);
  27227. }
  27228. }
  27229. if (!rawData.persistent && rawData.clean) {
  27230. // Clean unused data if data source is typed array.
  27231. rawData.clean();
  27232. }
  27233. this._rawCount = this._count = end;
  27234. // Reset data extent
  27235. this._extent = {};
  27236. prepareInvertedIndex(this);
  27237. };
  27238. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  27239. var DataCtor = dataCtors[dimInfo.type];
  27240. var lastChunkIndex = chunkCount - 1;
  27241. var dim = dimInfo.name;
  27242. var resizeChunkArray = storage[dim][lastChunkIndex];
  27243. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  27244. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  27245. // The cost of the copy is probably inconsiderable
  27246. // within the initial chunkSize.
  27247. for (var j = 0; j < resizeChunkArray.length; j++) {
  27248. newStore[j] = resizeChunkArray[j];
  27249. }
  27250. storage[dim][lastChunkIndex] = newStore;
  27251. }
  27252. // Create new chunks.
  27253. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  27254. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  27255. }
  27256. }
  27257. function prepareInvertedIndex(list) {
  27258. var invertedIndicesMap = list._invertedIndicesMap;
  27259. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  27260. var dimInfo = list._dimensionInfos[dim];
  27261. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  27262. var ordinalMeta = dimInfo.ordinalMeta;
  27263. if (ordinalMeta) {
  27264. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  27265. ordinalMeta.categories.length
  27266. );
  27267. // The default value of TypedArray is 0. To avoid miss
  27268. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  27269. for (var i = 0; i < invertedIndices.length; i++) {
  27270. invertedIndices[i] = INDEX_NOT_FOUND;
  27271. }
  27272. for (var i = 0; i < list._count; i++) {
  27273. // Only support the case that all values are distinct.
  27274. invertedIndices[list.get(dim, i)] = i;
  27275. }
  27276. }
  27277. });
  27278. }
  27279. function getRawValueFromStore(list, dimIndex, rawIndex) {
  27280. var val;
  27281. if (dimIndex != null) {
  27282. var chunkSize = list._chunkSize;
  27283. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27284. var chunkOffset = rawIndex % chunkSize;
  27285. var dim = list.dimensions[dimIndex];
  27286. var chunk = list._storage[dim][chunkIndex];
  27287. if (chunk) {
  27288. val = chunk[chunkOffset];
  27289. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  27290. if (ordinalMeta && ordinalMeta.categories.length) {
  27291. val = ordinalMeta.categories[val];
  27292. }
  27293. }
  27294. }
  27295. return val;
  27296. }
  27297. /**
  27298. * @return {number}
  27299. */
  27300. listProto.count = function () {
  27301. return this._count;
  27302. };
  27303. listProto.getIndices = function () {
  27304. var newIndices;
  27305. var indices = this._indices;
  27306. if (indices) {
  27307. var Ctor = indices.constructor;
  27308. var thisCount = this._count;
  27309. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27310. if (Ctor === Array) {
  27311. newIndices = new Ctor(thisCount);
  27312. for (var i = 0; i < thisCount; i++) {
  27313. newIndices[i] = indices[i];
  27314. }
  27315. }
  27316. else {
  27317. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27318. }
  27319. }
  27320. else {
  27321. var Ctor = getIndicesCtor(this);
  27322. var newIndices = new Ctor(this.count());
  27323. for (var i = 0; i < newIndices.length; i++) {
  27324. newIndices[i] = i;
  27325. }
  27326. }
  27327. return newIndices;
  27328. };
  27329. /**
  27330. * Get value. Return NaN if idx is out of range.
  27331. * @param {string} dim Dim must be concrete name.
  27332. * @param {number} idx
  27333. * @param {boolean} stack
  27334. * @return {number}
  27335. */
  27336. listProto.get = function (dim, idx /*, stack */) {
  27337. if (!(idx >= 0 && idx < this._count)) {
  27338. return NaN;
  27339. }
  27340. var storage = this._storage;
  27341. if (!storage[dim]) {
  27342. // TODO Warn ?
  27343. return NaN;
  27344. }
  27345. idx = this.getRawIndex(idx);
  27346. var chunkIndex = Math.floor(idx / this._chunkSize);
  27347. var chunkOffset = idx % this._chunkSize;
  27348. var chunkStore = storage[dim][chunkIndex];
  27349. var value = chunkStore[chunkOffset];
  27350. // FIXME ordinal data type is not stackable
  27351. // if (stack) {
  27352. // var dimensionInfo = this._dimensionInfos[dim];
  27353. // if (dimensionInfo && dimensionInfo.stackable) {
  27354. // var stackedOn = this.stackedOn;
  27355. // while (stackedOn) {
  27356. // // Get no stacked data of stacked on
  27357. // var stackedValue = stackedOn.get(dim, idx);
  27358. // // Considering positive stack, negative stack and empty data
  27359. // if ((value >= 0 && stackedValue > 0) // Positive stack
  27360. // || (value <= 0 && stackedValue < 0) // Negative stack
  27361. // ) {
  27362. // value += stackedValue;
  27363. // }
  27364. // stackedOn = stackedOn.stackedOn;
  27365. // }
  27366. // }
  27367. // }
  27368. return value;
  27369. };
  27370. /**
  27371. * @param {string} dim concrete dim
  27372. * @param {number} rawIndex
  27373. * @return {number|string}
  27374. */
  27375. listProto.getByRawIndex = function (dim, rawIdx) {
  27376. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27377. return NaN;
  27378. }
  27379. var dimStore = this._storage[dim];
  27380. if (!dimStore) {
  27381. // TODO Warn ?
  27382. return NaN;
  27383. }
  27384. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27385. var chunkOffset = rawIdx % this._chunkSize;
  27386. var chunkStore = dimStore[chunkIndex];
  27387. return chunkStore[chunkOffset];
  27388. };
  27389. /**
  27390. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  27391. * Hack a much simpler _getFast
  27392. * @private
  27393. */
  27394. listProto._getFast = function (dim, rawIdx) {
  27395. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  27396. var chunkOffset = rawIdx % this._chunkSize;
  27397. var chunkStore = this._storage[dim][chunkIndex];
  27398. return chunkStore[chunkOffset];
  27399. };
  27400. /**
  27401. * Get value for multi dimensions.
  27402. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  27403. * @param {number} idx
  27404. * @return {number}
  27405. */
  27406. listProto.getValues = function (dimensions, idx /*, stack */) {
  27407. var values = [];
  27408. if (!isArray(dimensions)) {
  27409. // stack = idx;
  27410. idx = dimensions;
  27411. dimensions = this.dimensions;
  27412. }
  27413. for (var i = 0, len = dimensions.length; i < len; i++) {
  27414. values.push(this.get(dimensions[i], idx /*, stack */));
  27415. }
  27416. return values;
  27417. };
  27418. /**
  27419. * If value is NaN. Inlcuding '-'
  27420. * Only check the coord dimensions.
  27421. * @param {string} dim
  27422. * @param {number} idx
  27423. * @return {number}
  27424. */
  27425. listProto.hasValue = function (idx) {
  27426. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27427. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27428. // Ordinal type originally can be string or number.
  27429. // But when an ordinal type is used on coord, it can
  27430. // not be string but only number. So we can also use isNaN.
  27431. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27432. return false;
  27433. }
  27434. }
  27435. return true;
  27436. };
  27437. /**
  27438. * Get extent of data in one dimension
  27439. * @param {string} dim
  27440. * @param {boolean} stack
  27441. */
  27442. listProto.getDataExtent = function (dim /*, stack */) {
  27443. // Make sure use concrete dim as cache name.
  27444. dim = this.getDimension(dim);
  27445. var dimData = this._storage[dim];
  27446. var initialExtent = getInitialExtent();
  27447. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27448. if (!dimData) {
  27449. return initialExtent;
  27450. }
  27451. // Make more strict checkings to ensure hitting cache.
  27452. var currEnd = this.count();
  27453. // var cacheName = [dim, !!stack].join('_');
  27454. // var cacheName = dim;
  27455. // Consider the most cases when using data zoom, `getDataExtent`
  27456. // happened before filtering. We cache raw extent, which is not
  27457. // necessary to be cleared and recalculated when restore data.
  27458. var useRaw = !this._indices; // && !stack;
  27459. var dimExtent;
  27460. if (useRaw) {
  27461. return this._rawExtent[dim].slice();
  27462. }
  27463. dimExtent = this._extent[dim];
  27464. if (dimExtent) {
  27465. return dimExtent.slice();
  27466. }
  27467. dimExtent = initialExtent;
  27468. var min = dimExtent[0];
  27469. var max = dimExtent[1];
  27470. for (var i = 0; i < currEnd; i++) {
  27471. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  27472. var value = this._getFast(dim, this.getRawIndex(i));
  27473. value < min && (min = value);
  27474. value > max && (max = value);
  27475. }
  27476. dimExtent = [min, max];
  27477. this._extent[dim] = dimExtent;
  27478. return dimExtent;
  27479. };
  27480. /**
  27481. * Optimize for the scenario that data is filtered by a given extent.
  27482. * Consider that if data amount is more than hundreds of thousand,
  27483. * extent calculation will cost more than 10ms and the cache will
  27484. * be erased because of the filtering.
  27485. */
  27486. listProto.getApproximateExtent = function (dim /*, stack */) {
  27487. dim = this.getDimension(dim);
  27488. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  27489. };
  27490. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  27491. dim = this.getDimension(dim);
  27492. this._approximateExtent[dim] = extent.slice();
  27493. };
  27494. /**
  27495. * @param {string} key
  27496. * @return {*}
  27497. */
  27498. listProto.getCalculationInfo = function (key) {
  27499. return this._calculationInfo[key];
  27500. };
  27501. /**
  27502. * @param {string|Object} key or k-v object
  27503. * @param {*} [value]
  27504. */
  27505. listProto.setCalculationInfo = function (key, value) {
  27506. isObject$4(key)
  27507. ? extend(this._calculationInfo, key)
  27508. : (this._calculationInfo[key] = value);
  27509. };
  27510. /**
  27511. * Get sum of data in one dimension
  27512. * @param {string} dim
  27513. */
  27514. listProto.getSum = function (dim /*, stack */) {
  27515. var dimData = this._storage[dim];
  27516. var sum = 0;
  27517. if (dimData) {
  27518. for (var i = 0, len = this.count(); i < len; i++) {
  27519. var value = this.get(dim, i /*, stack */);
  27520. if (!isNaN(value)) {
  27521. sum += value;
  27522. }
  27523. }
  27524. }
  27525. return sum;
  27526. };
  27527. /**
  27528. * Get median of data in one dimension
  27529. * @param {string} dim
  27530. */
  27531. listProto.getMedian = function (dim /*, stack */) {
  27532. var dimDataArray = [];
  27533. // map all data of one dimension
  27534. this.each(dim, function (val, idx) {
  27535. if (!isNaN(val)) {
  27536. dimDataArray.push(val);
  27537. }
  27538. });
  27539. // TODO
  27540. // Use quick select?
  27541. // immutability & sort
  27542. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  27543. return a - b;
  27544. });
  27545. var len = this.count();
  27546. // calculate median
  27547. return len === 0
  27548. ? 0
  27549. : len % 2 === 1
  27550. ? sortedDimDataArray[(len - 1) / 2]
  27551. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27552. };
  27553. // /**
  27554. // * Retreive the index with given value
  27555. // * @param {string} dim Concrete dimension.
  27556. // * @param {number} value
  27557. // * @return {number}
  27558. // */
  27559. // Currently incorrect: should return dataIndex but not rawIndex.
  27560. // Do not fix it until this method is to be used somewhere.
  27561. // FIXME Precision of float value
  27562. // listProto.indexOf = function (dim, value) {
  27563. // var storage = this._storage;
  27564. // var dimData = storage[dim];
  27565. // var chunkSize = this._chunkSize;
  27566. // if (dimData) {
  27567. // for (var i = 0, len = this.count(); i < len; i++) {
  27568. // var chunkIndex = Math.floor(i / chunkSize);
  27569. // var chunkOffset = i % chunkSize;
  27570. // if (dimData[chunkIndex][chunkOffset] === value) {
  27571. // return i;
  27572. // }
  27573. // }
  27574. // }
  27575. // return -1;
  27576. // };
  27577. /**
  27578. * Only support the dimension which inverted index created.
  27579. * Do not support other cases until required.
  27580. * @param {string} concrete dim
  27581. * @param {number|string} value
  27582. * @return {number} rawIndex
  27583. */
  27584. listProto.rawIndexOf = function (dim, value) {
  27585. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27586. if (__DEV__) {
  27587. if (!invertedIndices) {
  27588. throw new Error('Do not supported yet');
  27589. }
  27590. }
  27591. var rawIndex = invertedIndices[value];
  27592. if (rawIndex == null || isNaN(rawIndex)) {
  27593. return INDEX_NOT_FOUND;
  27594. }
  27595. return rawIndex;
  27596. };
  27597. /**
  27598. * Retreive the index with given name
  27599. * @param {number} idx
  27600. * @param {number} name
  27601. * @return {number}
  27602. */
  27603. listProto.indexOfName = function (name) {
  27604. for (var i = 0, len = this.count(); i < len; i++) {
  27605. if (this.getName(i) === name) {
  27606. return i;
  27607. }
  27608. }
  27609. return -1;
  27610. };
  27611. /**
  27612. * Retreive the index with given raw data index
  27613. * @param {number} idx
  27614. * @param {number} name
  27615. * @return {number}
  27616. */
  27617. listProto.indexOfRawIndex = function (rawIndex) {
  27618. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27619. return -1;
  27620. }
  27621. if (!this._indices) {
  27622. return rawIndex;
  27623. }
  27624. // Indices are ascending
  27625. var indices = this._indices;
  27626. // If rawIndex === dataIndex
  27627. var rawDataIndex = indices[rawIndex];
  27628. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  27629. return rawIndex;
  27630. }
  27631. var left = 0;
  27632. var right = this._count - 1;
  27633. while (left <= right) {
  27634. var mid = (left + right) / 2 | 0;
  27635. if (indices[mid] < rawIndex) {
  27636. left = mid + 1;
  27637. }
  27638. else if (indices[mid] > rawIndex) {
  27639. right = mid - 1;
  27640. }
  27641. else {
  27642. return mid;
  27643. }
  27644. }
  27645. return -1;
  27646. };
  27647. /**
  27648. * Retreive the index of nearest value
  27649. * @param {string} dim
  27650. * @param {number} value
  27651. * @param {number} [maxDistance=Infinity]
  27652. * @return {Array.<number>} If and only if multiple indices has
  27653. * the same value, they are put to the result.
  27654. */
  27655. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27656. var storage = this._storage;
  27657. var dimData = storage[dim];
  27658. var nearestIndices = [];
  27659. if (!dimData) {
  27660. return nearestIndices;
  27661. }
  27662. if (maxDistance == null) {
  27663. maxDistance = Infinity;
  27664. }
  27665. var minDist = Infinity;
  27666. var minDiff = -1;
  27667. var nearestIndicesLen = 0;
  27668. // Check the test case of `test/ut/spec/data/List.js`.
  27669. for (var i = 0, len = this.count(); i < len; i++) {
  27670. var diff = value - this.get(dim, i);
  27671. var dist = Math.abs(diff);
  27672. if (dist <= maxDistance) {
  27673. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27674. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27675. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27676. // So we chose the one that `diff >= 0` in this csae.
  27677. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27678. // should be push to `nearestIndices`.
  27679. if (dist < minDist
  27680. || (dist === minDist && diff >= 0 && minDiff < 0)
  27681. ) {
  27682. minDist = dist;
  27683. minDiff = diff;
  27684. nearestIndicesLen = 0;
  27685. }
  27686. if (diff === minDiff) {
  27687. nearestIndices[nearestIndicesLen++] = i;
  27688. }
  27689. }
  27690. }
  27691. nearestIndices.length = nearestIndicesLen;
  27692. return nearestIndices;
  27693. };
  27694. /**
  27695. * Get raw data index
  27696. * @param {number} idx
  27697. * @return {number}
  27698. */
  27699. listProto.getRawIndex = getRawIndexWithoutIndices;
  27700. function getRawIndexWithoutIndices(idx) {
  27701. return idx;
  27702. }
  27703. function getRawIndexWithIndices(idx) {
  27704. if (idx < this._count && idx >= 0) {
  27705. return this._indices[idx];
  27706. }
  27707. return -1;
  27708. }
  27709. /**
  27710. * Get raw data item
  27711. * @param {number} idx
  27712. * @return {number}
  27713. */
  27714. listProto.getRawDataItem = function (idx) {
  27715. if (!this._rawData.persistent) {
  27716. var val = [];
  27717. for (var i = 0; i < this.dimensions.length; i++) {
  27718. var dim = this.dimensions[i];
  27719. val.push(this.get(dim, idx));
  27720. }
  27721. return val;
  27722. }
  27723. else {
  27724. return this._rawData.getItem(this.getRawIndex(idx));
  27725. }
  27726. };
  27727. /**
  27728. * @param {number} idx
  27729. * @param {boolean} [notDefaultIdx=false]
  27730. * @return {string}
  27731. */
  27732. listProto.getName = function (idx) {
  27733. var rawIndex = this.getRawIndex(idx);
  27734. return this._nameList[rawIndex]
  27735. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27736. || '';
  27737. };
  27738. /**
  27739. * @param {number} idx
  27740. * @param {boolean} [notDefaultIdx=false]
  27741. * @return {string}
  27742. */
  27743. listProto.getId = function (idx) {
  27744. return getId(this, this.getRawIndex(idx));
  27745. };
  27746. function getId(list, rawIndex) {
  27747. var id = list._idList[rawIndex];
  27748. if (id == null) {
  27749. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27750. }
  27751. if (id == null) {
  27752. // FIXME Check the usage in graph, should not use prefix.
  27753. id = ID_PREFIX + rawIndex;
  27754. }
  27755. return id;
  27756. }
  27757. function normalizeDimensions(dimensions) {
  27758. if (!isArray(dimensions)) {
  27759. dimensions = [dimensions];
  27760. }
  27761. return dimensions;
  27762. }
  27763. function validateDimensions(list, dims) {
  27764. for (var i = 0; i < dims.length; i++) {
  27765. // stroage may be empty when no data, so use
  27766. // dimensionInfos to check.
  27767. if (!list._dimensionInfos[dims[i]]) {
  27768. console.error('Unkown dimension ' + dims[i]);
  27769. }
  27770. }
  27771. }
  27772. /**
  27773. * Data iteration
  27774. * @param {string|Array.<string>}
  27775. * @param {Function} cb
  27776. * @param {*} [context=this]
  27777. *
  27778. * @example
  27779. * list.each('x', function (x, idx) {});
  27780. * list.each(['x', 'y'], function (x, y, idx) {});
  27781. * list.each(function (idx) {})
  27782. */
  27783. listProto.each = function (dims, cb, context, contextCompat) {
  27784. 'use strict';
  27785. if (!this._count) {
  27786. return;
  27787. }
  27788. if (typeof dims === 'function') {
  27789. contextCompat = context;
  27790. context = cb;
  27791. cb = dims;
  27792. dims = [];
  27793. }
  27794. // contextCompat just for compat echarts3
  27795. context = context || contextCompat || this;
  27796. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27797. if (__DEV__) {
  27798. validateDimensions(this, dims);
  27799. }
  27800. var dimSize = dims.length;
  27801. for (var i = 0; i < this.count(); i++) {
  27802. // Simple optimization
  27803. switch (dimSize) {
  27804. case 0:
  27805. cb.call(context, i);
  27806. break;
  27807. case 1:
  27808. cb.call(context, this.get(dims[0], i), i);
  27809. break;
  27810. case 2:
  27811. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27812. break;
  27813. default:
  27814. var k = 0;
  27815. var value = [];
  27816. for (; k < dimSize; k++) {
  27817. value[k] = this.get(dims[k], i);
  27818. }
  27819. // Index
  27820. value[k] = i;
  27821. cb.apply(context, value);
  27822. }
  27823. }
  27824. };
  27825. /**
  27826. * Data filter
  27827. * @param {string|Array.<string>}
  27828. * @param {Function} cb
  27829. * @param {*} [context=this]
  27830. */
  27831. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27832. 'use strict';
  27833. if (!this._count) {
  27834. return;
  27835. }
  27836. if (typeof dimensions === 'function') {
  27837. contextCompat = context;
  27838. context = cb;
  27839. cb = dimensions;
  27840. dimensions = [];
  27841. }
  27842. // contextCompat just for compat echarts3
  27843. context = context || contextCompat || this;
  27844. dimensions = map(
  27845. normalizeDimensions(dimensions), this.getDimension, this
  27846. );
  27847. if (__DEV__) {
  27848. validateDimensions(this, dimensions);
  27849. }
  27850. var count = this.count();
  27851. var Ctor = getIndicesCtor(this);
  27852. var newIndices = new Ctor(count);
  27853. var value = [];
  27854. var dimSize = dimensions.length;
  27855. var offset = 0;
  27856. var dim0 = dimensions[0];
  27857. for (var i = 0; i < count; i++) {
  27858. var keep;
  27859. var rawIdx = this.getRawIndex(i);
  27860. // Simple optimization
  27861. if (dimSize === 0) {
  27862. keep = cb.call(context, i);
  27863. }
  27864. else if (dimSize === 1) {
  27865. var val = this._getFast(dim0, rawIdx);
  27866. keep = cb.call(context, val, i);
  27867. }
  27868. else {
  27869. for (var k = 0; k < dimSize; k++) {
  27870. value[k] = this._getFast(dim0, rawIdx);
  27871. }
  27872. value[k] = i;
  27873. keep = cb.apply(context, value);
  27874. }
  27875. if (keep) {
  27876. newIndices[offset++] = rawIdx;
  27877. }
  27878. }
  27879. // Set indices after filtered.
  27880. if (offset < count) {
  27881. this._indices = newIndices;
  27882. }
  27883. this._count = offset;
  27884. // Reset data extent
  27885. this._extent = {};
  27886. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27887. return this;
  27888. };
  27889. /**
  27890. * Select data in range. (For optimization of filter)
  27891. * (Manually inline code, support 5 million data filtering in data zoom.)
  27892. */
  27893. listProto.selectRange = function (range) {
  27894. 'use strict';
  27895. if (!this._count) {
  27896. return;
  27897. }
  27898. var dimensions = [];
  27899. for (var dim in range) {
  27900. if (range.hasOwnProperty(dim)) {
  27901. dimensions.push(dim);
  27902. }
  27903. }
  27904. if (__DEV__) {
  27905. validateDimensions(this, dimensions);
  27906. }
  27907. var dimSize = dimensions.length;
  27908. if (!dimSize) {
  27909. return;
  27910. }
  27911. var originalCount = this.count();
  27912. var Ctor = getIndicesCtor(this);
  27913. var newIndices = new Ctor(originalCount);
  27914. var offset = 0;
  27915. var dim0 = dimensions[0];
  27916. var min = range[dim0][0];
  27917. var max = range[dim0][1];
  27918. var quickFinished = false;
  27919. if (!this._indices) {
  27920. // Extreme optimization for common case. About 2x faster in chrome.
  27921. var idx = 0;
  27922. if (dimSize === 1) {
  27923. var dimStorage = this._storage[dimensions[0]];
  27924. for (var k = 0; k < this._chunkCount; k++) {
  27925. var chunkStorage = dimStorage[k];
  27926. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27927. for (var i = 0; i < len; i++) {
  27928. var val = chunkStorage[i];
  27929. // NaN will not be filtered. Consider the case, in line chart, empty
  27930. // value indicates the line should be broken. But for the case like
  27931. // scatter plot, a data item with empty value will not be rendered,
  27932. // but the axis extent may be effected if some other dim of the data
  27933. // item has value. Fortunately it is not a significant negative effect.
  27934. if (
  27935. (val >= min && val <= max) || isNaN(val)
  27936. ) {
  27937. newIndices[offset++] = idx;
  27938. }
  27939. idx++;
  27940. }
  27941. }
  27942. quickFinished = true;
  27943. }
  27944. else if (dimSize === 2) {
  27945. var dimStorage = this._storage[dim0];
  27946. var dimStorage2 = this._storage[dimensions[1]];
  27947. var min2 = range[dimensions[1]][0];
  27948. var max2 = range[dimensions[1]][1];
  27949. for (var k = 0; k < this._chunkCount; k++) {
  27950. var chunkStorage = dimStorage[k];
  27951. var chunkStorage2 = dimStorage2[k];
  27952. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27953. for (var i = 0; i < len; i++) {
  27954. var val = chunkStorage[i];
  27955. var val2 = chunkStorage2[i];
  27956. // Do not filter NaN, see comment above.
  27957. if ((
  27958. (val >= min && val <= max) || isNaN(val)
  27959. )
  27960. && (
  27961. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27962. )
  27963. ) {
  27964. newIndices[offset++] = idx;
  27965. }
  27966. idx++;
  27967. }
  27968. }
  27969. quickFinished = true;
  27970. }
  27971. }
  27972. if (!quickFinished) {
  27973. if (dimSize === 1) {
  27974. for (var i = 0; i < originalCount; i++) {
  27975. var rawIndex = this.getRawIndex(i);
  27976. var val = this._getFast(dim0, rawIndex);
  27977. // Do not filter NaN, see comment above.
  27978. if (
  27979. (val >= min && val <= max) || isNaN(val)
  27980. ) {
  27981. newIndices[offset++] = rawIndex;
  27982. }
  27983. }
  27984. }
  27985. else {
  27986. for (var i = 0; i < originalCount; i++) {
  27987. var keep = true;
  27988. var rawIndex = this.getRawIndex(i);
  27989. for (var k = 0; k < dimSize; k++) {
  27990. var dimk = dimensions[k];
  27991. var val = this._getFast(dim, rawIndex);
  27992. // Do not filter NaN, see comment above.
  27993. if (val < range[dimk][0] || val > range[dimk][1]) {
  27994. keep = false;
  27995. }
  27996. }
  27997. if (keep) {
  27998. newIndices[offset++] = this.getRawIndex(i);
  27999. }
  28000. }
  28001. }
  28002. }
  28003. // Set indices after filtered.
  28004. if (offset < originalCount) {
  28005. this._indices = newIndices;
  28006. }
  28007. this._count = offset;
  28008. // Reset data extent
  28009. this._extent = {};
  28010. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28011. return this;
  28012. };
  28013. /**
  28014. * Data mapping to a plain array
  28015. * @param {string|Array.<string>} [dimensions]
  28016. * @param {Function} cb
  28017. * @param {*} [context=this]
  28018. * @return {Array}
  28019. */
  28020. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  28021. 'use strict';
  28022. if (typeof dimensions === 'function') {
  28023. contextCompat = context;
  28024. context = cb;
  28025. cb = dimensions;
  28026. dimensions = [];
  28027. }
  28028. // contextCompat just for compat echarts3
  28029. context = context || contextCompat || this;
  28030. var result = [];
  28031. this.each(dimensions, function () {
  28032. result.push(cb && cb.apply(this, arguments));
  28033. }, context);
  28034. return result;
  28035. };
  28036. // Data in excludeDimensions is copied, otherwise transfered.
  28037. function cloneListForMapAndSample(original, excludeDimensions) {
  28038. var allDimensions = original.dimensions;
  28039. var list = new List(
  28040. map(allDimensions, original.getDimensionInfo, original),
  28041. original.hostModel
  28042. );
  28043. // FIXME If needs stackedOn, value may already been stacked
  28044. transferProperties(list, original);
  28045. var storage = list._storage = {};
  28046. var originalStorage = original._storage;
  28047. // Init storage
  28048. for (var i = 0; i < allDimensions.length; i++) {
  28049. var dim = allDimensions[i];
  28050. if (originalStorage[dim]) {
  28051. // Notice that we do not reset invertedIndicesMap here, becuase
  28052. // there is no scenario of mapping or sampling ordinal dimension.
  28053. if (indexOf(excludeDimensions, dim) >= 0) {
  28054. storage[dim] = cloneDimStore(originalStorage[dim]);
  28055. list._rawExtent[dim] = getInitialExtent();
  28056. list._extent[dim] = null;
  28057. }
  28058. else {
  28059. // Direct reference for other dimensions
  28060. storage[dim] = originalStorage[dim];
  28061. }
  28062. }
  28063. }
  28064. return list;
  28065. }
  28066. function cloneDimStore(originalDimStore) {
  28067. var newDimStore = new Array(originalDimStore.length);
  28068. for (var j = 0; j < originalDimStore.length; j++) {
  28069. newDimStore[j] = cloneChunk(originalDimStore[j]);
  28070. }
  28071. return newDimStore;
  28072. }
  28073. function getInitialExtent() {
  28074. return [Infinity, -Infinity];
  28075. }
  28076. /**
  28077. * Data mapping to a new List with given dimensions
  28078. * @param {string|Array.<string>} dimensions
  28079. * @param {Function} cb
  28080. * @param {*} [context=this]
  28081. * @return {Array}
  28082. */
  28083. listProto.map = function (dimensions, cb, context, contextCompat) {
  28084. 'use strict';
  28085. // contextCompat just for compat echarts3
  28086. context = context || contextCompat || this;
  28087. dimensions = map(
  28088. normalizeDimensions(dimensions), this.getDimension, this
  28089. );
  28090. if (__DEV__) {
  28091. validateDimensions(this, dimensions);
  28092. }
  28093. var list = cloneListForMapAndSample(this, dimensions);
  28094. // Following properties are all immutable.
  28095. // So we can reference to the same value
  28096. list._indices = this._indices;
  28097. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28098. var storage = list._storage;
  28099. var tmpRetValue = [];
  28100. var chunkSize = this._chunkSize;
  28101. var dimSize = dimensions.length;
  28102. var dataCount = this.count();
  28103. var values = [];
  28104. var rawExtent = list._rawExtent;
  28105. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28106. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28107. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  28108. }
  28109. values[dimSize] = dataIndex;
  28110. var retValue = cb && cb.apply(context, values);
  28111. if (retValue != null) {
  28112. // a number or string (in oridinal dimension)?
  28113. if (typeof retValue !== 'object') {
  28114. tmpRetValue[0] = retValue;
  28115. retValue = tmpRetValue;
  28116. }
  28117. var rawIndex = this.getRawIndex(dataIndex);
  28118. var chunkIndex = Math.floor(rawIndex / chunkSize);
  28119. var chunkOffset = rawIndex % chunkSize;
  28120. for (var i = 0; i < retValue.length; i++) {
  28121. var dim = dimensions[i];
  28122. var val = retValue[i];
  28123. var rawExtentOnDim = rawExtent[dim];
  28124. var dimStore = storage[dim];
  28125. if (dimStore) {
  28126. dimStore[chunkIndex][chunkOffset] = val;
  28127. }
  28128. if (val < rawExtentOnDim[0]) {
  28129. rawExtentOnDim[0] = val;
  28130. }
  28131. if (val > rawExtentOnDim[1]) {
  28132. rawExtentOnDim[1] = val;
  28133. }
  28134. }
  28135. }
  28136. }
  28137. return list;
  28138. };
  28139. /**
  28140. * Large data down sampling on given dimension
  28141. * @param {string} dimension
  28142. * @param {number} rate
  28143. * @param {Function} sampleValue
  28144. * @param {Function} sampleIndex Sample index for name and id
  28145. */
  28146. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28147. var list = cloneListForMapAndSample(this, [dimension]);
  28148. var targetStorage = list._storage;
  28149. var frameValues = [];
  28150. var frameSize = Math.floor(1 / rate);
  28151. var dimStore = targetStorage[dimension];
  28152. var len = this.count();
  28153. var chunkSize = this._chunkSize;
  28154. var rawExtentOnDim = list._rawExtent[dimension];
  28155. var newIndices = new (getIndicesCtor(this))(len);
  28156. var offset = 0;
  28157. for (var i = 0; i < len; i += frameSize) {
  28158. // Last frame
  28159. if (frameSize > len - i) {
  28160. frameSize = len - i;
  28161. frameValues.length = frameSize;
  28162. }
  28163. for (var k = 0; k < frameSize; k++) {
  28164. var dataIdx = this.getRawIndex(i + k);
  28165. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  28166. var originalChunkOffset = dataIdx % chunkSize;
  28167. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  28168. }
  28169. var value = sampleValue(frameValues);
  28170. var sampleFrameIdx = this.getRawIndex(
  28171. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  28172. );
  28173. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  28174. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  28175. // Only write value on the filtered data
  28176. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  28177. if (value < rawExtentOnDim[0]) {
  28178. rawExtentOnDim[0] = value;
  28179. }
  28180. if (value > rawExtentOnDim[1]) {
  28181. rawExtentOnDim[1] = value;
  28182. }
  28183. newIndices[offset++] = sampleFrameIdx;
  28184. }
  28185. list._count = offset;
  28186. list._indices = newIndices;
  28187. list.getRawIndex = getRawIndexWithIndices;
  28188. return list;
  28189. };
  28190. /**
  28191. * Get model of one data item.
  28192. *
  28193. * @param {number} idx
  28194. */
  28195. // FIXME Model proxy ?
  28196. listProto.getItemModel = function (idx) {
  28197. var hostModel = this.hostModel;
  28198. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  28199. };
  28200. /**
  28201. * Create a data differ
  28202. * @param {module:echarts/data/List} otherList
  28203. * @return {module:echarts/data/DataDiffer}
  28204. */
  28205. listProto.diff = function (otherList) {
  28206. var thisList = this;
  28207. return new DataDiffer(
  28208. otherList ? otherList.getIndices() : [],
  28209. this.getIndices(),
  28210. function (idx) {
  28211. return getId(otherList, idx);
  28212. },
  28213. function (idx) {
  28214. return getId(thisList, idx);
  28215. }
  28216. );
  28217. };
  28218. /**
  28219. * Get visual property.
  28220. * @param {string} key
  28221. */
  28222. listProto.getVisual = function (key) {
  28223. var visual = this._visual;
  28224. return visual && visual[key];
  28225. };
  28226. /**
  28227. * Set visual property
  28228. * @param {string|Object} key
  28229. * @param {*} [value]
  28230. *
  28231. * @example
  28232. * setVisual('color', color);
  28233. * setVisual({
  28234. * 'color': color
  28235. * });
  28236. */
  28237. listProto.setVisual = function (key, val) {
  28238. if (isObject$4(key)) {
  28239. for (var name in key) {
  28240. if (key.hasOwnProperty(name)) {
  28241. this.setVisual(name, key[name]);
  28242. }
  28243. }
  28244. return;
  28245. }
  28246. this._visual = this._visual || {};
  28247. this._visual[key] = val;
  28248. };
  28249. /**
  28250. * Set layout property.
  28251. * @param {string|Object} key
  28252. * @param {*} [val]
  28253. */
  28254. listProto.setLayout = function (key, val) {
  28255. if (isObject$4(key)) {
  28256. for (var name in key) {
  28257. if (key.hasOwnProperty(name)) {
  28258. this.setLayout(name, key[name]);
  28259. }
  28260. }
  28261. return;
  28262. }
  28263. this._layout[key] = val;
  28264. };
  28265. /**
  28266. * Get layout property.
  28267. * @param {string} key.
  28268. * @return {*}
  28269. */
  28270. listProto.getLayout = function (key) {
  28271. return this._layout[key];
  28272. };
  28273. /**
  28274. * Get layout of single data item
  28275. * @param {number} idx
  28276. */
  28277. listProto.getItemLayout = function (idx) {
  28278. return this._itemLayouts[idx];
  28279. };
  28280. /**
  28281. * Set layout of single data item
  28282. * @param {number} idx
  28283. * @param {Object} layout
  28284. * @param {boolean=} [merge=false]
  28285. */
  28286. listProto.setItemLayout = function (idx, layout, merge$$1) {
  28287. this._itemLayouts[idx] = merge$$1
  28288. ? extend(this._itemLayouts[idx] || {}, layout)
  28289. : layout;
  28290. };
  28291. /**
  28292. * Clear all layout of single data item
  28293. */
  28294. listProto.clearItemLayouts = function () {
  28295. this._itemLayouts.length = 0;
  28296. };
  28297. /**
  28298. * Get visual property of single data item
  28299. * @param {number} idx
  28300. * @param {string} key
  28301. * @param {boolean} [ignoreParent=false]
  28302. */
  28303. listProto.getItemVisual = function (idx, key, ignoreParent) {
  28304. var itemVisual = this._itemVisuals[idx];
  28305. var val = itemVisual && itemVisual[key];
  28306. if (val == null && !ignoreParent) {
  28307. // Use global visual property
  28308. return this.getVisual(key);
  28309. }
  28310. return val;
  28311. };
  28312. /**
  28313. * Set visual property of single data item
  28314. *
  28315. * @param {number} idx
  28316. * @param {string|Object} key
  28317. * @param {*} [value]
  28318. *
  28319. * @example
  28320. * setItemVisual(0, 'color', color);
  28321. * setItemVisual(0, {
  28322. * 'color': color
  28323. * });
  28324. */
  28325. listProto.setItemVisual = function (idx, key, value) {
  28326. var itemVisual = this._itemVisuals[idx] || {};
  28327. var hasItemVisual = this.hasItemVisual;
  28328. this._itemVisuals[idx] = itemVisual;
  28329. if (isObject$4(key)) {
  28330. for (var name in key) {
  28331. if (key.hasOwnProperty(name)) {
  28332. itemVisual[name] = key[name];
  28333. hasItemVisual[name] = true;
  28334. }
  28335. }
  28336. return;
  28337. }
  28338. itemVisual[key] = value;
  28339. hasItemVisual[key] = true;
  28340. };
  28341. /**
  28342. * Clear itemVisuals and list visual.
  28343. */
  28344. listProto.clearAllVisual = function () {
  28345. this._visual = {};
  28346. this._itemVisuals = [];
  28347. this.hasItemVisual = {};
  28348. };
  28349. var setItemDataAndSeriesIndex = function (child) {
  28350. child.seriesIndex = this.seriesIndex;
  28351. child.dataIndex = this.dataIndex;
  28352. child.dataType = this.dataType;
  28353. };
  28354. /**
  28355. * Set graphic element relative to data. It can be set as null
  28356. * @param {number} idx
  28357. * @param {module:zrender/Element} [el]
  28358. */
  28359. listProto.setItemGraphicEl = function (idx, el) {
  28360. var hostModel = this.hostModel;
  28361. if (el) {
  28362. // Add data index and series index for indexing the data by element
  28363. // Useful in tooltip
  28364. el.dataIndex = idx;
  28365. el.dataType = this.dataType;
  28366. el.seriesIndex = hostModel && hostModel.seriesIndex;
  28367. if (el.type === 'group') {
  28368. el.traverse(setItemDataAndSeriesIndex, el);
  28369. }
  28370. }
  28371. this._graphicEls[idx] = el;
  28372. };
  28373. /**
  28374. * @param {number} idx
  28375. * @return {module:zrender/Element}
  28376. */
  28377. listProto.getItemGraphicEl = function (idx) {
  28378. return this._graphicEls[idx];
  28379. };
  28380. /**
  28381. * @param {Function} cb
  28382. * @param {*} context
  28383. */
  28384. listProto.eachItemGraphicEl = function (cb, context) {
  28385. each$1(this._graphicEls, function (el, idx) {
  28386. if (el) {
  28387. cb && cb.call(context, el, idx);
  28388. }
  28389. });
  28390. };
  28391. /**
  28392. * Shallow clone a new list except visual and layout properties, and graph elements.
  28393. * New list only change the indices.
  28394. */
  28395. listProto.cloneShallow = function (list) {
  28396. if (!list) {
  28397. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  28398. list = new List(dimensionInfoList, this.hostModel);
  28399. }
  28400. // FIXME
  28401. list._storage = this._storage;
  28402. transferProperties(list, this);
  28403. // Clone will not change the data extent and indices
  28404. if (this._indices) {
  28405. var Ctor = this._indices.constructor;
  28406. list._indices = new Ctor(this._indices);
  28407. }
  28408. else {
  28409. list._indices = null;
  28410. }
  28411. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28412. return list;
  28413. };
  28414. /**
  28415. * Wrap some method to add more feature
  28416. * @param {string} methodName
  28417. * @param {Function} injectFunction
  28418. */
  28419. listProto.wrapMethod = function (methodName, injectFunction) {
  28420. var originalMethod = this[methodName];
  28421. if (typeof originalMethod !== 'function') {
  28422. return;
  28423. }
  28424. this.__wrappedMethods = this.__wrappedMethods || [];
  28425. this.__wrappedMethods.push(methodName);
  28426. this[methodName] = function () {
  28427. var res = originalMethod.apply(this, arguments);
  28428. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28429. };
  28430. };
  28431. // Methods that create a new list based on this list should be listed here.
  28432. // Notice that those method should `RETURN` the new list.
  28433. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  28434. // Methods that change indices of this list should be listed here.
  28435. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28436. /*
  28437. * Licensed to the Apache Software Foundation (ASF) under one
  28438. * or more contributor license agreements. See the NOTICE file
  28439. * distributed with this work for additional information
  28440. * regarding copyright ownership. The ASF licenses this file
  28441. * to you under the Apache License, Version 2.0 (the
  28442. * "License"); you may not use this file except in compliance
  28443. * with the License. You may obtain a copy of the License at
  28444. *
  28445. * http://www.apache.org/licenses/LICENSE-2.0
  28446. *
  28447. * Unless required by applicable law or agreed to in writing,
  28448. * software distributed under the License is distributed on an
  28449. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28450. * KIND, either express or implied. See the License for the
  28451. * specific language governing permissions and limitations
  28452. * under the License.
  28453. */
  28454. /**
  28455. * @deprecated
  28456. * Use `echarts/data/helper/createDimensions` instead.
  28457. */
  28458. /**
  28459. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28460. *
  28461. * This method builds the relationship between:
  28462. * + "what the coord sys or series requires (see `sysDims`)",
  28463. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28464. * + "what the data source provids (see `source`)".
  28465. *
  28466. * Some guess strategy will be adapted if user does not define something.
  28467. * If no 'value' dimension specified, the first no-named dimension will be
  28468. * named as 'value'.
  28469. *
  28470. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28471. * provides not only dim template, but also default order.
  28472. * properties: 'name', 'type', 'displayName'.
  28473. * `name` of each item provides default coord name.
  28474. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28475. * provide dims count that the sysDim required.
  28476. * [{ordinalMeta}] can be specified.
  28477. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28478. * @param {Object} [opt]
  28479. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28480. * For example: ['asdf', {name, type}, ...].
  28481. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28482. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28483. * If not specified, auto find the next available data dim.
  28484. * param source {module:data/Source}
  28485. * param dimCount {number}
  28486. * return {Object} encode Never be `null/undefined`.
  28487. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28488. * If not specified, extra dim names will be:
  28489. * 'value', 'value0', 'value1', ...
  28490. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28491. * If `generateCoordCount` specified, the generated dim names will be:
  28492. * `generateCoord` + 0, `generateCoord` + 1, ...
  28493. * can be Infinity, indicate that use all of the remain columns.
  28494. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28495. * @return {Array.<module:data/DataDimensionInfo>}
  28496. */
  28497. function completeDimensions(sysDims, source, opt) {
  28498. if (!Source.isInstance(source)) {
  28499. source = Source.seriesDataToSource(source);
  28500. }
  28501. opt = opt || {};
  28502. sysDims = (sysDims || []).slice();
  28503. var dimsDef = (opt.dimsDef || []).slice();
  28504. var dataDimNameMap = createHashMap();
  28505. var coordDimNameMap = createHashMap();
  28506. // var valueCandidate;
  28507. var result = [];
  28508. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  28509. // Apply user defined dims (`name` and `type`) and init result.
  28510. for (var i = 0; i < dimCount; i++) {
  28511. var dimDefItem = dimsDef[i] = extend(
  28512. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  28513. );
  28514. var userDimName = dimDefItem.name;
  28515. var resultItem = result[i] = new DataDimensionInfo();
  28516. // Name will be applied later for avoiding duplication.
  28517. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28518. // Only if `series.dimensions` is defined in option
  28519. // displayName, will be set, and dimension will be diplayed vertically in
  28520. // tooltip by default.
  28521. resultItem.name = resultItem.displayName = userDimName;
  28522. dataDimNameMap.set(userDimName, i);
  28523. }
  28524. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28525. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28526. }
  28527. var encodeDef = opt.encodeDef;
  28528. if (!encodeDef && opt.encodeDefaulter) {
  28529. encodeDef = opt.encodeDefaulter(source, dimCount);
  28530. }
  28531. encodeDef = createHashMap(encodeDef);
  28532. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  28533. encodeDef.each(function (dataDims, coordDim) {
  28534. dataDims = normalizeToArray(dataDims).slice();
  28535. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28536. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28537. // this case.
  28538. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28539. encodeDef.set(coordDim, false);
  28540. return;
  28541. }
  28542. var validDataDims = encodeDef.set(coordDim, []);
  28543. each$1(dataDims, function (resultDimIdx, idx) {
  28544. // The input resultDimIdx can be dim name or index.
  28545. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  28546. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28547. validDataDims[idx] = resultDimIdx;
  28548. applyDim(result[resultDimIdx], coordDim, idx);
  28549. }
  28550. });
  28551. });
  28552. // Apply templetes and default order from `sysDims`.
  28553. var availDimIdx = 0;
  28554. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  28555. var coordDim;
  28556. var sysDimItem;
  28557. var sysDimItemDimsDef;
  28558. var sysDimItemOtherDims;
  28559. if (isString(sysDimItem)) {
  28560. coordDim = sysDimItem;
  28561. sysDimItem = {};
  28562. }
  28563. else {
  28564. coordDim = sysDimItem.name;
  28565. var ordinalMeta = sysDimItem.ordinalMeta;
  28566. sysDimItem.ordinalMeta = null;
  28567. sysDimItem = clone(sysDimItem);
  28568. sysDimItem.ordinalMeta = ordinalMeta;
  28569. // `coordDimIndex` should not be set directly.
  28570. sysDimItemDimsDef = sysDimItem.dimsDef;
  28571. sysDimItemOtherDims = sysDimItem.otherDims;
  28572. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  28573. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28574. }
  28575. var dataDims = encodeDef.get(coordDim);
  28576. // negative resultDimIdx means no need to mapping.
  28577. if (dataDims === false) {
  28578. return;
  28579. }
  28580. var dataDims = normalizeToArray(dataDims);
  28581. // dimensions provides default dim sequences.
  28582. if (!dataDims.length) {
  28583. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28584. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28585. availDimIdx++;
  28586. }
  28587. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28588. }
  28589. }
  28590. // Apply templates.
  28591. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  28592. var resultItem = result[resultDimIdx];
  28593. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28594. if (resultItem.name == null && sysDimItemDimsDef) {
  28595. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28596. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  28597. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28598. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28599. }
  28600. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28601. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28602. });
  28603. });
  28604. function applyDim(resultItem, coordDim, coordDimIndex) {
  28605. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  28606. resultItem.otherDims[coordDim] = coordDimIndex;
  28607. }
  28608. else {
  28609. resultItem.coordDim = coordDim;
  28610. resultItem.coordDimIndex = coordDimIndex;
  28611. coordDimNameMap.set(coordDim, true);
  28612. }
  28613. }
  28614. // Make sure the first extra dim is 'value'.
  28615. var generateCoord = opt.generateCoord;
  28616. var generateCoordCount = opt.generateCoordCount;
  28617. var fromZero = generateCoordCount != null;
  28618. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  28619. var extra = generateCoord || 'value';
  28620. // Set dim `name` and other `coordDim` and other props.
  28621. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  28622. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  28623. var coordDim = resultItem.coordDim;
  28624. if (coordDim == null) {
  28625. resultItem.coordDim = genName(
  28626. extra, coordDimNameMap, fromZero
  28627. );
  28628. resultItem.coordDimIndex = 0;
  28629. if (!generateCoord || generateCoordCount <= 0) {
  28630. resultItem.isExtraCoord = true;
  28631. }
  28632. generateCoordCount--;
  28633. }
  28634. resultItem.name == null && (resultItem.name = genName(
  28635. resultItem.coordDim,
  28636. dataDimNameMap
  28637. ));
  28638. if (resultItem.type == null
  28639. && (
  28640. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28641. // Consider the case:
  28642. // {
  28643. // dataset: {source: [
  28644. // ['2001', 123],
  28645. // ['2002', 456],
  28646. // ...
  28647. // ['The others', 987],
  28648. // ]},
  28649. // series: {type: 'pie'}
  28650. // }
  28651. // The first colum should better be treated as a "ordinal" although it
  28652. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28653. || (resultItem.isExtraCoord
  28654. && (resultItem.otherDims.itemName != null
  28655. || resultItem.otherDims.seriesName != null
  28656. )
  28657. )
  28658. )
  28659. ) {
  28660. resultItem.type = 'ordinal';
  28661. }
  28662. }
  28663. return result;
  28664. }
  28665. // ??? TODO
  28666. // Originally detect dimCount by data[0]. Should we
  28667. // optimize it to only by sysDims and dimensions and encode.
  28668. // So only necessary dims will be initialized.
  28669. // But
  28670. // (1) custom series should be considered. where other dims
  28671. // may be visited.
  28672. // (2) sometimes user need to calcualte bubble size or use visualMap
  28673. // on other dimensions besides coordSys needed.
  28674. // So, dims that is not used by system, should be shared in storage?
  28675. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28676. // Note that the result dimCount should not small than columns count
  28677. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28678. var dimCount = Math.max(
  28679. source.dimensionsDetectCount || 1,
  28680. sysDims.length,
  28681. dimsDef.length,
  28682. optDimCount || 0
  28683. );
  28684. each$1(sysDims, function (sysDimItem) {
  28685. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28686. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28687. });
  28688. return dimCount;
  28689. }
  28690. function genName(name, map$$1, fromZero) {
  28691. if (fromZero || map$$1.get(name) != null) {
  28692. var i = 0;
  28693. while (map$$1.get(name + i) != null) {
  28694. i++;
  28695. }
  28696. name += i;
  28697. }
  28698. map$$1.set(name, true);
  28699. return name;
  28700. }
  28701. /*
  28702. * Licensed to the Apache Software Foundation (ASF) under one
  28703. * or more contributor license agreements. See the NOTICE file
  28704. * distributed with this work for additional information
  28705. * regarding copyright ownership. The ASF licenses this file
  28706. * to you under the Apache License, Version 2.0 (the
  28707. * "License"); you may not use this file except in compliance
  28708. * with the License. You may obtain a copy of the License at
  28709. *
  28710. * http://www.apache.org/licenses/LICENSE-2.0
  28711. *
  28712. * Unless required by applicable law or agreed to in writing,
  28713. * software distributed under the License is distributed on an
  28714. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28715. * KIND, either express or implied. See the License for the
  28716. * specific language governing permissions and limitations
  28717. * under the License.
  28718. */
  28719. /**
  28720. * Substitute `completeDimensions`.
  28721. * `completeDimensions` is to be deprecated.
  28722. */
  28723. /**
  28724. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28725. * @param {Object|Array} [opt]
  28726. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28727. * @param {number} [opt.dimensionsCount]
  28728. * @param {string} [opt.generateCoord]
  28729. * @param {string} [opt.generateCoordCount]
  28730. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28731. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28732. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28733. * @return {Array.<Object>} dimensionsInfo
  28734. */
  28735. var createDimensions = function (source, opt) {
  28736. opt = opt || {};
  28737. return completeDimensions(opt.coordDimensions || [], source, {
  28738. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28739. encodeDef: opt.encodeDefine || source.encodeDefine,
  28740. dimCount: opt.dimensionsCount,
  28741. encodeDefaulter: opt.encodeDefaulter,
  28742. generateCoord: opt.generateCoord,
  28743. generateCoordCount: opt.generateCoordCount
  28744. });
  28745. };
  28746. /*
  28747. * Licensed to the Apache Software Foundation (ASF) under one
  28748. * or more contributor license agreements. See the NOTICE file
  28749. * distributed with this work for additional information
  28750. * regarding copyright ownership. The ASF licenses this file
  28751. * to you under the Apache License, Version 2.0 (the
  28752. * "License"); you may not use this file except in compliance
  28753. * with the License. You may obtain a copy of the License at
  28754. *
  28755. * http://www.apache.org/licenses/LICENSE-2.0
  28756. *
  28757. * Unless required by applicable law or agreed to in writing,
  28758. * software distributed under the License is distributed on an
  28759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28760. * KIND, either express or implied. See the License for the
  28761. * specific language governing permissions and limitations
  28762. * under the License.
  28763. */
  28764. /**
  28765. * Helper for model references.
  28766. * There are many manners to refer axis/coordSys.
  28767. */
  28768. // TODO
  28769. // merge relevant logic to this file?
  28770. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28771. /**
  28772. * @class
  28773. * For example:
  28774. * {
  28775. * coordSysName: 'cartesian2d',
  28776. * coordSysDims: ['x', 'y', ...],
  28777. * axisMap: HashMap({
  28778. * x: xAxisModel,
  28779. * y: yAxisModel
  28780. * }),
  28781. * categoryAxisMap: HashMap({
  28782. * x: xAxisModel,
  28783. * y: undefined
  28784. * }),
  28785. * // The index of the first category axis in `coordSysDims`.
  28786. * // `null/undefined` means no category axis exists.
  28787. * firstCategoryDimIndex: 1,
  28788. * // To replace user specified encode.
  28789. * }
  28790. */
  28791. function CoordSysInfo(coordSysName) {
  28792. /**
  28793. * @type {string}
  28794. */
  28795. this.coordSysName = coordSysName;
  28796. /**
  28797. * @type {Array.<string>}
  28798. */
  28799. this.coordSysDims = [];
  28800. /**
  28801. * @type {module:zrender/core/util#HashMap}
  28802. */
  28803. this.axisMap = createHashMap();
  28804. /**
  28805. * @type {module:zrender/core/util#HashMap}
  28806. */
  28807. this.categoryAxisMap = createHashMap();
  28808. /**
  28809. * @type {number}
  28810. */
  28811. this.firstCategoryDimIndex = null;
  28812. }
  28813. /**
  28814. * @return {module:model/referHelper#CoordSysInfo}
  28815. */
  28816. function getCoordSysInfoBySeries(seriesModel) {
  28817. var coordSysName = seriesModel.get('coordinateSystem');
  28818. var result = new CoordSysInfo(coordSysName);
  28819. var fetch = fetchers[coordSysName];
  28820. if (fetch) {
  28821. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28822. return result;
  28823. }
  28824. }
  28825. var fetchers = {
  28826. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28827. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28828. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28829. if (__DEV__) {
  28830. if (!xAxisModel) {
  28831. throw new Error('xAxis "' + retrieve(
  28832. seriesModel.get('xAxisIndex'),
  28833. seriesModel.get('xAxisId'),
  28834. 0
  28835. ) + '" not found');
  28836. }
  28837. if (!yAxisModel) {
  28838. throw new Error('yAxis "' + retrieve(
  28839. seriesModel.get('xAxisIndex'),
  28840. seriesModel.get('yAxisId'),
  28841. 0
  28842. ) + '" not found');
  28843. }
  28844. }
  28845. result.coordSysDims = ['x', 'y'];
  28846. axisMap.set('x', xAxisModel);
  28847. axisMap.set('y', yAxisModel);
  28848. if (isCategory(xAxisModel)) {
  28849. categoryAxisMap.set('x', xAxisModel);
  28850. result.firstCategoryDimIndex = 0;
  28851. }
  28852. if (isCategory(yAxisModel)) {
  28853. categoryAxisMap.set('y', yAxisModel);
  28854. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28855. }
  28856. },
  28857. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28858. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28859. if (__DEV__) {
  28860. if (!singleAxisModel) {
  28861. throw new Error('singleAxis should be specified.');
  28862. }
  28863. }
  28864. result.coordSysDims = ['single'];
  28865. axisMap.set('single', singleAxisModel);
  28866. if (isCategory(singleAxisModel)) {
  28867. categoryAxisMap.set('single', singleAxisModel);
  28868. result.firstCategoryDimIndex = 0;
  28869. }
  28870. },
  28871. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28872. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28873. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28874. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28875. if (__DEV__) {
  28876. if (!angleAxisModel) {
  28877. throw new Error('angleAxis option not found');
  28878. }
  28879. if (!radiusAxisModel) {
  28880. throw new Error('radiusAxis option not found');
  28881. }
  28882. }
  28883. result.coordSysDims = ['radius', 'angle'];
  28884. axisMap.set('radius', radiusAxisModel);
  28885. axisMap.set('angle', angleAxisModel);
  28886. if (isCategory(radiusAxisModel)) {
  28887. categoryAxisMap.set('radius', radiusAxisModel);
  28888. result.firstCategoryDimIndex = 0;
  28889. }
  28890. if (isCategory(angleAxisModel)) {
  28891. categoryAxisMap.set('angle', angleAxisModel);
  28892. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28893. }
  28894. },
  28895. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28896. result.coordSysDims = ['lng', 'lat'];
  28897. },
  28898. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28899. var ecModel = seriesModel.ecModel;
  28900. var parallelModel = ecModel.getComponent(
  28901. 'parallel', seriesModel.get('parallelIndex')
  28902. );
  28903. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28904. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28905. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28906. var axisDim = coordSysDims[index];
  28907. axisMap.set(axisDim, axisModel);
  28908. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28909. categoryAxisMap.set(axisDim, axisModel);
  28910. result.firstCategoryDimIndex = index;
  28911. }
  28912. });
  28913. }
  28914. };
  28915. function isCategory(axisModel) {
  28916. return axisModel.get('type') === 'category';
  28917. }
  28918. /*
  28919. * Licensed to the Apache Software Foundation (ASF) under one
  28920. * or more contributor license agreements. See the NOTICE file
  28921. * distributed with this work for additional information
  28922. * regarding copyright ownership. The ASF licenses this file
  28923. * to you under the Apache License, Version 2.0 (the
  28924. * "License"); you may not use this file except in compliance
  28925. * with the License. You may obtain a copy of the License at
  28926. *
  28927. * http://www.apache.org/licenses/LICENSE-2.0
  28928. *
  28929. * Unless required by applicable law or agreed to in writing,
  28930. * software distributed under the License is distributed on an
  28931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28932. * KIND, either express or implied. See the License for the
  28933. * specific language governing permissions and limitations
  28934. * under the License.
  28935. */
  28936. /**
  28937. * Note that it is too complicated to support 3d stack by value
  28938. * (have to create two-dimension inverted index), so in 3d case
  28939. * we just support that stacked by index.
  28940. *
  28941. * @param {module:echarts/model/Series} seriesModel
  28942. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28943. * The input dimensionInfoList will be modified.
  28944. * @param {Object} [opt]
  28945. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28946. * @param {boolean} [opt.byIndex=false]
  28947. * @return {Object} calculationInfo
  28948. * {
  28949. * stackedDimension: string
  28950. * stackedByDimension: string
  28951. * isStackedByIndex: boolean
  28952. * stackedOverDimension: string
  28953. * stackResultDimension: string
  28954. * }
  28955. */
  28956. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28957. opt = opt || {};
  28958. var byIndex = opt.byIndex;
  28959. var stackedCoordDimension = opt.stackedCoordDimension;
  28960. // Compatibal: when `stack` is set as '', do not stack.
  28961. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28962. var stackedByDimInfo;
  28963. var stackedDimInfo;
  28964. var stackResultDimension;
  28965. var stackedOverDimension;
  28966. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28967. if (isString(dimensionInfo)) {
  28968. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28969. }
  28970. if (mayStack && !dimensionInfo.isExtraCoord) {
  28971. // Find the first ordinal dimension as the stackedByDimInfo.
  28972. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28973. stackedByDimInfo = dimensionInfo;
  28974. }
  28975. // Find the first stackable dimension as the stackedDimInfo.
  28976. if (!stackedDimInfo
  28977. && dimensionInfo.type !== 'ordinal'
  28978. && dimensionInfo.type !== 'time'
  28979. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28980. ) {
  28981. stackedDimInfo = dimensionInfo;
  28982. }
  28983. }
  28984. });
  28985. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28986. // Compatible with previous design, value axis (time axis) only stack by index.
  28987. // It may make sense if the user provides elaborately constructed data.
  28988. byIndex = true;
  28989. }
  28990. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28991. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28992. // might not be a good way.
  28993. if (stackedDimInfo) {
  28994. // Use a weird name that not duplicated with other names.
  28995. stackResultDimension = '__\0ecstackresult';
  28996. stackedOverDimension = '__\0ecstackedover';
  28997. // Create inverted index to fast query index by value.
  28998. if (stackedByDimInfo) {
  28999. stackedByDimInfo.createInvertedIndices = true;
  29000. }
  29001. var stackedDimCoordDim = stackedDimInfo.coordDim;
  29002. var stackedDimType = stackedDimInfo.type;
  29003. var stackedDimCoordIndex = 0;
  29004. each$1(dimensionInfoList, function (dimensionInfo) {
  29005. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  29006. stackedDimCoordIndex++;
  29007. }
  29008. });
  29009. dimensionInfoList.push({
  29010. name: stackResultDimension,
  29011. coordDim: stackedDimCoordDim,
  29012. coordDimIndex: stackedDimCoordIndex,
  29013. type: stackedDimType,
  29014. isExtraCoord: true,
  29015. isCalculationCoord: true
  29016. });
  29017. stackedDimCoordIndex++;
  29018. dimensionInfoList.push({
  29019. name: stackedOverDimension,
  29020. // This dimension contains stack base (generally, 0), so do not set it as
  29021. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29022. coordDim: stackedOverDimension,
  29023. coordDimIndex: stackedDimCoordIndex,
  29024. type: stackedDimType,
  29025. isExtraCoord: true,
  29026. isCalculationCoord: true
  29027. });
  29028. }
  29029. return {
  29030. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29031. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29032. isStackedByIndex: byIndex,
  29033. stackedOverDimension: stackedOverDimension,
  29034. stackResultDimension: stackResultDimension
  29035. };
  29036. }
  29037. /**
  29038. * @param {module:echarts/data/List} data
  29039. * @param {string} stackedDim
  29040. */
  29041. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  29042. // Each single series only maps to one pair of axis. So we do not need to
  29043. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29044. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29045. // && (
  29046. // stackedByDim != null
  29047. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  29048. // : data.getCalculationInfo('isStackedByIndex')
  29049. // );
  29050. }
  29051. /**
  29052. * @param {module:echarts/data/List} data
  29053. * @param {string} targetDim
  29054. * @param {string} [stackedByDim] If not input this parameter, check whether
  29055. * stacked by index.
  29056. * @return {string} dimension
  29057. */
  29058. function getStackedDimension(data, targetDim) {
  29059. return isDimensionStacked(data, targetDim)
  29060. ? data.getCalculationInfo('stackResultDimension')
  29061. : targetDim;
  29062. }
  29063. /*
  29064. * Licensed to the Apache Software Foundation (ASF) under one
  29065. * or more contributor license agreements. See the NOTICE file
  29066. * distributed with this work for additional information
  29067. * regarding copyright ownership. The ASF licenses this file
  29068. * to you under the Apache License, Version 2.0 (the
  29069. * "License"); you may not use this file except in compliance
  29070. * with the License. You may obtain a copy of the License at
  29071. *
  29072. * http://www.apache.org/licenses/LICENSE-2.0
  29073. *
  29074. * Unless required by applicable law or agreed to in writing,
  29075. * software distributed under the License is distributed on an
  29076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29077. * KIND, either express or implied. See the License for the
  29078. * specific language governing permissions and limitations
  29079. * under the License.
  29080. */
  29081. /**
  29082. * @param {module:echarts/data/Source|Array} source Or raw data.
  29083. * @param {module:echarts/model/Series} seriesModel
  29084. * @param {Object} [opt]
  29085. * @param {string} [opt.generateCoord]
  29086. * @param {boolean} [opt.useEncodeDefaulter]
  29087. */
  29088. function createListFromArray(source, seriesModel, opt) {
  29089. opt = opt || {};
  29090. if (!Source.isInstance(source)) {
  29091. source = Source.seriesDataToSource(source);
  29092. }
  29093. var coordSysName = seriesModel.get('coordinateSystem');
  29094. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29095. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29096. var coordSysDimDefs;
  29097. if (coordSysInfo) {
  29098. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29099. var dimInfo = {name: dim};
  29100. var axisModel = coordSysInfo.axisMap.get(dim);
  29101. if (axisModel) {
  29102. var axisType = axisModel.get('type');
  29103. dimInfo.type = getDimensionTypeByAxis(axisType);
  29104. // dimInfo.stackable = isStackable(axisType);
  29105. }
  29106. return dimInfo;
  29107. });
  29108. }
  29109. if (!coordSysDimDefs) {
  29110. // Get dimensions from registered coordinate system
  29111. coordSysDimDefs = (registeredCoordSys && (
  29112. registeredCoordSys.getDimensionsInfo
  29113. ? registeredCoordSys.getDimensionsInfo()
  29114. : registeredCoordSys.dimensions.slice()
  29115. )) || ['x', 'y'];
  29116. }
  29117. var dimInfoList = createDimensions(source, {
  29118. coordDimensions: coordSysDimDefs,
  29119. generateCoord: opt.generateCoord,
  29120. encodeDefaulter: opt.useEncodeDefaulter
  29121. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  29122. : null
  29123. });
  29124. var firstCategoryDimIndex;
  29125. var hasNameEncode;
  29126. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  29127. var coordDim = dimInfo.coordDim;
  29128. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29129. if (categoryAxisModel) {
  29130. if (firstCategoryDimIndex == null) {
  29131. firstCategoryDimIndex = dimIndex;
  29132. }
  29133. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29134. }
  29135. if (dimInfo.otherDims.itemName != null) {
  29136. hasNameEncode = true;
  29137. }
  29138. });
  29139. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29140. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29141. }
  29142. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29143. var list = new List(dimInfoList, seriesModel);
  29144. list.setCalculationInfo(stackCalculationInfo);
  29145. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  29146. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29147. // Use dataIndex as ordinal value in categoryAxis
  29148. return dimIndex === firstCategoryDimIndex
  29149. ? dataIndex
  29150. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29151. }
  29152. : null;
  29153. list.hasItemOption = false;
  29154. list.initData(source, null, dimValueGetter);
  29155. return list;
  29156. }
  29157. function isNeedCompleteOrdinalData(source) {
  29158. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29159. var sampleItem = firstDataNotNull(source.data || []);
  29160. return sampleItem != null
  29161. && !isArray(getDataItemValue(sampleItem));
  29162. }
  29163. }
  29164. function firstDataNotNull(data) {
  29165. var i = 0;
  29166. while (i < data.length && data[i] == null) {
  29167. i++;
  29168. }
  29169. return data[i];
  29170. }
  29171. /*
  29172. * Licensed to the Apache Software Foundation (ASF) under one
  29173. * or more contributor license agreements. See the NOTICE file
  29174. * distributed with this work for additional information
  29175. * regarding copyright ownership. The ASF licenses this file
  29176. * to you under the Apache License, Version 2.0 (the
  29177. * "License"); you may not use this file except in compliance
  29178. * with the License. You may obtain a copy of the License at
  29179. *
  29180. * http://www.apache.org/licenses/LICENSE-2.0
  29181. *
  29182. * Unless required by applicable law or agreed to in writing,
  29183. * software distributed under the License is distributed on an
  29184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29185. * KIND, either express or implied. See the License for the
  29186. * specific language governing permissions and limitations
  29187. * under the License.
  29188. */
  29189. /**
  29190. * // Scale class management
  29191. * @module echarts/scale/Scale
  29192. */
  29193. /**
  29194. * @param {Object} [setting]
  29195. */
  29196. function Scale(setting) {
  29197. this._setting = setting || {};
  29198. /**
  29199. * Extent
  29200. * @type {Array.<number>}
  29201. * @protected
  29202. */
  29203. this._extent = [Infinity, -Infinity];
  29204. /**
  29205. * Step is calculated in adjustExtent
  29206. * @type {Array.<number>}
  29207. * @protected
  29208. */
  29209. this._interval = 0;
  29210. this.init && this.init.apply(this, arguments);
  29211. }
  29212. /**
  29213. * Parse input val to valid inner number.
  29214. * @param {*} val
  29215. * @return {number}
  29216. */
  29217. Scale.prototype.parse = function (val) {
  29218. // Notice: This would be a trap here, If the implementation
  29219. // of this method depends on extent, and this method is used
  29220. // before extent set (like in dataZoom), it would be wrong.
  29221. // Nevertheless, parse does not depend on extent generally.
  29222. return val;
  29223. };
  29224. Scale.prototype.getSetting = function (name) {
  29225. return this._setting[name];
  29226. };
  29227. Scale.prototype.contain = function (val) {
  29228. var extent = this._extent;
  29229. return val >= extent[0] && val <= extent[1];
  29230. };
  29231. /**
  29232. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29233. * @param {number} val
  29234. * @return {number}
  29235. */
  29236. Scale.prototype.normalize = function (val) {
  29237. var extent = this._extent;
  29238. if (extent[1] === extent[0]) {
  29239. return 0.5;
  29240. }
  29241. return (val - extent[0]) / (extent[1] - extent[0]);
  29242. };
  29243. /**
  29244. * Scale normalized value
  29245. * @param {number} val
  29246. * @return {number}
  29247. */
  29248. Scale.prototype.scale = function (val) {
  29249. var extent = this._extent;
  29250. return val * (extent[1] - extent[0]) + extent[0];
  29251. };
  29252. /**
  29253. * Set extent from data
  29254. * @param {Array.<number>} other
  29255. */
  29256. Scale.prototype.unionExtent = function (other) {
  29257. var extent = this._extent;
  29258. other[0] < extent[0] && (extent[0] = other[0]);
  29259. other[1] > extent[1] && (extent[1] = other[1]);
  29260. // not setExtent because in log axis it may transformed to power
  29261. // this.setExtent(extent[0], extent[1]);
  29262. };
  29263. /**
  29264. * Set extent from data
  29265. * @param {module:echarts/data/List} data
  29266. * @param {string} dim
  29267. */
  29268. Scale.prototype.unionExtentFromData = function (data, dim) {
  29269. this.unionExtent(data.getApproximateExtent(dim));
  29270. };
  29271. /**
  29272. * Get extent
  29273. * @return {Array.<number>}
  29274. */
  29275. Scale.prototype.getExtent = function () {
  29276. return this._extent.slice();
  29277. };
  29278. /**
  29279. * Set extent
  29280. * @param {number} start
  29281. * @param {number} end
  29282. */
  29283. Scale.prototype.setExtent = function (start, end) {
  29284. var thisExtent = this._extent;
  29285. if (!isNaN(start)) {
  29286. thisExtent[0] = start;
  29287. }
  29288. if (!isNaN(end)) {
  29289. thisExtent[1] = end;
  29290. }
  29291. };
  29292. /**
  29293. * When axis extent depends on data and no data exists,
  29294. * axis ticks should not be drawn, which is named 'blank'.
  29295. */
  29296. Scale.prototype.isBlank = function () {
  29297. return this._isBlank;
  29298. },
  29299. /**
  29300. * When axis extent depends on data and no data exists,
  29301. * axis ticks should not be drawn, which is named 'blank'.
  29302. */
  29303. Scale.prototype.setBlank = function (isBlank) {
  29304. this._isBlank = isBlank;
  29305. };
  29306. /**
  29307. * @abstract
  29308. * @param {*} tick
  29309. * @return {string} label of the tick.
  29310. */
  29311. Scale.prototype.getLabel = null;
  29312. enableClassExtend(Scale);
  29313. enableClassManagement(Scale, {
  29314. registerWhenExtend: true
  29315. });
  29316. /*
  29317. * Licensed to the Apache Software Foundation (ASF) under one
  29318. * or more contributor license agreements. See the NOTICE file
  29319. * distributed with this work for additional information
  29320. * regarding copyright ownership. The ASF licenses this file
  29321. * to you under the Apache License, Version 2.0 (the
  29322. * "License"); you may not use this file except in compliance
  29323. * with the License. You may obtain a copy of the License at
  29324. *
  29325. * http://www.apache.org/licenses/LICENSE-2.0
  29326. *
  29327. * Unless required by applicable law or agreed to in writing,
  29328. * software distributed under the License is distributed on an
  29329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29330. * KIND, either express or implied. See the License for the
  29331. * specific language governing permissions and limitations
  29332. * under the License.
  29333. */
  29334. /**
  29335. * @constructor
  29336. * @param {Object} [opt]
  29337. * @param {Object} [opt.categories=[]]
  29338. * @param {Object} [opt.needCollect=false]
  29339. * @param {Object} [opt.deduplication=false]
  29340. */
  29341. function OrdinalMeta(opt) {
  29342. /**
  29343. * @readOnly
  29344. * @type {Array.<string>}
  29345. */
  29346. this.categories = opt.categories || [];
  29347. /**
  29348. * @private
  29349. * @type {boolean}
  29350. */
  29351. this._needCollect = opt.needCollect;
  29352. /**
  29353. * @private
  29354. * @type {boolean}
  29355. */
  29356. this._deduplication = opt.deduplication;
  29357. /**
  29358. * @private
  29359. * @type {boolean}
  29360. */
  29361. this._map;
  29362. }
  29363. /**
  29364. * @param {module:echarts/model/Model} axisModel
  29365. * @return {module:echarts/data/OrdinalMeta}
  29366. */
  29367. OrdinalMeta.createByAxisModel = function (axisModel) {
  29368. var option = axisModel.option;
  29369. var data = option.data;
  29370. var categories = data && map(data, getName);
  29371. return new OrdinalMeta({
  29372. categories: categories,
  29373. needCollect: !categories,
  29374. // deduplication is default in axis.
  29375. deduplication: option.dedplication !== false
  29376. });
  29377. };
  29378. var proto$1 = OrdinalMeta.prototype;
  29379. /**
  29380. * @param {string} category
  29381. * @return {number} ordinal
  29382. */
  29383. proto$1.getOrdinal = function (category) {
  29384. return getOrCreateMap(this).get(category);
  29385. };
  29386. /**
  29387. * @param {*} category
  29388. * @return {number} The ordinal. If not found, return NaN.
  29389. */
  29390. proto$1.parseAndCollect = function (category) {
  29391. var index;
  29392. var needCollect = this._needCollect;
  29393. // The value of category dim can be the index of the given category set.
  29394. // This feature is only supported when !needCollect, because we should
  29395. // consider a common case: a value is 2017, which is a number but is
  29396. // expected to be tread as a category. This case usually happen in dataset,
  29397. // where it happent to be no need of the index feature.
  29398. if (typeof category !== 'string' && !needCollect) {
  29399. return category;
  29400. }
  29401. // Optimize for the scenario:
  29402. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29403. // data has been ensured not duplicate and is large data.
  29404. // Notice, if a dataset dimension provide categroies, usually echarts
  29405. // should remove duplication except user tell echarts dont do that
  29406. // (set axis.deduplication = false), because echarts do not know whether
  29407. // the values in the category dimension has duplication (consider the
  29408. // parallel-aqi example)
  29409. if (needCollect && !this._deduplication) {
  29410. index = this.categories.length;
  29411. this.categories[index] = category;
  29412. return index;
  29413. }
  29414. var map$$1 = getOrCreateMap(this);
  29415. index = map$$1.get(category);
  29416. if (index == null) {
  29417. if (needCollect) {
  29418. index = this.categories.length;
  29419. this.categories[index] = category;
  29420. map$$1.set(category, index);
  29421. }
  29422. else {
  29423. index = NaN;
  29424. }
  29425. }
  29426. return index;
  29427. };
  29428. // Consider big data, do not create map until needed.
  29429. function getOrCreateMap(ordinalMeta) {
  29430. return ordinalMeta._map || (
  29431. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29432. );
  29433. }
  29434. function getName(obj) {
  29435. if (isObject$1(obj) && obj.value != null) {
  29436. return obj.value;
  29437. }
  29438. else {
  29439. return obj + '';
  29440. }
  29441. }
  29442. /*
  29443. * Licensed to the Apache Software Foundation (ASF) under one
  29444. * or more contributor license agreements. See the NOTICE file
  29445. * distributed with this work for additional information
  29446. * regarding copyright ownership. The ASF licenses this file
  29447. * to you under the Apache License, Version 2.0 (the
  29448. * "License"); you may not use this file except in compliance
  29449. * with the License. You may obtain a copy of the License at
  29450. *
  29451. * http://www.apache.org/licenses/LICENSE-2.0
  29452. *
  29453. * Unless required by applicable law or agreed to in writing,
  29454. * software distributed under the License is distributed on an
  29455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29456. * KIND, either express or implied. See the License for the
  29457. * specific language governing permissions and limitations
  29458. * under the License.
  29459. */
  29460. /**
  29461. * Linear continuous scale
  29462. * @module echarts/coord/scale/Ordinal
  29463. *
  29464. * http://en.wikipedia.org/wiki/Level_of_measurement
  29465. */
  29466. // FIXME only one data
  29467. var scaleProto = Scale.prototype;
  29468. var OrdinalScale = Scale.extend({
  29469. type: 'ordinal',
  29470. /**
  29471. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  29472. */
  29473. init: function (ordinalMeta, extent) {
  29474. // Caution: Should not use instanceof, consider ec-extensions using
  29475. // import approach to get OrdinalMeta class.
  29476. if (!ordinalMeta || isArray(ordinalMeta)) {
  29477. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  29478. }
  29479. this._ordinalMeta = ordinalMeta;
  29480. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  29481. },
  29482. parse: function (val) {
  29483. return typeof val === 'string'
  29484. ? this._ordinalMeta.getOrdinal(val)
  29485. // val might be float.
  29486. : Math.round(val);
  29487. },
  29488. contain: function (rank) {
  29489. rank = this.parse(rank);
  29490. return scaleProto.contain.call(this, rank)
  29491. && this._ordinalMeta.categories[rank] != null;
  29492. },
  29493. /**
  29494. * Normalize given rank or name to linear [0, 1]
  29495. * @param {number|string} [val]
  29496. * @return {number}
  29497. */
  29498. normalize: function (val) {
  29499. return scaleProto.normalize.call(this, this.parse(val));
  29500. },
  29501. scale: function (val) {
  29502. return Math.round(scaleProto.scale.call(this, val));
  29503. },
  29504. /**
  29505. * @return {Array}
  29506. */
  29507. getTicks: function () {
  29508. var ticks = [];
  29509. var extent = this._extent;
  29510. var rank = extent[0];
  29511. while (rank <= extent[1]) {
  29512. ticks.push(rank);
  29513. rank++;
  29514. }
  29515. return ticks;
  29516. },
  29517. /**
  29518. * Get item on rank n
  29519. * @param {number} n
  29520. * @return {string}
  29521. */
  29522. getLabel: function (n) {
  29523. if (!this.isBlank()) {
  29524. // Note that if no data, ordinalMeta.categories is an empty array.
  29525. return this._ordinalMeta.categories[n];
  29526. }
  29527. },
  29528. /**
  29529. * @return {number}
  29530. */
  29531. count: function () {
  29532. return this._extent[1] - this._extent[0] + 1;
  29533. },
  29534. /**
  29535. * @override
  29536. */
  29537. unionExtentFromData: function (data, dim) {
  29538. this.unionExtent(data.getApproximateExtent(dim));
  29539. },
  29540. getOrdinalMeta: function () {
  29541. return this._ordinalMeta;
  29542. },
  29543. niceTicks: noop,
  29544. niceExtent: noop
  29545. });
  29546. /**
  29547. * @return {module:echarts/scale/Time}
  29548. */
  29549. OrdinalScale.create = function () {
  29550. return new OrdinalScale();
  29551. };
  29552. /*
  29553. * Licensed to the Apache Software Foundation (ASF) under one
  29554. * or more contributor license agreements. See the NOTICE file
  29555. * distributed with this work for additional information
  29556. * regarding copyright ownership. The ASF licenses this file
  29557. * to you under the Apache License, Version 2.0 (the
  29558. * "License"); you may not use this file except in compliance
  29559. * with the License. You may obtain a copy of the License at
  29560. *
  29561. * http://www.apache.org/licenses/LICENSE-2.0
  29562. *
  29563. * Unless required by applicable law or agreed to in writing,
  29564. * software distributed under the License is distributed on an
  29565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29566. * KIND, either express or implied. See the License for the
  29567. * specific language governing permissions and limitations
  29568. * under the License.
  29569. */
  29570. /**
  29571. * For testable.
  29572. */
  29573. var roundNumber$1 = round$1;
  29574. /**
  29575. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  29576. * Should be extent[0] < extent[1].
  29577. * @param {number} splitNumber splitNumber should be >= 1.
  29578. * @param {number} [minInterval]
  29579. * @param {number} [maxInterval]
  29580. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  29581. */
  29582. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29583. var result = {};
  29584. var span = extent[1] - extent[0];
  29585. var interval = result.interval = nice(span / splitNumber, true);
  29586. if (minInterval != null && interval < minInterval) {
  29587. interval = result.interval = minInterval;
  29588. }
  29589. if (maxInterval != null && interval > maxInterval) {
  29590. interval = result.interval = maxInterval;
  29591. }
  29592. // Tow more digital for tick.
  29593. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  29594. // Niced extent inside original extent
  29595. var niceTickExtent = result.niceTickExtent = [
  29596. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  29597. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  29598. ];
  29599. fixExtent(niceTickExtent, extent);
  29600. return result;
  29601. }
  29602. /**
  29603. * @param {number} interval
  29604. * @return {number} interval precision
  29605. */
  29606. function getIntervalPrecision(interval) {
  29607. // Tow more digital for tick.
  29608. return getPrecisionSafe(interval) + 2;
  29609. }
  29610. function clamp(niceTickExtent, idx, extent) {
  29611. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29612. }
  29613. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29614. function fixExtent(niceTickExtent, extent) {
  29615. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29616. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29617. clamp(niceTickExtent, 0, extent);
  29618. clamp(niceTickExtent, 1, extent);
  29619. if (niceTickExtent[0] > niceTickExtent[1]) {
  29620. niceTickExtent[0] = niceTickExtent[1];
  29621. }
  29622. }
  29623. /*
  29624. * Licensed to the Apache Software Foundation (ASF) under one
  29625. * or more contributor license agreements. See the NOTICE file
  29626. * distributed with this work for additional information
  29627. * regarding copyright ownership. The ASF licenses this file
  29628. * to you under the Apache License, Version 2.0 (the
  29629. * "License"); you may not use this file except in compliance
  29630. * with the License. You may obtain a copy of the License at
  29631. *
  29632. * http://www.apache.org/licenses/LICENSE-2.0
  29633. *
  29634. * Unless required by applicable law or agreed to in writing,
  29635. * software distributed under the License is distributed on an
  29636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29637. * KIND, either express or implied. See the License for the
  29638. * specific language governing permissions and limitations
  29639. * under the License.
  29640. */
  29641. /**
  29642. * Interval scale
  29643. * @module echarts/scale/Interval
  29644. */
  29645. var roundNumber = round$1;
  29646. /**
  29647. * @alias module:echarts/coord/scale/Interval
  29648. * @constructor
  29649. */
  29650. var IntervalScale = Scale.extend({
  29651. type: 'interval',
  29652. _interval: 0,
  29653. _intervalPrecision: 2,
  29654. setExtent: function (start, end) {
  29655. var thisExtent = this._extent;
  29656. //start,end may be a Number like '25',so...
  29657. if (!isNaN(start)) {
  29658. thisExtent[0] = parseFloat(start);
  29659. }
  29660. if (!isNaN(end)) {
  29661. thisExtent[1] = parseFloat(end);
  29662. }
  29663. },
  29664. unionExtent: function (other) {
  29665. var extent = this._extent;
  29666. other[0] < extent[0] && (extent[0] = other[0]);
  29667. other[1] > extent[1] && (extent[1] = other[1]);
  29668. // unionExtent may called by it's sub classes
  29669. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  29670. },
  29671. /**
  29672. * Get interval
  29673. */
  29674. getInterval: function () {
  29675. return this._interval;
  29676. },
  29677. /**
  29678. * Set interval
  29679. */
  29680. setInterval: function (interval) {
  29681. this._interval = interval;
  29682. // Dropped auto calculated niceExtent and use user setted extent
  29683. // We assume user wan't to set both interval, min, max to get a better result
  29684. this._niceExtent = this._extent.slice();
  29685. this._intervalPrecision = getIntervalPrecision(interval);
  29686. },
  29687. /**
  29688. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  29689. * @return {Array.<number>}
  29690. */
  29691. getTicks: function (expandToNicedExtent) {
  29692. var interval = this._interval;
  29693. var extent = this._extent;
  29694. var niceTickExtent = this._niceExtent;
  29695. var intervalPrecision = this._intervalPrecision;
  29696. var ticks = [];
  29697. // If interval is 0, return [];
  29698. if (!interval) {
  29699. return ticks;
  29700. }
  29701. // Consider this case: using dataZoom toolbox, zoom and zoom.
  29702. var safeLimit = 10000;
  29703. if (extent[0] < niceTickExtent[0]) {
  29704. if (expandToNicedExtent) {
  29705. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  29706. }
  29707. else {
  29708. ticks.push(extent[0]);
  29709. }
  29710. }
  29711. var tick = niceTickExtent[0];
  29712. while (tick <= niceTickExtent[1]) {
  29713. ticks.push(tick);
  29714. // Avoid rounding error
  29715. tick = roundNumber(tick + interval, intervalPrecision);
  29716. if (tick === ticks[ticks.length - 1]) {
  29717. // Consider out of safe float point, e.g.,
  29718. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29719. break;
  29720. }
  29721. if (ticks.length > safeLimit) {
  29722. return [];
  29723. }
  29724. }
  29725. // Consider this case: the last item of ticks is smaller
  29726. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29727. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  29728. if (extent[1] > lastNiceTick) {
  29729. if (expandToNicedExtent) {
  29730. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  29731. }
  29732. else {
  29733. ticks.push(extent[1]);
  29734. }
  29735. }
  29736. return ticks;
  29737. },
  29738. /**
  29739. * @param {number} [splitNumber=5]
  29740. * @return {Array.<Array.<number>>}
  29741. */
  29742. getMinorTicks: function (splitNumber) {
  29743. var ticks = this.getTicks(true);
  29744. var minorTicks = [];
  29745. var extent = this.getExtent();
  29746. for (var i = 1; i < ticks.length; i++) {
  29747. var nextTick = ticks[i];
  29748. var prevTick = ticks[i - 1];
  29749. var count = 0;
  29750. var minorTicksGroup = [];
  29751. var interval = nextTick - prevTick;
  29752. var minorInterval = interval / splitNumber;
  29753. while (count < splitNumber - 1) {
  29754. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  29755. // For the first and last interval. The count may be less than splitNumber.
  29756. if (minorTick > extent[0] && minorTick < extent[1]) {
  29757. minorTicksGroup.push(minorTick);
  29758. }
  29759. count++;
  29760. }
  29761. minorTicks.push(minorTicksGroup);
  29762. }
  29763. return minorTicks;
  29764. },
  29765. /**
  29766. * @param {number} data
  29767. * @param {Object} [opt]
  29768. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  29769. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  29770. * @return {string}
  29771. */
  29772. getLabel: function (data, opt) {
  29773. if (data == null) {
  29774. return '';
  29775. }
  29776. var precision = opt && opt.precision;
  29777. if (precision == null) {
  29778. precision = getPrecisionSafe(data) || 0;
  29779. }
  29780. else if (precision === 'auto') {
  29781. // Should be more precise then tick.
  29782. precision = this._intervalPrecision;
  29783. }
  29784. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29785. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29786. data = roundNumber(data, precision, true);
  29787. return addCommas(data);
  29788. },
  29789. /**
  29790. * Update interval and extent of intervals for nice ticks
  29791. *
  29792. * @param {number} [splitNumber = 5] Desired number of ticks
  29793. * @param {number} [minInterval]
  29794. * @param {number} [maxInterval]
  29795. */
  29796. niceTicks: function (splitNumber, minInterval, maxInterval) {
  29797. splitNumber = splitNumber || 5;
  29798. var extent = this._extent;
  29799. var span = extent[1] - extent[0];
  29800. if (!isFinite(span)) {
  29801. return;
  29802. }
  29803. // User may set axis min 0 and data are all negative
  29804. // FIXME If it needs to reverse ?
  29805. if (span < 0) {
  29806. span = -span;
  29807. extent.reverse();
  29808. }
  29809. var result = intervalScaleNiceTicks(
  29810. extent, splitNumber, minInterval, maxInterval
  29811. );
  29812. this._intervalPrecision = result.intervalPrecision;
  29813. this._interval = result.interval;
  29814. this._niceExtent = result.niceTickExtent;
  29815. },
  29816. /**
  29817. * Nice extent.
  29818. * @param {Object} opt
  29819. * @param {number} [opt.splitNumber = 5] Given approx tick number
  29820. * @param {boolean} [opt.fixMin=false]
  29821. * @param {boolean} [opt.fixMax=false]
  29822. * @param {boolean} [opt.minInterval]
  29823. * @param {boolean} [opt.maxInterval]
  29824. */
  29825. niceExtent: function (opt) {
  29826. var extent = this._extent;
  29827. // If extent start and end are same, expand them
  29828. if (extent[0] === extent[1]) {
  29829. if (extent[0] !== 0) {
  29830. // Expand extent
  29831. var expandSize = extent[0];
  29832. // In the fowllowing case
  29833. // Axis has been fixed max 100
  29834. // Plus data are all 100 and axis extent are [100, 100].
  29835. // Extend to the both side will cause expanded max is larger than fixed max.
  29836. // So only expand to the smaller side.
  29837. if (!opt.fixMax) {
  29838. extent[1] += expandSize / 2;
  29839. extent[0] -= expandSize / 2;
  29840. }
  29841. else {
  29842. extent[0] -= expandSize / 2;
  29843. }
  29844. }
  29845. else {
  29846. extent[1] = 1;
  29847. }
  29848. }
  29849. var span = extent[1] - extent[0];
  29850. // If there are no data and extent are [Infinity, -Infinity]
  29851. if (!isFinite(span)) {
  29852. extent[0] = 0;
  29853. extent[1] = 1;
  29854. }
  29855. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  29856. // var extent = this._extent;
  29857. var interval = this._interval;
  29858. if (!opt.fixMin) {
  29859. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  29860. }
  29861. if (!opt.fixMax) {
  29862. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  29863. }
  29864. }
  29865. });
  29866. /**
  29867. * @return {module:echarts/scale/Time}
  29868. */
  29869. IntervalScale.create = function () {
  29870. return new IntervalScale();
  29871. };
  29872. /*
  29873. * Licensed to the Apache Software Foundation (ASF) under one
  29874. * or more contributor license agreements. See the NOTICE file
  29875. * distributed with this work for additional information
  29876. * regarding copyright ownership. The ASF licenses this file
  29877. * to you under the Apache License, Version 2.0 (the
  29878. * "License"); you may not use this file except in compliance
  29879. * with the License. You may obtain a copy of the License at
  29880. *
  29881. * http://www.apache.org/licenses/LICENSE-2.0
  29882. *
  29883. * Unless required by applicable law or agreed to in writing,
  29884. * software distributed under the License is distributed on an
  29885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29886. * KIND, either express or implied. See the License for the
  29887. * specific language governing permissions and limitations
  29888. * under the License.
  29889. */
  29890. /* global Float32Array */
  29891. var STACK_PREFIX = '__ec_stack_';
  29892. var LARGE_BAR_MIN_WIDTH = 0.5;
  29893. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29894. function getSeriesStackId(seriesModel) {
  29895. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29896. }
  29897. function getAxisKey(axis) {
  29898. return axis.dim + axis.index;
  29899. }
  29900. /**
  29901. * @param {Object} opt
  29902. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  29903. * @param {number} opt.count Positive interger.
  29904. * @param {number} [opt.barWidth]
  29905. * @param {number} [opt.barMaxWidth]
  29906. * @param {number} [opt.barMinWidth]
  29907. * @param {number} [opt.barGap]
  29908. * @param {number} [opt.barCategoryGap]
  29909. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29910. */
  29911. function prepareLayoutBarSeries(seriesType, ecModel) {
  29912. var seriesModels = [];
  29913. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29914. // Check series coordinate, do layout for cartesian2d only
  29915. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29916. seriesModels.push(seriesModel);
  29917. }
  29918. });
  29919. return seriesModels;
  29920. }
  29921. /**
  29922. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29923. * values.
  29924. * This works for time axes, value axes, and log axes.
  29925. * For a single time axis, return value is in the form like
  29926. * {'x_0': [1000000]}.
  29927. * The value of 1000000 is in milliseconds.
  29928. */
  29929. function getValueAxesMinGaps(barSeries) {
  29930. /**
  29931. * Map from axis.index to values.
  29932. * For a single time axis, axisValues is in the form like
  29933. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  29934. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  29935. * series.
  29936. */
  29937. var axisValues = {};
  29938. each$1(barSeries, function (seriesModel) {
  29939. var cartesian = seriesModel.coordinateSystem;
  29940. var baseAxis = cartesian.getBaseAxis();
  29941. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  29942. return;
  29943. }
  29944. var data = seriesModel.getData();
  29945. var key = baseAxis.dim + '_' + baseAxis.index;
  29946. var dim = data.mapDimension(baseAxis.dim);
  29947. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  29948. var value = data.get(dim, i);
  29949. if (!axisValues[key]) {
  29950. // No previous data for the axis
  29951. axisValues[key] = [value];
  29952. }
  29953. else {
  29954. // No value in previous series
  29955. axisValues[key].push(value);
  29956. }
  29957. // Ignore duplicated time values in the same axis
  29958. }
  29959. });
  29960. var axisMinGaps = [];
  29961. for (var key in axisValues) {
  29962. if (axisValues.hasOwnProperty(key)) {
  29963. var valuesInAxis = axisValues[key];
  29964. if (valuesInAxis) {
  29965. // Sort axis values into ascending order to calculate gaps
  29966. valuesInAxis.sort(function (a, b) {
  29967. return a - b;
  29968. });
  29969. var min = null;
  29970. for (var j = 1; j < valuesInAxis.length; ++j) {
  29971. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  29972. if (delta > 0) {
  29973. // Ignore 0 delta because they are of the same axis value
  29974. min = min === null ? delta : Math.min(min, delta);
  29975. }
  29976. }
  29977. // Set to null if only have one data
  29978. axisMinGaps[key] = min;
  29979. }
  29980. }
  29981. }
  29982. return axisMinGaps;
  29983. }
  29984. function makeColumnLayout(barSeries) {
  29985. var axisMinGaps = getValueAxesMinGaps(barSeries);
  29986. var seriesInfoList = [];
  29987. each$1(barSeries, function (seriesModel) {
  29988. var cartesian = seriesModel.coordinateSystem;
  29989. var baseAxis = cartesian.getBaseAxis();
  29990. var axisExtent = baseAxis.getExtent();
  29991. var bandWidth;
  29992. if (baseAxis.type === 'category') {
  29993. bandWidth = baseAxis.getBandWidth();
  29994. }
  29995. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  29996. var key = baseAxis.dim + '_' + baseAxis.index;
  29997. var minGap = axisMinGaps[key];
  29998. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  29999. var scale = baseAxis.scale.getExtent();
  30000. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30001. bandWidth = minGap
  30002. ? extentSpan / scaleSpan * minGap
  30003. : extentSpan; // When there is only one data value
  30004. }
  30005. else {
  30006. var data = seriesModel.getData();
  30007. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30008. }
  30009. var barWidth = parsePercent$1(
  30010. seriesModel.get('barWidth'), bandWidth
  30011. );
  30012. var barMaxWidth = parsePercent$1(
  30013. seriesModel.get('barMaxWidth'), bandWidth
  30014. );
  30015. var barMinWidth = parsePercent$1(
  30016. // barMinWidth by default is 1 in cartesian. Because in value axis,
  30017. // the auto-calculated bar width might be less than 1.
  30018. seriesModel.get('barMinWidth') || 1, bandWidth
  30019. );
  30020. var barGap = seriesModel.get('barGap');
  30021. var barCategoryGap = seriesModel.get('barCategoryGap');
  30022. seriesInfoList.push({
  30023. bandWidth: bandWidth,
  30024. barWidth: barWidth,
  30025. barMaxWidth: barMaxWidth,
  30026. barMinWidth: barMinWidth,
  30027. barGap: barGap,
  30028. barCategoryGap: barCategoryGap,
  30029. axisKey: getAxisKey(baseAxis),
  30030. stackId: getSeriesStackId(seriesModel)
  30031. });
  30032. });
  30033. return doCalBarWidthAndOffset(seriesInfoList);
  30034. }
  30035. function doCalBarWidthAndOffset(seriesInfoList) {
  30036. // Columns info on each category axis. Key is cartesian name
  30037. var columnsMap = {};
  30038. each$1(seriesInfoList, function (seriesInfo, idx) {
  30039. var axisKey = seriesInfo.axisKey;
  30040. var bandWidth = seriesInfo.bandWidth;
  30041. var columnsOnAxis = columnsMap[axisKey] || {
  30042. bandWidth: bandWidth,
  30043. remainedWidth: bandWidth,
  30044. autoWidthCount: 0,
  30045. categoryGap: '20%',
  30046. gap: '30%',
  30047. stacks: {}
  30048. };
  30049. var stacks = columnsOnAxis.stacks;
  30050. columnsMap[axisKey] = columnsOnAxis;
  30051. var stackId = seriesInfo.stackId;
  30052. if (!stacks[stackId]) {
  30053. columnsOnAxis.autoWidthCount++;
  30054. }
  30055. stacks[stackId] = stacks[stackId] || {
  30056. width: 0,
  30057. maxWidth: 0
  30058. };
  30059. // Caution: In a single coordinate system, these barGrid attributes
  30060. // will be shared by series. Consider that they have default values,
  30061. // only the attributes set on the last series will work.
  30062. // Do not change this fact unless there will be a break change.
  30063. var barWidth = seriesInfo.barWidth;
  30064. if (barWidth && !stacks[stackId].width) {
  30065. // See #6312, do not restrict width.
  30066. stacks[stackId].width = barWidth;
  30067. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30068. columnsOnAxis.remainedWidth -= barWidth;
  30069. }
  30070. var barMaxWidth = seriesInfo.barMaxWidth;
  30071. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30072. var barMinWidth = seriesInfo.barMinWidth;
  30073. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30074. var barGap = seriesInfo.barGap;
  30075. (barGap != null) && (columnsOnAxis.gap = barGap);
  30076. var barCategoryGap = seriesInfo.barCategoryGap;
  30077. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30078. });
  30079. var result = {};
  30080. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30081. result[coordSysName] = {};
  30082. var stacks = columnsOnAxis.stacks;
  30083. var bandWidth = columnsOnAxis.bandWidth;
  30084. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30085. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30086. var remainedWidth = columnsOnAxis.remainedWidth;
  30087. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30088. var autoWidth = (remainedWidth - categoryGap)
  30089. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30090. autoWidth = Math.max(autoWidth, 0);
  30091. // Find if any auto calculated bar exceeded maxBarWidth
  30092. each$1(stacks, function (column) {
  30093. var maxWidth = column.maxWidth;
  30094. var minWidth = column.minWidth;
  30095. if (!column.width) {
  30096. var finalWidth = autoWidth;
  30097. if (maxWidth && maxWidth < finalWidth) {
  30098. finalWidth = Math.min(maxWidth, remainedWidth);
  30099. }
  30100. // `minWidth` has higher priority. `minWidth` decide that wheter the
  30101. // bar is able to be visible. So `minWidth` should not be restricted
  30102. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30103. // the extreme cases for `value` axis, bars are allowed to overlap
  30104. // with each other if `minWidth` specified.
  30105. if (minWidth && minWidth > finalWidth) {
  30106. finalWidth = minWidth;
  30107. }
  30108. if (finalWidth !== autoWidth) {
  30109. column.width = finalWidth;
  30110. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30111. autoWidthCount--;
  30112. }
  30113. }
  30114. else {
  30115. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30116. // CSS does. Becuase barWidth can be a percent value, where
  30117. // `barMaxWidth` can be used to restrict the final width.
  30118. var finalWidth = column.width;
  30119. if (maxWidth) {
  30120. finalWidth = Math.min(finalWidth, maxWidth);
  30121. }
  30122. // `minWidth` has higher priority, as described above
  30123. if (minWidth) {
  30124. finalWidth = Math.max(finalWidth, minWidth);
  30125. }
  30126. column.width = finalWidth;
  30127. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30128. autoWidthCount--;
  30129. }
  30130. });
  30131. // Recalculate width again
  30132. autoWidth = (remainedWidth - categoryGap)
  30133. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30134. autoWidth = Math.max(autoWidth, 0);
  30135. var widthSum = 0;
  30136. var lastColumn;
  30137. each$1(stacks, function (column, idx) {
  30138. if (!column.width) {
  30139. column.width = autoWidth;
  30140. }
  30141. lastColumn = column;
  30142. widthSum += column.width * (1 + barGapPercent);
  30143. });
  30144. if (lastColumn) {
  30145. widthSum -= lastColumn.width * barGapPercent;
  30146. }
  30147. var offset = -widthSum / 2;
  30148. each$1(stacks, function (column, stackId) {
  30149. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30150. bandWidth: bandWidth,
  30151. offset: offset,
  30152. width: column.width
  30153. };
  30154. offset += column.width * (1 + barGapPercent);
  30155. });
  30156. });
  30157. return result;
  30158. }
  30159. /**
  30160. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30161. * @param {module:echarts/coord/Axis} axis
  30162. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30163. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30164. */
  30165. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30166. if (barWidthAndOffset && axis) {
  30167. var result = barWidthAndOffset[getAxisKey(axis)];
  30168. if (result != null && seriesModel != null) {
  30169. result = result[getSeriesStackId(seriesModel)];
  30170. }
  30171. return result;
  30172. }
  30173. }
  30174. /**
  30175. * @param {string} seriesType
  30176. * @param {module:echarts/model/Global} ecModel
  30177. */
  30178. function layout(seriesType, ecModel) {
  30179. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30180. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30181. var lastStackCoords = {};
  30182. each$1(seriesModels, function (seriesModel) {
  30183. var data = seriesModel.getData();
  30184. var cartesian = seriesModel.coordinateSystem;
  30185. var baseAxis = cartesian.getBaseAxis();
  30186. var stackId = getSeriesStackId(seriesModel);
  30187. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30188. var columnOffset = columnLayoutInfo.offset;
  30189. var columnWidth = columnLayoutInfo.width;
  30190. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30191. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30192. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30193. data.setLayout({
  30194. bandWidth: columnLayoutInfo.bandWidth,
  30195. offset: columnOffset,
  30196. size: columnWidth
  30197. });
  30198. var valueDim = data.mapDimension(valueAxis.dim);
  30199. var baseDim = data.mapDimension(baseAxis.dim);
  30200. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30201. var isValueAxisH = valueAxis.isHorizontal();
  30202. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30203. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30204. var value = data.get(valueDim, idx);
  30205. var baseValue = data.get(baseDim, idx);
  30206. var sign = value >= 0 ? 'p' : 'n';
  30207. var baseCoord = valueAxisStart;
  30208. // Because of the barMinHeight, we can not use the value in
  30209. // stackResultDimension directly.
  30210. if (stacked) {
  30211. // Only ordinal axis can be stacked.
  30212. if (!lastStackCoords[stackId][baseValue]) {
  30213. lastStackCoords[stackId][baseValue] = {
  30214. p: valueAxisStart, // Positive stack
  30215. n: valueAxisStart // Negative stack
  30216. };
  30217. }
  30218. // Should also consider #4243
  30219. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30220. }
  30221. var x;
  30222. var y;
  30223. var width;
  30224. var height;
  30225. if (isValueAxisH) {
  30226. var coord = cartesian.dataToPoint([value, baseValue]);
  30227. x = baseCoord;
  30228. y = coord[1] + columnOffset;
  30229. width = coord[0] - valueAxisStart;
  30230. height = columnWidth;
  30231. if (Math.abs(width) < barMinHeight) {
  30232. width = (width < 0 ? -1 : 1) * barMinHeight;
  30233. }
  30234. // Ignore stack from NaN value
  30235. if (!isNaN(width)) {
  30236. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30237. }
  30238. }
  30239. else {
  30240. var coord = cartesian.dataToPoint([baseValue, value]);
  30241. x = coord[0] + columnOffset;
  30242. y = baseCoord;
  30243. width = columnWidth;
  30244. height = coord[1] - valueAxisStart;
  30245. if (Math.abs(height) < barMinHeight) {
  30246. // Include zero to has a positive bar
  30247. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30248. }
  30249. // Ignore stack from NaN value
  30250. if (!isNaN(height)) {
  30251. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30252. }
  30253. }
  30254. data.setItemLayout(idx, {
  30255. x: x,
  30256. y: y,
  30257. width: width,
  30258. height: height
  30259. });
  30260. }
  30261. }, this);
  30262. }
  30263. // TODO: Do not support stack in large mode yet.
  30264. var largeLayout = {
  30265. seriesType: 'bar',
  30266. plan: createRenderPlanner(),
  30267. reset: function (seriesModel) {
  30268. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30269. return;
  30270. }
  30271. var data = seriesModel.getData();
  30272. var cartesian = seriesModel.coordinateSystem;
  30273. var coordLayout = cartesian.grid.getRect();
  30274. var baseAxis = cartesian.getBaseAxis();
  30275. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30276. var valueDim = data.mapDimension(valueAxis.dim);
  30277. var baseDim = data.mapDimension(baseAxis.dim);
  30278. var valueAxisHorizontal = valueAxis.isHorizontal();
  30279. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30280. var barWidth = retrieveColumnLayout(
  30281. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30282. ).width;
  30283. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30284. barWidth = LARGE_BAR_MIN_WIDTH;
  30285. }
  30286. return {progress: progress};
  30287. function progress(params, data) {
  30288. var count = params.count;
  30289. var largePoints = new LargeArr(count * 2);
  30290. var largeBackgroundPoints = new LargeArr(count * 2);
  30291. var largeDataIndices = new LargeArr(count);
  30292. var dataIndex;
  30293. var coord = [];
  30294. var valuePair = [];
  30295. var pointsOffset = 0;
  30296. var idxOffset = 0;
  30297. while ((dataIndex = params.next()) != null) {
  30298. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30299. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30300. coord = cartesian.dataToPoint(valuePair, null, coord);
  30301. // Data index might not be in order, depends on `progressiveChunkMode`.
  30302. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30303. ? coordLayout.x + coordLayout.width : coord[0];
  30304. largePoints[pointsOffset++] = coord[0];
  30305. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal
  30306. ? coord[1] : coordLayout.y + coordLayout.height;
  30307. largePoints[pointsOffset++] = coord[1];
  30308. largeDataIndices[idxOffset++] = dataIndex;
  30309. }
  30310. data.setLayout({
  30311. largePoints: largePoints,
  30312. largeDataIndices: largeDataIndices,
  30313. largeBackgroundPoints: largeBackgroundPoints,
  30314. barWidth: barWidth,
  30315. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30316. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  30317. valueAxisHorizontal: valueAxisHorizontal
  30318. });
  30319. }
  30320. }
  30321. };
  30322. function isOnCartesian(seriesModel) {
  30323. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30324. }
  30325. function isInLargeMode(seriesModel) {
  30326. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30327. }
  30328. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30329. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30330. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30331. }
  30332. /*
  30333. * Licensed to the Apache Software Foundation (ASF) under one
  30334. * or more contributor license agreements. See the NOTICE file
  30335. * distributed with this work for additional information
  30336. * regarding copyright ownership. The ASF licenses this file
  30337. * to you under the Apache License, Version 2.0 (the
  30338. * "License"); you may not use this file except in compliance
  30339. * with the License. You may obtain a copy of the License at
  30340. *
  30341. * http://www.apache.org/licenses/LICENSE-2.0
  30342. *
  30343. * Unless required by applicable law or agreed to in writing,
  30344. * software distributed under the License is distributed on an
  30345. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30346. * KIND, either express or implied. See the License for the
  30347. * specific language governing permissions and limitations
  30348. * under the License.
  30349. */
  30350. /*
  30351. * A third-party license is embeded for some of the code in this file:
  30352. * The "scaleLevels" was originally copied from "d3.js" with some
  30353. * modifications made for this project.
  30354. * (See more details in the comment on the definition of "scaleLevels" below.)
  30355. * The use of the source code of this file is also subject to the terms
  30356. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30357. * </licenses/LICENSE-d3>).
  30358. */
  30359. // [About UTC and local time zone]:
  30360. // In most cases, `number.parseDate` will treat input data string as local time
  30361. // (except time zone is specified in time string). And `format.formateTime` returns
  30362. // local time by default. option.useUTC is false by default. This design have
  30363. // concidered these common case:
  30364. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30365. // in local time by default.
  30366. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30367. // as its original time, without any time difference.
  30368. var intervalScaleProto = IntervalScale.prototype;
  30369. var mathCeil = Math.ceil;
  30370. var mathFloor = Math.floor;
  30371. var ONE_SECOND = 1000;
  30372. var ONE_MINUTE = ONE_SECOND * 60;
  30373. var ONE_HOUR = ONE_MINUTE * 60;
  30374. var ONE_DAY = ONE_HOUR * 24;
  30375. // FIXME 公用?
  30376. var bisect = function (a, x, lo, hi) {
  30377. while (lo < hi) {
  30378. var mid = lo + hi >>> 1;
  30379. if (a[mid][1] < x) {
  30380. lo = mid + 1;
  30381. }
  30382. else {
  30383. hi = mid;
  30384. }
  30385. }
  30386. return lo;
  30387. };
  30388. /**
  30389. * @alias module:echarts/coord/scale/Time
  30390. * @constructor
  30391. */
  30392. var TimeScale = IntervalScale.extend({
  30393. type: 'time',
  30394. /**
  30395. * @override
  30396. */
  30397. getLabel: function (val) {
  30398. var stepLvl = this._stepLvl;
  30399. var date = new Date(val);
  30400. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30401. },
  30402. /**
  30403. * @override
  30404. */
  30405. niceExtent: function (opt) {
  30406. var extent = this._extent;
  30407. // If extent start and end are same, expand them
  30408. if (extent[0] === extent[1]) {
  30409. // Expand extent
  30410. extent[0] -= ONE_DAY;
  30411. extent[1] += ONE_DAY;
  30412. }
  30413. // If there are no data and extent are [Infinity, -Infinity]
  30414. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30415. var d = new Date();
  30416. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30417. extent[0] = extent[1] - ONE_DAY;
  30418. }
  30419. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30420. // var extent = this._extent;
  30421. var interval = this._interval;
  30422. if (!opt.fixMin) {
  30423. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  30424. }
  30425. if (!opt.fixMax) {
  30426. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  30427. }
  30428. },
  30429. /**
  30430. * @override
  30431. */
  30432. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30433. approxTickNum = approxTickNum || 10;
  30434. var extent = this._extent;
  30435. var span = extent[1] - extent[0];
  30436. var approxInterval = span / approxTickNum;
  30437. if (minInterval != null && approxInterval < minInterval) {
  30438. approxInterval = minInterval;
  30439. }
  30440. if (maxInterval != null && approxInterval > maxInterval) {
  30441. approxInterval = maxInterval;
  30442. }
  30443. var scaleLevelsLen = scaleLevels.length;
  30444. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30445. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30446. var interval = level[1];
  30447. // Same with interval scale if span is much larger than 1 year
  30448. if (level[0] === 'year') {
  30449. var yearSpan = span / interval;
  30450. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30451. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30452. var yearStep = nice(yearSpan / approxTickNum, true);
  30453. interval *= yearStep;
  30454. }
  30455. var timezoneOffset = this.getSetting('useUTC')
  30456. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30457. var niceExtent = [
  30458. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30459. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30460. ];
  30461. fixExtent(niceExtent, extent);
  30462. this._stepLvl = level;
  30463. // Interval will be used in getTicks
  30464. this._interval = interval;
  30465. this._niceExtent = niceExtent;
  30466. },
  30467. parse: function (val) {
  30468. // val might be float.
  30469. return +parseDate(val);
  30470. }
  30471. });
  30472. each$1(['contain', 'normalize'], function (methodName) {
  30473. TimeScale.prototype[methodName] = function (val) {
  30474. return intervalScaleProto[methodName].call(this, this.parse(val));
  30475. };
  30476. });
  30477. /**
  30478. * This implementation was originally copied from "d3.js"
  30479. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30480. * with some modifications made for this program.
  30481. * See the license statement at the head of this file.
  30482. */
  30483. var scaleLevels = [
  30484. // Format interval
  30485. ['hh:mm:ss', ONE_SECOND], // 1s
  30486. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30487. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30488. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30489. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30490. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30491. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30492. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30493. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30494. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30495. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30496. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30497. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30498. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30499. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30500. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30501. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30502. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30503. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30504. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30505. ['week', ONE_DAY * 7], // 7d
  30506. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30507. ['week', ONE_DAY * 14], // 2w
  30508. ['week', ONE_DAY * 21], // 3w
  30509. ['month', ONE_DAY * 31], // 1M
  30510. ['week', ONE_DAY * 42], // 6w
  30511. ['month', ONE_DAY * 62], // 2M
  30512. ['week', ONE_DAY * 70], // 10w
  30513. ['quarter', ONE_DAY * 95], // 3M
  30514. ['month', ONE_DAY * 31 * 4], // 4M
  30515. ['month', ONE_DAY * 31 * 5], // 5M
  30516. ['half-year', ONE_DAY * 380 / 2], // 6M
  30517. ['month', ONE_DAY * 31 * 8], // 8M
  30518. ['month', ONE_DAY * 31 * 10], // 10M
  30519. ['year', ONE_DAY * 380] // 1Y
  30520. ];
  30521. /**
  30522. * @param {module:echarts/model/Model}
  30523. * @return {module:echarts/scale/Time}
  30524. */
  30525. TimeScale.create = function (model) {
  30526. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30527. };
  30528. /*
  30529. * Licensed to the Apache Software Foundation (ASF) under one
  30530. * or more contributor license agreements. See the NOTICE file
  30531. * distributed with this work for additional information
  30532. * regarding copyright ownership. The ASF licenses this file
  30533. * to you under the Apache License, Version 2.0 (the
  30534. * "License"); you may not use this file except in compliance
  30535. * with the License. You may obtain a copy of the License at
  30536. *
  30537. * http://www.apache.org/licenses/LICENSE-2.0
  30538. *
  30539. * Unless required by applicable law or agreed to in writing,
  30540. * software distributed under the License is distributed on an
  30541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30542. * KIND, either express or implied. See the License for the
  30543. * specific language governing permissions and limitations
  30544. * under the License.
  30545. */
  30546. /**
  30547. * Log scale
  30548. * @module echarts/scale/Log
  30549. */
  30550. // Use some method of IntervalScale
  30551. var scaleProto$1 = Scale.prototype;
  30552. var intervalScaleProto$1 = IntervalScale.prototype;
  30553. var getPrecisionSafe$1 = getPrecisionSafe;
  30554. var roundingErrorFix = round$1;
  30555. var mathFloor$1 = Math.floor;
  30556. var mathCeil$1 = Math.ceil;
  30557. var mathPow$1 = Math.pow;
  30558. var mathLog = Math.log;
  30559. var LogScale = Scale.extend({
  30560. type: 'log',
  30561. base: 10,
  30562. $constructor: function () {
  30563. Scale.apply(this, arguments);
  30564. this._originalScale = new IntervalScale();
  30565. },
  30566. /**
  30567. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  30568. * @return {Array.<number>}
  30569. */
  30570. getTicks: function (expandToNicedExtent) {
  30571. var originalScale = this._originalScale;
  30572. var extent = this._extent;
  30573. var originalExtent = originalScale.getExtent();
  30574. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  30575. var powVal = round$1(mathPow$1(this.base, val));
  30576. // Fix #4158
  30577. powVal = (val === extent[0] && originalScale.__fixMin)
  30578. ? fixRoundingError(powVal, originalExtent[0])
  30579. : powVal;
  30580. powVal = (val === extent[1] && originalScale.__fixMax)
  30581. ? fixRoundingError(powVal, originalExtent[1])
  30582. : powVal;
  30583. return powVal;
  30584. }, this);
  30585. },
  30586. /**
  30587. * @param {number} splitNumber
  30588. * @return {Array.<Array.<number>>}
  30589. */
  30590. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  30591. /**
  30592. * @param {number} val
  30593. * @return {string}
  30594. */
  30595. getLabel: intervalScaleProto$1.getLabel,
  30596. /**
  30597. * @param {number} val
  30598. * @return {number}
  30599. */
  30600. scale: function (val) {
  30601. val = scaleProto$1.scale.call(this, val);
  30602. return mathPow$1(this.base, val);
  30603. },
  30604. /**
  30605. * @param {number} start
  30606. * @param {number} end
  30607. */
  30608. setExtent: function (start, end) {
  30609. var base = this.base;
  30610. start = mathLog(start) / mathLog(base);
  30611. end = mathLog(end) / mathLog(base);
  30612. intervalScaleProto$1.setExtent.call(this, start, end);
  30613. },
  30614. /**
  30615. * @return {number} end
  30616. */
  30617. getExtent: function () {
  30618. var base = this.base;
  30619. var extent = scaleProto$1.getExtent.call(this);
  30620. extent[0] = mathPow$1(base, extent[0]);
  30621. extent[1] = mathPow$1(base, extent[1]);
  30622. // Fix #4158
  30623. var originalScale = this._originalScale;
  30624. var originalExtent = originalScale.getExtent();
  30625. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30626. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30627. return extent;
  30628. },
  30629. /**
  30630. * @param {Array.<number>} extent
  30631. */
  30632. unionExtent: function (extent) {
  30633. this._originalScale.unionExtent(extent);
  30634. var base = this.base;
  30635. extent[0] = mathLog(extent[0]) / mathLog(base);
  30636. extent[1] = mathLog(extent[1]) / mathLog(base);
  30637. scaleProto$1.unionExtent.call(this, extent);
  30638. },
  30639. /**
  30640. * @override
  30641. */
  30642. unionExtentFromData: function (data, dim) {
  30643. // TODO
  30644. // filter value that <= 0
  30645. this.unionExtent(data.getApproximateExtent(dim));
  30646. },
  30647. /**
  30648. * Update interval and extent of intervals for nice ticks
  30649. * @param {number} [approxTickNum = 10] Given approx tick number
  30650. */
  30651. niceTicks: function (approxTickNum) {
  30652. approxTickNum = approxTickNum || 10;
  30653. var extent = this._extent;
  30654. var span = extent[1] - extent[0];
  30655. if (span === Infinity || span <= 0) {
  30656. return;
  30657. }
  30658. var interval = quantity(span);
  30659. var err = approxTickNum / span * interval;
  30660. // Filter ticks to get closer to the desired count.
  30661. if (err <= 0.5) {
  30662. interval *= 10;
  30663. }
  30664. // Interval should be integer
  30665. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30666. interval *= 10;
  30667. }
  30668. var niceExtent = [
  30669. round$1(mathCeil$1(extent[0] / interval) * interval),
  30670. round$1(mathFloor$1(extent[1] / interval) * interval)
  30671. ];
  30672. this._interval = interval;
  30673. this._niceExtent = niceExtent;
  30674. },
  30675. /**
  30676. * Nice extent.
  30677. * @override
  30678. */
  30679. niceExtent: function (opt) {
  30680. intervalScaleProto$1.niceExtent.call(this, opt);
  30681. var originalScale = this._originalScale;
  30682. originalScale.__fixMin = opt.fixMin;
  30683. originalScale.__fixMax = opt.fixMax;
  30684. }
  30685. });
  30686. each$1(['contain', 'normalize'], function (methodName) {
  30687. LogScale.prototype[methodName] = function (val) {
  30688. val = mathLog(val) / mathLog(this.base);
  30689. return scaleProto$1[methodName].call(this, val);
  30690. };
  30691. });
  30692. LogScale.create = function () {
  30693. return new LogScale();
  30694. };
  30695. function fixRoundingError(val, originalVal) {
  30696. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30697. }
  30698. /*
  30699. * Licensed to the Apache Software Foundation (ASF) under one
  30700. * or more contributor license agreements. See the NOTICE file
  30701. * distributed with this work for additional information
  30702. * regarding copyright ownership. The ASF licenses this file
  30703. * to you under the Apache License, Version 2.0 (the
  30704. * "License"); you may not use this file except in compliance
  30705. * with the License. You may obtain a copy of the License at
  30706. *
  30707. * http://www.apache.org/licenses/LICENSE-2.0
  30708. *
  30709. * Unless required by applicable law or agreed to in writing,
  30710. * software distributed under the License is distributed on an
  30711. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30712. * KIND, either express or implied. See the License for the
  30713. * specific language governing permissions and limitations
  30714. * under the License.
  30715. */
  30716. /**
  30717. * Get axis scale extent before niced.
  30718. * Item of returned array can only be number (including Infinity and NaN).
  30719. */
  30720. function getScaleExtent(scale, model) {
  30721. var scaleType = scale.type;
  30722. var min = model.getMin();
  30723. var max = model.getMax();
  30724. var originalExtent = scale.getExtent();
  30725. var axisDataLen;
  30726. var boundaryGap;
  30727. var span;
  30728. if (scaleType === 'ordinal') {
  30729. axisDataLen = model.getCategories().length;
  30730. }
  30731. else {
  30732. boundaryGap = model.get('boundaryGap');
  30733. if (!isArray(boundaryGap)) {
  30734. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  30735. }
  30736. if (typeof boundaryGap[0] === 'boolean') {
  30737. if (__DEV__) {
  30738. console.warn('Boolean type for boundaryGap is only '
  30739. + 'allowed for ordinal axis. Please use string in '
  30740. + 'percentage instead, e.g., "20%". Currently, '
  30741. + 'boundaryGap is set to be 0.');
  30742. }
  30743. boundaryGap = [0, 0];
  30744. }
  30745. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  30746. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  30747. span = (originalExtent[1] - originalExtent[0])
  30748. || Math.abs(originalExtent[0]);
  30749. }
  30750. // Notice: When min/max is not set (that is, when there are null/undefined,
  30751. // which is the most common case), these cases should be ensured:
  30752. // (1) For 'ordinal', show all axis.data.
  30753. // (2) For others:
  30754. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30755. // disabled).
  30756. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30757. // be the result that originalExtent enlarged by boundaryGap.
  30758. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30759. // FIXME
  30760. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  30761. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  30762. // that the results processed by boundaryGap are positive/negative?
  30763. if (min === 'dataMin') {
  30764. min = originalExtent[0];
  30765. }
  30766. else if (typeof min === 'function') {
  30767. min = min({
  30768. min: originalExtent[0],
  30769. max: originalExtent[1]
  30770. });
  30771. }
  30772. if (max === 'dataMax') {
  30773. max = originalExtent[1];
  30774. }
  30775. else if (typeof max === 'function') {
  30776. max = max({
  30777. min: originalExtent[0],
  30778. max: originalExtent[1]
  30779. });
  30780. }
  30781. var fixMin = min != null;
  30782. var fixMax = max != null;
  30783. if (min == null) {
  30784. min = scaleType === 'ordinal'
  30785. ? (axisDataLen ? 0 : NaN)
  30786. : originalExtent[0] - boundaryGap[0] * span;
  30787. }
  30788. if (max == null) {
  30789. max = scaleType === 'ordinal'
  30790. ? (axisDataLen ? axisDataLen - 1 : NaN)
  30791. : originalExtent[1] + boundaryGap[1] * span;
  30792. }
  30793. (min == null || !isFinite(min)) && (min = NaN);
  30794. (max == null || !isFinite(max)) && (max = NaN);
  30795. scale.setBlank(
  30796. eqNaN(min)
  30797. || eqNaN(max)
  30798. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  30799. );
  30800. // Evaluate if axis needs cross zero
  30801. if (model.getNeedCrossZero()) {
  30802. // Axis is over zero and min is not set
  30803. if (min > 0 && max > 0 && !fixMin) {
  30804. min = 0;
  30805. }
  30806. // Axis is under zero and max is not set
  30807. if (min < 0 && max < 0 && !fixMax) {
  30808. max = 0;
  30809. }
  30810. }
  30811. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  30812. // is base axis
  30813. // FIXME
  30814. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  30815. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  30816. // Should not depend on series type `bar`?
  30817. // (3) Fix that might overlap when using dataZoom.
  30818. // (4) Consider other chart types using `barGrid`?
  30819. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  30820. var ecModel = model.ecModel;
  30821. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  30822. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  30823. var isBaseAxisAndHasBarSeries;
  30824. each$1(barSeriesModels, function (seriesModel) {
  30825. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  30826. });
  30827. if (isBaseAxisAndHasBarSeries) {
  30828. // Calculate placement of bars on axis
  30829. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  30830. // Adjust axis min and max to account for overflow
  30831. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  30832. min = adjustedScale.min;
  30833. max = adjustedScale.max;
  30834. }
  30835. }
  30836. return {
  30837. extent: [min, max],
  30838. // "fix" means "fixed", the value should not be
  30839. // changed in the subsequent steps.
  30840. fixMin: fixMin,
  30841. fixMax: fixMax
  30842. };
  30843. }
  30844. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  30845. // Get Axis Length
  30846. var axisExtent = model.axis.getExtent();
  30847. var axisLength = axisExtent[1] - axisExtent[0];
  30848. // Get bars on current base axis and calculate min and max overflow
  30849. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  30850. if (barsOnCurrentAxis === undefined) {
  30851. return {min: min, max: max};
  30852. }
  30853. var minOverflow = Infinity;
  30854. each$1(barsOnCurrentAxis, function (item) {
  30855. minOverflow = Math.min(item.offset, minOverflow);
  30856. });
  30857. var maxOverflow = -Infinity;
  30858. each$1(barsOnCurrentAxis, function (item) {
  30859. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  30860. });
  30861. minOverflow = Math.abs(minOverflow);
  30862. maxOverflow = Math.abs(maxOverflow);
  30863. var totalOverFlow = minOverflow + maxOverflow;
  30864. // Calulate required buffer based on old range and overflow
  30865. var oldRange = max - min;
  30866. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  30867. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  30868. max += overflowBuffer * (maxOverflow / totalOverFlow);
  30869. min -= overflowBuffer * (minOverflow / totalOverFlow);
  30870. return {min: min, max: max};
  30871. }
  30872. function niceScaleExtent(scale, model) {
  30873. var extentInfo = getScaleExtent(scale, model);
  30874. var extent = extentInfo.extent;
  30875. var splitNumber = model.get('splitNumber');
  30876. if (scale.type === 'log') {
  30877. scale.base = model.get('logBase');
  30878. }
  30879. var scaleType = scale.type;
  30880. scale.setExtent(extent[0], extent[1]);
  30881. scale.niceExtent({
  30882. splitNumber: splitNumber,
  30883. fixMin: extentInfo.fixMin,
  30884. fixMax: extentInfo.fixMax,
  30885. minInterval: (scaleType === 'interval' || scaleType === 'time')
  30886. ? model.get('minInterval') : null,
  30887. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  30888. ? model.get('maxInterval') : null
  30889. });
  30890. // If some one specified the min, max. And the default calculated interval
  30891. // is not good enough. He can specify the interval. It is often appeared
  30892. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  30893. // to be 60.
  30894. // FIXME
  30895. var interval = model.get('interval');
  30896. if (interval != null) {
  30897. scale.setInterval && scale.setInterval(interval);
  30898. }
  30899. }
  30900. /**
  30901. * @param {module:echarts/model/Model} model
  30902. * @param {string} [axisType] Default retrieve from model.type
  30903. * @return {module:echarts/scale/*}
  30904. */
  30905. function createScaleByModel(model, axisType) {
  30906. axisType = axisType || model.get('type');
  30907. if (axisType) {
  30908. switch (axisType) {
  30909. // Buildin scale
  30910. case 'category':
  30911. return new OrdinalScale(
  30912. model.getOrdinalMeta
  30913. ? model.getOrdinalMeta()
  30914. : model.getCategories(),
  30915. [Infinity, -Infinity]
  30916. );
  30917. case 'value':
  30918. return new IntervalScale();
  30919. // Extended scale, like time and log
  30920. default:
  30921. return (Scale.getClass(axisType) || IntervalScale).create(model);
  30922. }
  30923. }
  30924. }
  30925. /**
  30926. * Check if the axis corss 0
  30927. */
  30928. function ifAxisCrossZero(axis) {
  30929. var dataExtent = axis.scale.getExtent();
  30930. var min = dataExtent[0];
  30931. var max = dataExtent[1];
  30932. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  30933. }
  30934. /**
  30935. * @param {module:echarts/coord/Axis} axis
  30936. * @return {Function} Label formatter function.
  30937. * param: {number} tickValue,
  30938. * param: {number} idx, the index in all ticks.
  30939. * If category axis, this param is not requied.
  30940. * return: {string} label string.
  30941. */
  30942. function makeLabelFormatter(axis) {
  30943. var labelFormatter = axis.getLabelModel().get('formatter');
  30944. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  30945. if (typeof labelFormatter === 'string') {
  30946. labelFormatter = (function (tpl) {
  30947. return function (val) {
  30948. // For category axis, get raw value; for numeric axis,
  30949. // get foramtted label like '1,333,444'.
  30950. val = axis.scale.getLabel(val);
  30951. return tpl.replace('{value}', val != null ? val : '');
  30952. };
  30953. })(labelFormatter);
  30954. // Consider empty array
  30955. return labelFormatter;
  30956. }
  30957. else if (typeof labelFormatter === 'function') {
  30958. return function (tickValue, idx) {
  30959. // The original intention of `idx` is "the index of the tick in all ticks".
  30960. // But the previous implementation of category axis do not consider the
  30961. // `axisLabel.interval`, which cause that, for example, the `interval` is
  30962. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  30963. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  30964. // the definition here for back compatibility.
  30965. if (categoryTickStart != null) {
  30966. idx = tickValue - categoryTickStart;
  30967. }
  30968. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  30969. };
  30970. }
  30971. else {
  30972. return function (tick) {
  30973. return axis.scale.getLabel(tick);
  30974. };
  30975. }
  30976. }
  30977. function getAxisRawValue(axis, value) {
  30978. // In category axis with data zoom, tick is not the original
  30979. // index of axis.data. So tick should not be exposed to user
  30980. // in category axis.
  30981. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  30982. }
  30983. /**
  30984. * @param {module:echarts/coord/Axis} axis
  30985. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  30986. */
  30987. function estimateLabelUnionRect(axis) {
  30988. var axisModel = axis.model;
  30989. var scale = axis.scale;
  30990. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  30991. return;
  30992. }
  30993. var isCategory = axis.type === 'category';
  30994. var realNumberScaleTicks;
  30995. var tickCount;
  30996. var categoryScaleExtent = scale.getExtent();
  30997. // Optimize for large category data, avoid call `getTicks()`.
  30998. if (isCategory) {
  30999. tickCount = scale.count();
  31000. }
  31001. else {
  31002. realNumberScaleTicks = scale.getTicks();
  31003. tickCount = realNumberScaleTicks.length;
  31004. }
  31005. var axisLabelModel = axis.getLabelModel();
  31006. var labelFormatter = makeLabelFormatter(axis);
  31007. var rect;
  31008. var step = 1;
  31009. // Simple optimization for large amount of labels
  31010. if (tickCount > 40) {
  31011. step = Math.ceil(tickCount / 40);
  31012. }
  31013. for (var i = 0; i < tickCount; i += step) {
  31014. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  31015. var label = labelFormatter(tickValue);
  31016. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31017. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31018. rect ? rect.union(singleRect) : (rect = singleRect);
  31019. }
  31020. return rect;
  31021. }
  31022. function rotateTextRect(textRect, rotate) {
  31023. var rotateRadians = rotate * Math.PI / 180;
  31024. var boundingBox = textRect.plain();
  31025. var beforeWidth = boundingBox.width;
  31026. var beforeHeight = boundingBox.height;
  31027. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  31028. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  31029. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  31030. return rotatedRect;
  31031. }
  31032. /**
  31033. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  31034. * @return {number|String} Can be null|'auto'|number|function
  31035. */
  31036. function getOptionCategoryInterval(model) {
  31037. var interval = model.get('interval');
  31038. return interval == null ? 'auto' : interval;
  31039. }
  31040. /**
  31041. * Set `categoryInterval` as 0 implicitly indicates that
  31042. * show all labels reguardless of overlap.
  31043. * @param {Object} axis axisModel.axis
  31044. * @return {boolean}
  31045. */
  31046. function shouldShowAllLabels(axis) {
  31047. return axis.type === 'category'
  31048. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31049. }
  31050. /*
  31051. * Licensed to the Apache Software Foundation (ASF) under one
  31052. * or more contributor license agreements. See the NOTICE file
  31053. * distributed with this work for additional information
  31054. * regarding copyright ownership. The ASF licenses this file
  31055. * to you under the Apache License, Version 2.0 (the
  31056. * "License"); you may not use this file except in compliance
  31057. * with the License. You may obtain a copy of the License at
  31058. *
  31059. * http://www.apache.org/licenses/LICENSE-2.0
  31060. *
  31061. * Unless required by applicable law or agreed to in writing,
  31062. * software distributed under the License is distributed on an
  31063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31064. * KIND, either express or implied. See the License for the
  31065. * specific language governing permissions and limitations
  31066. * under the License.
  31067. */
  31068. // import * as axisHelper from './axisHelper';
  31069. var axisModelCommonMixin = {
  31070. /**
  31071. * @param {boolean} origin
  31072. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  31073. */
  31074. getMin: function (origin) {
  31075. var option = this.option;
  31076. var min = (!origin && option.rangeStart != null)
  31077. ? option.rangeStart : option.min;
  31078. if (this.axis
  31079. && min != null
  31080. && min !== 'dataMin'
  31081. && typeof min !== 'function'
  31082. && !eqNaN(min)
  31083. ) {
  31084. min = this.axis.scale.parse(min);
  31085. }
  31086. return min;
  31087. },
  31088. /**
  31089. * @param {boolean} origin
  31090. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  31091. */
  31092. getMax: function (origin) {
  31093. var option = this.option;
  31094. var max = (!origin && option.rangeEnd != null)
  31095. ? option.rangeEnd : option.max;
  31096. if (this.axis
  31097. && max != null
  31098. && max !== 'dataMax'
  31099. && typeof max !== 'function'
  31100. && !eqNaN(max)
  31101. ) {
  31102. max = this.axis.scale.parse(max);
  31103. }
  31104. return max;
  31105. },
  31106. /**
  31107. * @return {boolean}
  31108. */
  31109. getNeedCrossZero: function () {
  31110. var option = this.option;
  31111. return (option.rangeStart != null || option.rangeEnd != null)
  31112. ? false : !option.scale;
  31113. },
  31114. /**
  31115. * Should be implemented by each axis model if necessary.
  31116. * @return {module:echarts/model/Component} coordinate system model
  31117. */
  31118. getCoordSysModel: noop,
  31119. /**
  31120. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  31121. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  31122. */
  31123. setRange: function (rangeStart, rangeEnd) {
  31124. this.option.rangeStart = rangeStart;
  31125. this.option.rangeEnd = rangeEnd;
  31126. },
  31127. /**
  31128. * Reset range
  31129. */
  31130. resetRange: function () {
  31131. // rangeStart and rangeEnd is readonly.
  31132. this.option.rangeStart = this.option.rangeEnd = null;
  31133. }
  31134. };
  31135. /*
  31136. * Licensed to the Apache Software Foundation (ASF) under one
  31137. * or more contributor license agreements. See the NOTICE file
  31138. * distributed with this work for additional information
  31139. * regarding copyright ownership. The ASF licenses this file
  31140. * to you under the Apache License, Version 2.0 (the
  31141. * "License"); you may not use this file except in compliance
  31142. * with the License. You may obtain a copy of the License at
  31143. *
  31144. * http://www.apache.org/licenses/LICENSE-2.0
  31145. *
  31146. * Unless required by applicable law or agreed to in writing,
  31147. * software distributed under the License is distributed on an
  31148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31149. * KIND, either express or implied. See the License for the
  31150. * specific language governing permissions and limitations
  31151. * under the License.
  31152. */
  31153. // Symbol factory
  31154. /**
  31155. * Triangle shape
  31156. * @inner
  31157. */
  31158. var Triangle = extendShape({
  31159. type: 'triangle',
  31160. shape: {
  31161. cx: 0,
  31162. cy: 0,
  31163. width: 0,
  31164. height: 0
  31165. },
  31166. buildPath: function (path, shape) {
  31167. var cx = shape.cx;
  31168. var cy = shape.cy;
  31169. var width = shape.width / 2;
  31170. var height = shape.height / 2;
  31171. path.moveTo(cx, cy - height);
  31172. path.lineTo(cx + width, cy + height);
  31173. path.lineTo(cx - width, cy + height);
  31174. path.closePath();
  31175. }
  31176. });
  31177. /**
  31178. * Diamond shape
  31179. * @inner
  31180. */
  31181. var Diamond = extendShape({
  31182. type: 'diamond',
  31183. shape: {
  31184. cx: 0,
  31185. cy: 0,
  31186. width: 0,
  31187. height: 0
  31188. },
  31189. buildPath: function (path, shape) {
  31190. var cx = shape.cx;
  31191. var cy = shape.cy;
  31192. var width = shape.width / 2;
  31193. var height = shape.height / 2;
  31194. path.moveTo(cx, cy - height);
  31195. path.lineTo(cx + width, cy);
  31196. path.lineTo(cx, cy + height);
  31197. path.lineTo(cx - width, cy);
  31198. path.closePath();
  31199. }
  31200. });
  31201. /**
  31202. * Pin shape
  31203. * @inner
  31204. */
  31205. var Pin = extendShape({
  31206. type: 'pin',
  31207. shape: {
  31208. // x, y on the cusp
  31209. x: 0,
  31210. y: 0,
  31211. width: 0,
  31212. height: 0
  31213. },
  31214. buildPath: function (path, shape) {
  31215. var x = shape.x;
  31216. var y = shape.y;
  31217. var w = shape.width / 5 * 3;
  31218. // Height must be larger than width
  31219. var h = Math.max(w, shape.height);
  31220. var r = w / 2;
  31221. // Dist on y with tangent point and circle center
  31222. var dy = r * r / (h - r);
  31223. var cy = y - h + r + dy;
  31224. var angle = Math.asin(dy / r);
  31225. // Dist on x with tangent point and circle center
  31226. var dx = Math.cos(angle) * r;
  31227. var tanX = Math.sin(angle);
  31228. var tanY = Math.cos(angle);
  31229. var cpLen = r * 0.6;
  31230. var cpLen2 = r * 0.7;
  31231. path.moveTo(x - dx, cy + dy);
  31232. path.arc(
  31233. x, cy, r,
  31234. Math.PI - angle,
  31235. Math.PI * 2 + angle
  31236. );
  31237. path.bezierCurveTo(
  31238. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  31239. x, y - cpLen2,
  31240. x, y
  31241. );
  31242. path.bezierCurveTo(
  31243. x, y - cpLen2,
  31244. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  31245. x - dx, cy + dy
  31246. );
  31247. path.closePath();
  31248. }
  31249. });
  31250. /**
  31251. * Arrow shape
  31252. * @inner
  31253. */
  31254. var Arrow = extendShape({
  31255. type: 'arrow',
  31256. shape: {
  31257. x: 0,
  31258. y: 0,
  31259. width: 0,
  31260. height: 0
  31261. },
  31262. buildPath: function (ctx, shape) {
  31263. var height = shape.height;
  31264. var width = shape.width;
  31265. var x = shape.x;
  31266. var y = shape.y;
  31267. var dx = width / 3 * 2;
  31268. ctx.moveTo(x, y);
  31269. ctx.lineTo(x + dx, y + height);
  31270. ctx.lineTo(x, y + height / 4 * 3);
  31271. ctx.lineTo(x - dx, y + height);
  31272. ctx.lineTo(x, y);
  31273. ctx.closePath();
  31274. }
  31275. });
  31276. /**
  31277. * Map of path contructors
  31278. * @type {Object.<string, module:zrender/graphic/Path>}
  31279. */
  31280. var symbolCtors = {
  31281. line: Line,
  31282. rect: Rect,
  31283. roundRect: Rect,
  31284. square: Rect,
  31285. circle: Circle,
  31286. diamond: Diamond,
  31287. pin: Pin,
  31288. arrow: Arrow,
  31289. triangle: Triangle
  31290. };
  31291. var symbolShapeMakers = {
  31292. line: function (x, y, w, h, shape) {
  31293. // FIXME
  31294. shape.x1 = x;
  31295. shape.y1 = y + h / 2;
  31296. shape.x2 = x + w;
  31297. shape.y2 = y + h / 2;
  31298. },
  31299. rect: function (x, y, w, h, shape) {
  31300. shape.x = x;
  31301. shape.y = y;
  31302. shape.width = w;
  31303. shape.height = h;
  31304. },
  31305. roundRect: function (x, y, w, h, shape) {
  31306. shape.x = x;
  31307. shape.y = y;
  31308. shape.width = w;
  31309. shape.height = h;
  31310. shape.r = Math.min(w, h) / 4;
  31311. },
  31312. square: function (x, y, w, h, shape) {
  31313. var size = Math.min(w, h);
  31314. shape.x = x;
  31315. shape.y = y;
  31316. shape.width = size;
  31317. shape.height = size;
  31318. },
  31319. circle: function (x, y, w, h, shape) {
  31320. // Put circle in the center of square
  31321. shape.cx = x + w / 2;
  31322. shape.cy = y + h / 2;
  31323. shape.r = Math.min(w, h) / 2;
  31324. },
  31325. diamond: function (x, y, w, h, shape) {
  31326. shape.cx = x + w / 2;
  31327. shape.cy = y + h / 2;
  31328. shape.width = w;
  31329. shape.height = h;
  31330. },
  31331. pin: function (x, y, w, h, shape) {
  31332. shape.x = x + w / 2;
  31333. shape.y = y + h / 2;
  31334. shape.width = w;
  31335. shape.height = h;
  31336. },
  31337. arrow: function (x, y, w, h, shape) {
  31338. shape.x = x + w / 2;
  31339. shape.y = y + h / 2;
  31340. shape.width = w;
  31341. shape.height = h;
  31342. },
  31343. triangle: function (x, y, w, h, shape) {
  31344. shape.cx = x + w / 2;
  31345. shape.cy = y + h / 2;
  31346. shape.width = w;
  31347. shape.height = h;
  31348. }
  31349. };
  31350. var symbolBuildProxies = {};
  31351. each$1(symbolCtors, function (Ctor, name) {
  31352. symbolBuildProxies[name] = new Ctor();
  31353. });
  31354. var SymbolClz = extendShape({
  31355. type: 'symbol',
  31356. shape: {
  31357. symbolType: '',
  31358. x: 0,
  31359. y: 0,
  31360. width: 0,
  31361. height: 0
  31362. },
  31363. calculateTextPosition: function (out, style, rect) {
  31364. var res = calculateTextPosition(out, style, rect);
  31365. var shape = this.shape;
  31366. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  31367. res.y = rect.y + rect.height * 0.4;
  31368. }
  31369. return res;
  31370. },
  31371. buildPath: function (ctx, shape, inBundle) {
  31372. var symbolType = shape.symbolType;
  31373. if (symbolType !== 'none') {
  31374. var proxySymbol = symbolBuildProxies[symbolType];
  31375. if (!proxySymbol) {
  31376. // Default rect
  31377. symbolType = 'rect';
  31378. proxySymbol = symbolBuildProxies[symbolType];
  31379. }
  31380. symbolShapeMakers[symbolType](
  31381. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  31382. );
  31383. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  31384. }
  31385. }
  31386. });
  31387. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  31388. function symbolPathSetColor(color, innerColor) {
  31389. if (this.type !== 'image') {
  31390. var symbolStyle = this.style;
  31391. var symbolShape = this.shape;
  31392. if (symbolShape && symbolShape.symbolType === 'line') {
  31393. symbolStyle.stroke = color;
  31394. }
  31395. else if (this.__isEmptyBrush) {
  31396. symbolStyle.stroke = color;
  31397. symbolStyle.fill = innerColor || '#fff';
  31398. }
  31399. else {
  31400. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  31401. symbolStyle.fill && (symbolStyle.fill = color);
  31402. symbolStyle.stroke && (symbolStyle.stroke = color);
  31403. }
  31404. this.dirty(false);
  31405. }
  31406. }
  31407. /**
  31408. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  31409. * @param {string} symbolType
  31410. * @param {number} x
  31411. * @param {number} y
  31412. * @param {number} w
  31413. * @param {number} h
  31414. * @param {string} color
  31415. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  31416. * for path and image only.
  31417. */
  31418. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  31419. // TODO Support image object, DynamicImage.
  31420. var isEmpty = symbolType.indexOf('empty') === 0;
  31421. if (isEmpty) {
  31422. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  31423. }
  31424. var symbolPath;
  31425. if (symbolType.indexOf('image://') === 0) {
  31426. symbolPath = makeImage(
  31427. symbolType.slice(8),
  31428. new BoundingRect(x, y, w, h),
  31429. keepAspect ? 'center' : 'cover'
  31430. );
  31431. }
  31432. else if (symbolType.indexOf('path://') === 0) {
  31433. symbolPath = makePath(
  31434. symbolType.slice(7),
  31435. {},
  31436. new BoundingRect(x, y, w, h),
  31437. keepAspect ? 'center' : 'cover'
  31438. );
  31439. }
  31440. else {
  31441. symbolPath = new SymbolClz({
  31442. shape: {
  31443. symbolType: symbolType,
  31444. x: x,
  31445. y: y,
  31446. width: w,
  31447. height: h
  31448. }
  31449. });
  31450. }
  31451. symbolPath.__isEmptyBrush = isEmpty;
  31452. symbolPath.setColor = symbolPathSetColor;
  31453. symbolPath.setColor(color);
  31454. return symbolPath;
  31455. }
  31456. /*
  31457. * Licensed to the Apache Software Foundation (ASF) under one
  31458. * or more contributor license agreements. See the NOTICE file
  31459. * distributed with this work for additional information
  31460. * regarding copyright ownership. The ASF licenses this file
  31461. * to you under the Apache License, Version 2.0 (the
  31462. * "License"); you may not use this file except in compliance
  31463. * with the License. You may obtain a copy of the License at
  31464. *
  31465. * http://www.apache.org/licenses/LICENSE-2.0
  31466. *
  31467. * Unless required by applicable law or agreed to in writing,
  31468. * software distributed under the License is distributed on an
  31469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31470. * KIND, either express or implied. See the License for the
  31471. * specific language governing permissions and limitations
  31472. * under the License.
  31473. */
  31474. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  31475. /**
  31476. * Create a muti dimension List structure from seriesModel.
  31477. * @param {module:echarts/model/Model} seriesModel
  31478. * @return {module:echarts/data/List} list
  31479. */
  31480. function createList(seriesModel) {
  31481. return createListFromArray(seriesModel.getSource(), seriesModel);
  31482. }
  31483. var dataStack$1 = {
  31484. isDimensionStacked: isDimensionStacked,
  31485. enableDataStack: enableDataStack,
  31486. getStackedDimension: getStackedDimension
  31487. };
  31488. /**
  31489. * Create scale
  31490. * @param {Array.<number>} dataExtent
  31491. * @param {Object|module:echarts/Model} option
  31492. */
  31493. function createScale(dataExtent, option) {
  31494. var axisModel = option;
  31495. if (!Model.isInstance(option)) {
  31496. axisModel = new Model(option);
  31497. mixin(axisModel, axisModelCommonMixin);
  31498. }
  31499. var scale = createScaleByModel(axisModel);
  31500. scale.setExtent(dataExtent[0], dataExtent[1]);
  31501. niceScaleExtent(scale, axisModel);
  31502. return scale;
  31503. }
  31504. /**
  31505. * Mixin common methods to axis model,
  31506. *
  31507. * Inlcude methods
  31508. * `getFormattedLabels() => Array.<string>`
  31509. * `getCategories() => Array.<string>`
  31510. * `getMin(origin: boolean) => number`
  31511. * `getMax(origin: boolean) => number`
  31512. * `getNeedCrossZero() => boolean`
  31513. * `setRange(start: number, end: number)`
  31514. * `resetRange()`
  31515. */
  31516. function mixinAxisModelCommonMethods(Model$$1) {
  31517. mixin(Model$$1, axisModelCommonMixin);
  31518. }
  31519. var helper = (Object.freeze || Object)({
  31520. createList: createList,
  31521. getLayoutRect: getLayoutRect,
  31522. dataStack: dataStack$1,
  31523. createScale: createScale,
  31524. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31525. completeDimensions: completeDimensions,
  31526. createDimensions: createDimensions,
  31527. createSymbol: createSymbol
  31528. });
  31529. var EPSILON$3 = 1e-8;
  31530. function isAroundEqual$1(a, b) {
  31531. return Math.abs(a - b) < EPSILON$3;
  31532. }
  31533. function contain$1(points, x, y) {
  31534. var w = 0;
  31535. var p = points[0];
  31536. if (!p) {
  31537. return false;
  31538. }
  31539. for (var i = 1; i < points.length; i++) {
  31540. var p2 = points[i];
  31541. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31542. p = p2;
  31543. }
  31544. // Close polygon
  31545. var p0 = points[0];
  31546. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31547. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31548. }
  31549. return w !== 0;
  31550. }
  31551. /*
  31552. * Licensed to the Apache Software Foundation (ASF) under one
  31553. * or more contributor license agreements. See the NOTICE file
  31554. * distributed with this work for additional information
  31555. * regarding copyright ownership. The ASF licenses this file
  31556. * to you under the Apache License, Version 2.0 (the
  31557. * "License"); you may not use this file except in compliance
  31558. * with the License. You may obtain a copy of the License at
  31559. *
  31560. * http://www.apache.org/licenses/LICENSE-2.0
  31561. *
  31562. * Unless required by applicable law or agreed to in writing,
  31563. * software distributed under the License is distributed on an
  31564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31565. * KIND, either express or implied. See the License for the
  31566. * specific language governing permissions and limitations
  31567. * under the License.
  31568. */
  31569. /**
  31570. * @module echarts/coord/geo/Region
  31571. */
  31572. /**
  31573. * @param {string|Region} name
  31574. * @param {Array} geometries
  31575. * @param {Array.<number>} cp
  31576. */
  31577. function Region(name, geometries, cp) {
  31578. /**
  31579. * @type {string}
  31580. * @readOnly
  31581. */
  31582. this.name = name;
  31583. /**
  31584. * @type {Array.<Array>}
  31585. * @readOnly
  31586. */
  31587. this.geometries = geometries;
  31588. if (!cp) {
  31589. var rect = this.getBoundingRect();
  31590. cp = [
  31591. rect.x + rect.width / 2,
  31592. rect.y + rect.height / 2
  31593. ];
  31594. }
  31595. else {
  31596. cp = [cp[0], cp[1]];
  31597. }
  31598. /**
  31599. * @type {Array.<number>}
  31600. */
  31601. this.center = cp;
  31602. }
  31603. Region.prototype = {
  31604. constructor: Region,
  31605. properties: null,
  31606. /**
  31607. * @return {module:zrender/core/BoundingRect}
  31608. */
  31609. getBoundingRect: function () {
  31610. var rect = this._rect;
  31611. if (rect) {
  31612. return rect;
  31613. }
  31614. var MAX_NUMBER = Number.MAX_VALUE;
  31615. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  31616. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31617. var min2 = [];
  31618. var max2 = [];
  31619. var geometries = this.geometries;
  31620. for (var i = 0; i < geometries.length; i++) {
  31621. // Only support polygon
  31622. if (geometries[i].type !== 'polygon') {
  31623. continue;
  31624. }
  31625. // Doesn't consider hole
  31626. var exterior = geometries[i].exterior;
  31627. fromPoints(exterior, min2, max2);
  31628. min(min$$1, min$$1, min2);
  31629. max(max$$1, max$$1, max2);
  31630. }
  31631. // No data
  31632. if (i === 0) {
  31633. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  31634. }
  31635. return (this._rect = new BoundingRect(
  31636. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  31637. ));
  31638. },
  31639. /**
  31640. * @param {<Array.<number>} coord
  31641. * @return {boolean}
  31642. */
  31643. contain: function (coord) {
  31644. var rect = this.getBoundingRect();
  31645. var geometries = this.geometries;
  31646. if (!rect.contain(coord[0], coord[1])) {
  31647. return false;
  31648. }
  31649. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  31650. // Only support polygon.
  31651. if (geometries[i].type !== 'polygon') {
  31652. continue;
  31653. }
  31654. var exterior = geometries[i].exterior;
  31655. var interiors = geometries[i].interiors;
  31656. if (contain$1(exterior, coord[0], coord[1])) {
  31657. // Not in the region if point is in the hole.
  31658. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31659. if (contain$1(interiors[k])) {
  31660. continue loopGeo;
  31661. }
  31662. }
  31663. return true;
  31664. }
  31665. }
  31666. return false;
  31667. },
  31668. transformTo: function (x, y, width, height) {
  31669. var rect = this.getBoundingRect();
  31670. var aspect = rect.width / rect.height;
  31671. if (!width) {
  31672. width = aspect * height;
  31673. }
  31674. else if (!height) {
  31675. height = width / aspect;
  31676. }
  31677. var target = new BoundingRect(x, y, width, height);
  31678. var transform = rect.calculateTransform(target);
  31679. var geometries = this.geometries;
  31680. for (var i = 0; i < geometries.length; i++) {
  31681. // Only support polygon.
  31682. if (geometries[i].type !== 'polygon') {
  31683. continue;
  31684. }
  31685. var exterior = geometries[i].exterior;
  31686. var interiors = geometries[i].interiors;
  31687. for (var p = 0; p < exterior.length; p++) {
  31688. applyTransform(exterior[p], exterior[p], transform);
  31689. }
  31690. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31691. for (var p = 0; p < interiors[h].length; p++) {
  31692. applyTransform(interiors[h][p], interiors[h][p], transform);
  31693. }
  31694. }
  31695. }
  31696. rect = this._rect;
  31697. rect.copy(target);
  31698. // Update center
  31699. this.center = [
  31700. rect.x + rect.width / 2,
  31701. rect.y + rect.height / 2
  31702. ];
  31703. },
  31704. cloneShallow: function (name) {
  31705. name == null && (name = this.name);
  31706. var newRegion = new Region(name, this.geometries, this.center);
  31707. newRegion._rect = this._rect;
  31708. newRegion.transformTo = null; // Simply avoid to be called.
  31709. return newRegion;
  31710. }
  31711. };
  31712. /*
  31713. * Licensed to the Apache Software Foundation (ASF) under one
  31714. * or more contributor license agreements. See the NOTICE file
  31715. * distributed with this work for additional information
  31716. * regarding copyright ownership. The ASF licenses this file
  31717. * to you under the Apache License, Version 2.0 (the
  31718. * "License"); you may not use this file except in compliance
  31719. * with the License. You may obtain a copy of the License at
  31720. *
  31721. * http://www.apache.org/licenses/LICENSE-2.0
  31722. *
  31723. * Unless required by applicable law or agreed to in writing,
  31724. * software distributed under the License is distributed on an
  31725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31726. * KIND, either express or implied. See the License for the
  31727. * specific language governing permissions and limitations
  31728. * under the License.
  31729. */
  31730. /**
  31731. * Parse and decode geo json
  31732. * @module echarts/coord/geo/parseGeoJson
  31733. */
  31734. function decode(json) {
  31735. if (!json.UTF8Encoding) {
  31736. return json;
  31737. }
  31738. var encodeScale = json.UTF8Scale;
  31739. if (encodeScale == null) {
  31740. encodeScale = 1024;
  31741. }
  31742. var features = json.features;
  31743. for (var f = 0; f < features.length; f++) {
  31744. var feature = features[f];
  31745. var geometry = feature.geometry;
  31746. var coordinates = geometry.coordinates;
  31747. var encodeOffsets = geometry.encodeOffsets;
  31748. for (var c = 0; c < coordinates.length; c++) {
  31749. var coordinate = coordinates[c];
  31750. if (geometry.type === 'Polygon') {
  31751. coordinates[c] = decodePolygon(
  31752. coordinate,
  31753. encodeOffsets[c],
  31754. encodeScale
  31755. );
  31756. }
  31757. else if (geometry.type === 'MultiPolygon') {
  31758. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31759. var polygon = coordinate[c2];
  31760. coordinate[c2] = decodePolygon(
  31761. polygon,
  31762. encodeOffsets[c][c2],
  31763. encodeScale
  31764. );
  31765. }
  31766. }
  31767. }
  31768. }
  31769. // Has been decoded
  31770. json.UTF8Encoding = false;
  31771. return json;
  31772. }
  31773. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31774. var result = [];
  31775. var prevX = encodeOffsets[0];
  31776. var prevY = encodeOffsets[1];
  31777. for (var i = 0; i < coordinate.length; i += 2) {
  31778. var x = coordinate.charCodeAt(i) - 64;
  31779. var y = coordinate.charCodeAt(i + 1) - 64;
  31780. // ZigZag decoding
  31781. x = (x >> 1) ^ (-(x & 1));
  31782. y = (y >> 1) ^ (-(y & 1));
  31783. // Delta deocding
  31784. x += prevX;
  31785. y += prevY;
  31786. prevX = x;
  31787. prevY = y;
  31788. // Dequantize
  31789. result.push([x / encodeScale, y / encodeScale]);
  31790. }
  31791. return result;
  31792. }
  31793. /**
  31794. * @alias module:echarts/coord/geo/parseGeoJson
  31795. * @param {Object} geoJson
  31796. * @param {string} nameProperty
  31797. * @return {module:zrender/container/Group}
  31798. */
  31799. var parseGeoJSON = function (geoJson, nameProperty) {
  31800. decode(geoJson);
  31801. return map(filter(geoJson.features, function (featureObj) {
  31802. // Output of mapshaper may have geometry null
  31803. return featureObj.geometry
  31804. && featureObj.properties
  31805. && featureObj.geometry.coordinates.length > 0;
  31806. }), function (featureObj) {
  31807. var properties = featureObj.properties;
  31808. var geo = featureObj.geometry;
  31809. var coordinates = geo.coordinates;
  31810. var geometries = [];
  31811. if (geo.type === 'Polygon') {
  31812. geometries.push({
  31813. type: 'polygon',
  31814. // According to the GeoJSON specification.
  31815. // First must be exterior, and the rest are all interior(holes).
  31816. exterior: coordinates[0],
  31817. interiors: coordinates.slice(1)
  31818. });
  31819. }
  31820. if (geo.type === 'MultiPolygon') {
  31821. each$1(coordinates, function (item) {
  31822. if (item[0]) {
  31823. geometries.push({
  31824. type: 'polygon',
  31825. exterior: item[0],
  31826. interiors: item.slice(1)
  31827. });
  31828. }
  31829. });
  31830. }
  31831. var region = new Region(
  31832. properties[nameProperty || 'name'],
  31833. geometries,
  31834. properties.cp
  31835. );
  31836. region.properties = properties;
  31837. return region;
  31838. });
  31839. };
  31840. /*
  31841. * Licensed to the Apache Software Foundation (ASF) under one
  31842. * or more contributor license agreements. See the NOTICE file
  31843. * distributed with this work for additional information
  31844. * regarding copyright ownership. The ASF licenses this file
  31845. * to you under the Apache License, Version 2.0 (the
  31846. * "License"); you may not use this file except in compliance
  31847. * with the License. You may obtain a copy of the License at
  31848. *
  31849. * http://www.apache.org/licenses/LICENSE-2.0
  31850. *
  31851. * Unless required by applicable law or agreed to in writing,
  31852. * software distributed under the License is distributed on an
  31853. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31854. * KIND, either express or implied. See the License for the
  31855. * specific language governing permissions and limitations
  31856. * under the License.
  31857. */
  31858. var inner$6 = makeInner();
  31859. /**
  31860. * @param {module:echats/coord/Axis} axis
  31861. * @return {Object} {
  31862. * labels: [{
  31863. * formattedLabel: string,
  31864. * rawLabel: string,
  31865. * tickValue: number
  31866. * }, ...],
  31867. * labelCategoryInterval: number
  31868. * }
  31869. */
  31870. function createAxisLabels(axis) {
  31871. // Only ordinal scale support tick interval
  31872. return axis.type === 'category'
  31873. ? makeCategoryLabels(axis)
  31874. : makeRealNumberLabels(axis);
  31875. }
  31876. /**
  31877. * @param {module:echats/coord/Axis} axis
  31878. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31879. * @return {Object} {
  31880. * ticks: Array.<number>
  31881. * tickCategoryInterval: number
  31882. * }
  31883. */
  31884. function createAxisTicks(axis, tickModel) {
  31885. // Only ordinal scale support tick interval
  31886. return axis.type === 'category'
  31887. ? makeCategoryTicks(axis, tickModel)
  31888. : {ticks: axis.scale.getTicks()};
  31889. }
  31890. function makeCategoryLabels(axis) {
  31891. var labelModel = axis.getLabelModel();
  31892. var result = makeCategoryLabelsActually(axis, labelModel);
  31893. return (!labelModel.get('show') || axis.scale.isBlank())
  31894. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31895. : result;
  31896. }
  31897. function makeCategoryLabelsActually(axis, labelModel) {
  31898. var labelsCache = getListCache(axis, 'labels');
  31899. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31900. var result = listCacheGet(labelsCache, optionLabelInterval);
  31901. if (result) {
  31902. return result;
  31903. }
  31904. var labels;
  31905. var numericLabelInterval;
  31906. if (isFunction$1(optionLabelInterval)) {
  31907. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31908. }
  31909. else {
  31910. numericLabelInterval = optionLabelInterval === 'auto'
  31911. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31912. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31913. }
  31914. // Cache to avoid calling interval function repeatly.
  31915. return listCacheSet(labelsCache, optionLabelInterval, {
  31916. labels: labels, labelCategoryInterval: numericLabelInterval
  31917. });
  31918. }
  31919. function makeCategoryTicks(axis, tickModel) {
  31920. var ticksCache = getListCache(axis, 'ticks');
  31921. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31922. var result = listCacheGet(ticksCache, optionTickInterval);
  31923. if (result) {
  31924. return result;
  31925. }
  31926. var ticks;
  31927. var tickCategoryInterval;
  31928. // Optimize for the case that large category data and no label displayed,
  31929. // we should not return all ticks.
  31930. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31931. ticks = [];
  31932. }
  31933. if (isFunction$1(optionTickInterval)) {
  31934. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31935. }
  31936. // Always use label interval by default despite label show. Consider this
  31937. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31938. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31939. else if (optionTickInterval === 'auto') {
  31940. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31941. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31942. ticks = map(labelsResult.labels, function (labelItem) {
  31943. return labelItem.tickValue;
  31944. });
  31945. }
  31946. else {
  31947. tickCategoryInterval = optionTickInterval;
  31948. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31949. }
  31950. // Cache to avoid calling interval function repeatly.
  31951. return listCacheSet(ticksCache, optionTickInterval, {
  31952. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31953. });
  31954. }
  31955. function makeRealNumberLabels(axis) {
  31956. var ticks = axis.scale.getTicks();
  31957. var labelFormatter = makeLabelFormatter(axis);
  31958. return {
  31959. labels: map(ticks, function (tickValue, idx) {
  31960. return {
  31961. formattedLabel: labelFormatter(tickValue, idx),
  31962. rawLabel: axis.scale.getLabel(tickValue),
  31963. tickValue: tickValue
  31964. };
  31965. })
  31966. };
  31967. }
  31968. // Large category data calculation is performence sensitive, and ticks and label
  31969. // probably be fetched by multiple times. So we cache the result.
  31970. // axis is created each time during a ec process, so we do not need to clear cache.
  31971. function getListCache(axis, prop) {
  31972. // Because key can be funciton, and cache size always be small, we use array cache.
  31973. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31974. }
  31975. function listCacheGet(cache, key) {
  31976. for (var i = 0; i < cache.length; i++) {
  31977. if (cache[i].key === key) {
  31978. return cache[i].value;
  31979. }
  31980. }
  31981. }
  31982. function listCacheSet(cache, key, value) {
  31983. cache.push({key: key, value: value});
  31984. return value;
  31985. }
  31986. function makeAutoCategoryInterval(axis) {
  31987. var result = inner$6(axis).autoInterval;
  31988. return result != null
  31989. ? result
  31990. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31991. }
  31992. /**
  31993. * Calculate interval for category axis ticks and labels.
  31994. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31995. * should be implemented in axis.
  31996. */
  31997. function calculateCategoryInterval(axis) {
  31998. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31999. var labelFormatter = makeLabelFormatter(axis);
  32000. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32001. var ordinalScale = axis.scale;
  32002. var ordinalExtent = ordinalScale.getExtent();
  32003. // Providing this method is for optimization:
  32004. // avoid generating a long array by `getTicks`
  32005. // in large category data case.
  32006. var tickCount = ordinalScale.count();
  32007. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32008. return 0;
  32009. }
  32010. var step = 1;
  32011. // Simple optimization. Empirical value: tick count should less than 40.
  32012. if (tickCount > 40) {
  32013. step = Math.max(1, Math.floor(tickCount / 40));
  32014. }
  32015. var tickValue = ordinalExtent[0];
  32016. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32017. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32018. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32019. var maxW = 0;
  32020. var maxH = 0;
  32021. // Caution: Performance sensitive for large category data.
  32022. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32023. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32024. var width = 0;
  32025. var height = 0;
  32026. // Not precise, do not consider align and vertical align
  32027. // and each distance from axis line yet.
  32028. var rect = getBoundingRect(
  32029. labelFormatter(tickValue), params.font, 'center', 'top'
  32030. );
  32031. // Magic number
  32032. width = rect.width * 1.3;
  32033. height = rect.height * 1.3;
  32034. // Min size, void long loop.
  32035. maxW = Math.max(maxW, width, 7);
  32036. maxH = Math.max(maxH, height, 7);
  32037. }
  32038. var dw = maxW / unitW;
  32039. var dh = maxH / unitH;
  32040. // 0/0 is NaN, 1/0 is Infinity.
  32041. isNaN(dw) && (dw = Infinity);
  32042. isNaN(dh) && (dh = Infinity);
  32043. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32044. var cache = inner$6(axis.model);
  32045. var axisExtent = axis.getExtent();
  32046. var lastAutoInterval = cache.lastAutoInterval;
  32047. var lastTickCount = cache.lastTickCount;
  32048. // Use cache to keep interval stable while moving zoom window,
  32049. // otherwise the calculated interval might jitter when the zoom
  32050. // window size is close to the interval-changing size.
  32051. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32052. // The jitter will cause that sometimes the displayed labels are
  32053. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32054. if (lastAutoInterval != null
  32055. && lastTickCount != null
  32056. && Math.abs(lastAutoInterval - interval) <= 1
  32057. && Math.abs(lastTickCount - tickCount) <= 1
  32058. // Always choose the bigger one, otherwise the critical
  32059. // point is not the same when zooming in or zooming out.
  32060. && lastAutoInterval > interval
  32061. // If the axis change is caused by chart resize, the cache should not
  32062. // be used. Otherwise some hiden labels might not be shown again.
  32063. && cache.axisExtend0 === axisExtent[0]
  32064. && cache.axisExtend1 === axisExtent[1]
  32065. ) {
  32066. interval = lastAutoInterval;
  32067. }
  32068. // Only update cache if cache not used, otherwise the
  32069. // changing of interval is too insensitive.
  32070. else {
  32071. cache.lastTickCount = tickCount;
  32072. cache.lastAutoInterval = interval;
  32073. cache.axisExtend0 = axisExtent[0];
  32074. cache.axisExtend1 = axisExtent[1];
  32075. }
  32076. return interval;
  32077. }
  32078. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32079. var labelModel = axis.getLabelModel();
  32080. return {
  32081. axisRotate: axis.getRotate
  32082. ? axis.getRotate()
  32083. : (axis.isHorizontal && !axis.isHorizontal())
  32084. ? 90
  32085. : 0,
  32086. labelRotate: labelModel.get('rotate') || 0,
  32087. font: labelModel.getFont()
  32088. };
  32089. }
  32090. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32091. var labelFormatter = makeLabelFormatter(axis);
  32092. var ordinalScale = axis.scale;
  32093. var ordinalExtent = ordinalScale.getExtent();
  32094. var labelModel = axis.getLabelModel();
  32095. var result = [];
  32096. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32097. var step = Math.max((categoryInterval || 0) + 1, 1);
  32098. var startTick = ordinalExtent[0];
  32099. var tickCount = ordinalScale.count();
  32100. // Calculate start tick based on zero if possible to keep label consistent
  32101. // while zooming and moving while interval > 0. Otherwise the selection
  32102. // of displayable ticks and symbols probably keep changing.
  32103. // 3 is empirical value.
  32104. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32105. startTick = Math.round(Math.ceil(startTick / step) * step);
  32106. }
  32107. // (1) Only add min max label here but leave overlap checking
  32108. // to render stage, which also ensure the returned list
  32109. // suitable for splitLine and splitArea rendering.
  32110. // (2) Scales except category always contain min max label so
  32111. // do not need to perform this process.
  32112. var showAllLabel = shouldShowAllLabels(axis);
  32113. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32114. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32115. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32116. addItem(ordinalExtent[0]);
  32117. }
  32118. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32119. var tickValue = startTick;
  32120. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32121. addItem(tickValue);
  32122. }
  32123. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32124. addItem(ordinalExtent[1]);
  32125. }
  32126. function addItem(tVal) {
  32127. result.push(onlyTick
  32128. ? tVal
  32129. : {
  32130. formattedLabel: labelFormatter(tVal),
  32131. rawLabel: ordinalScale.getLabel(tVal),
  32132. tickValue: tVal
  32133. }
  32134. );
  32135. }
  32136. return result;
  32137. }
  32138. // When interval is function, the result `false` means ignore the tick.
  32139. // It is time consuming for large category data.
  32140. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32141. var ordinalScale = axis.scale;
  32142. var labelFormatter = makeLabelFormatter(axis);
  32143. var result = [];
  32144. each$1(ordinalScale.getTicks(), function (tickValue) {
  32145. var rawLabel = ordinalScale.getLabel(tickValue);
  32146. if (categoryInterval(tickValue, rawLabel)) {
  32147. result.push(onlyTick
  32148. ? tickValue
  32149. : {
  32150. formattedLabel: labelFormatter(tickValue),
  32151. rawLabel: rawLabel,
  32152. tickValue: tickValue
  32153. }
  32154. );
  32155. }
  32156. });
  32157. return result;
  32158. }
  32159. /*
  32160. * Licensed to the Apache Software Foundation (ASF) under one
  32161. * or more contributor license agreements. See the NOTICE file
  32162. * distributed with this work for additional information
  32163. * regarding copyright ownership. The ASF licenses this file
  32164. * to you under the Apache License, Version 2.0 (the
  32165. * "License"); you may not use this file except in compliance
  32166. * with the License. You may obtain a copy of the License at
  32167. *
  32168. * http://www.apache.org/licenses/LICENSE-2.0
  32169. *
  32170. * Unless required by applicable law or agreed to in writing,
  32171. * software distributed under the License is distributed on an
  32172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32173. * KIND, either express or implied. See the License for the
  32174. * specific language governing permissions and limitations
  32175. * under the License.
  32176. */
  32177. var NORMALIZED_EXTENT = [0, 1];
  32178. /**
  32179. * Base class of Axis.
  32180. * @constructor
  32181. */
  32182. var Axis = function (dim, scale, extent) {
  32183. /**
  32184. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32185. * @type {string}
  32186. */
  32187. this.dim = dim;
  32188. /**
  32189. * Axis scale
  32190. * @type {module:echarts/coord/scale/*}
  32191. */
  32192. this.scale = scale;
  32193. /**
  32194. * @type {Array.<number>}
  32195. * @private
  32196. */
  32197. this._extent = extent || [0, 0];
  32198. /**
  32199. * @type {boolean}
  32200. */
  32201. this.inverse = false;
  32202. /**
  32203. * Usually true when axis has a ordinal scale
  32204. * @type {boolean}
  32205. */
  32206. this.onBand = false;
  32207. };
  32208. Axis.prototype = {
  32209. constructor: Axis,
  32210. /**
  32211. * If axis extent contain given coord
  32212. * @param {number} coord
  32213. * @return {boolean}
  32214. */
  32215. contain: function (coord) {
  32216. var extent = this._extent;
  32217. var min = Math.min(extent[0], extent[1]);
  32218. var max = Math.max(extent[0], extent[1]);
  32219. return coord >= min && coord <= max;
  32220. },
  32221. /**
  32222. * If axis extent contain given data
  32223. * @param {number} data
  32224. * @return {boolean}
  32225. */
  32226. containData: function (data) {
  32227. return this.scale.contain(data);
  32228. },
  32229. /**
  32230. * Get coord extent.
  32231. * @return {Array.<number>}
  32232. */
  32233. getExtent: function () {
  32234. return this._extent.slice();
  32235. },
  32236. /**
  32237. * Get precision used for formatting
  32238. * @param {Array.<number>} [dataExtent]
  32239. * @return {number}
  32240. */
  32241. getPixelPrecision: function (dataExtent) {
  32242. return getPixelPrecision(
  32243. dataExtent || this.scale.getExtent(),
  32244. this._extent
  32245. );
  32246. },
  32247. /**
  32248. * Set coord extent
  32249. * @param {number} start
  32250. * @param {number} end
  32251. */
  32252. setExtent: function (start, end) {
  32253. var extent = this._extent;
  32254. extent[0] = start;
  32255. extent[1] = end;
  32256. },
  32257. /**
  32258. * Convert data to coord. Data is the rank if it has an ordinal scale
  32259. * @param {number} data
  32260. * @param {boolean} clamp
  32261. * @return {number}
  32262. */
  32263. dataToCoord: function (data, clamp) {
  32264. var extent = this._extent;
  32265. var scale = this.scale;
  32266. data = scale.normalize(data);
  32267. if (this.onBand && scale.type === 'ordinal') {
  32268. extent = extent.slice();
  32269. fixExtentWithBands(extent, scale.count());
  32270. }
  32271. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32272. },
  32273. /**
  32274. * Convert coord to data. Data is the rank if it has an ordinal scale
  32275. * @param {number} coord
  32276. * @param {boolean} clamp
  32277. * @return {number}
  32278. */
  32279. coordToData: function (coord, clamp) {
  32280. var extent = this._extent;
  32281. var scale = this.scale;
  32282. if (this.onBand && scale.type === 'ordinal') {
  32283. extent = extent.slice();
  32284. fixExtentWithBands(extent, scale.count());
  32285. }
  32286. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32287. return this.scale.scale(t);
  32288. },
  32289. /**
  32290. * Convert pixel point to data in axis
  32291. * @param {Array.<number>} point
  32292. * @param {boolean} clamp
  32293. * @return {number} data
  32294. */
  32295. pointToData: function (point, clamp) {
  32296. // Should be implemented in derived class if necessary.
  32297. },
  32298. /**
  32299. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32300. * `axis.getTicksCoords` considers `onBand`, which is used by
  32301. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32302. * @param {Object} [opt]
  32303. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  32304. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32305. * tick must be at the axis end points. Otherwise, clip ticks
  32306. * that outside the axis extent.
  32307. * @return {Array.<Object>} [{
  32308. * coord: ...,
  32309. * tickValue: ...
  32310. * }, ...]
  32311. */
  32312. getTicksCoords: function (opt) {
  32313. opt = opt || {};
  32314. var tickModel = opt.tickModel || this.getTickModel();
  32315. var result = createAxisTicks(this, tickModel);
  32316. var ticks = result.ticks;
  32317. var ticksCoords = map(ticks, function (tickValue) {
  32318. return {
  32319. coord: this.dataToCoord(tickValue),
  32320. tickValue: tickValue
  32321. };
  32322. }, this);
  32323. var alignWithLabel = tickModel.get('alignWithLabel');
  32324. fixOnBandTicksCoords(
  32325. this, ticksCoords, alignWithLabel, opt.clamp
  32326. );
  32327. return ticksCoords;
  32328. },
  32329. /**
  32330. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  32331. */
  32332. getMinorTicksCoords: function () {
  32333. if (this.scale.type === 'ordinal') {
  32334. // Category axis doesn't support minor ticks
  32335. return [];
  32336. }
  32337. var minorTickModel = this.model.getModel('minorTick');
  32338. var splitNumber = minorTickModel.get('splitNumber');
  32339. // Protection.
  32340. if (!(splitNumber > 0 && splitNumber < 100)) {
  32341. splitNumber = 5;
  32342. }
  32343. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32344. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32345. return map(minorTicksGroup, function (minorTick) {
  32346. return {
  32347. coord: this.dataToCoord(minorTick),
  32348. tickValue: minorTick
  32349. };
  32350. }, this);
  32351. }, this);
  32352. return minorTicksCoords;
  32353. },
  32354. /**
  32355. * @return {Array.<Object>} [{
  32356. * formattedLabel: string,
  32357. * rawLabel: axis.scale.getLabel(tickValue)
  32358. * tickValue: number
  32359. * }, ...]
  32360. */
  32361. getViewLabels: function () {
  32362. return createAxisLabels(this).labels;
  32363. },
  32364. /**
  32365. * @return {module:echarts/coord/model/Model}
  32366. */
  32367. getLabelModel: function () {
  32368. return this.model.getModel('axisLabel');
  32369. },
  32370. /**
  32371. * Notice here we only get the default tick model. For splitLine
  32372. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32373. * manually when calling `getTicksCoords`.
  32374. * In GL, this method may be overrided to:
  32375. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32376. * @return {module:echarts/coord/model/Model}
  32377. */
  32378. getTickModel: function () {
  32379. return this.model.getModel('axisTick');
  32380. },
  32381. /**
  32382. * Get width of band
  32383. * @return {number}
  32384. */
  32385. getBandWidth: function () {
  32386. var axisExtent = this._extent;
  32387. var dataExtent = this.scale.getExtent();
  32388. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32389. // Fix #2728, avoid NaN when only one data.
  32390. len === 0 && (len = 1);
  32391. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32392. return Math.abs(size) / len;
  32393. },
  32394. /**
  32395. * @abstract
  32396. * @return {boolean} Is horizontal
  32397. */
  32398. isHorizontal: null,
  32399. /**
  32400. * @abstract
  32401. * @return {number} Get axis rotate, by degree.
  32402. */
  32403. getRotate: null,
  32404. /**
  32405. * Only be called in category axis.
  32406. * Can be overrided, consider other axes like in 3D.
  32407. * @return {number} Auto interval for cateogry axis tick and label
  32408. */
  32409. calculateCategoryInterval: function () {
  32410. return calculateCategoryInterval(this);
  32411. }
  32412. };
  32413. function fixExtentWithBands(extent, nTick) {
  32414. var size = extent[1] - extent[0];
  32415. var len = nTick;
  32416. var margin = size / len / 2;
  32417. extent[0] += margin;
  32418. extent[1] -= margin;
  32419. }
  32420. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32421. // |---1---|---2---|---3---|---4---|.
  32422. // So the displayed ticks and splitLine/splitArea should between
  32423. // each data item, otherwise cause misleading (e.g., split tow bars
  32424. // of a single data item when there are two bar series).
  32425. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32426. // splitLine/spliteArea should layout appropriately corresponding
  32427. // to displayed labels. (So we should not use `getBandWidth` in this
  32428. // case).
  32429. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32430. var ticksLen = ticksCoords.length;
  32431. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32432. return;
  32433. }
  32434. var axisExtent = axis.getExtent();
  32435. var last;
  32436. var diffSize;
  32437. if (ticksLen === 1) {
  32438. ticksCoords[0].coord = axisExtent[0];
  32439. last = ticksCoords[1] = {coord: axisExtent[0]};
  32440. }
  32441. else {
  32442. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32443. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32444. each$1(ticksCoords, function (ticksItem) {
  32445. ticksItem.coord -= shift / 2;
  32446. });
  32447. var dataExtent = axis.scale.getExtent();
  32448. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32449. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  32450. ticksCoords.push(last);
  32451. }
  32452. var inverse = axisExtent[0] > axisExtent[1];
  32453. // Handling clamp.
  32454. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32455. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32456. }
  32457. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32458. ticksCoords.unshift({coord: axisExtent[0]});
  32459. }
  32460. if (littleThan(axisExtent[1], last.coord)) {
  32461. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32462. }
  32463. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32464. ticksCoords.push({coord: axisExtent[1]});
  32465. }
  32466. function littleThan(a, b) {
  32467. // Avoid rounding error cause calculated tick coord different with extent.
  32468. // It may cause an extra unecessary tick added.
  32469. a = round$1(a);
  32470. b = round$1(b);
  32471. return inverse ? a > b : a < b;
  32472. }
  32473. }
  32474. /*
  32475. * Licensed to the Apache Software Foundation (ASF) under one
  32476. * or more contributor license agreements. See the NOTICE file
  32477. * distributed with this work for additional information
  32478. * regarding copyright ownership. The ASF licenses this file
  32479. * to you under the Apache License, Version 2.0 (the
  32480. * "License"); you may not use this file except in compliance
  32481. * with the License. You may obtain a copy of the License at
  32482. *
  32483. * http://www.apache.org/licenses/LICENSE-2.0
  32484. *
  32485. * Unless required by applicable law or agreed to in writing,
  32486. * software distributed under the License is distributed on an
  32487. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32488. * KIND, either express or implied. See the License for the
  32489. * specific language governing permissions and limitations
  32490. * under the License.
  32491. */
  32492. /**
  32493. * Do not mount those modules on 'src/echarts' for better tree shaking.
  32494. */
  32495. var parseGeoJson = parseGeoJSON;
  32496. var ecUtil = {};
  32497. each$1(
  32498. [
  32499. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  32500. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  32501. 'extend', 'defaults', 'clone', 'merge'
  32502. ],
  32503. function (name) {
  32504. ecUtil[name] = zrUtil[name];
  32505. }
  32506. );
  32507. var graphic$1 = {};
  32508. each$1(
  32509. [
  32510. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  32511. 'mergePath', 'resizePath', 'createIcon',
  32512. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  32513. 'getFont', 'updateProps', 'initProps', 'getTransform',
  32514. 'clipPointsByRect', 'clipRectByRect',
  32515. 'registerShape', 'getShapeClass',
  32516. 'Group',
  32517. 'Image',
  32518. 'Text',
  32519. 'Circle',
  32520. 'Sector',
  32521. 'Ring',
  32522. 'Polygon',
  32523. 'Polyline',
  32524. 'Rect',
  32525. 'Line',
  32526. 'BezierCurve',
  32527. 'Arc',
  32528. 'IncrementalDisplayable',
  32529. 'CompoundPath',
  32530. 'LinearGradient',
  32531. 'RadialGradient',
  32532. 'BoundingRect'
  32533. ],
  32534. function (name) {
  32535. graphic$1[name] = graphic[name];
  32536. }
  32537. );
  32538. /*
  32539. * Licensed to the Apache Software Foundation (ASF) under one
  32540. * or more contributor license agreements. See the NOTICE file
  32541. * distributed with this work for additional information
  32542. * regarding copyright ownership. The ASF licenses this file
  32543. * to you under the Apache License, Version 2.0 (the
  32544. * "License"); you may not use this file except in compliance
  32545. * with the License. You may obtain a copy of the License at
  32546. *
  32547. * http://www.apache.org/licenses/LICENSE-2.0
  32548. *
  32549. * Unless required by applicable law or agreed to in writing,
  32550. * software distributed under the License is distributed on an
  32551. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32552. * KIND, either express or implied. See the License for the
  32553. * specific language governing permissions and limitations
  32554. * under the License.
  32555. */
  32556. SeriesModel.extend({
  32557. type: 'series.line',
  32558. dependencies: ['grid', 'polar'],
  32559. getInitialData: function (option, ecModel) {
  32560. if (__DEV__) {
  32561. var coordSys = option.coordinateSystem;
  32562. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  32563. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  32564. }
  32565. }
  32566. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  32567. },
  32568. defaultOption: {
  32569. zlevel: 0,
  32570. z: 2,
  32571. coordinateSystem: 'cartesian2d',
  32572. legendHoverLink: true,
  32573. hoverAnimation: true,
  32574. // stack: null
  32575. // xAxisIndex: 0,
  32576. // yAxisIndex: 0,
  32577. // polarIndex: 0,
  32578. // If clip the overflow value
  32579. clip: true,
  32580. // cursor: null,
  32581. label: {
  32582. position: 'top'
  32583. },
  32584. // itemStyle: {
  32585. // },
  32586. lineStyle: {
  32587. width: 2,
  32588. type: 'solid'
  32589. },
  32590. // areaStyle: {
  32591. // origin of areaStyle. Valid values:
  32592. // `'auto'/null/undefined`: from axisLine to data
  32593. // `'start'`: from min to data
  32594. // `'end'`: from data to max
  32595. // origin: 'auto'
  32596. // },
  32597. // false, 'start', 'end', 'middle'
  32598. step: false,
  32599. // Disabled if step is true
  32600. smooth: false,
  32601. smoothMonotone: null,
  32602. symbol: 'emptyCircle',
  32603. symbolSize: 4,
  32604. symbolRotate: null,
  32605. showSymbol: true,
  32606. // `false`: follow the label interval strategy.
  32607. // `true`: show all symbols.
  32608. // `'auto'`: If possible, show all symbols, otherwise
  32609. // follow the label interval strategy.
  32610. showAllSymbol: 'auto',
  32611. // Whether to connect break point.
  32612. connectNulls: false,
  32613. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  32614. sampling: 'none',
  32615. animationEasing: 'linear',
  32616. // Disable progressive
  32617. progressive: 0,
  32618. hoverLayerThreshold: Infinity
  32619. }
  32620. });
  32621. /*
  32622. * Licensed to the Apache Software Foundation (ASF) under one
  32623. * or more contributor license agreements. See the NOTICE file
  32624. * distributed with this work for additional information
  32625. * regarding copyright ownership. The ASF licenses this file
  32626. * to you under the Apache License, Version 2.0 (the
  32627. * "License"); you may not use this file except in compliance
  32628. * with the License. You may obtain a copy of the License at
  32629. *
  32630. * http://www.apache.org/licenses/LICENSE-2.0
  32631. *
  32632. * Unless required by applicable law or agreed to in writing,
  32633. * software distributed under the License is distributed on an
  32634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32635. * KIND, either express or implied. See the License for the
  32636. * specific language governing permissions and limitations
  32637. * under the License.
  32638. */
  32639. /**
  32640. * @param {module:echarts/data/List} data
  32641. * @param {number} dataIndex
  32642. * @return {string} label string. Not null/undefined
  32643. */
  32644. function getDefaultLabel(data, dataIndex) {
  32645. var labelDims = data.mapDimension('defaultedLabel', true);
  32646. var len = labelDims.length;
  32647. // Simple optimization (in lots of cases, label dims length is 1)
  32648. if (len === 1) {
  32649. return retrieveRawValue(data, dataIndex, labelDims[0]);
  32650. }
  32651. else if (len) {
  32652. var vals = [];
  32653. for (var i = 0; i < labelDims.length; i++) {
  32654. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  32655. vals.push(val);
  32656. }
  32657. return vals.join(' ');
  32658. }
  32659. }
  32660. /*
  32661. * Licensed to the Apache Software Foundation (ASF) under one
  32662. * or more contributor license agreements. See the NOTICE file
  32663. * distributed with this work for additional information
  32664. * regarding copyright ownership. The ASF licenses this file
  32665. * to you under the Apache License, Version 2.0 (the
  32666. * "License"); you may not use this file except in compliance
  32667. * with the License. You may obtain a copy of the License at
  32668. *
  32669. * http://www.apache.org/licenses/LICENSE-2.0
  32670. *
  32671. * Unless required by applicable law or agreed to in writing,
  32672. * software distributed under the License is distributed on an
  32673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32674. * KIND, either express or implied. See the License for the
  32675. * specific language governing permissions and limitations
  32676. * under the License.
  32677. */
  32678. /**
  32679. * @module echarts/chart/helper/Symbol
  32680. */
  32681. /**
  32682. * @constructor
  32683. * @alias {module:echarts/chart/helper/Symbol}
  32684. * @param {module:echarts/data/List} data
  32685. * @param {number} idx
  32686. * @extends {module:zrender/graphic/Group}
  32687. */
  32688. function SymbolClz$1(data, idx, seriesScope) {
  32689. Group.call(this);
  32690. this.updateData(data, idx, seriesScope);
  32691. }
  32692. var symbolProto = SymbolClz$1.prototype;
  32693. /**
  32694. * @public
  32695. * @static
  32696. * @param {module:echarts/data/List} data
  32697. * @param {number} dataIndex
  32698. * @return {Array.<number>} [width, height]
  32699. */
  32700. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  32701. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  32702. return symbolSize instanceof Array
  32703. ? symbolSize.slice()
  32704. : [+symbolSize, +symbolSize];
  32705. };
  32706. function getScale(symbolSize) {
  32707. return [symbolSize[0] / 2, symbolSize[1] / 2];
  32708. }
  32709. function driftSymbol(dx, dy) {
  32710. this.parent.drift(dx, dy);
  32711. }
  32712. symbolProto._createSymbol = function (
  32713. symbolType,
  32714. data,
  32715. idx,
  32716. symbolSize,
  32717. keepAspect
  32718. ) {
  32719. // Remove paths created before
  32720. this.removeAll();
  32721. var color = data.getItemVisual(idx, 'color');
  32722. // var symbolPath = createSymbol(
  32723. // symbolType, -0.5, -0.5, 1, 1, color
  32724. // );
  32725. // If width/height are set too small (e.g., set to 1) on ios10
  32726. // and macOS Sierra, a circle stroke become a rect, no matter what
  32727. // the scale is set. So we set width/height as 2. See #4150.
  32728. var symbolPath = createSymbol(
  32729. symbolType, -1, -1, 2, 2, color, keepAspect
  32730. );
  32731. symbolPath.attr({
  32732. z2: 100,
  32733. culling: true,
  32734. scale: getScale(symbolSize)
  32735. });
  32736. // Rewrite drift method
  32737. symbolPath.drift = driftSymbol;
  32738. this._symbolType = symbolType;
  32739. this.add(symbolPath);
  32740. };
  32741. /**
  32742. * Stop animation
  32743. * @param {boolean} toLastFrame
  32744. */
  32745. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  32746. this.childAt(0).stopAnimation(toLastFrame);
  32747. };
  32748. /**
  32749. * FIXME:
  32750. * Caution: This method breaks the encapsulation of this module,
  32751. * but it indeed brings convenience. So do not use the method
  32752. * unless you detailedly know all the implements of `Symbol`,
  32753. * especially animation.
  32754. *
  32755. * Get symbol path element.
  32756. */
  32757. symbolProto.getSymbolPath = function () {
  32758. return this.childAt(0);
  32759. };
  32760. /**
  32761. * Get scale(aka, current symbol size).
  32762. * Including the change caused by animation
  32763. */
  32764. symbolProto.getScale = function () {
  32765. return this.childAt(0).scale;
  32766. };
  32767. /**
  32768. * Highlight symbol
  32769. */
  32770. symbolProto.highlight = function () {
  32771. this.childAt(0).trigger('emphasis');
  32772. };
  32773. /**
  32774. * Downplay symbol
  32775. */
  32776. symbolProto.downplay = function () {
  32777. this.childAt(0).trigger('normal');
  32778. };
  32779. /**
  32780. * @param {number} zlevel
  32781. * @param {number} z
  32782. */
  32783. symbolProto.setZ = function (zlevel, z) {
  32784. var symbolPath = this.childAt(0);
  32785. symbolPath.zlevel = zlevel;
  32786. symbolPath.z = z;
  32787. };
  32788. symbolProto.setDraggable = function (draggable) {
  32789. var symbolPath = this.childAt(0);
  32790. symbolPath.draggable = draggable;
  32791. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  32792. };
  32793. /**
  32794. * Update symbol properties
  32795. * @param {module:echarts/data/List} data
  32796. * @param {number} idx
  32797. * @param {Object} [seriesScope]
  32798. * @param {Object} [seriesScope.itemStyle]
  32799. * @param {Object} [seriesScope.hoverItemStyle]
  32800. * @param {Object} [seriesScope.symbolRotate]
  32801. * @param {Object} [seriesScope.symbolOffset]
  32802. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  32803. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  32804. * @param {boolean} [seriesScope.hoverAnimation]
  32805. * @param {Object} [seriesScope.cursorStyle]
  32806. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  32807. * @param {string} [seriesScope.symbolInnerColor]
  32808. * @param {Object} [seriesScope.fadeIn=false]
  32809. */
  32810. symbolProto.updateData = function (data, idx, seriesScope) {
  32811. this.silent = false;
  32812. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  32813. var seriesModel = data.hostModel;
  32814. var symbolSize = getSymbolSize(data, idx);
  32815. var isInit = symbolType !== this._symbolType;
  32816. if (isInit) {
  32817. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  32818. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  32819. }
  32820. else {
  32821. var symbolPath = this.childAt(0);
  32822. symbolPath.silent = false;
  32823. updateProps(symbolPath, {
  32824. scale: getScale(symbolSize)
  32825. }, seriesModel, idx);
  32826. }
  32827. this._updateCommon(data, idx, symbolSize, seriesScope);
  32828. if (isInit) {
  32829. var symbolPath = this.childAt(0);
  32830. var fadeIn = seriesScope && seriesScope.fadeIn;
  32831. var target = {scale: symbolPath.scale.slice()};
  32832. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  32833. symbolPath.scale = [0, 0];
  32834. fadeIn && (symbolPath.style.opacity = 0);
  32835. initProps(symbolPath, target, seriesModel, idx);
  32836. }
  32837. this._seriesModel = seriesModel;
  32838. };
  32839. // Update common properties
  32840. var normalStyleAccessPath = ['itemStyle'];
  32841. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  32842. var normalLabelAccessPath = ['label'];
  32843. var emphasisLabelAccessPath = ['emphasis', 'label'];
  32844. /**
  32845. * @param {module:echarts/data/List} data
  32846. * @param {number} idx
  32847. * @param {Array.<number>} symbolSize
  32848. * @param {Object} [seriesScope]
  32849. */
  32850. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  32851. var symbolPath = this.childAt(0);
  32852. var seriesModel = data.hostModel;
  32853. var color = data.getItemVisual(idx, 'color');
  32854. // Reset style
  32855. if (symbolPath.type !== 'image') {
  32856. symbolPath.useStyle({
  32857. strokeNoScale: true
  32858. });
  32859. }
  32860. else {
  32861. symbolPath.setStyle({
  32862. opacity: null,
  32863. shadowBlur: null,
  32864. shadowOffsetX: null,
  32865. shadowOffsetY: null,
  32866. shadowColor: null
  32867. });
  32868. }
  32869. var itemStyle = seriesScope && seriesScope.itemStyle;
  32870. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  32871. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  32872. var labelModel = seriesScope && seriesScope.labelModel;
  32873. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  32874. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  32875. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  32876. if (!seriesScope || data.hasItemOption) {
  32877. var itemModel = (seriesScope && seriesScope.itemModel)
  32878. ? seriesScope.itemModel : data.getItemModel(idx);
  32879. // Color must be excluded.
  32880. // Because symbol provide setColor individually to set fill and stroke
  32881. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  32882. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  32883. symbolOffset = itemModel.getShallow('symbolOffset');
  32884. labelModel = itemModel.getModel(normalLabelAccessPath);
  32885. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  32886. hoverAnimation = itemModel.getShallow('hoverAnimation');
  32887. cursorStyle = itemModel.getShallow('cursor');
  32888. }
  32889. else {
  32890. hoverItemStyle = extend({}, hoverItemStyle);
  32891. }
  32892. var elStyle = symbolPath.style;
  32893. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  32894. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  32895. if (symbolOffset) {
  32896. symbolPath.attr('position', [
  32897. parsePercent$1(symbolOffset[0], symbolSize[0]),
  32898. parsePercent$1(symbolOffset[1], symbolSize[1])
  32899. ]);
  32900. }
  32901. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  32902. // PENDING setColor before setStyle!!!
  32903. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  32904. symbolPath.setStyle(itemStyle);
  32905. var opacity = data.getItemVisual(idx, 'opacity');
  32906. if (opacity != null) {
  32907. elStyle.opacity = opacity;
  32908. }
  32909. var liftZ = data.getItemVisual(idx, 'liftZ');
  32910. var z2Origin = symbolPath.__z2Origin;
  32911. if (liftZ != null) {
  32912. if (z2Origin == null) {
  32913. symbolPath.__z2Origin = symbolPath.z2;
  32914. symbolPath.z2 += liftZ;
  32915. }
  32916. }
  32917. else if (z2Origin != null) {
  32918. symbolPath.z2 = z2Origin;
  32919. symbolPath.__z2Origin = null;
  32920. }
  32921. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  32922. setLabelStyle(
  32923. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  32924. {
  32925. labelFetcher: seriesModel,
  32926. labelDataIndex: idx,
  32927. defaultText: getLabelDefaultText,
  32928. isRectText: true,
  32929. autoColor: color
  32930. }
  32931. );
  32932. // Do not execute util needed.
  32933. function getLabelDefaultText(idx, opt) {
  32934. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  32935. }
  32936. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  32937. symbolPath.hoverStyle = hoverItemStyle;
  32938. symbolPath.highDownOnUpdate = (
  32939. hoverAnimation && seriesModel.isAnimationEnabled()
  32940. ) ? highDownOnUpdate : null;
  32941. setHoverStyle(symbolPath);
  32942. };
  32943. function highDownOnUpdate(fromState, toState) {
  32944. // Do not support this hover animation util some scenario required.
  32945. // Animation can only be supported in hover layer when using `el.incremetal`.
  32946. if (this.incremental || this.useHoverLayer) {
  32947. return;
  32948. }
  32949. if (toState === 'emphasis') {
  32950. var scale = this.__symbolOriginalScale;
  32951. var ratio = scale[1] / scale[0];
  32952. var emphasisOpt = {
  32953. scale: [
  32954. Math.max(scale[0] * 1.1, scale[0] + 3),
  32955. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  32956. ]
  32957. };
  32958. // FIXME
  32959. // modify it after support stop specified animation.
  32960. // toState === fromState
  32961. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  32962. this.animateTo(emphasisOpt, 400, 'elasticOut');
  32963. }
  32964. else if (toState === 'normal') {
  32965. this.animateTo({
  32966. scale: this.__symbolOriginalScale
  32967. }, 400, 'elasticOut');
  32968. }
  32969. }
  32970. /**
  32971. * @param {Function} cb
  32972. * @param {Object} [opt]
  32973. * @param {Object} [opt.keepLabel=true]
  32974. */
  32975. symbolProto.fadeOut = function (cb, opt) {
  32976. var symbolPath = this.childAt(0);
  32977. // Avoid mistaken hover when fading out
  32978. this.silent = symbolPath.silent = true;
  32979. // Not show text when animating
  32980. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  32981. updateProps(
  32982. symbolPath,
  32983. {
  32984. style: {opacity: 0},
  32985. scale: [0, 0]
  32986. },
  32987. this._seriesModel,
  32988. this.dataIndex,
  32989. cb
  32990. );
  32991. };
  32992. inherits(SymbolClz$1, Group);
  32993. /*
  32994. * Licensed to the Apache Software Foundation (ASF) under one
  32995. * or more contributor license agreements. See the NOTICE file
  32996. * distributed with this work for additional information
  32997. * regarding copyright ownership. The ASF licenses this file
  32998. * to you under the Apache License, Version 2.0 (the
  32999. * "License"); you may not use this file except in compliance
  33000. * with the License. You may obtain a copy of the License at
  33001. *
  33002. * http://www.apache.org/licenses/LICENSE-2.0
  33003. *
  33004. * Unless required by applicable law or agreed to in writing,
  33005. * software distributed under the License is distributed on an
  33006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33007. * KIND, either express or implied. See the License for the
  33008. * specific language governing permissions and limitations
  33009. * under the License.
  33010. */
  33011. /**
  33012. * @module echarts/chart/helper/SymbolDraw
  33013. */
  33014. /**
  33015. * @constructor
  33016. * @alias module:echarts/chart/helper/SymbolDraw
  33017. * @param {module:zrender/graphic/Group} [symbolCtor]
  33018. */
  33019. function SymbolDraw(symbolCtor) {
  33020. this.group = new Group();
  33021. this._symbolCtor = symbolCtor || SymbolClz$1;
  33022. }
  33023. var symbolDrawProto = SymbolDraw.prototype;
  33024. function symbolNeedsDraw(data, point, idx, opt) {
  33025. return point && !isNaN(point[0]) && !isNaN(point[1])
  33026. && !(opt.isIgnore && opt.isIgnore(idx))
  33027. // We do not set clipShape on group, because it will cut part of
  33028. // the symbol element shape. We use the same clip shape here as
  33029. // the line clip.
  33030. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  33031. && data.getItemVisual(idx, 'symbol') !== 'none';
  33032. }
  33033. /**
  33034. * Update symbols draw by new data
  33035. * @param {module:echarts/data/List} data
  33036. * @param {Object} [opt] Or isIgnore
  33037. * @param {Function} [opt.isIgnore]
  33038. * @param {Object} [opt.clipShape]
  33039. */
  33040. symbolDrawProto.updateData = function (data, opt) {
  33041. opt = normalizeUpdateOpt(opt);
  33042. var group = this.group;
  33043. var seriesModel = data.hostModel;
  33044. var oldData = this._data;
  33045. var SymbolCtor = this._symbolCtor;
  33046. var seriesScope = makeSeriesScope(data);
  33047. // There is no oldLineData only when first rendering or switching from
  33048. // stream mode to normal mode, where previous elements should be removed.
  33049. if (!oldData) {
  33050. group.removeAll();
  33051. }
  33052. data.diff(oldData)
  33053. .add(function (newIdx) {
  33054. var point = data.getItemLayout(newIdx);
  33055. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33056. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  33057. symbolEl.attr('position', point);
  33058. data.setItemGraphicEl(newIdx, symbolEl);
  33059. group.add(symbolEl);
  33060. }
  33061. })
  33062. .update(function (newIdx, oldIdx) {
  33063. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33064. var point = data.getItemLayout(newIdx);
  33065. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33066. group.remove(symbolEl);
  33067. return;
  33068. }
  33069. if (!symbolEl) {
  33070. symbolEl = new SymbolCtor(data, newIdx);
  33071. symbolEl.attr('position', point);
  33072. }
  33073. else {
  33074. symbolEl.updateData(data, newIdx, seriesScope);
  33075. updateProps(symbolEl, {
  33076. position: point
  33077. }, seriesModel);
  33078. }
  33079. // Add back
  33080. group.add(symbolEl);
  33081. data.setItemGraphicEl(newIdx, symbolEl);
  33082. })
  33083. .remove(function (oldIdx) {
  33084. var el = oldData.getItemGraphicEl(oldIdx);
  33085. el && el.fadeOut(function () {
  33086. group.remove(el);
  33087. });
  33088. })
  33089. .execute();
  33090. this._data = data;
  33091. };
  33092. symbolDrawProto.isPersistent = function () {
  33093. return true;
  33094. };
  33095. symbolDrawProto.updateLayout = function () {
  33096. var data = this._data;
  33097. if (data) {
  33098. // Not use animation
  33099. data.eachItemGraphicEl(function (el, idx) {
  33100. var point = data.getItemLayout(idx);
  33101. el.attr('position', point);
  33102. });
  33103. }
  33104. };
  33105. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33106. this._seriesScope = makeSeriesScope(data);
  33107. this._data = null;
  33108. this.group.removeAll();
  33109. };
  33110. /**
  33111. * Update symbols draw by new data
  33112. * @param {module:echarts/data/List} data
  33113. * @param {Object} [opt] Or isIgnore
  33114. * @param {Function} [opt.isIgnore]
  33115. * @param {Object} [opt.clipShape]
  33116. */
  33117. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33118. opt = normalizeUpdateOpt(opt);
  33119. function updateIncrementalAndHover(el) {
  33120. if (!el.isGroup) {
  33121. el.incremental = el.useHoverLayer = true;
  33122. }
  33123. }
  33124. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33125. var point = data.getItemLayout(idx);
  33126. if (symbolNeedsDraw(data, point, idx, opt)) {
  33127. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33128. el.traverse(updateIncrementalAndHover);
  33129. el.attr('position', point);
  33130. this.group.add(el);
  33131. data.setItemGraphicEl(idx, el);
  33132. }
  33133. }
  33134. };
  33135. function normalizeUpdateOpt(opt) {
  33136. if (opt != null && !isObject$1(opt)) {
  33137. opt = {isIgnore: opt};
  33138. }
  33139. return opt || {};
  33140. }
  33141. symbolDrawProto.remove = function (enableAnimation) {
  33142. var group = this.group;
  33143. var data = this._data;
  33144. // Incremental model do not have this._data.
  33145. if (data && enableAnimation) {
  33146. data.eachItemGraphicEl(function (el) {
  33147. el.fadeOut(function () {
  33148. group.remove(el);
  33149. });
  33150. });
  33151. }
  33152. else {
  33153. group.removeAll();
  33154. }
  33155. };
  33156. function makeSeriesScope(data) {
  33157. var seriesModel = data.hostModel;
  33158. return {
  33159. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33160. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33161. symbolRotate: seriesModel.get('symbolRotate'),
  33162. symbolOffset: seriesModel.get('symbolOffset'),
  33163. hoverAnimation: seriesModel.get('hoverAnimation'),
  33164. labelModel: seriesModel.getModel('label'),
  33165. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33166. cursorStyle: seriesModel.get('cursor')
  33167. };
  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. /**
  33188. * @param {Object} coordSys
  33189. * @param {module:echarts/data/List} data
  33190. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33191. */
  33192. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33193. var baseAxis = coordSys.getBaseAxis();
  33194. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33195. var valueStart = getValueStart(valueAxis, valueOrigin);
  33196. var baseAxisDim = baseAxis.dim;
  33197. var valueAxisDim = valueAxis.dim;
  33198. var valueDim = data.mapDimension(valueAxisDim);
  33199. var baseDim = data.mapDimension(baseAxisDim);
  33200. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33201. var dims = map(coordSys.dimensions, function (coordDim) {
  33202. return data.mapDimension(coordDim);
  33203. });
  33204. var stacked;
  33205. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33206. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  33207. dims[0] = stackResultDim;
  33208. }
  33209. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  33210. dims[1] = stackResultDim;
  33211. }
  33212. return {
  33213. dataDimsForPoint: dims,
  33214. valueStart: valueStart,
  33215. valueAxisDim: valueAxisDim,
  33216. baseAxisDim: baseAxisDim,
  33217. stacked: !!stacked,
  33218. valueDim: valueDim,
  33219. baseDim: baseDim,
  33220. baseDataOffset: baseDataOffset,
  33221. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33222. };
  33223. }
  33224. function getValueStart(valueAxis, valueOrigin) {
  33225. var valueStart = 0;
  33226. var extent = valueAxis.scale.getExtent();
  33227. if (valueOrigin === 'start') {
  33228. valueStart = extent[0];
  33229. }
  33230. else if (valueOrigin === 'end') {
  33231. valueStart = extent[1];
  33232. }
  33233. // auto
  33234. else {
  33235. // Both positive
  33236. if (extent[0] > 0) {
  33237. valueStart = extent[0];
  33238. }
  33239. // Both negative
  33240. else if (extent[1] < 0) {
  33241. valueStart = extent[1];
  33242. }
  33243. // If is one positive, and one negative, onZero shall be true
  33244. }
  33245. return valueStart;
  33246. }
  33247. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33248. var value = NaN;
  33249. if (dataCoordInfo.stacked) {
  33250. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33251. }
  33252. if (isNaN(value)) {
  33253. value = dataCoordInfo.valueStart;
  33254. }
  33255. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33256. var stackedData = [];
  33257. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33258. stackedData[1 - baseDataOffset] = value;
  33259. return coordSys.dataToPoint(stackedData);
  33260. }
  33261. /*
  33262. * Licensed to the Apache Software Foundation (ASF) under one
  33263. * or more contributor license agreements. See the NOTICE file
  33264. * distributed with this work for additional information
  33265. * regarding copyright ownership. The ASF licenses this file
  33266. * to you under the Apache License, Version 2.0 (the
  33267. * "License"); you may not use this file except in compliance
  33268. * with the License. You may obtain a copy of the License at
  33269. *
  33270. * http://www.apache.org/licenses/LICENSE-2.0
  33271. *
  33272. * Unless required by applicable law or agreed to in writing,
  33273. * software distributed under the License is distributed on an
  33274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33275. * KIND, either express or implied. See the License for the
  33276. * specific language governing permissions and limitations
  33277. * under the License.
  33278. */
  33279. // var arrayDiff = require('zrender/src/core/arrayDiff');
  33280. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33281. // not do well in performance when roam with fixed dataZoom window.
  33282. // function convertToIntId(newIdList, oldIdList) {
  33283. // // Generate int id instead of string id.
  33284. // // Compare string maybe slow in score function of arrDiff
  33285. // // Assume id in idList are all unique
  33286. // var idIndicesMap = {};
  33287. // var idx = 0;
  33288. // for (var i = 0; i < newIdList.length; i++) {
  33289. // idIndicesMap[newIdList[i]] = idx;
  33290. // newIdList[i] = idx++;
  33291. // }
  33292. // for (var i = 0; i < oldIdList.length; i++) {
  33293. // var oldId = oldIdList[i];
  33294. // // Same with newIdList
  33295. // if (idIndicesMap[oldId]) {
  33296. // oldIdList[i] = idIndicesMap[oldId];
  33297. // }
  33298. // else {
  33299. // oldIdList[i] = idx++;
  33300. // }
  33301. // }
  33302. // }
  33303. function diffData(oldData, newData) {
  33304. var diffResult = [];
  33305. newData.diff(oldData)
  33306. .add(function (idx) {
  33307. diffResult.push({cmd: '+', idx: idx});
  33308. })
  33309. .update(function (newIdx, oldIdx) {
  33310. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  33311. })
  33312. .remove(function (idx) {
  33313. diffResult.push({cmd: '-', idx: idx});
  33314. })
  33315. .execute();
  33316. return diffResult;
  33317. }
  33318. var lineAnimationDiff = function (
  33319. oldData, newData,
  33320. oldStackedOnPoints, newStackedOnPoints,
  33321. oldCoordSys, newCoordSys,
  33322. oldValueOrigin, newValueOrigin
  33323. ) {
  33324. var diff = diffData(oldData, newData);
  33325. // var newIdList = newData.mapArray(newData.getId);
  33326. // var oldIdList = oldData.mapArray(oldData.getId);
  33327. // convertToIntId(newIdList, oldIdList);
  33328. // // FIXME One data ?
  33329. // diff = arrayDiff(oldIdList, newIdList);
  33330. var currPoints = [];
  33331. var nextPoints = [];
  33332. // Points for stacking base line
  33333. var currStackedPoints = [];
  33334. var nextStackedPoints = [];
  33335. var status = [];
  33336. var sortedIndices = [];
  33337. var rawIndices = [];
  33338. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33339. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33340. for (var i = 0; i < diff.length; i++) {
  33341. var diffItem = diff[i];
  33342. var pointAdded = true;
  33343. // FIXME, animation is not so perfect when dataZoom window moves fast
  33344. // Which is in case remvoing or add more than one data in the tail or head
  33345. switch (diffItem.cmd) {
  33346. case '=':
  33347. var currentPt = oldData.getItemLayout(diffItem.idx);
  33348. var nextPt = newData.getItemLayout(diffItem.idx1);
  33349. // If previous data is NaN, use next point directly
  33350. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33351. currentPt = nextPt.slice();
  33352. }
  33353. currPoints.push(currentPt);
  33354. nextPoints.push(nextPt);
  33355. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33356. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33357. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33358. break;
  33359. case '+':
  33360. var idx = diffItem.idx;
  33361. currPoints.push(
  33362. oldCoordSys.dataToPoint([
  33363. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  33364. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  33365. ])
  33366. );
  33367. nextPoints.push(newData.getItemLayout(idx).slice());
  33368. currStackedPoints.push(
  33369. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  33370. );
  33371. nextStackedPoints.push(newStackedOnPoints[idx]);
  33372. rawIndices.push(newData.getRawIndex(idx));
  33373. break;
  33374. case '-':
  33375. var idx = diffItem.idx;
  33376. var rawIndex = oldData.getRawIndex(idx);
  33377. // Data is replaced. In the case of dynamic data queue
  33378. // FIXME FIXME FIXME
  33379. if (rawIndex !== idx) {
  33380. currPoints.push(oldData.getItemLayout(idx));
  33381. nextPoints.push(newCoordSys.dataToPoint([
  33382. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  33383. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  33384. ]));
  33385. currStackedPoints.push(oldStackedOnPoints[idx]);
  33386. nextStackedPoints.push(
  33387. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  33388. );
  33389. rawIndices.push(rawIndex);
  33390. }
  33391. else {
  33392. pointAdded = false;
  33393. }
  33394. }
  33395. // Original indices
  33396. if (pointAdded) {
  33397. status.push(diffItem);
  33398. sortedIndices.push(sortedIndices.length);
  33399. }
  33400. }
  33401. // Diff result may be crossed if all items are changed
  33402. // Sort by data index
  33403. sortedIndices.sort(function (a, b) {
  33404. return rawIndices[a] - rawIndices[b];
  33405. });
  33406. var sortedCurrPoints = [];
  33407. var sortedNextPoints = [];
  33408. var sortedCurrStackedPoints = [];
  33409. var sortedNextStackedPoints = [];
  33410. var sortedStatus = [];
  33411. for (var i = 0; i < sortedIndices.length; i++) {
  33412. var idx = sortedIndices[i];
  33413. sortedCurrPoints[i] = currPoints[idx];
  33414. sortedNextPoints[i] = nextPoints[idx];
  33415. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  33416. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  33417. sortedStatus[i] = status[idx];
  33418. }
  33419. return {
  33420. current: sortedCurrPoints,
  33421. next: sortedNextPoints,
  33422. stackedOnCurrent: sortedCurrStackedPoints,
  33423. stackedOnNext: sortedNextStackedPoints,
  33424. status: sortedStatus
  33425. };
  33426. };
  33427. /*
  33428. * Licensed to the Apache Software Foundation (ASF) under one
  33429. * or more contributor license agreements. See the NOTICE file
  33430. * distributed with this work for additional information
  33431. * regarding copyright ownership. The ASF licenses this file
  33432. * to you under the Apache License, Version 2.0 (the
  33433. * "License"); you may not use this file except in compliance
  33434. * with the License. You may obtain a copy of the License at
  33435. *
  33436. * http://www.apache.org/licenses/LICENSE-2.0
  33437. *
  33438. * Unless required by applicable law or agreed to in writing,
  33439. * software distributed under the License is distributed on an
  33440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33441. * KIND, either express or implied. See the License for the
  33442. * specific language governing permissions and limitations
  33443. * under the License.
  33444. */
  33445. // Poly path support NaN point
  33446. var vec2Min = min;
  33447. var vec2Max = max;
  33448. var scaleAndAdd$1 = scaleAndAdd;
  33449. var v2Copy = copy;
  33450. // Temporary variable
  33451. var v = [];
  33452. var cp0 = [];
  33453. var cp1 = [];
  33454. function isPointNull(p) {
  33455. return isNaN(p[0]) || isNaN(p[1]);
  33456. }
  33457. function drawSegment(
  33458. ctx, points, start, segLen, allLen,
  33459. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33460. ) {
  33461. // if (smoothMonotone == null) {
  33462. // if (isMono(points, 'x')) {
  33463. // return drawMono(ctx, points, start, segLen, allLen,
  33464. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  33465. // }
  33466. // else if (isMono(points, 'y')) {
  33467. // return drawMono(ctx, points, start, segLen, allLen,
  33468. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  33469. // }
  33470. // else {
  33471. // return drawNonMono.apply(this, arguments);
  33472. // }
  33473. // }
  33474. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  33475. // return drawMono.apply(this, arguments);
  33476. // }
  33477. // else {
  33478. // return drawNonMono.apply(this, arguments);
  33479. // }
  33480. if (smoothMonotone === 'none' || !smoothMonotone) {
  33481. return drawNonMono.apply(this, arguments);
  33482. }
  33483. else {
  33484. return drawMono.apply(this, arguments);
  33485. }
  33486. }
  33487. /**
  33488. * Check if points is in monotone.
  33489. *
  33490. * @param {number[][]} points Array of points which is in [x, y] form
  33491. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  33492. * dimension that is checking.
  33493. * If is 'none', `drawNonMono` should be
  33494. * called.
  33495. * If is undefined, either being monotone
  33496. * in 'x' or 'y' will call `drawMono`.
  33497. */
  33498. // function isMono(points, smoothMonotone) {
  33499. // if (points.length <= 1) {
  33500. // return true;
  33501. // }
  33502. // var dim = smoothMonotone === 'x' ? 0 : 1;
  33503. // var last = points[0][dim];
  33504. // var lastDiff = 0;
  33505. // for (var i = 1; i < points.length; ++i) {
  33506. // var diff = points[i][dim] - last;
  33507. // if (!isNaN(diff) && !isNaN(lastDiff)
  33508. // && diff !== 0 && lastDiff !== 0
  33509. // && ((diff >= 0) !== (lastDiff >= 0))
  33510. // ) {
  33511. // return false;
  33512. // }
  33513. // if (!isNaN(diff) && diff !== 0) {
  33514. // lastDiff = diff;
  33515. // last = points[i][dim];
  33516. // }
  33517. // }
  33518. // return true;
  33519. // }
  33520. /**
  33521. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  33522. * control points will be used. This should be used when points are monotone
  33523. * either in x or y dimension.
  33524. */
  33525. function drawMono(
  33526. ctx, points, start, segLen, allLen,
  33527. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33528. ) {
  33529. var prevIdx = 0;
  33530. var idx = start;
  33531. for (var k = 0; k < segLen; k++) {
  33532. var p = points[idx];
  33533. if (idx >= allLen || idx < 0) {
  33534. break;
  33535. }
  33536. if (isPointNull(p)) {
  33537. if (connectNulls) {
  33538. idx += dir;
  33539. continue;
  33540. }
  33541. break;
  33542. }
  33543. if (idx === start) {
  33544. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33545. }
  33546. else {
  33547. if (smooth > 0) {
  33548. var prevP = points[prevIdx];
  33549. var dim = smoothMonotone === 'y' ? 1 : 0;
  33550. // Length of control point to p, either in x or y, but not both
  33551. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  33552. v2Copy(cp0, prevP);
  33553. cp0[dim] = prevP[dim] + ctrlLen;
  33554. v2Copy(cp1, p);
  33555. cp1[dim] = p[dim] - ctrlLen;
  33556. ctx.bezierCurveTo(
  33557. cp0[0], cp0[1],
  33558. cp1[0], cp1[1],
  33559. p[0], p[1]
  33560. );
  33561. }
  33562. else {
  33563. ctx.lineTo(p[0], p[1]);
  33564. }
  33565. }
  33566. prevIdx = idx;
  33567. idx += dir;
  33568. }
  33569. return k;
  33570. }
  33571. /**
  33572. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  33573. * situations. This should be used when points are non-monotone neither in x or
  33574. * y dimension.
  33575. */
  33576. function drawNonMono(
  33577. ctx, points, start, segLen, allLen,
  33578. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  33579. ) {
  33580. var prevIdx = 0;
  33581. var idx = start;
  33582. for (var k = 0; k < segLen; k++) {
  33583. var p = points[idx];
  33584. if (idx >= allLen || idx < 0) {
  33585. break;
  33586. }
  33587. if (isPointNull(p)) {
  33588. if (connectNulls) {
  33589. idx += dir;
  33590. continue;
  33591. }
  33592. break;
  33593. }
  33594. if (idx === start) {
  33595. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  33596. v2Copy(cp0, p);
  33597. }
  33598. else {
  33599. if (smooth > 0) {
  33600. var nextIdx = idx + dir;
  33601. var nextP = points[nextIdx];
  33602. if (connectNulls) {
  33603. // Find next point not null
  33604. while (nextP && isPointNull(points[nextIdx])) {
  33605. nextIdx += dir;
  33606. nextP = points[nextIdx];
  33607. }
  33608. }
  33609. var ratioNextSeg = 0.5;
  33610. var prevP = points[prevIdx];
  33611. var nextP = points[nextIdx];
  33612. // Last point
  33613. if (!nextP || isPointNull(nextP)) {
  33614. v2Copy(cp1, p);
  33615. }
  33616. else {
  33617. // If next data is null in not connect case
  33618. if (isPointNull(nextP) && !connectNulls) {
  33619. nextP = p;
  33620. }
  33621. sub(v, nextP, prevP);
  33622. var lenPrevSeg;
  33623. var lenNextSeg;
  33624. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  33625. var dim = smoothMonotone === 'x' ? 0 : 1;
  33626. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  33627. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  33628. }
  33629. else {
  33630. lenPrevSeg = dist(p, prevP);
  33631. lenNextSeg = dist(p, nextP);
  33632. }
  33633. // Use ratio of seg length
  33634. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  33635. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  33636. }
  33637. // Smooth constraint
  33638. vec2Min(cp0, cp0, smoothMax);
  33639. vec2Max(cp0, cp0, smoothMin);
  33640. vec2Min(cp1, cp1, smoothMax);
  33641. vec2Max(cp1, cp1, smoothMin);
  33642. ctx.bezierCurveTo(
  33643. cp0[0], cp0[1],
  33644. cp1[0], cp1[1],
  33645. p[0], p[1]
  33646. );
  33647. // cp0 of next segment
  33648. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  33649. }
  33650. else {
  33651. ctx.lineTo(p[0], p[1]);
  33652. }
  33653. }
  33654. prevIdx = idx;
  33655. idx += dir;
  33656. }
  33657. return k;
  33658. }
  33659. function getBoundingBox(points, smoothConstraint) {
  33660. var ptMin = [Infinity, Infinity];
  33661. var ptMax = [-Infinity, -Infinity];
  33662. if (smoothConstraint) {
  33663. for (var i = 0; i < points.length; i++) {
  33664. var pt = points[i];
  33665. if (pt[0] < ptMin[0]) {
  33666. ptMin[0] = pt[0];
  33667. }
  33668. if (pt[1] < ptMin[1]) {
  33669. ptMin[1] = pt[1];
  33670. }
  33671. if (pt[0] > ptMax[0]) {
  33672. ptMax[0] = pt[0];
  33673. }
  33674. if (pt[1] > ptMax[1]) {
  33675. ptMax[1] = pt[1];
  33676. }
  33677. }
  33678. }
  33679. return {
  33680. min: smoothConstraint ? ptMin : ptMax,
  33681. max: smoothConstraint ? ptMax : ptMin
  33682. };
  33683. }
  33684. var Polyline$1 = Path.extend({
  33685. type: 'ec-polyline',
  33686. shape: {
  33687. points: [],
  33688. smooth: 0,
  33689. smoothConstraint: true,
  33690. smoothMonotone: null,
  33691. connectNulls: false
  33692. },
  33693. style: {
  33694. fill: null,
  33695. stroke: '#000'
  33696. },
  33697. brush: fixClipWithShadow(Path.prototype.brush),
  33698. buildPath: function (ctx, shape) {
  33699. var points = shape.points;
  33700. var i = 0;
  33701. var len$$1 = points.length;
  33702. var result = getBoundingBox(points, shape.smoothConstraint);
  33703. if (shape.connectNulls) {
  33704. // Must remove first and last null values avoid draw error in polygon
  33705. for (; len$$1 > 0; len$$1--) {
  33706. if (!isPointNull(points[len$$1 - 1])) {
  33707. break;
  33708. }
  33709. }
  33710. for (; i < len$$1; i++) {
  33711. if (!isPointNull(points[i])) {
  33712. break;
  33713. }
  33714. }
  33715. }
  33716. while (i < len$$1) {
  33717. i += drawSegment(
  33718. ctx, points, i, len$$1, len$$1,
  33719. 1, result.min, result.max, shape.smooth,
  33720. shape.smoothMonotone, shape.connectNulls
  33721. ) + 1;
  33722. }
  33723. }
  33724. });
  33725. var Polygon$1 = Path.extend({
  33726. type: 'ec-polygon',
  33727. shape: {
  33728. points: [],
  33729. // Offset between stacked base points and points
  33730. stackedOnPoints: [],
  33731. smooth: 0,
  33732. stackedOnSmooth: 0,
  33733. smoothConstraint: true,
  33734. smoothMonotone: null,
  33735. connectNulls: false
  33736. },
  33737. brush: fixClipWithShadow(Path.prototype.brush),
  33738. buildPath: function (ctx, shape) {
  33739. var points = shape.points;
  33740. var stackedOnPoints = shape.stackedOnPoints;
  33741. var i = 0;
  33742. var len$$1 = points.length;
  33743. var smoothMonotone = shape.smoothMonotone;
  33744. var bbox = getBoundingBox(points, shape.smoothConstraint);
  33745. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  33746. if (shape.connectNulls) {
  33747. // Must remove first and last null values avoid draw error in polygon
  33748. for (; len$$1 > 0; len$$1--) {
  33749. if (!isPointNull(points[len$$1 - 1])) {
  33750. break;
  33751. }
  33752. }
  33753. for (; i < len$$1; i++) {
  33754. if (!isPointNull(points[i])) {
  33755. break;
  33756. }
  33757. }
  33758. }
  33759. while (i < len$$1) {
  33760. var k = drawSegment(
  33761. ctx, points, i, len$$1, len$$1,
  33762. 1, bbox.min, bbox.max, shape.smooth,
  33763. smoothMonotone, shape.connectNulls
  33764. );
  33765. drawSegment(
  33766. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  33767. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  33768. smoothMonotone, shape.connectNulls
  33769. );
  33770. i += k + 1;
  33771. ctx.closePath();
  33772. }
  33773. }
  33774. });
  33775. /*
  33776. * Licensed to the Apache Software Foundation (ASF) under one
  33777. * or more contributor license agreements. See the NOTICE file
  33778. * distributed with this work for additional information
  33779. * regarding copyright ownership. The ASF licenses this file
  33780. * to you under the Apache License, Version 2.0 (the
  33781. * "License"); you may not use this file except in compliance
  33782. * with the License. You may obtain a copy of the License at
  33783. *
  33784. * http://www.apache.org/licenses/LICENSE-2.0
  33785. *
  33786. * Unless required by applicable law or agreed to in writing,
  33787. * software distributed under the License is distributed on an
  33788. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33789. * KIND, either express or implied. See the License for the
  33790. * specific language governing permissions and limitations
  33791. * under the License.
  33792. */
  33793. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  33794. var rect = cartesian.getArea();
  33795. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  33796. var x = rect.x;
  33797. var y = rect.y;
  33798. var width = rect.width;
  33799. var height = rect.height;
  33800. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  33801. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  33802. x -= lineWidth / 2;
  33803. y -= lineWidth / 2;
  33804. width += lineWidth;
  33805. height += lineWidth;
  33806. // fix: https://github.com/apache/incubator-echarts/issues/11369
  33807. x = Math.floor(x);
  33808. width = Math.round(width);
  33809. var clipPath = new Rect({
  33810. shape: {
  33811. x: x,
  33812. y: y,
  33813. width: width,
  33814. height: height
  33815. }
  33816. });
  33817. if (hasAnimation) {
  33818. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  33819. initProps(clipPath, {
  33820. shape: {
  33821. width: width,
  33822. height: height
  33823. }
  33824. }, seriesModel);
  33825. }
  33826. return clipPath;
  33827. }
  33828. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  33829. var sectorArea = polar.getArea();
  33830. // Avoid float number rounding error for symbol on the edge of axis extent.
  33831. var clipPath = new Sector({
  33832. shape: {
  33833. cx: round$1(polar.cx, 1),
  33834. cy: round$1(polar.cy, 1),
  33835. r0: round$1(sectorArea.r0, 1),
  33836. r: round$1(sectorArea.r, 1),
  33837. startAngle: sectorArea.startAngle,
  33838. endAngle: sectorArea.endAngle,
  33839. clockwise: sectorArea.clockwise
  33840. }
  33841. });
  33842. if (hasAnimation) {
  33843. clipPath.shape.endAngle = sectorArea.startAngle;
  33844. initProps(clipPath, {
  33845. shape: {
  33846. endAngle: sectorArea.endAngle
  33847. }
  33848. }, seriesModel);
  33849. }
  33850. return clipPath;
  33851. }
  33852. function createClipPath(coordSys, hasAnimation, seriesModel) {
  33853. if (!coordSys) {
  33854. return null;
  33855. }
  33856. else if (coordSys.type === 'polar') {
  33857. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  33858. }
  33859. else if (coordSys.type === 'cartesian2d') {
  33860. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  33861. }
  33862. return null;
  33863. }
  33864. /*
  33865. * Licensed to the Apache Software Foundation (ASF) under one
  33866. * or more contributor license agreements. See the NOTICE file
  33867. * distributed with this work for additional information
  33868. * regarding copyright ownership. The ASF licenses this file
  33869. * to you under the Apache License, Version 2.0 (the
  33870. * "License"); you may not use this file except in compliance
  33871. * with the License. You may obtain a copy of the License at
  33872. *
  33873. * http://www.apache.org/licenses/LICENSE-2.0
  33874. *
  33875. * Unless required by applicable law or agreed to in writing,
  33876. * software distributed under the License is distributed on an
  33877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33878. * KIND, either express or implied. See the License for the
  33879. * specific language governing permissions and limitations
  33880. * under the License.
  33881. */
  33882. // FIXME step not support polar
  33883. function isPointsSame(points1, points2) {
  33884. if (points1.length !== points2.length) {
  33885. return;
  33886. }
  33887. for (var i = 0; i < points1.length; i++) {
  33888. var p1 = points1[i];
  33889. var p2 = points2[i];
  33890. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  33891. return;
  33892. }
  33893. }
  33894. return true;
  33895. }
  33896. function getBoundingDiff(points1, points2) {
  33897. var min1 = [];
  33898. var max1 = [];
  33899. var min2 = [];
  33900. var max2 = [];
  33901. fromPoints(points1, min1, max1);
  33902. fromPoints(points2, min2, max2);
  33903. // Get a max value from each corner of two boundings.
  33904. return Math.max(
  33905. Math.abs(min1[0] - min2[0]),
  33906. Math.abs(min1[1] - min2[1]),
  33907. Math.abs(max1[0] - max2[0]),
  33908. Math.abs(max1[1] - max2[1])
  33909. );
  33910. }
  33911. function getSmooth(smooth) {
  33912. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  33913. }
  33914. /**
  33915. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  33916. * @param {module:echarts/data/List} data
  33917. * @param {Object} dataCoordInfo
  33918. * @param {Array.<Array.<number>>} points
  33919. */
  33920. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  33921. if (!dataCoordInfo.valueDim) {
  33922. return [];
  33923. }
  33924. var points = [];
  33925. for (var idx = 0, len = data.count(); idx < len; idx++) {
  33926. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  33927. }
  33928. return points;
  33929. }
  33930. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  33931. var baseAxis = coordSys.getBaseAxis();
  33932. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  33933. var stepPoints = [];
  33934. for (var i = 0; i < points.length - 1; i++) {
  33935. var nextPt = points[i + 1];
  33936. var pt = points[i];
  33937. stepPoints.push(pt);
  33938. var stepPt = [];
  33939. switch (stepTurnAt) {
  33940. case 'end':
  33941. stepPt[baseIndex] = nextPt[baseIndex];
  33942. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33943. // default is start
  33944. stepPoints.push(stepPt);
  33945. break;
  33946. case 'middle':
  33947. // default is start
  33948. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  33949. var stepPt2 = [];
  33950. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  33951. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  33952. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  33953. stepPoints.push(stepPt);
  33954. stepPoints.push(stepPt2);
  33955. break;
  33956. default:
  33957. stepPt[baseIndex] = pt[baseIndex];
  33958. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  33959. // default is start
  33960. stepPoints.push(stepPt);
  33961. }
  33962. }
  33963. // Last points
  33964. points[i] && stepPoints.push(points[i]);
  33965. return stepPoints;
  33966. }
  33967. function getVisualGradient(data, coordSys) {
  33968. var visualMetaList = data.getVisual('visualMeta');
  33969. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  33970. // When data.count() is 0, gradient range can not be calculated.
  33971. return;
  33972. }
  33973. if (coordSys.type !== 'cartesian2d') {
  33974. if (__DEV__) {
  33975. console.warn('Visual map on line style is only supported on cartesian2d.');
  33976. }
  33977. return;
  33978. }
  33979. var coordDim;
  33980. var visualMeta;
  33981. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  33982. var dimIndex = visualMetaList[i].dimension;
  33983. var dimName = data.dimensions[dimIndex];
  33984. var dimInfo = data.getDimensionInfo(dimName);
  33985. coordDim = dimInfo && dimInfo.coordDim;
  33986. // Can only be x or y
  33987. if (coordDim === 'x' || coordDim === 'y') {
  33988. visualMeta = visualMetaList[i];
  33989. break;
  33990. }
  33991. }
  33992. if (!visualMeta) {
  33993. if (__DEV__) {
  33994. console.warn('Visual map on line style only support x or y dimension.');
  33995. }
  33996. return;
  33997. }
  33998. // If the area to be rendered is bigger than area defined by LinearGradient,
  33999. // the canvas spec prescribes that the color of the first stop and the last
  34000. // stop should be used. But if two stops are added at offset 0, in effect
  34001. // browsers use the color of the second stop to render area outside
  34002. // LinearGradient. So we can only infinitesimally extend area defined in
  34003. // LinearGradient to render `outerColors`.
  34004. var axis = coordSys.getAxis(coordDim);
  34005. // dataToCoor mapping may not be linear, but must be monotonic.
  34006. var colorStops = map(visualMeta.stops, function (stop) {
  34007. return {
  34008. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34009. color: stop.color
  34010. };
  34011. });
  34012. var stopLen = colorStops.length;
  34013. var outerColors = visualMeta.outerColors.slice();
  34014. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34015. colorStops.reverse();
  34016. outerColors.reverse();
  34017. }
  34018. var tinyExtent = 10; // Arbitrary value: 10px
  34019. var minCoord = colorStops[0].coord - tinyExtent;
  34020. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  34021. var coordSpan = maxCoord - minCoord;
  34022. if (coordSpan < 1e-3) {
  34023. return 'transparent';
  34024. }
  34025. each$1(colorStops, function (stop) {
  34026. stop.offset = (stop.coord - minCoord) / coordSpan;
  34027. });
  34028. colorStops.push({
  34029. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  34030. color: outerColors[1] || 'transparent'
  34031. });
  34032. colorStops.unshift({ // notice colorStops.length have been changed.
  34033. offset: stopLen ? colorStops[0].offset : 0.5,
  34034. color: outerColors[0] || 'transparent'
  34035. });
  34036. // zrUtil.each(colorStops, function (colorStop) {
  34037. // // Make sure each offset has rounded px to avoid not sharp edge
  34038. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  34039. // });
  34040. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  34041. gradient[coordDim] = minCoord;
  34042. gradient[coordDim + '2'] = maxCoord;
  34043. return gradient;
  34044. }
  34045. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34046. var showAllSymbol = seriesModel.get('showAllSymbol');
  34047. var isAuto = showAllSymbol === 'auto';
  34048. if (showAllSymbol && !isAuto) {
  34049. return;
  34050. }
  34051. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34052. if (!categoryAxis) {
  34053. return;
  34054. }
  34055. // Note that category label interval strategy might bring some weird effect
  34056. // in some scenario: users may wonder why some of the symbols are not
  34057. // displayed. So we show all symbols as possible as we can.
  34058. if (isAuto
  34059. // Simplify the logic, do not determine label overlap here.
  34060. && canShowAllSymbolForCategory(categoryAxis, data)
  34061. ) {
  34062. return;
  34063. }
  34064. // Otherwise follow the label interval strategy on category axis.
  34065. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34066. var labelMap = {};
  34067. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  34068. labelMap[labelItem.tickValue] = 1;
  34069. });
  34070. return function (dataIndex) {
  34071. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34072. };
  34073. }
  34074. function canShowAllSymbolForCategory(categoryAxis, data) {
  34075. // In mose cases, line is monotonous on category axis, and the label size
  34076. // is close with each other. So we check the symbol size and some of the
  34077. // label size alone with the category axis to estimate whether all symbol
  34078. // can be shown without overlap.
  34079. var axisExtent = categoryAxis.getExtent();
  34080. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34081. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34082. // Sampling some points, max 5.
  34083. var dataLen = data.count();
  34084. var step = Math.max(1, Math.round(dataLen / 5));
  34085. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34086. if (SymbolClz$1.getSymbolSize(
  34087. data, dataIndex
  34088. // Only for cartesian, where `isHorizontal` exists.
  34089. )[categoryAxis.isHorizontal() ? 1 : 0]
  34090. // Empirical number
  34091. * 1.5 > availSize
  34092. ) {
  34093. return false;
  34094. }
  34095. }
  34096. return true;
  34097. }
  34098. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  34099. if (coordSys.type === 'cartesian2d') {
  34100. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34101. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  34102. // Expand clip shape to avoid clipping when line value exceeds axis
  34103. if (!seriesModel.get('clip', true)) {
  34104. var rectShape = clipPath.shape;
  34105. var expandSize = Math.max(rectShape.width, rectShape.height);
  34106. if (isHorizontal) {
  34107. rectShape.y -= expandSize;
  34108. rectShape.height += expandSize * 2;
  34109. }
  34110. else {
  34111. rectShape.x -= expandSize;
  34112. rectShape.width += expandSize * 2;
  34113. }
  34114. }
  34115. return clipPath;
  34116. }
  34117. else {
  34118. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34119. }
  34120. }
  34121. Chart.extend({
  34122. type: 'line',
  34123. init: function () {
  34124. var lineGroup = new Group();
  34125. var symbolDraw = new SymbolDraw();
  34126. this.group.add(symbolDraw.group);
  34127. this._symbolDraw = symbolDraw;
  34128. this._lineGroup = lineGroup;
  34129. },
  34130. render: function (seriesModel, ecModel, api) {
  34131. var coordSys = seriesModel.coordinateSystem;
  34132. var group = this.group;
  34133. var data = seriesModel.getData();
  34134. var lineStyleModel = seriesModel.getModel('lineStyle');
  34135. var areaStyleModel = seriesModel.getModel('areaStyle');
  34136. var points = data.mapArray(data.getItemLayout);
  34137. var isCoordSysPolar = coordSys.type === 'polar';
  34138. var prevCoordSys = this._coordSys;
  34139. var symbolDraw = this._symbolDraw;
  34140. var polyline = this._polyline;
  34141. var polygon = this._polygon;
  34142. var lineGroup = this._lineGroup;
  34143. var hasAnimation = seriesModel.get('animation');
  34144. var isAreaChart = !areaStyleModel.isEmpty();
  34145. var valueOrigin = areaStyleModel.get('origin');
  34146. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34147. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34148. var showSymbol = seriesModel.get('showSymbol');
  34149. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  34150. && getIsIgnoreFunc(seriesModel, data, coordSys);
  34151. // Remove temporary symbols
  34152. var oldData = this._data;
  34153. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34154. if (el.__temp) {
  34155. group.remove(el);
  34156. oldData.setItemGraphicEl(idx, null);
  34157. }
  34158. });
  34159. // Remove previous created symbols if showSymbol changed to false
  34160. if (!showSymbol) {
  34161. symbolDraw.remove();
  34162. }
  34163. group.add(lineGroup);
  34164. // FIXME step not support polar
  34165. var step = !isCoordSysPolar && seriesModel.get('step');
  34166. var clipShapeForSymbol;
  34167. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34168. clipShapeForSymbol = coordSys.getArea();
  34169. // Avoid float number rounding error for symbol on the edge of axis extent.
  34170. // See #7913 and `test/dataZoom-clip.html`.
  34171. if (clipShapeForSymbol.width != null) {
  34172. clipShapeForSymbol.x -= 0.1;
  34173. clipShapeForSymbol.y -= 0.1;
  34174. clipShapeForSymbol.width += 0.2;
  34175. clipShapeForSymbol.height += 0.2;
  34176. }
  34177. else if (clipShapeForSymbol.r0) {
  34178. clipShapeForSymbol.r0 -= 0.5;
  34179. clipShapeForSymbol.r1 += 0.5;
  34180. }
  34181. }
  34182. this._clipShapeForSymbol = clipShapeForSymbol;
  34183. // Initialization animation or coordinate system changed
  34184. if (
  34185. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  34186. ) {
  34187. showSymbol && symbolDraw.updateData(data, {
  34188. isIgnore: isIgnoreFunc,
  34189. clipShape: clipShapeForSymbol
  34190. });
  34191. if (step) {
  34192. // TODO If stacked series is not step
  34193. points = turnPointsIntoStep(points, coordSys, step);
  34194. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34195. }
  34196. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34197. if (isAreaChart) {
  34198. polygon = this._newPolygon(
  34199. points, stackedOnPoints,
  34200. coordSys, hasAnimation
  34201. );
  34202. }
  34203. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34204. }
  34205. else {
  34206. if (isAreaChart && !polygon) {
  34207. // If areaStyle is added
  34208. polygon = this._newPolygon(
  34209. points, stackedOnPoints,
  34210. coordSys, hasAnimation
  34211. );
  34212. }
  34213. else if (polygon && !isAreaChart) {
  34214. // If areaStyle is removed
  34215. lineGroup.remove(polygon);
  34216. polygon = this._polygon = null;
  34217. }
  34218. // Update clipPath
  34219. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  34220. // Always update, or it is wrong in the case turning on legend
  34221. // because points are not changed
  34222. showSymbol && symbolDraw.updateData(data, {
  34223. isIgnore: isIgnoreFunc,
  34224. clipShape: clipShapeForSymbol
  34225. });
  34226. // Stop symbol animation and sync with line points
  34227. // FIXME performance?
  34228. data.eachItemGraphicEl(function (el) {
  34229. el.stopAnimation(true);
  34230. });
  34231. // In the case data zoom triggerred refreshing frequently
  34232. // Data may not change if line has a category axis. So it should animate nothing
  34233. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  34234. || !isPointsSame(this._points, points)
  34235. ) {
  34236. if (hasAnimation) {
  34237. this._updateAnimation(
  34238. data, stackedOnPoints, coordSys, api, step, valueOrigin
  34239. );
  34240. }
  34241. else {
  34242. // Not do it in update with animation
  34243. if (step) {
  34244. // TODO If stacked series is not step
  34245. points = turnPointsIntoStep(points, coordSys, step);
  34246. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34247. }
  34248. polyline.setShape({
  34249. points: points
  34250. });
  34251. polygon && polygon.setShape({
  34252. points: points,
  34253. stackedOnPoints: stackedOnPoints
  34254. });
  34255. }
  34256. }
  34257. }
  34258. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34259. polyline.useStyle(defaults(
  34260. // Use color in lineStyle first
  34261. lineStyleModel.getLineStyle(),
  34262. {
  34263. fill: 'none',
  34264. stroke: visualColor,
  34265. lineJoin: 'bevel'
  34266. }
  34267. ));
  34268. var smooth = seriesModel.get('smooth');
  34269. smooth = getSmooth(seriesModel.get('smooth'));
  34270. polyline.setShape({
  34271. smooth: smooth,
  34272. smoothMonotone: seriesModel.get('smoothMonotone'),
  34273. connectNulls: seriesModel.get('connectNulls')
  34274. });
  34275. if (polygon) {
  34276. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34277. var stackedOnSmooth = 0;
  34278. polygon.useStyle(defaults(
  34279. areaStyleModel.getAreaStyle(),
  34280. {
  34281. fill: visualColor,
  34282. opacity: 0.7,
  34283. lineJoin: 'bevel'
  34284. }
  34285. ));
  34286. if (stackedOnSeries) {
  34287. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34288. }
  34289. polygon.setShape({
  34290. smooth: smooth,
  34291. stackedOnSmooth: stackedOnSmooth,
  34292. smoothMonotone: seriesModel.get('smoothMonotone'),
  34293. connectNulls: seriesModel.get('connectNulls')
  34294. });
  34295. }
  34296. this._data = data;
  34297. // Save the coordinate system for transition animation when data changed
  34298. this._coordSys = coordSys;
  34299. this._stackedOnPoints = stackedOnPoints;
  34300. this._points = points;
  34301. this._step = step;
  34302. this._valueOrigin = valueOrigin;
  34303. },
  34304. dispose: function () {},
  34305. highlight: function (seriesModel, ecModel, api, payload) {
  34306. var data = seriesModel.getData();
  34307. var dataIndex = queryDataIndex(data, payload);
  34308. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34309. var symbol = data.getItemGraphicEl(dataIndex);
  34310. if (!symbol) {
  34311. // Create a temporary symbol if it is not exists
  34312. var pt = data.getItemLayout(dataIndex);
  34313. if (!pt) {
  34314. // Null data
  34315. return;
  34316. }
  34317. // fix #11360: should't draw symbol outside clipShapeForSymbol
  34318. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34319. return;
  34320. }
  34321. symbol = new SymbolClz$1(data, dataIndex);
  34322. symbol.position = pt;
  34323. symbol.setZ(
  34324. seriesModel.get('zlevel'),
  34325. seriesModel.get('z')
  34326. );
  34327. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34328. symbol.__temp = true;
  34329. data.setItemGraphicEl(dataIndex, symbol);
  34330. // Stop scale animation
  34331. symbol.stopSymbolAnimation(true);
  34332. this.group.add(symbol);
  34333. }
  34334. symbol.highlight();
  34335. }
  34336. else {
  34337. // Highlight whole series
  34338. Chart.prototype.highlight.call(
  34339. this, seriesModel, ecModel, api, payload
  34340. );
  34341. }
  34342. },
  34343. downplay: function (seriesModel, ecModel, api, payload) {
  34344. var data = seriesModel.getData();
  34345. var dataIndex = queryDataIndex(data, payload);
  34346. if (dataIndex != null && dataIndex >= 0) {
  34347. var symbol = data.getItemGraphicEl(dataIndex);
  34348. if (symbol) {
  34349. if (symbol.__temp) {
  34350. data.setItemGraphicEl(dataIndex, null);
  34351. this.group.remove(symbol);
  34352. }
  34353. else {
  34354. symbol.downplay();
  34355. }
  34356. }
  34357. }
  34358. else {
  34359. // FIXME
  34360. // can not downplay completely.
  34361. // Downplay whole series
  34362. Chart.prototype.downplay.call(
  34363. this, seriesModel, ecModel, api, payload
  34364. );
  34365. }
  34366. },
  34367. /**
  34368. * @param {module:zrender/container/Group} group
  34369. * @param {Array.<Array.<number>>} points
  34370. * @private
  34371. */
  34372. _newPolyline: function (points) {
  34373. var polyline = this._polyline;
  34374. // Remove previous created polyline
  34375. if (polyline) {
  34376. this._lineGroup.remove(polyline);
  34377. }
  34378. polyline = new Polyline$1({
  34379. shape: {
  34380. points: points
  34381. },
  34382. silent: true,
  34383. z2: 10
  34384. });
  34385. this._lineGroup.add(polyline);
  34386. this._polyline = polyline;
  34387. return polyline;
  34388. },
  34389. /**
  34390. * @param {module:zrender/container/Group} group
  34391. * @param {Array.<Array.<number>>} stackedOnPoints
  34392. * @param {Array.<Array.<number>>} points
  34393. * @private
  34394. */
  34395. _newPolygon: function (points, stackedOnPoints) {
  34396. var polygon = this._polygon;
  34397. // Remove previous created polygon
  34398. if (polygon) {
  34399. this._lineGroup.remove(polygon);
  34400. }
  34401. polygon = new Polygon$1({
  34402. shape: {
  34403. points: points,
  34404. stackedOnPoints: stackedOnPoints
  34405. },
  34406. silent: true
  34407. });
  34408. this._lineGroup.add(polygon);
  34409. this._polygon = polygon;
  34410. return polygon;
  34411. },
  34412. /**
  34413. * @private
  34414. */
  34415. // FIXME Two value axis
  34416. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34417. var polyline = this._polyline;
  34418. var polygon = this._polygon;
  34419. var seriesModel = data.hostModel;
  34420. var diff = lineAnimationDiff(
  34421. this._data, data,
  34422. this._stackedOnPoints, stackedOnPoints,
  34423. this._coordSys, coordSys,
  34424. this._valueOrigin, valueOrigin
  34425. );
  34426. var current = diff.current;
  34427. var stackedOnCurrent = diff.stackedOnCurrent;
  34428. var next = diff.next;
  34429. var stackedOnNext = diff.stackedOnNext;
  34430. if (step) {
  34431. // TODO If stacked series is not step
  34432. current = turnPointsIntoStep(diff.current, coordSys, step);
  34433. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34434. next = turnPointsIntoStep(diff.next, coordSys, step);
  34435. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34436. }
  34437. // Don't apply animation if diff is large.
  34438. // For better result and avoid memory explosion problems like
  34439. // https://github.com/apache/incubator-echarts/issues/12229
  34440. if (getBoundingDiff(current, next) > 3000
  34441. || (polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000)
  34442. ) {
  34443. polyline.setShape({
  34444. points: next
  34445. });
  34446. if (polygon) {
  34447. polygon.setShape({
  34448. points: next,
  34449. stackedOnPoints: stackedOnNext
  34450. });
  34451. }
  34452. return;
  34453. }
  34454. // `diff.current` is subset of `current` (which should be ensured by
  34455. // turnPointsIntoStep), so points in `__points` can be updated when
  34456. // points in `current` are update during animation.
  34457. polyline.shape.__points = diff.current;
  34458. polyline.shape.points = current;
  34459. updateProps(polyline, {
  34460. shape: {
  34461. points: next
  34462. }
  34463. }, seriesModel);
  34464. if (polygon) {
  34465. polygon.setShape({
  34466. points: current,
  34467. stackedOnPoints: stackedOnCurrent
  34468. });
  34469. updateProps(polygon, {
  34470. shape: {
  34471. points: next,
  34472. stackedOnPoints: stackedOnNext
  34473. }
  34474. }, seriesModel);
  34475. }
  34476. var updatedDataInfo = [];
  34477. var diffStatus = diff.status;
  34478. for (var i = 0; i < diffStatus.length; i++) {
  34479. var cmd = diffStatus[i].cmd;
  34480. if (cmd === '=') {
  34481. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34482. if (el) {
  34483. updatedDataInfo.push({
  34484. el: el,
  34485. ptIdx: i // Index of points
  34486. });
  34487. }
  34488. }
  34489. }
  34490. if (polyline.animators && polyline.animators.length) {
  34491. polyline.animators[0].during(function () {
  34492. for (var i = 0; i < updatedDataInfo.length; i++) {
  34493. var el = updatedDataInfo[i].el;
  34494. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34495. }
  34496. });
  34497. }
  34498. },
  34499. remove: function (ecModel) {
  34500. var group = this.group;
  34501. var oldData = this._data;
  34502. this._lineGroup.removeAll();
  34503. this._symbolDraw.remove(true);
  34504. // Remove temporary created elements when highlighting
  34505. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34506. if (el.__temp) {
  34507. group.remove(el);
  34508. oldData.setItemGraphicEl(idx, null);
  34509. }
  34510. });
  34511. this._polyline =
  34512. this._polygon =
  34513. this._coordSys =
  34514. this._points =
  34515. this._stackedOnPoints =
  34516. this._data = null;
  34517. }
  34518. });
  34519. /*
  34520. * Licensed to the Apache Software Foundation (ASF) under one
  34521. * or more contributor license agreements. See the NOTICE file
  34522. * distributed with this work for additional information
  34523. * regarding copyright ownership. The ASF licenses this file
  34524. * to you under the Apache License, Version 2.0 (the
  34525. * "License"); you may not use this file except in compliance
  34526. * with the License. You may obtain a copy of the License at
  34527. *
  34528. * http://www.apache.org/licenses/LICENSE-2.0
  34529. *
  34530. * Unless required by applicable law or agreed to in writing,
  34531. * software distributed under the License is distributed on an
  34532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34533. * KIND, either express or implied. See the License for the
  34534. * specific language governing permissions and limitations
  34535. * under the License.
  34536. */
  34537. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34538. // Encoding visual for all series include which is filtered for legend drawing
  34539. return {
  34540. seriesType: seriesType,
  34541. // For legend.
  34542. performRawSeries: true,
  34543. reset: function (seriesModel, ecModel, api) {
  34544. var data = seriesModel.getData();
  34545. var symbolType = seriesModel.get('symbol');
  34546. var symbolSize = seriesModel.get('symbolSize');
  34547. var keepAspect = seriesModel.get('symbolKeepAspect');
  34548. var symbolRotate = seriesModel.get('symbolRotate');
  34549. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34550. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34551. var hasSymbolRotateCallback = isFunction$1(symbolRotate);
  34552. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  34553. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  34554. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34555. data.setVisual({
  34556. legendSymbol: legendSymbol || seriesSymbol,
  34557. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34558. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34559. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34560. // some cases but generally it is not recommanded.
  34561. symbol: seriesSymbol,
  34562. symbolSize: seriesSymbolSize,
  34563. symbolKeepAspect: keepAspect,
  34564. symbolRotate: symbolRotate
  34565. });
  34566. // Only visible series has each data be visual encoded
  34567. if (ecModel.isSeriesFiltered(seriesModel)) {
  34568. return;
  34569. }
  34570. function dataEach(data, idx) {
  34571. if (hasCallback) {
  34572. var rawValue = seriesModel.getRawValue(idx);
  34573. var params = seriesModel.getDataParams(idx);
  34574. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34575. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34576. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  34577. }
  34578. if (data.hasItemOption) {
  34579. var itemModel = data.getItemModel(idx);
  34580. var itemSymbolType = itemModel.getShallow('symbol', true);
  34581. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34582. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  34583. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  34584. // If has item symbol
  34585. if (itemSymbolType != null) {
  34586. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34587. }
  34588. if (itemSymbolSize != null) {
  34589. // PENDING Transform symbolSize ?
  34590. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34591. }
  34592. if (itemSymbolRotate != null) {
  34593. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  34594. }
  34595. if (itemSymbolKeepAspect != null) {
  34596. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34597. }
  34598. }
  34599. }
  34600. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  34601. }
  34602. };
  34603. };
  34604. /*
  34605. * Licensed to the Apache Software Foundation (ASF) under one
  34606. * or more contributor license agreements. See the NOTICE file
  34607. * distributed with this work for additional information
  34608. * regarding copyright ownership. The ASF licenses this file
  34609. * to you under the Apache License, Version 2.0 (the
  34610. * "License"); you may not use this file except in compliance
  34611. * with the License. You may obtain a copy of the License at
  34612. *
  34613. * http://www.apache.org/licenses/LICENSE-2.0
  34614. *
  34615. * Unless required by applicable law or agreed to in writing,
  34616. * software distributed under the License is distributed on an
  34617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34618. * KIND, either express or implied. See the License for the
  34619. * specific language governing permissions and limitations
  34620. * under the License.
  34621. */
  34622. /* global Float32Array */
  34623. var pointsLayout = function (seriesType) {
  34624. return {
  34625. seriesType: seriesType,
  34626. plan: createRenderPlanner(),
  34627. reset: function (seriesModel) {
  34628. var data = seriesModel.getData();
  34629. var coordSys = seriesModel.coordinateSystem;
  34630. var pipelineContext = seriesModel.pipelineContext;
  34631. var isLargeRender = pipelineContext.large;
  34632. if (!coordSys) {
  34633. return;
  34634. }
  34635. var dims = map(coordSys.dimensions, function (dim) {
  34636. return data.mapDimension(dim);
  34637. }).slice(0, 2);
  34638. var dimLen = dims.length;
  34639. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  34640. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  34641. dims[0] = stackResultDim;
  34642. }
  34643. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  34644. dims[1] = stackResultDim;
  34645. }
  34646. function progress(params, data) {
  34647. var segCount = params.end - params.start;
  34648. var points = isLargeRender && new Float32Array(segCount * dimLen);
  34649. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  34650. var point;
  34651. if (dimLen === 1) {
  34652. var x = data.get(dims[0], i);
  34653. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  34654. }
  34655. else {
  34656. var x = tmpIn[0] = data.get(dims[0], i);
  34657. var y = tmpIn[1] = data.get(dims[1], i);
  34658. // Also {Array.<number>}, not undefined to avoid if...else... statement
  34659. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  34660. }
  34661. if (isLargeRender) {
  34662. points[offset++] = point ? point[0] : NaN;
  34663. points[offset++] = point ? point[1] : NaN;
  34664. }
  34665. else {
  34666. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  34667. }
  34668. }
  34669. isLargeRender && data.setLayout('symbolPoints', points);
  34670. }
  34671. return dimLen && {progress: progress};
  34672. }
  34673. };
  34674. };
  34675. /*
  34676. * Licensed to the Apache Software Foundation (ASF) under one
  34677. * or more contributor license agreements. See the NOTICE file
  34678. * distributed with this work for additional information
  34679. * regarding copyright ownership. The ASF licenses this file
  34680. * to you under the Apache License, Version 2.0 (the
  34681. * "License"); you may not use this file except in compliance
  34682. * with the License. You may obtain a copy of the License at
  34683. *
  34684. * http://www.apache.org/licenses/LICENSE-2.0
  34685. *
  34686. * Unless required by applicable law or agreed to in writing,
  34687. * software distributed under the License is distributed on an
  34688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34689. * KIND, either express or implied. See the License for the
  34690. * specific language governing permissions and limitations
  34691. * under the License.
  34692. */
  34693. var samplers = {
  34694. average: function (frame) {
  34695. var sum = 0;
  34696. var count = 0;
  34697. for (var i = 0; i < frame.length; i++) {
  34698. if (!isNaN(frame[i])) {
  34699. sum += frame[i];
  34700. count++;
  34701. }
  34702. }
  34703. // Return NaN if count is 0
  34704. return count === 0 ? NaN : sum / count;
  34705. },
  34706. sum: function (frame) {
  34707. var sum = 0;
  34708. for (var i = 0; i < frame.length; i++) {
  34709. // Ignore NaN
  34710. sum += frame[i] || 0;
  34711. }
  34712. return sum;
  34713. },
  34714. max: function (frame) {
  34715. var max = -Infinity;
  34716. for (var i = 0; i < frame.length; i++) {
  34717. frame[i] > max && (max = frame[i]);
  34718. }
  34719. // NaN will cause illegal axis extent.
  34720. return isFinite(max) ? max : NaN;
  34721. },
  34722. min: function (frame) {
  34723. var min = Infinity;
  34724. for (var i = 0; i < frame.length; i++) {
  34725. frame[i] < min && (min = frame[i]);
  34726. }
  34727. // NaN will cause illegal axis extent.
  34728. return isFinite(min) ? min : NaN;
  34729. },
  34730. // TODO
  34731. // Median
  34732. nearest: function (frame) {
  34733. return frame[0];
  34734. }
  34735. };
  34736. var indexSampler = function (frame, value) {
  34737. return Math.round(frame.length / 2);
  34738. };
  34739. var dataSample = function (seriesType) {
  34740. return {
  34741. seriesType: seriesType,
  34742. modifyOutputEnd: true,
  34743. reset: function (seriesModel, ecModel, api) {
  34744. var data = seriesModel.getData();
  34745. var sampling = seriesModel.get('sampling');
  34746. var coordSys = seriesModel.coordinateSystem;
  34747. // Only cartesian2d support down sampling
  34748. if (coordSys.type === 'cartesian2d' && sampling) {
  34749. var baseAxis = coordSys.getBaseAxis();
  34750. var valueAxis = coordSys.getOtherAxis(baseAxis);
  34751. var extent = baseAxis.getExtent();
  34752. // Coordinste system has been resized
  34753. var size = extent[1] - extent[0];
  34754. var rate = Math.round(data.count() / size);
  34755. if (rate > 1) {
  34756. var sampler;
  34757. if (typeof sampling === 'string') {
  34758. sampler = samplers[sampling];
  34759. }
  34760. else if (typeof sampling === 'function') {
  34761. sampler = sampling;
  34762. }
  34763. if (sampler) {
  34764. // Only support sample the first dim mapped from value axis.
  34765. seriesModel.setData(data.downSample(
  34766. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  34767. ));
  34768. }
  34769. }
  34770. }
  34771. }
  34772. };
  34773. };
  34774. /*
  34775. * Licensed to the Apache Software Foundation (ASF) under one
  34776. * or more contributor license agreements. See the NOTICE file
  34777. * distributed with this work for additional information
  34778. * regarding copyright ownership. The ASF licenses this file
  34779. * to you under the Apache License, Version 2.0 (the
  34780. * "License"); you may not use this file except in compliance
  34781. * with the License. You may obtain a copy of the License at
  34782. *
  34783. * http://www.apache.org/licenses/LICENSE-2.0
  34784. *
  34785. * Unless required by applicable law or agreed to in writing,
  34786. * software distributed under the License is distributed on an
  34787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34788. * KIND, either express or implied. See the License for the
  34789. * specific language governing permissions and limitations
  34790. * under the License.
  34791. */
  34792. /**
  34793. * Cartesian coordinate system
  34794. * @module echarts/coord/Cartesian
  34795. *
  34796. */
  34797. function dimAxisMapper(dim) {
  34798. return this._axes[dim];
  34799. }
  34800. /**
  34801. * @alias module:echarts/coord/Cartesian
  34802. * @constructor
  34803. */
  34804. var Cartesian = function (name) {
  34805. this._axes = {};
  34806. this._dimList = [];
  34807. /**
  34808. * @type {string}
  34809. */
  34810. this.name = name || '';
  34811. };
  34812. Cartesian.prototype = {
  34813. constructor: Cartesian,
  34814. type: 'cartesian',
  34815. /**
  34816. * Get axis
  34817. * @param {number|string} dim
  34818. * @return {module:echarts/coord/Cartesian~Axis}
  34819. */
  34820. getAxis: function (dim) {
  34821. return this._axes[dim];
  34822. },
  34823. /**
  34824. * Get axes list
  34825. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  34826. */
  34827. getAxes: function () {
  34828. return map(this._dimList, dimAxisMapper, this);
  34829. },
  34830. /**
  34831. * Get axes list by given scale type
  34832. */
  34833. getAxesByScale: function (scaleType) {
  34834. scaleType = scaleType.toLowerCase();
  34835. return filter(
  34836. this.getAxes(),
  34837. function (axis) {
  34838. return axis.scale.type === scaleType;
  34839. }
  34840. );
  34841. },
  34842. /**
  34843. * Add axis
  34844. * @param {module:echarts/coord/Cartesian.Axis}
  34845. */
  34846. addAxis: function (axis) {
  34847. var dim = axis.dim;
  34848. this._axes[dim] = axis;
  34849. this._dimList.push(dim);
  34850. },
  34851. /**
  34852. * Convert data to coord in nd space
  34853. * @param {Array.<number>|Object.<string, number>} val
  34854. * @return {Array.<number>|Object.<string, number>}
  34855. */
  34856. dataToCoord: function (val) {
  34857. return this._dataCoordConvert(val, 'dataToCoord');
  34858. },
  34859. /**
  34860. * Convert coord in nd space to data
  34861. * @param {Array.<number>|Object.<string, number>} val
  34862. * @return {Array.<number>|Object.<string, number>}
  34863. */
  34864. coordToData: function (val) {
  34865. return this._dataCoordConvert(val, 'coordToData');
  34866. },
  34867. _dataCoordConvert: function (input, method) {
  34868. var dimList = this._dimList;
  34869. var output = input instanceof Array ? [] : {};
  34870. for (var i = 0; i < dimList.length; i++) {
  34871. var dim = dimList[i];
  34872. var axis = this._axes[dim];
  34873. output[dim] = axis[method](input[dim]);
  34874. }
  34875. return output;
  34876. }
  34877. };
  34878. /*
  34879. * Licensed to the Apache Software Foundation (ASF) under one
  34880. * or more contributor license agreements. See the NOTICE file
  34881. * distributed with this work for additional information
  34882. * regarding copyright ownership. The ASF licenses this file
  34883. * to you under the Apache License, Version 2.0 (the
  34884. * "License"); you may not use this file except in compliance
  34885. * with the License. You may obtain a copy of the License at
  34886. *
  34887. * http://www.apache.org/licenses/LICENSE-2.0
  34888. *
  34889. * Unless required by applicable law or agreed to in writing,
  34890. * software distributed under the License is distributed on an
  34891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34892. * KIND, either express or implied. See the License for the
  34893. * specific language governing permissions and limitations
  34894. * under the License.
  34895. */
  34896. function Cartesian2D(name) {
  34897. Cartesian.call(this, name);
  34898. }
  34899. Cartesian2D.prototype = {
  34900. constructor: Cartesian2D,
  34901. type: 'cartesian2d',
  34902. /**
  34903. * @type {Array.<string>}
  34904. * @readOnly
  34905. */
  34906. dimensions: ['x', 'y'],
  34907. /**
  34908. * Base axis will be used on stacking.
  34909. *
  34910. * @return {module:echarts/coord/cartesian/Axis2D}
  34911. */
  34912. getBaseAxis: function () {
  34913. return this.getAxesByScale('ordinal')[0]
  34914. || this.getAxesByScale('time')[0]
  34915. || this.getAxis('x');
  34916. },
  34917. /**
  34918. * If contain point
  34919. * @param {Array.<number>} point
  34920. * @return {boolean}
  34921. */
  34922. containPoint: function (point) {
  34923. var axisX = this.getAxis('x');
  34924. var axisY = this.getAxis('y');
  34925. return axisX.contain(axisX.toLocalCoord(point[0]))
  34926. && axisY.contain(axisY.toLocalCoord(point[1]));
  34927. },
  34928. /**
  34929. * If contain data
  34930. * @param {Array.<number>} data
  34931. * @return {boolean}
  34932. */
  34933. containData: function (data) {
  34934. return this.getAxis('x').containData(data[0])
  34935. && this.getAxis('y').containData(data[1]);
  34936. },
  34937. /**
  34938. * @param {Array.<number>} data
  34939. * @param {Array.<number>} out
  34940. * @return {Array.<number>}
  34941. */
  34942. dataToPoint: function (data, reserved, out) {
  34943. var xAxis = this.getAxis('x');
  34944. var yAxis = this.getAxis('y');
  34945. out = out || [];
  34946. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  34947. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  34948. return out;
  34949. },
  34950. /**
  34951. * @param {Array.<number>} data
  34952. * @param {Array.<number>} out
  34953. * @return {Array.<number>}
  34954. */
  34955. clampData: function (data, out) {
  34956. var xScale = this.getAxis('x').scale;
  34957. var yScale = this.getAxis('y').scale;
  34958. var xAxisExtent = xScale.getExtent();
  34959. var yAxisExtent = yScale.getExtent();
  34960. var x = xScale.parse(data[0]);
  34961. var y = yScale.parse(data[1]);
  34962. out = out || [];
  34963. out[0] = Math.min(
  34964. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  34965. Math.max(xAxisExtent[0], xAxisExtent[1])
  34966. );
  34967. out[1] = Math.min(
  34968. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  34969. Math.max(yAxisExtent[0], yAxisExtent[1])
  34970. );
  34971. return out;
  34972. },
  34973. /**
  34974. * @param {Array.<number>} point
  34975. * @param {Array.<number>} out
  34976. * @return {Array.<number>}
  34977. */
  34978. pointToData: function (point, out) {
  34979. var xAxis = this.getAxis('x');
  34980. var yAxis = this.getAxis('y');
  34981. out = out || [];
  34982. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  34983. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  34984. return out;
  34985. },
  34986. /**
  34987. * Get other axis
  34988. * @param {module:echarts/coord/cartesian/Axis2D} axis
  34989. */
  34990. getOtherAxis: function (axis) {
  34991. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  34992. },
  34993. /**
  34994. * Get rect area of cartesian.
  34995. * Area will have a contain function to determine if a point is in the coordinate system.
  34996. * @return {BoundingRect}
  34997. */
  34998. getArea: function () {
  34999. var xExtent = this.getAxis('x').getGlobalExtent();
  35000. var yExtent = this.getAxis('y').getGlobalExtent();
  35001. var x = Math.min(xExtent[0], xExtent[1]);
  35002. var y = Math.min(yExtent[0], yExtent[1]);
  35003. var width = Math.max(xExtent[0], xExtent[1]) - x;
  35004. var height = Math.max(yExtent[0], yExtent[1]) - y;
  35005. var rect = new BoundingRect(x, y, width, height);
  35006. return rect;
  35007. }
  35008. };
  35009. inherits(Cartesian2D, Cartesian);
  35010. /*
  35011. * Licensed to the Apache Software Foundation (ASF) under one
  35012. * or more contributor license agreements. See the NOTICE file
  35013. * distributed with this work for additional information
  35014. * regarding copyright ownership. The ASF licenses this file
  35015. * to you under the Apache License, Version 2.0 (the
  35016. * "License"); you may not use this file except in compliance
  35017. * with the License. You may obtain a copy of the License at
  35018. *
  35019. * http://www.apache.org/licenses/LICENSE-2.0
  35020. *
  35021. * Unless required by applicable law or agreed to in writing,
  35022. * software distributed under the License is distributed on an
  35023. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35024. * KIND, either express or implied. See the License for the
  35025. * specific language governing permissions and limitations
  35026. * under the License.
  35027. */
  35028. /**
  35029. * Extend axis 2d
  35030. * @constructor module:echarts/coord/cartesian/Axis2D
  35031. * @extends {module:echarts/coord/cartesian/Axis}
  35032. * @param {string} dim
  35033. * @param {*} scale
  35034. * @param {Array.<number>} coordExtent
  35035. * @param {string} axisType
  35036. * @param {string} position
  35037. */
  35038. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  35039. Axis.call(this, dim, scale, coordExtent);
  35040. /**
  35041. * Axis type
  35042. * - 'category'
  35043. * - 'value'
  35044. * - 'time'
  35045. * - 'log'
  35046. * @type {string}
  35047. */
  35048. this.type = axisType || 'value';
  35049. /**
  35050. * Axis position
  35051. * - 'top'
  35052. * - 'bottom'
  35053. * - 'left'
  35054. * - 'right'
  35055. */
  35056. this.position = position || 'bottom';
  35057. };
  35058. Axis2D.prototype = {
  35059. constructor: Axis2D,
  35060. /**
  35061. * Index of axis, can be used as key
  35062. */
  35063. index: 0,
  35064. /**
  35065. * Implemented in <module:echarts/coord/cartesian/Grid>.
  35066. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  35067. * If not on zero of other axis, return null/undefined.
  35068. * If no axes, return an empty array.
  35069. */
  35070. getAxesOnZeroOf: null,
  35071. /**
  35072. * Axis model
  35073. * @param {module:echarts/coord/cartesian/AxisModel}
  35074. */
  35075. model: null,
  35076. isHorizontal: function () {
  35077. var position = this.position;
  35078. return position === 'top' || position === 'bottom';
  35079. },
  35080. /**
  35081. * Each item cooresponds to this.getExtent(), which
  35082. * means globalExtent[0] may greater than globalExtent[1],
  35083. * unless `asc` is input.
  35084. *
  35085. * @param {boolean} [asc]
  35086. * @return {Array.<number>}
  35087. */
  35088. getGlobalExtent: function (asc) {
  35089. var ret = this.getExtent();
  35090. ret[0] = this.toGlobalCoord(ret[0]);
  35091. ret[1] = this.toGlobalCoord(ret[1]);
  35092. asc && ret[0] > ret[1] && ret.reverse();
  35093. return ret;
  35094. },
  35095. getOtherAxis: function () {
  35096. this.grid.getOtherAxis();
  35097. },
  35098. /**
  35099. * @override
  35100. */
  35101. pointToData: function (point, clamp) {
  35102. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  35103. },
  35104. /**
  35105. * Transform global coord to local coord,
  35106. * i.e. var localCoord = axis.toLocalCoord(80);
  35107. * designate by module:echarts/coord/cartesian/Grid.
  35108. * @type {Function}
  35109. */
  35110. toLocalCoord: null,
  35111. /**
  35112. * Transform global coord to local coord,
  35113. * i.e. var globalCoord = axis.toLocalCoord(40);
  35114. * designate by module:echarts/coord/cartesian/Grid.
  35115. * @type {Function}
  35116. */
  35117. toGlobalCoord: null
  35118. };
  35119. inherits(Axis2D, Axis);
  35120. /*
  35121. * Licensed to the Apache Software Foundation (ASF) under one
  35122. * or more contributor license agreements. See the NOTICE file
  35123. * distributed with this work for additional information
  35124. * regarding copyright ownership. The ASF licenses this file
  35125. * to you under the Apache License, Version 2.0 (the
  35126. * "License"); you may not use this file except in compliance
  35127. * with the License. You may obtain a copy of the License at
  35128. *
  35129. * http://www.apache.org/licenses/LICENSE-2.0
  35130. *
  35131. * Unless required by applicable law or agreed to in writing,
  35132. * software distributed under the License is distributed on an
  35133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35134. * KIND, either express or implied. See the License for the
  35135. * specific language governing permissions and limitations
  35136. * under the License.
  35137. */
  35138. var defaultOption = {
  35139. show: true,
  35140. zlevel: 0,
  35141. z: 0,
  35142. // Inverse the axis.
  35143. inverse: false,
  35144. // Axis name displayed.
  35145. name: '',
  35146. // 'start' | 'middle' | 'end'
  35147. nameLocation: 'end',
  35148. // By degree. By defualt auto rotate by nameLocation.
  35149. nameRotate: null,
  35150. nameTruncate: {
  35151. maxWidth: null,
  35152. ellipsis: '...',
  35153. placeholder: '.'
  35154. },
  35155. // Use global text style by default.
  35156. nameTextStyle: {},
  35157. // The gap between axisName and axisLine.
  35158. nameGap: 15,
  35159. // Default `false` to support tooltip.
  35160. silent: false,
  35161. // Default `false` to avoid legacy user event listener fail.
  35162. triggerEvent: false,
  35163. tooltip: {
  35164. show: false
  35165. },
  35166. axisPointer: {},
  35167. axisLine: {
  35168. show: true,
  35169. onZero: true,
  35170. onZeroAxisIndex: null,
  35171. lineStyle: {
  35172. color: '#333',
  35173. width: 1,
  35174. type: 'solid'
  35175. },
  35176. // The arrow at both ends the the axis.
  35177. symbol: ['none', 'none'],
  35178. symbolSize: [10, 15]
  35179. },
  35180. axisTick: {
  35181. show: true,
  35182. // Whether axisTick is inside the grid or outside the grid.
  35183. inside: false,
  35184. // The length of axisTick.
  35185. length: 5,
  35186. lineStyle: {
  35187. width: 1
  35188. }
  35189. },
  35190. axisLabel: {
  35191. show: true,
  35192. // Whether axisLabel is inside the grid or outside the grid.
  35193. inside: false,
  35194. rotate: 0,
  35195. // true | false | null/undefined (auto)
  35196. showMinLabel: null,
  35197. // true | false | null/undefined (auto)
  35198. showMaxLabel: null,
  35199. margin: 8,
  35200. // formatter: null,
  35201. fontSize: 12
  35202. },
  35203. splitLine: {
  35204. show: true,
  35205. lineStyle: {
  35206. color: ['#ccc'],
  35207. width: 1,
  35208. type: 'solid'
  35209. }
  35210. },
  35211. splitArea: {
  35212. show: false,
  35213. areaStyle: {
  35214. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  35215. }
  35216. }
  35217. };
  35218. var axisDefault = {};
  35219. axisDefault.categoryAxis = merge({
  35220. // The gap at both ends of the axis. For categoryAxis, boolean.
  35221. boundaryGap: true,
  35222. // Set false to faster category collection.
  35223. // Only usefull in the case like: category is
  35224. // ['2012-01-01', '2012-01-02', ...], where the input
  35225. // data has been ensured not duplicate and is large data.
  35226. // null means "auto":
  35227. // if axis.data provided, do not deduplication,
  35228. // else do deduplication.
  35229. deduplication: null,
  35230. // splitArea: {
  35231. // show: false
  35232. // },
  35233. splitLine: {
  35234. show: false
  35235. },
  35236. axisTick: {
  35237. // If tick is align with label when boundaryGap is true
  35238. alignWithLabel: false,
  35239. interval: 'auto'
  35240. },
  35241. axisLabel: {
  35242. interval: 'auto'
  35243. }
  35244. }, defaultOption);
  35245. axisDefault.valueAxis = merge({
  35246. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  35247. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  35248. boundaryGap: [0, 0],
  35249. // TODO
  35250. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  35251. // Min value of the axis. can be:
  35252. // + a number
  35253. // + 'dataMin': use the min value in data.
  35254. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  35255. // min: null,
  35256. // Max value of the axis. can be:
  35257. // + a number
  35258. // + 'dataMax': use the max value in data.
  35259. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  35260. // max: null,
  35261. // Readonly prop, specifies start value of the range when using data zoom.
  35262. // rangeStart: null
  35263. // Readonly prop, specifies end value of the range when using data zoom.
  35264. // rangeEnd: null
  35265. // Optional value can be:
  35266. // + `false`: always include value 0.
  35267. // + `true`: the extent do not consider value 0.
  35268. // scale: false,
  35269. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  35270. splitNumber: 5,
  35271. // Interval specifies the span of the ticks is mandatorily.
  35272. // interval: null
  35273. // Specify min interval when auto calculate tick interval.
  35274. // minInterval: null
  35275. // Specify max interval when auto calculate tick interval.
  35276. // maxInterval: null
  35277. minorTick: {
  35278. // Minor tick, not available for cateogry axis.
  35279. show: false,
  35280. // Split number of minor ticks. The value should be in range of (0, 100)
  35281. splitNumber: 5,
  35282. // Lenght of minor tick
  35283. length: 3,
  35284. // Same inside with axisTick
  35285. // Line style
  35286. lineStyle: {
  35287. // Default to be same with axisTick
  35288. }
  35289. },
  35290. minorSplitLine: {
  35291. show: false,
  35292. lineStyle: {
  35293. color: '#eee',
  35294. width: 1
  35295. }
  35296. }
  35297. }, defaultOption);
  35298. axisDefault.timeAxis = defaults({
  35299. scale: true,
  35300. min: 'dataMin',
  35301. max: 'dataMax'
  35302. }, axisDefault.valueAxis);
  35303. axisDefault.logAxis = defaults({
  35304. scale: true,
  35305. logBase: 10
  35306. }, axisDefault.valueAxis);
  35307. /*
  35308. * Licensed to the Apache Software Foundation (ASF) under one
  35309. * or more contributor license agreements. See the NOTICE file
  35310. * distributed with this work for additional information
  35311. * regarding copyright ownership. The ASF licenses this file
  35312. * to you under the Apache License, Version 2.0 (the
  35313. * "License"); you may not use this file except in compliance
  35314. * with the License. You may obtain a copy of the License at
  35315. *
  35316. * http://www.apache.org/licenses/LICENSE-2.0
  35317. *
  35318. * Unless required by applicable law or agreed to in writing,
  35319. * software distributed under the License is distributed on an
  35320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35321. * KIND, either express or implied. See the License for the
  35322. * specific language governing permissions and limitations
  35323. * under the License.
  35324. */
  35325. // FIXME axisType is fixed ?
  35326. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  35327. /**
  35328. * Generate sub axis model class
  35329. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  35330. * @param {module:echarts/model/Component} BaseAxisModelClass
  35331. * @param {Function} axisTypeDefaulter
  35332. * @param {Object} [extraDefaultOption]
  35333. */
  35334. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  35335. each$1(AXIS_TYPES, function (axisType) {
  35336. BaseAxisModelClass.extend({
  35337. /**
  35338. * @readOnly
  35339. */
  35340. type: axisName + 'Axis.' + axisType,
  35341. mergeDefaultAndTheme: function (option, ecModel) {
  35342. var layoutMode = this.layoutMode;
  35343. var inputPositionParams = layoutMode
  35344. ? getLayoutParams(option) : {};
  35345. var themeModel = ecModel.getTheme();
  35346. merge(option, themeModel.get(axisType + 'Axis'));
  35347. merge(option, this.getDefaultOption());
  35348. option.type = axisTypeDefaulter(axisName, option);
  35349. if (layoutMode) {
  35350. mergeLayoutParam(option, inputPositionParams, layoutMode);
  35351. }
  35352. },
  35353. /**
  35354. * @override
  35355. */
  35356. optionUpdated: function () {
  35357. var thisOption = this.option;
  35358. if (thisOption.type === 'category') {
  35359. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  35360. }
  35361. },
  35362. /**
  35363. * Should not be called before all of 'getInitailData' finished.
  35364. * Because categories are collected during initializing data.
  35365. */
  35366. getCategories: function (rawData) {
  35367. var option = this.option;
  35368. // FIXME
  35369. // warning if called before all of 'getInitailData' finished.
  35370. if (option.type === 'category') {
  35371. if (rawData) {
  35372. return option.data;
  35373. }
  35374. return this.__ordinalMeta.categories;
  35375. }
  35376. },
  35377. getOrdinalMeta: function () {
  35378. return this.__ordinalMeta;
  35379. },
  35380. defaultOption: mergeAll(
  35381. [
  35382. {},
  35383. axisDefault[axisType + 'Axis'],
  35384. extraDefaultOption
  35385. ],
  35386. true
  35387. )
  35388. });
  35389. });
  35390. ComponentModel.registerSubTypeDefaulter(
  35391. axisName + 'Axis',
  35392. curry(axisTypeDefaulter, axisName)
  35393. );
  35394. };
  35395. /*
  35396. * Licensed to the Apache Software Foundation (ASF) under one
  35397. * or more contributor license agreements. See the NOTICE file
  35398. * distributed with this work for additional information
  35399. * regarding copyright ownership. The ASF licenses this file
  35400. * to you under the Apache License, Version 2.0 (the
  35401. * "License"); you may not use this file except in compliance
  35402. * with the License. You may obtain a copy of the License at
  35403. *
  35404. * http://www.apache.org/licenses/LICENSE-2.0
  35405. *
  35406. * Unless required by applicable law or agreed to in writing,
  35407. * software distributed under the License is distributed on an
  35408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35409. * KIND, either express or implied. See the License for the
  35410. * specific language governing permissions and limitations
  35411. * under the License.
  35412. */
  35413. var AxisModel = ComponentModel.extend({
  35414. type: 'cartesian2dAxis',
  35415. /**
  35416. * @type {module:echarts/coord/cartesian/Axis2D}
  35417. */
  35418. axis: null,
  35419. /**
  35420. * @override
  35421. */
  35422. init: function () {
  35423. AxisModel.superApply(this, 'init', arguments);
  35424. this.resetRange();
  35425. },
  35426. /**
  35427. * @override
  35428. */
  35429. mergeOption: function () {
  35430. AxisModel.superApply(this, 'mergeOption', arguments);
  35431. this.resetRange();
  35432. },
  35433. /**
  35434. * @override
  35435. */
  35436. restoreData: function () {
  35437. AxisModel.superApply(this, 'restoreData', arguments);
  35438. this.resetRange();
  35439. },
  35440. /**
  35441. * @override
  35442. * @return {module:echarts/model/Component}
  35443. */
  35444. getCoordSysModel: function () {
  35445. return this.ecModel.queryComponents({
  35446. mainType: 'grid',
  35447. index: this.option.gridIndex,
  35448. id: this.option.gridId
  35449. })[0];
  35450. }
  35451. });
  35452. function getAxisType(axisDim, option) {
  35453. // Default axis with data is category axis
  35454. return option.type || (option.data ? 'category' : 'value');
  35455. }
  35456. merge(AxisModel.prototype, axisModelCommonMixin);
  35457. var extraOption = {
  35458. // gridIndex: 0,
  35459. // gridId: '',
  35460. // Offset is for multiple axis on the same position
  35461. offset: 0
  35462. };
  35463. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  35464. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  35465. /*
  35466. * Licensed to the Apache Software Foundation (ASF) under one
  35467. * or more contributor license agreements. See the NOTICE file
  35468. * distributed with this work for additional information
  35469. * regarding copyright ownership. The ASF licenses this file
  35470. * to you under the Apache License, Version 2.0 (the
  35471. * "License"); you may not use this file except in compliance
  35472. * with the License. You may obtain a copy of the License at
  35473. *
  35474. * http://www.apache.org/licenses/LICENSE-2.0
  35475. *
  35476. * Unless required by applicable law or agreed to in writing,
  35477. * software distributed under the License is distributed on an
  35478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35479. * KIND, either express or implied. See the License for the
  35480. * specific language governing permissions and limitations
  35481. * under the License.
  35482. */
  35483. // Grid 是在有直角坐标系的时候必须要存在的
  35484. // 所以这里也要被 Cartesian2D 依赖
  35485. ComponentModel.extend({
  35486. type: 'grid',
  35487. dependencies: ['xAxis', 'yAxis'],
  35488. layoutMode: 'box',
  35489. /**
  35490. * @type {module:echarts/coord/cartesian/Grid}
  35491. */
  35492. coordinateSystem: null,
  35493. defaultOption: {
  35494. show: false,
  35495. zlevel: 0,
  35496. z: 0,
  35497. left: '10%',
  35498. top: 60,
  35499. right: '10%',
  35500. bottom: 60,
  35501. // If grid size contain label
  35502. containLabel: false,
  35503. // width: {totalWidth} - left - right,
  35504. // height: {totalHeight} - top - bottom,
  35505. backgroundColor: 'rgba(0,0,0,0)',
  35506. borderWidth: 1,
  35507. borderColor: '#ccc'
  35508. }
  35509. });
  35510. /*
  35511. * Licensed to the Apache Software Foundation (ASF) under one
  35512. * or more contributor license agreements. See the NOTICE file
  35513. * distributed with this work for additional information
  35514. * regarding copyright ownership. The ASF licenses this file
  35515. * to you under the Apache License, Version 2.0 (the
  35516. * "License"); you may not use this file except in compliance
  35517. * with the License. You may obtain a copy of the License at
  35518. *
  35519. * http://www.apache.org/licenses/LICENSE-2.0
  35520. *
  35521. * Unless required by applicable law or agreed to in writing,
  35522. * software distributed under the License is distributed on an
  35523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35524. * KIND, either express or implied. See the License for the
  35525. * specific language governing permissions and limitations
  35526. * under the License.
  35527. */
  35528. /**
  35529. * Grid is a region which contains at most 4 cartesian systems
  35530. *
  35531. * TODO Default cartesian
  35532. */
  35533. // Depends on GridModel, AxisModel, which performs preprocess.
  35534. /**
  35535. * Check if the axis is used in the specified grid
  35536. * @inner
  35537. */
  35538. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  35539. return axisModel.getCoordSysModel() === gridModel;
  35540. }
  35541. function Grid(gridModel, ecModel, api) {
  35542. /**
  35543. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  35544. * @private
  35545. */
  35546. this._coordsMap = {};
  35547. /**
  35548. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  35549. * @private
  35550. */
  35551. this._coordsList = [];
  35552. /**
  35553. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  35554. * @private
  35555. */
  35556. this._axesMap = {};
  35557. /**
  35558. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  35559. * @private
  35560. */
  35561. this._axesList = [];
  35562. this._initCartesian(gridModel, ecModel, api);
  35563. this.model = gridModel;
  35564. }
  35565. var gridProto = Grid.prototype;
  35566. gridProto.type = 'grid';
  35567. gridProto.axisPointerEnabled = true;
  35568. gridProto.getRect = function () {
  35569. return this._rect;
  35570. };
  35571. gridProto.update = function (ecModel, api) {
  35572. var axesMap = this._axesMap;
  35573. this._updateScale(ecModel, this.model);
  35574. each$1(axesMap.x, function (xAxis) {
  35575. niceScaleExtent(xAxis.scale, xAxis.model);
  35576. });
  35577. each$1(axesMap.y, function (yAxis) {
  35578. niceScaleExtent(yAxis.scale, yAxis.model);
  35579. });
  35580. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  35581. var onZeroRecords = {};
  35582. each$1(axesMap.x, function (xAxis) {
  35583. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  35584. });
  35585. each$1(axesMap.y, function (yAxis) {
  35586. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  35587. });
  35588. // Resize again if containLabel is enabled
  35589. // FIXME It may cause getting wrong grid size in data processing stage
  35590. this.resize(this.model, api);
  35591. };
  35592. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  35593. axis.getAxesOnZeroOf = function () {
  35594. // TODO: onZero of multiple axes.
  35595. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  35596. };
  35597. // onZero can not be enabled in these two situations:
  35598. // 1. When any other axis is a category axis.
  35599. // 2. When no axis is cross 0 point.
  35600. var otherAxes = axesMap[otherAxisDim];
  35601. var otherAxisOnZeroOf;
  35602. var axisModel = axis.model;
  35603. var onZero = axisModel.get('axisLine.onZero');
  35604. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  35605. if (!onZero) {
  35606. return;
  35607. }
  35608. // If target axis is specified.
  35609. if (onZeroAxisIndex != null) {
  35610. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  35611. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  35612. }
  35613. }
  35614. else {
  35615. // Find the first available other axis.
  35616. for (var idx in otherAxes) {
  35617. if (otherAxes.hasOwnProperty(idx)
  35618. && canOnZeroToAxis(otherAxes[idx])
  35619. // Consider that two Y axes on one value axis,
  35620. // if both onZero, the two Y axes overlap.
  35621. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  35622. ) {
  35623. otherAxisOnZeroOf = otherAxes[idx];
  35624. break;
  35625. }
  35626. }
  35627. }
  35628. if (otherAxisOnZeroOf) {
  35629. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  35630. }
  35631. function getOnZeroRecordKey(axis) {
  35632. return axis.dim + '_' + axis.index;
  35633. }
  35634. }
  35635. function canOnZeroToAxis(axis) {
  35636. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  35637. }
  35638. /**
  35639. * Resize the grid
  35640. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35641. * @param {module:echarts/ExtensionAPI} api
  35642. */
  35643. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  35644. var gridRect = getLayoutRect(
  35645. gridModel.getBoxLayoutParams(), {
  35646. width: api.getWidth(),
  35647. height: api.getHeight()
  35648. });
  35649. this._rect = gridRect;
  35650. var axesList = this._axesList;
  35651. adjustAxes();
  35652. // Minus label size
  35653. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  35654. each$1(axesList, function (axis) {
  35655. if (!axis.model.get('axisLabel.inside')) {
  35656. var labelUnionRect = estimateLabelUnionRect(axis);
  35657. if (labelUnionRect) {
  35658. var dim = axis.isHorizontal() ? 'height' : 'width';
  35659. var margin = axis.model.get('axisLabel.margin');
  35660. gridRect[dim] -= labelUnionRect[dim] + margin;
  35661. if (axis.position === 'top') {
  35662. gridRect.y += labelUnionRect.height + margin;
  35663. }
  35664. else if (axis.position === 'left') {
  35665. gridRect.x += labelUnionRect.width + margin;
  35666. }
  35667. }
  35668. }
  35669. });
  35670. adjustAxes();
  35671. }
  35672. function adjustAxes() {
  35673. each$1(axesList, function (axis) {
  35674. var isHorizontal = axis.isHorizontal();
  35675. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  35676. var idx = axis.inverse ? 1 : 0;
  35677. axis.setExtent(extent[idx], extent[1 - idx]);
  35678. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  35679. });
  35680. }
  35681. };
  35682. /**
  35683. * @param {string} axisType
  35684. * @param {number} [axisIndex]
  35685. */
  35686. gridProto.getAxis = function (axisType, axisIndex) {
  35687. var axesMapOnDim = this._axesMap[axisType];
  35688. if (axesMapOnDim != null) {
  35689. if (axisIndex == null) {
  35690. // Find first axis
  35691. for (var name in axesMapOnDim) {
  35692. if (axesMapOnDim.hasOwnProperty(name)) {
  35693. return axesMapOnDim[name];
  35694. }
  35695. }
  35696. }
  35697. return axesMapOnDim[axisIndex];
  35698. }
  35699. };
  35700. /**
  35701. * @return {Array.<module:echarts/coord/Axis>}
  35702. */
  35703. gridProto.getAxes = function () {
  35704. return this._axesList.slice();
  35705. };
  35706. /**
  35707. * Usage:
  35708. * grid.getCartesian(xAxisIndex, yAxisIndex);
  35709. * grid.getCartesian(xAxisIndex);
  35710. * grid.getCartesian(null, yAxisIndex);
  35711. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  35712. *
  35713. * @param {number|Object} [xAxisIndex]
  35714. * @param {number} [yAxisIndex]
  35715. */
  35716. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  35717. if (xAxisIndex != null && yAxisIndex != null) {
  35718. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35719. return this._coordsMap[key];
  35720. }
  35721. if (isObject$1(xAxisIndex)) {
  35722. yAxisIndex = xAxisIndex.yAxisIndex;
  35723. xAxisIndex = xAxisIndex.xAxisIndex;
  35724. }
  35725. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  35726. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  35727. if (coordList[i].getAxis('x').index === xAxisIndex
  35728. || coordList[i].getAxis('y').index === yAxisIndex
  35729. ) {
  35730. return coordList[i];
  35731. }
  35732. }
  35733. };
  35734. gridProto.getCartesians = function () {
  35735. return this._coordsList.slice();
  35736. };
  35737. /**
  35738. * @implements
  35739. * see {module:echarts/CoodinateSystem}
  35740. */
  35741. gridProto.convertToPixel = function (ecModel, finder, value) {
  35742. var target = this._findConvertTarget(ecModel, finder);
  35743. return target.cartesian
  35744. ? target.cartesian.dataToPoint(value)
  35745. : target.axis
  35746. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  35747. : null;
  35748. };
  35749. /**
  35750. * @implements
  35751. * see {module:echarts/CoodinateSystem}
  35752. */
  35753. gridProto.convertFromPixel = function (ecModel, finder, value) {
  35754. var target = this._findConvertTarget(ecModel, finder);
  35755. return target.cartesian
  35756. ? target.cartesian.pointToData(value)
  35757. : target.axis
  35758. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  35759. : null;
  35760. };
  35761. /**
  35762. * @inner
  35763. */
  35764. gridProto._findConvertTarget = function (ecModel, finder) {
  35765. var seriesModel = finder.seriesModel;
  35766. var xAxisModel = finder.xAxisModel
  35767. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  35768. var yAxisModel = finder.yAxisModel
  35769. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  35770. var gridModel = finder.gridModel;
  35771. var coordsList = this._coordsList;
  35772. var cartesian;
  35773. var axis;
  35774. if (seriesModel) {
  35775. cartesian = seriesModel.coordinateSystem;
  35776. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  35777. }
  35778. else if (xAxisModel && yAxisModel) {
  35779. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  35780. }
  35781. else if (xAxisModel) {
  35782. axis = this.getAxis('x', xAxisModel.componentIndex);
  35783. }
  35784. else if (yAxisModel) {
  35785. axis = this.getAxis('y', yAxisModel.componentIndex);
  35786. }
  35787. // Lowest priority.
  35788. else if (gridModel) {
  35789. var grid = gridModel.coordinateSystem;
  35790. if (grid === this) {
  35791. cartesian = this._coordsList[0];
  35792. }
  35793. }
  35794. return {cartesian: cartesian, axis: axis};
  35795. };
  35796. /**
  35797. * @implements
  35798. * see {module:echarts/CoodinateSystem}
  35799. */
  35800. gridProto.containPoint = function (point) {
  35801. var coord = this._coordsList[0];
  35802. if (coord) {
  35803. return coord.containPoint(point);
  35804. }
  35805. };
  35806. /**
  35807. * Initialize cartesian coordinate systems
  35808. * @private
  35809. */
  35810. gridProto._initCartesian = function (gridModel, ecModel, api) {
  35811. var axisPositionUsed = {
  35812. left: false,
  35813. right: false,
  35814. top: false,
  35815. bottom: false
  35816. };
  35817. var axesMap = {
  35818. x: {},
  35819. y: {}
  35820. };
  35821. var axesCount = {
  35822. x: 0,
  35823. y: 0
  35824. };
  35825. /// Create axis
  35826. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  35827. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  35828. if (!axesCount.x || !axesCount.y) {
  35829. // Roll back when there no either x or y axis
  35830. this._axesMap = {};
  35831. this._axesList = [];
  35832. return;
  35833. }
  35834. this._axesMap = axesMap;
  35835. /// Create cartesian2d
  35836. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  35837. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  35838. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  35839. var cartesian = new Cartesian2D(key);
  35840. cartesian.grid = this;
  35841. cartesian.model = gridModel;
  35842. this._coordsMap[key] = cartesian;
  35843. this._coordsList.push(cartesian);
  35844. cartesian.addAxis(xAxis);
  35845. cartesian.addAxis(yAxis);
  35846. }, this);
  35847. }, this);
  35848. function createAxisCreator(axisType) {
  35849. return function (axisModel, idx) {
  35850. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  35851. return;
  35852. }
  35853. var axisPosition = axisModel.get('position');
  35854. if (axisType === 'x') {
  35855. // Fix position
  35856. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  35857. // Default bottom of X
  35858. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  35859. }
  35860. }
  35861. else {
  35862. // Fix position
  35863. if (axisPosition !== 'left' && axisPosition !== 'right') {
  35864. // Default left of Y
  35865. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  35866. }
  35867. }
  35868. axisPositionUsed[axisPosition] = true;
  35869. var axis = new Axis2D(
  35870. axisType, createScaleByModel(axisModel),
  35871. [0, 0],
  35872. axisModel.get('type'),
  35873. axisPosition
  35874. );
  35875. var isCategory = axis.type === 'category';
  35876. axis.onBand = isCategory && axisModel.get('boundaryGap');
  35877. axis.inverse = axisModel.get('inverse');
  35878. // Inject axis into axisModel
  35879. axisModel.axis = axis;
  35880. // Inject axisModel into axis
  35881. axis.model = axisModel;
  35882. // Inject grid info axis
  35883. axis.grid = this;
  35884. // Index of axis, can be used as key
  35885. axis.index = idx;
  35886. this._axesList.push(axis);
  35887. axesMap[axisType][idx] = axis;
  35888. axesCount[axisType]++;
  35889. };
  35890. }
  35891. };
  35892. /**
  35893. * Update cartesian properties from series
  35894. * @param {module:echarts/model/Option} option
  35895. * @private
  35896. */
  35897. gridProto._updateScale = function (ecModel, gridModel) {
  35898. // Reset scale
  35899. each$1(this._axesList, function (axis) {
  35900. axis.scale.setExtent(Infinity, -Infinity);
  35901. });
  35902. ecModel.eachSeries(function (seriesModel) {
  35903. if (isCartesian2D(seriesModel)) {
  35904. var axesModels = findAxesModels(seriesModel, ecModel);
  35905. var xAxisModel = axesModels[0];
  35906. var yAxisModel = axesModels[1];
  35907. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  35908. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  35909. ) {
  35910. return;
  35911. }
  35912. var cartesian = this.getCartesian(
  35913. xAxisModel.componentIndex, yAxisModel.componentIndex
  35914. );
  35915. var data = seriesModel.getData();
  35916. var xAxis = cartesian.getAxis('x');
  35917. var yAxis = cartesian.getAxis('y');
  35918. if (data.type === 'list') {
  35919. unionExtent(data, xAxis, seriesModel);
  35920. unionExtent(data, yAxis, seriesModel);
  35921. }
  35922. }
  35923. }, this);
  35924. function unionExtent(data, axis, seriesModel) {
  35925. each$1(data.mapDimension(axis.dim, true), function (dim) {
  35926. axis.scale.unionExtentFromData(
  35927. // For example, the extent of the orginal dimension
  35928. // is [0.1, 0.5], the extent of the `stackResultDimension`
  35929. // is [7, 9], the final extent should not include [0.1, 0.5].
  35930. data, getStackedDimension(data, dim)
  35931. );
  35932. });
  35933. }
  35934. };
  35935. /**
  35936. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  35937. * @return {Object} {baseAxes: [], otherAxes: []}
  35938. */
  35939. gridProto.getTooltipAxes = function (dim) {
  35940. var baseAxes = [];
  35941. var otherAxes = [];
  35942. each$1(this.getCartesians(), function (cartesian) {
  35943. var baseAxis = (dim != null && dim !== 'auto')
  35944. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  35945. var otherAxis = cartesian.getOtherAxis(baseAxis);
  35946. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  35947. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  35948. });
  35949. return {baseAxes: baseAxes, otherAxes: otherAxes};
  35950. };
  35951. /**
  35952. * @inner
  35953. */
  35954. function updateAxisTransform(axis, coordBase) {
  35955. var axisExtent = axis.getExtent();
  35956. var axisExtentSum = axisExtent[0] + axisExtent[1];
  35957. // Fast transform
  35958. axis.toGlobalCoord = axis.dim === 'x'
  35959. ? function (coord) {
  35960. return coord + coordBase;
  35961. }
  35962. : function (coord) {
  35963. return axisExtentSum - coord + coordBase;
  35964. };
  35965. axis.toLocalCoord = axis.dim === 'x'
  35966. ? function (coord) {
  35967. return coord - coordBase;
  35968. }
  35969. : function (coord) {
  35970. return axisExtentSum - coord + coordBase;
  35971. };
  35972. }
  35973. var axesTypes = ['xAxis', 'yAxis'];
  35974. /**
  35975. * @inner
  35976. */
  35977. function findAxesModels(seriesModel, ecModel) {
  35978. return map(axesTypes, function (axisType) {
  35979. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  35980. if (__DEV__) {
  35981. if (!axisModel) {
  35982. throw new Error(axisType + ' "' + retrieve(
  35983. seriesModel.get(axisType + 'Index'),
  35984. seriesModel.get(axisType + 'Id'),
  35985. 0
  35986. ) + '" not found');
  35987. }
  35988. }
  35989. return axisModel;
  35990. });
  35991. }
  35992. /**
  35993. * @inner
  35994. */
  35995. function isCartesian2D(seriesModel) {
  35996. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  35997. }
  35998. Grid.create = function (ecModel, api) {
  35999. var grids = [];
  36000. ecModel.eachComponent('grid', function (gridModel, idx) {
  36001. var grid = new Grid(gridModel, ecModel, api);
  36002. grid.name = 'grid_' + idx;
  36003. // dataSampling requires axis extent, so resize
  36004. // should be performed in create stage.
  36005. grid.resize(gridModel, api, true);
  36006. gridModel.coordinateSystem = grid;
  36007. grids.push(grid);
  36008. });
  36009. // Inject the coordinateSystems into seriesModel
  36010. ecModel.eachSeries(function (seriesModel) {
  36011. if (!isCartesian2D(seriesModel)) {
  36012. return;
  36013. }
  36014. var axesModels = findAxesModels(seriesModel, ecModel);
  36015. var xAxisModel = axesModels[0];
  36016. var yAxisModel = axesModels[1];
  36017. var gridModel = xAxisModel.getCoordSysModel();
  36018. if (__DEV__) {
  36019. if (!gridModel) {
  36020. throw new Error(
  36021. 'Grid "' + retrieve(
  36022. xAxisModel.get('gridIndex'),
  36023. xAxisModel.get('gridId'),
  36024. 0
  36025. ) + '" not found'
  36026. );
  36027. }
  36028. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  36029. throw new Error('xAxis and yAxis must use the same grid');
  36030. }
  36031. }
  36032. var grid = gridModel.coordinateSystem;
  36033. seriesModel.coordinateSystem = grid.getCartesian(
  36034. xAxisModel.componentIndex, yAxisModel.componentIndex
  36035. );
  36036. });
  36037. return grids;
  36038. };
  36039. // For deciding which dimensions to use when creating list data
  36040. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  36041. CoordinateSystemManager.register('cartesian2d', Grid);
  36042. /*
  36043. * Licensed to the Apache Software Foundation (ASF) under one
  36044. * or more contributor license agreements. See the NOTICE file
  36045. * distributed with this work for additional information
  36046. * regarding copyright ownership. The ASF licenses this file
  36047. * to you under the Apache License, Version 2.0 (the
  36048. * "License"); you may not use this file except in compliance
  36049. * with the License. You may obtain a copy of the License at
  36050. *
  36051. * http://www.apache.org/licenses/LICENSE-2.0
  36052. *
  36053. * Unless required by applicable law or agreed to in writing,
  36054. * software distributed under the License is distributed on an
  36055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36056. * KIND, either express or implied. See the License for the
  36057. * specific language governing permissions and limitations
  36058. * under the License.
  36059. */
  36060. var PI$2 = Math.PI;
  36061. /**
  36062. * A final axis is translated and rotated from a "standard axis".
  36063. * So opt.position and opt.rotation is required.
  36064. *
  36065. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  36066. * for example: (0, 0) ------------> (0, 50)
  36067. *
  36068. * nameDirection or tickDirection or labelDirection is 1 means tick
  36069. * or label is below the standard axis, whereas is -1 means above
  36070. * the standard axis. labelOffset means offset between label and axis,
  36071. * which is useful when 'onZero', where axisLabel is in the grid and
  36072. * label in outside grid.
  36073. *
  36074. * Tips: like always,
  36075. * positive rotation represents anticlockwise, and negative rotation
  36076. * represents clockwise.
  36077. * The direction of position coordinate is the same as the direction
  36078. * of screen coordinate.
  36079. *
  36080. * Do not need to consider axis 'inverse', which is auto processed by
  36081. * axis extent.
  36082. *
  36083. * @param {module:zrender/container/Group} group
  36084. * @param {Object} axisModel
  36085. * @param {Object} opt Standard axis parameters.
  36086. * @param {Array.<number>} opt.position [x, y]
  36087. * @param {number} opt.rotation by radian
  36088. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  36089. * @param {number} [opt.tickDirection=1] 1 or -1
  36090. * @param {number} [opt.labelDirection=1] 1 or -1
  36091. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  36092. * @param {string} [opt.axisLabelShow] default get from axisModel.
  36093. * @param {string} [opt.axisName] default get from axisModel.
  36094. * @param {number} [opt.axisNameAvailableWidth]
  36095. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  36096. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  36097. * @param {number} [opt.nameTruncateMaxWidth]
  36098. */
  36099. var AxisBuilder = function (axisModel, opt) {
  36100. /**
  36101. * @readOnly
  36102. */
  36103. this.opt = opt;
  36104. /**
  36105. * @readOnly
  36106. */
  36107. this.axisModel = axisModel;
  36108. // Default value
  36109. defaults(
  36110. opt,
  36111. {
  36112. labelOffset: 0,
  36113. nameDirection: 1,
  36114. tickDirection: 1,
  36115. labelDirection: 1,
  36116. silent: true
  36117. }
  36118. );
  36119. /**
  36120. * @readOnly
  36121. */
  36122. this.group = new Group();
  36123. // FIXME Not use a seperate text group?
  36124. var dumbGroup = new Group({
  36125. position: opt.position.slice(),
  36126. rotation: opt.rotation
  36127. });
  36128. // this.group.add(dumbGroup);
  36129. // this._dumbGroup = dumbGroup;
  36130. dumbGroup.updateTransform();
  36131. this._transform = dumbGroup.transform;
  36132. this._dumbGroup = dumbGroup;
  36133. };
  36134. AxisBuilder.prototype = {
  36135. constructor: AxisBuilder,
  36136. hasBuilder: function (name) {
  36137. return !!builders[name];
  36138. },
  36139. add: function (name) {
  36140. builders[name].call(this);
  36141. },
  36142. getGroup: function () {
  36143. return this.group;
  36144. }
  36145. };
  36146. var builders = {
  36147. /**
  36148. * @private
  36149. */
  36150. axisLine: function () {
  36151. var opt = this.opt;
  36152. var axisModel = this.axisModel;
  36153. if (!axisModel.get('axisLine.show')) {
  36154. return;
  36155. }
  36156. var extent = this.axisModel.axis.getExtent();
  36157. var matrix = this._transform;
  36158. var pt1 = [extent[0], 0];
  36159. var pt2 = [extent[1], 0];
  36160. if (matrix) {
  36161. applyTransform(pt1, pt1, matrix);
  36162. applyTransform(pt2, pt2, matrix);
  36163. }
  36164. var lineStyle = extend(
  36165. {
  36166. lineCap: 'round'
  36167. },
  36168. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  36169. );
  36170. this.group.add(new Line({
  36171. // Id for animation
  36172. anid: 'line',
  36173. subPixelOptimize: true,
  36174. shape: {
  36175. x1: pt1[0],
  36176. y1: pt1[1],
  36177. x2: pt2[0],
  36178. y2: pt2[1]
  36179. },
  36180. style: lineStyle,
  36181. strokeContainThreshold: opt.strokeContainThreshold || 5,
  36182. silent: true,
  36183. z2: 1
  36184. }));
  36185. var arrows = axisModel.get('axisLine.symbol');
  36186. var arrowSize = axisModel.get('axisLine.symbolSize');
  36187. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  36188. if (typeof arrowOffset === 'number') {
  36189. arrowOffset = [arrowOffset, arrowOffset];
  36190. }
  36191. if (arrows != null) {
  36192. if (typeof arrows === 'string') {
  36193. // Use the same arrow for start and end point
  36194. arrows = [arrows, arrows];
  36195. }
  36196. if (typeof arrowSize === 'string'
  36197. || typeof arrowSize === 'number'
  36198. ) {
  36199. // Use the same size for width and height
  36200. arrowSize = [arrowSize, arrowSize];
  36201. }
  36202. var symbolWidth = arrowSize[0];
  36203. var symbolHeight = arrowSize[1];
  36204. each$1([{
  36205. rotate: opt.rotation + Math.PI / 2,
  36206. offset: arrowOffset[0],
  36207. r: 0
  36208. }, {
  36209. rotate: opt.rotation - Math.PI / 2,
  36210. offset: arrowOffset[1],
  36211. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  36212. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  36213. }], function (point, index) {
  36214. if (arrows[index] !== 'none' && arrows[index] != null) {
  36215. var symbol = createSymbol(
  36216. arrows[index],
  36217. -symbolWidth / 2,
  36218. -symbolHeight / 2,
  36219. symbolWidth,
  36220. symbolHeight,
  36221. lineStyle.stroke,
  36222. true
  36223. );
  36224. // Calculate arrow position with offset
  36225. var r = point.r + point.offset;
  36226. var pos = [
  36227. pt1[0] + r * Math.cos(opt.rotation),
  36228. pt1[1] - r * Math.sin(opt.rotation)
  36229. ];
  36230. symbol.attr({
  36231. rotation: point.rotate,
  36232. position: pos,
  36233. silent: true,
  36234. z2: 11
  36235. });
  36236. this.group.add(symbol);
  36237. }
  36238. }, this);
  36239. }
  36240. },
  36241. /**
  36242. * @private
  36243. */
  36244. axisTickLabel: function () {
  36245. var axisModel = this.axisModel;
  36246. var opt = this.opt;
  36247. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  36248. var labelEls = buildAxisLabel(this, axisModel, opt);
  36249. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  36250. buildAxisMinorTicks(this, axisModel, opt);
  36251. },
  36252. /**
  36253. * @private
  36254. */
  36255. axisName: function () {
  36256. var opt = this.opt;
  36257. var axisModel = this.axisModel;
  36258. var name = retrieve(opt.axisName, axisModel.get('name'));
  36259. if (!name) {
  36260. return;
  36261. }
  36262. var nameLocation = axisModel.get('nameLocation');
  36263. var nameDirection = opt.nameDirection;
  36264. var textStyleModel = axisModel.getModel('nameTextStyle');
  36265. var gap = axisModel.get('nameGap') || 0;
  36266. var extent = this.axisModel.axis.getExtent();
  36267. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  36268. var pos = [
  36269. nameLocation === 'start'
  36270. ? extent[0] - gapSignal * gap
  36271. : nameLocation === 'end'
  36272. ? extent[1] + gapSignal * gap
  36273. : (extent[0] + extent[1]) / 2, // 'middle'
  36274. // Reuse labelOffset.
  36275. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  36276. ];
  36277. var labelLayout;
  36278. var nameRotation = axisModel.get('nameRotate');
  36279. if (nameRotation != null) {
  36280. nameRotation = nameRotation * PI$2 / 180; // To radian.
  36281. }
  36282. var axisNameAvailableWidth;
  36283. if (isNameLocationCenter(nameLocation)) {
  36284. labelLayout = innerTextLayout(
  36285. opt.rotation,
  36286. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  36287. nameDirection
  36288. );
  36289. }
  36290. else {
  36291. labelLayout = endTextLayout(
  36292. opt, nameLocation, nameRotation || 0, extent
  36293. );
  36294. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  36295. if (axisNameAvailableWidth != null) {
  36296. axisNameAvailableWidth = Math.abs(
  36297. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  36298. );
  36299. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  36300. }
  36301. }
  36302. var textFont = textStyleModel.getFont();
  36303. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  36304. var ellipsis = truncateOpt.ellipsis;
  36305. var maxWidth = retrieve(
  36306. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  36307. );
  36308. // FIXME
  36309. // truncate rich text? (consider performance)
  36310. var truncatedText = (ellipsis != null && maxWidth != null)
  36311. ? truncateText$1(
  36312. name, maxWidth, textFont, ellipsis,
  36313. {minChar: 2, placeholder: truncateOpt.placeholder}
  36314. )
  36315. : name;
  36316. var tooltipOpt = axisModel.get('tooltip', true);
  36317. var mainType = axisModel.mainType;
  36318. var formatterParams = {
  36319. componentType: mainType,
  36320. name: name,
  36321. $vars: ['name']
  36322. };
  36323. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  36324. var textEl = new Text({
  36325. // Id for animation
  36326. anid: 'name',
  36327. __fullText: name,
  36328. __truncatedText: truncatedText,
  36329. position: pos,
  36330. rotation: labelLayout.rotation,
  36331. silent: isLabelSilent(axisModel),
  36332. z2: 1,
  36333. tooltip: (tooltipOpt && tooltipOpt.show)
  36334. ? extend({
  36335. content: name,
  36336. formatter: function () {
  36337. return name;
  36338. },
  36339. formatterParams: formatterParams
  36340. }, tooltipOpt)
  36341. : null
  36342. });
  36343. setTextStyle(textEl.style, textStyleModel, {
  36344. text: truncatedText,
  36345. textFont: textFont,
  36346. textFill: textStyleModel.getTextColor()
  36347. || axisModel.get('axisLine.lineStyle.color'),
  36348. textAlign: textStyleModel.get('align')
  36349. || labelLayout.textAlign,
  36350. textVerticalAlign: textStyleModel.get('verticalAlign')
  36351. || labelLayout.textVerticalAlign
  36352. });
  36353. if (axisModel.get('triggerEvent')) {
  36354. textEl.eventData = makeAxisEventDataBase(axisModel);
  36355. textEl.eventData.targetType = 'axisName';
  36356. textEl.eventData.name = name;
  36357. }
  36358. // FIXME
  36359. this._dumbGroup.add(textEl);
  36360. textEl.updateTransform();
  36361. this.group.add(textEl);
  36362. textEl.decomposeTransform();
  36363. }
  36364. };
  36365. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  36366. var eventData = {
  36367. componentType: axisModel.mainType,
  36368. componentIndex: axisModel.componentIndex
  36369. };
  36370. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  36371. return eventData;
  36372. };
  36373. /**
  36374. * @public
  36375. * @static
  36376. * @param {Object} opt
  36377. * @param {number} axisRotation in radian
  36378. * @param {number} textRotation in radian
  36379. * @param {number} direction
  36380. * @return {Object} {
  36381. * rotation, // according to axis
  36382. * textAlign,
  36383. * textVerticalAlign
  36384. * }
  36385. */
  36386. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  36387. var rotationDiff = remRadian(textRotation - axisRotation);
  36388. var textAlign;
  36389. var textVerticalAlign;
  36390. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  36391. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  36392. textAlign = 'center';
  36393. }
  36394. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  36395. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  36396. textAlign = 'center';
  36397. }
  36398. else {
  36399. textVerticalAlign = 'middle';
  36400. if (rotationDiff > 0 && rotationDiff < PI$2) {
  36401. textAlign = direction > 0 ? 'right' : 'left';
  36402. }
  36403. else {
  36404. textAlign = direction > 0 ? 'left' : 'right';
  36405. }
  36406. }
  36407. return {
  36408. rotation: rotationDiff,
  36409. textAlign: textAlign,
  36410. textVerticalAlign: textVerticalAlign
  36411. };
  36412. };
  36413. function endTextLayout(opt, textPosition, textRotate, extent) {
  36414. var rotationDiff = remRadian(textRotate - opt.rotation);
  36415. var textAlign;
  36416. var textVerticalAlign;
  36417. var inverse = extent[0] > extent[1];
  36418. var onLeft = (textPosition === 'start' && !inverse)
  36419. || (textPosition !== 'start' && inverse);
  36420. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  36421. textVerticalAlign = onLeft ? 'bottom' : 'top';
  36422. textAlign = 'center';
  36423. }
  36424. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  36425. textVerticalAlign = onLeft ? 'top' : 'bottom';
  36426. textAlign = 'center';
  36427. }
  36428. else {
  36429. textVerticalAlign = 'middle';
  36430. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  36431. textAlign = onLeft ? 'left' : 'right';
  36432. }
  36433. else {
  36434. textAlign = onLeft ? 'right' : 'left';
  36435. }
  36436. }
  36437. return {
  36438. rotation: rotationDiff,
  36439. textAlign: textAlign,
  36440. textVerticalAlign: textVerticalAlign
  36441. };
  36442. }
  36443. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  36444. var tooltipOpt = axisModel.get('tooltip');
  36445. return axisModel.get('silent')
  36446. // Consider mouse cursor, add these restrictions.
  36447. || !(
  36448. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  36449. );
  36450. };
  36451. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  36452. if (shouldShowAllLabels(axisModel.axis)) {
  36453. return;
  36454. }
  36455. // If min or max are user set, we need to check
  36456. // If the tick on min(max) are overlap on their neighbour tick
  36457. // If they are overlapped, we need to hide the min(max) tick label
  36458. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  36459. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  36460. // FIXME
  36461. // Have not consider onBand yet, where tick els is more than label els.
  36462. labelEls = labelEls || [];
  36463. tickEls = tickEls || [];
  36464. var firstLabel = labelEls[0];
  36465. var nextLabel = labelEls[1];
  36466. var lastLabel = labelEls[labelEls.length - 1];
  36467. var prevLabel = labelEls[labelEls.length - 2];
  36468. var firstTick = tickEls[0];
  36469. var nextTick = tickEls[1];
  36470. var lastTick = tickEls[tickEls.length - 1];
  36471. var prevTick = tickEls[tickEls.length - 2];
  36472. if (showMinLabel === false) {
  36473. ignoreEl(firstLabel);
  36474. ignoreEl(firstTick);
  36475. }
  36476. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  36477. if (showMinLabel) {
  36478. ignoreEl(nextLabel);
  36479. ignoreEl(nextTick);
  36480. }
  36481. else {
  36482. ignoreEl(firstLabel);
  36483. ignoreEl(firstTick);
  36484. }
  36485. }
  36486. if (showMaxLabel === false) {
  36487. ignoreEl(lastLabel);
  36488. ignoreEl(lastTick);
  36489. }
  36490. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  36491. if (showMaxLabel) {
  36492. ignoreEl(prevLabel);
  36493. ignoreEl(prevTick);
  36494. }
  36495. else {
  36496. ignoreEl(lastLabel);
  36497. ignoreEl(lastTick);
  36498. }
  36499. }
  36500. }
  36501. function ignoreEl(el) {
  36502. el && (el.ignore = true);
  36503. }
  36504. function isTwoLabelOverlapped(current, next, labelLayout) {
  36505. // current and next has the same rotation.
  36506. var firstRect = current && current.getBoundingRect().clone();
  36507. var nextRect = next && next.getBoundingRect().clone();
  36508. if (!firstRect || !nextRect) {
  36509. return;
  36510. }
  36511. // When checking intersect of two rotated labels, we use mRotationBack
  36512. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  36513. var mRotationBack = identity([]);
  36514. rotate(mRotationBack, mRotationBack, -current.rotation);
  36515. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  36516. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  36517. return firstRect.intersect(nextRect);
  36518. }
  36519. function isNameLocationCenter(nameLocation) {
  36520. return nameLocation === 'middle' || nameLocation === 'center';
  36521. }
  36522. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  36523. var tickEls = [];
  36524. var pt1 = [];
  36525. var pt2 = [];
  36526. for (var i = 0; i < ticksCoords.length; i++) {
  36527. var tickCoord = ticksCoords[i].coord;
  36528. pt1[0] = tickCoord;
  36529. pt1[1] = 0;
  36530. pt2[0] = tickCoord;
  36531. pt2[1] = tickEndCoord;
  36532. if (tickTransform) {
  36533. applyTransform(pt1, pt1, tickTransform);
  36534. applyTransform(pt2, pt2, tickTransform);
  36535. }
  36536. // Tick line, Not use group transform to have better line draw
  36537. var tickEl = new Line({
  36538. // Id for animation
  36539. anid: aniid + '_' + ticksCoords[i].tickValue,
  36540. subPixelOptimize: true,
  36541. shape: {
  36542. x1: pt1[0],
  36543. y1: pt1[1],
  36544. x2: pt2[0],
  36545. y2: pt2[1]
  36546. },
  36547. style: tickLineStyle,
  36548. z2: 2,
  36549. silent: true
  36550. });
  36551. tickEls.push(tickEl);
  36552. }
  36553. return tickEls;
  36554. }
  36555. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  36556. var axis = axisModel.axis;
  36557. var tickModel = axisModel.getModel('axisTick');
  36558. if (!tickModel.get('show') || axis.scale.isBlank()) {
  36559. return;
  36560. }
  36561. var lineStyleModel = tickModel.getModel('lineStyle');
  36562. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  36563. var ticksCoords = axis.getTicksCoords();
  36564. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  36565. lineStyleModel.getLineStyle(),
  36566. {
  36567. stroke: axisModel.get('axisLine.lineStyle.color')
  36568. }
  36569. ), 'ticks');
  36570. for (var i = 0; i < ticksEls.length; i++) {
  36571. axisBuilder.group.add(ticksEls[i]);
  36572. }
  36573. return ticksEls;
  36574. }
  36575. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  36576. var axis = axisModel.axis;
  36577. var minorTickModel = axisModel.getModel('minorTick');
  36578. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  36579. return;
  36580. }
  36581. var minorTicksCoords = axis.getMinorTicksCoords();
  36582. if (!minorTicksCoords.length) {
  36583. return;
  36584. }
  36585. var lineStyleModel = minorTickModel.getModel('lineStyle');
  36586. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  36587. var minorTickLineStyle = defaults(
  36588. lineStyleModel.getLineStyle(),
  36589. defaults(
  36590. axisModel.getModel('axisTick').getLineStyle(),
  36591. {
  36592. stroke: axisModel.get('axisLine.lineStyle.color')
  36593. }
  36594. )
  36595. );
  36596. for (var i = 0; i < minorTicksCoords.length; i++) {
  36597. var minorTicksEls = createTicks(
  36598. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  36599. );
  36600. for (var k = 0; k < minorTicksEls.length; k++) {
  36601. axisBuilder.group.add(minorTicksEls[k]);
  36602. }
  36603. }
  36604. }
  36605. function buildAxisLabel(axisBuilder, axisModel, opt) {
  36606. var axis = axisModel.axis;
  36607. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  36608. if (!show || axis.scale.isBlank()) {
  36609. return;
  36610. }
  36611. var labelModel = axisModel.getModel('axisLabel');
  36612. var labelMargin = labelModel.get('margin');
  36613. var labels = axis.getViewLabels();
  36614. // Special label rotate.
  36615. var labelRotation = (
  36616. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  36617. ) * PI$2 / 180;
  36618. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  36619. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  36620. var labelEls = [];
  36621. var silent = isLabelSilent(axisModel);
  36622. var triggerEvent = axisModel.get('triggerEvent');
  36623. each$1(labels, function (labelItem, index) {
  36624. var tickValue = labelItem.tickValue;
  36625. var formattedLabel = labelItem.formattedLabel;
  36626. var rawLabel = labelItem.rawLabel;
  36627. var itemLabelModel = labelModel;
  36628. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  36629. itemLabelModel = new Model(
  36630. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  36631. );
  36632. }
  36633. var textColor = itemLabelModel.getTextColor()
  36634. || axisModel.get('axisLine.lineStyle.color');
  36635. var tickCoord = axis.dataToCoord(tickValue);
  36636. var pos = [
  36637. tickCoord,
  36638. opt.labelOffset + opt.labelDirection * labelMargin
  36639. ];
  36640. var textEl = new Text({
  36641. // Id for animation
  36642. anid: 'label_' + tickValue,
  36643. position: pos,
  36644. rotation: labelLayout.rotation,
  36645. silent: silent,
  36646. z2: 10
  36647. });
  36648. setTextStyle(textEl.style, itemLabelModel, {
  36649. text: formattedLabel,
  36650. textAlign: itemLabelModel.getShallow('align', true)
  36651. || labelLayout.textAlign,
  36652. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  36653. || itemLabelModel.getShallow('baseline', true)
  36654. || labelLayout.textVerticalAlign,
  36655. textFill: typeof textColor === 'function'
  36656. ? textColor(
  36657. // (1) In category axis with data zoom, tick is not the original
  36658. // index of axis.data. So tick should not be exposed to user
  36659. // in category axis.
  36660. // (2) Compatible with previous version, which always use formatted label as
  36661. // input. But in interval scale the formatted label is like '223,445', which
  36662. // maked user repalce ','. So we modify it to return original val but remain
  36663. // it as 'string' to avoid error in replacing.
  36664. axis.type === 'category'
  36665. ? rawLabel
  36666. : axis.type === 'value'
  36667. ? tickValue + ''
  36668. : tickValue,
  36669. index
  36670. )
  36671. : textColor
  36672. });
  36673. // Pack data for mouse event
  36674. if (triggerEvent) {
  36675. textEl.eventData = makeAxisEventDataBase(axisModel);
  36676. textEl.eventData.targetType = 'axisLabel';
  36677. textEl.eventData.value = rawLabel;
  36678. }
  36679. // FIXME
  36680. axisBuilder._dumbGroup.add(textEl);
  36681. textEl.updateTransform();
  36682. labelEls.push(textEl);
  36683. axisBuilder.group.add(textEl);
  36684. textEl.decomposeTransform();
  36685. });
  36686. return labelEls;
  36687. }
  36688. /*
  36689. * Licensed to the Apache Software Foundation (ASF) under one
  36690. * or more contributor license agreements. See the NOTICE file
  36691. * distributed with this work for additional information
  36692. * regarding copyright ownership. The ASF licenses this file
  36693. * to you under the Apache License, Version 2.0 (the
  36694. * "License"); you may not use this file except in compliance
  36695. * with the License. You may obtain a copy of the License at
  36696. *
  36697. * http://www.apache.org/licenses/LICENSE-2.0
  36698. *
  36699. * Unless required by applicable law or agreed to in writing,
  36700. * software distributed under the License is distributed on an
  36701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36702. * KIND, either express or implied. See the License for the
  36703. * specific language governing permissions and limitations
  36704. * under the License.
  36705. */
  36706. var each$6 = each$1;
  36707. var curry$1 = curry;
  36708. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  36709. // allAxesInfo should be updated when setOption performed.
  36710. function collect(ecModel, api) {
  36711. var result = {
  36712. /**
  36713. * key: makeKey(axis.model)
  36714. * value: {
  36715. * axis,
  36716. * coordSys,
  36717. * axisPointerModel,
  36718. * triggerTooltip,
  36719. * involveSeries,
  36720. * snap,
  36721. * seriesModels,
  36722. * seriesDataCount
  36723. * }
  36724. */
  36725. axesInfo: {},
  36726. seriesInvolved: false,
  36727. /**
  36728. * key: makeKey(coordSys.model)
  36729. * value: Object: key makeKey(axis.model), value: axisInfo
  36730. */
  36731. coordSysAxesInfo: {},
  36732. coordSysMap: {}
  36733. };
  36734. collectAxesInfo(result, ecModel, api);
  36735. // Check seriesInvolved for performance, in case too many series in some chart.
  36736. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  36737. return result;
  36738. }
  36739. function collectAxesInfo(result, ecModel, api) {
  36740. var globalTooltipModel = ecModel.getComponent('tooltip');
  36741. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  36742. // links can only be set on global.
  36743. var linksOption = globalAxisPointerModel.get('link', true) || [];
  36744. var linkGroups = [];
  36745. // Collect axes info.
  36746. each$6(api.getCoordinateSystems(), function (coordSys) {
  36747. // Some coordinate system do not support axes, like geo.
  36748. if (!coordSys.axisPointerEnabled) {
  36749. return;
  36750. }
  36751. var coordSysKey = makeKey(coordSys.model);
  36752. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  36753. result.coordSysMap[coordSysKey] = coordSys;
  36754. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  36755. // for user. So we enable seting tooltip on coordSys model.
  36756. var coordSysModel = coordSys.model;
  36757. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  36758. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  36759. // If axis tooltip used, choose tooltip axis for each coordSys.
  36760. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  36761. if (coordSys.getTooltipAxes
  36762. && globalTooltipModel
  36763. // If tooltip.showContent is set as false, tooltip will not
  36764. // show but axisPointer will show as normal.
  36765. && baseTooltipModel.get('show')
  36766. ) {
  36767. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  36768. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  36769. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  36770. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  36771. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  36772. if (triggerAxis || cross) {
  36773. each$6(tooltipAxes.baseAxes, curry$1(
  36774. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  36775. ));
  36776. }
  36777. if (cross) {
  36778. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  36779. }
  36780. }
  36781. // fromTooltip: true | false | 'cross'
  36782. // triggerTooltip: true | false | null
  36783. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  36784. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  36785. var axisPointerShow = axisPointerModel.get('show');
  36786. if (!axisPointerShow || (
  36787. axisPointerShow === 'auto'
  36788. && !fromTooltip
  36789. && !isHandleTrigger(axisPointerModel)
  36790. )) {
  36791. return;
  36792. }
  36793. if (triggerTooltip == null) {
  36794. triggerTooltip = axisPointerModel.get('triggerTooltip');
  36795. }
  36796. axisPointerModel = fromTooltip
  36797. ? makeAxisPointerModel(
  36798. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  36799. fromTooltip, triggerTooltip
  36800. )
  36801. : axisPointerModel;
  36802. var snap = axisPointerModel.get('snap');
  36803. var key = makeKey(axis.model);
  36804. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  36805. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  36806. var axisInfo = result.axesInfo[key] = {
  36807. key: key,
  36808. axis: axis,
  36809. coordSys: coordSys,
  36810. axisPointerModel: axisPointerModel,
  36811. triggerTooltip: triggerTooltip,
  36812. involveSeries: involveSeries,
  36813. snap: snap,
  36814. useHandle: isHandleTrigger(axisPointerModel),
  36815. seriesModels: []
  36816. };
  36817. axesInfoInCoordSys[key] = axisInfo;
  36818. result.seriesInvolved |= involveSeries;
  36819. var groupIndex = getLinkGroupIndex(linksOption, axis);
  36820. if (groupIndex != null) {
  36821. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  36822. linkGroup.axesInfo[key] = axisInfo;
  36823. linkGroup.mapper = linksOption[groupIndex].mapper;
  36824. axisInfo.linkGroup = linkGroup;
  36825. }
  36826. }
  36827. });
  36828. }
  36829. function makeAxisPointerModel(
  36830. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  36831. ) {
  36832. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  36833. var volatileOption = {};
  36834. each$6(
  36835. [
  36836. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  36837. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  36838. ],
  36839. function (field) {
  36840. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  36841. }
  36842. );
  36843. // category axis do not auto snap, otherwise some tick that do not
  36844. // has value can not be hovered. value/time/log axis default snap if
  36845. // triggered from tooltip and trigger tooltip.
  36846. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  36847. // Compatibel with previous behavior, tooltip axis do not show label by default.
  36848. // Only these properties can be overrided from tooltip to axisPointer.
  36849. if (tooltipAxisPointerModel.get('type') === 'cross') {
  36850. volatileOption.type = 'line';
  36851. }
  36852. var labelOption = volatileOption.label || (volatileOption.label = {});
  36853. // Follow the convention, do not show label when triggered by tooltip by default.
  36854. labelOption.show == null && (labelOption.show = false);
  36855. if (fromTooltip === 'cross') {
  36856. // When 'cross', both axes show labels.
  36857. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  36858. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  36859. // If triggerTooltip, this is a base axis, which should better not use cross style
  36860. // (cross style is dashed by default)
  36861. if (!triggerTooltip) {
  36862. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  36863. crossStyle && defaults(labelOption, crossStyle.textStyle);
  36864. }
  36865. }
  36866. return axis.model.getModel(
  36867. 'axisPointer',
  36868. new Model(volatileOption, globalAxisPointerModel, ecModel)
  36869. );
  36870. }
  36871. function collectSeriesInfo(result, ecModel) {
  36872. // Prepare data for axis trigger
  36873. ecModel.eachSeries(function (seriesModel) {
  36874. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  36875. var coordSys = seriesModel.coordinateSystem;
  36876. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  36877. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  36878. if (!coordSys
  36879. || seriesTooltipTrigger === 'none'
  36880. || seriesTooltipTrigger === false
  36881. || seriesTooltipTrigger === 'item'
  36882. || seriesTooltipShow === false
  36883. || seriesModel.get('axisPointer.show', true) === false
  36884. ) {
  36885. return;
  36886. }
  36887. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  36888. var axis = axisInfo.axis;
  36889. if (coordSys.getAxis(axis.dim) === axis) {
  36890. axisInfo.seriesModels.push(seriesModel);
  36891. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  36892. axisInfo.seriesDataCount += seriesModel.getData().count();
  36893. }
  36894. });
  36895. }, this);
  36896. }
  36897. /**
  36898. * For example:
  36899. * {
  36900. * axisPointer: {
  36901. * links: [{
  36902. * xAxisIndex: [2, 4],
  36903. * yAxisIndex: 'all'
  36904. * }, {
  36905. * xAxisId: ['a5', 'a7'],
  36906. * xAxisName: 'xxx'
  36907. * }]
  36908. * }
  36909. * }
  36910. */
  36911. function getLinkGroupIndex(linksOption, axis) {
  36912. var axisModel = axis.model;
  36913. var dim = axis.dim;
  36914. for (var i = 0; i < linksOption.length; i++) {
  36915. var linkOption = linksOption[i] || {};
  36916. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  36917. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  36918. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  36919. ) {
  36920. return i;
  36921. }
  36922. }
  36923. }
  36924. function checkPropInLink(linkPropValue, axisPropValue) {
  36925. return linkPropValue === 'all'
  36926. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  36927. || linkPropValue === axisPropValue;
  36928. }
  36929. function fixValue(axisModel) {
  36930. var axisInfo = getAxisInfo(axisModel);
  36931. if (!axisInfo) {
  36932. return;
  36933. }
  36934. var axisPointerModel = axisInfo.axisPointerModel;
  36935. var scale = axisInfo.axis.scale;
  36936. var option = axisPointerModel.option;
  36937. var status = axisPointerModel.get('status');
  36938. var value = axisPointerModel.get('value');
  36939. // Parse init value for category and time axis.
  36940. if (value != null) {
  36941. value = scale.parse(value);
  36942. }
  36943. var useHandle = isHandleTrigger(axisPointerModel);
  36944. // If `handle` used, `axisPointer` will always be displayed, so value
  36945. // and status should be initialized.
  36946. if (status == null) {
  36947. option.status = useHandle ? 'show' : 'hide';
  36948. }
  36949. var extent = scale.getExtent().slice();
  36950. extent[0] > extent[1] && extent.reverse();
  36951. if (// Pick a value on axis when initializing.
  36952. value == null
  36953. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  36954. // where we should re-pick a value to keep `handle` displaying normally.
  36955. || value > extent[1]
  36956. ) {
  36957. // Make handle displayed on the end of the axis when init, which looks better.
  36958. value = extent[1];
  36959. }
  36960. if (value < extent[0]) {
  36961. value = extent[0];
  36962. }
  36963. option.value = value;
  36964. if (useHandle) {
  36965. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  36966. }
  36967. }
  36968. function getAxisInfo(axisModel) {
  36969. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  36970. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  36971. }
  36972. function getAxisPointerModel(axisModel) {
  36973. var axisInfo = getAxisInfo(axisModel);
  36974. return axisInfo && axisInfo.axisPointerModel;
  36975. }
  36976. function isHandleTrigger(axisPointerModel) {
  36977. return !!axisPointerModel.get('handle.show');
  36978. }
  36979. /**
  36980. * @param {module:echarts/model/Model} model
  36981. * @return {string} unique key
  36982. */
  36983. function makeKey(model) {
  36984. return model.type + '||' + model.id;
  36985. }
  36986. /*
  36987. * Licensed to the Apache Software Foundation (ASF) under one
  36988. * or more contributor license agreements. See the NOTICE file
  36989. * distributed with this work for additional information
  36990. * regarding copyright ownership. The ASF licenses this file
  36991. * to you under the Apache License, Version 2.0 (the
  36992. * "License"); you may not use this file except in compliance
  36993. * with the License. You may obtain a copy of the License at
  36994. *
  36995. * http://www.apache.org/licenses/LICENSE-2.0
  36996. *
  36997. * Unless required by applicable law or agreed to in writing,
  36998. * software distributed under the License is distributed on an
  36999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37000. * KIND, either express or implied. See the License for the
  37001. * specific language governing permissions and limitations
  37002. * under the License.
  37003. */
  37004. /**
  37005. * Base class of AxisView.
  37006. */
  37007. var AxisView = extendComponentView({
  37008. type: 'axis',
  37009. /**
  37010. * @private
  37011. */
  37012. _axisPointer: null,
  37013. /**
  37014. * @protected
  37015. * @type {string}
  37016. */
  37017. axisPointerClass: null,
  37018. /**
  37019. * @override
  37020. */
  37021. render: function (axisModel, ecModel, api, payload) {
  37022. // FIXME
  37023. // This process should proformed after coordinate systems updated
  37024. // (axis scale updated), and should be performed each time update.
  37025. // So put it here temporarily, although it is not appropriate to
  37026. // put a model-writing procedure in `view`.
  37027. this.axisPointerClass && fixValue(axisModel);
  37028. AxisView.superApply(this, 'render', arguments);
  37029. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  37030. },
  37031. /**
  37032. * Action handler.
  37033. * @public
  37034. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37035. * @param {module:echarts/model/Global} ecModel
  37036. * @param {module:echarts/ExtensionAPI} api
  37037. * @param {Object} payload
  37038. */
  37039. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  37040. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  37041. },
  37042. /**
  37043. * @override
  37044. */
  37045. remove: function (ecModel, api) {
  37046. var axisPointer = this._axisPointer;
  37047. axisPointer && axisPointer.remove(api);
  37048. AxisView.superApply(this, 'remove', arguments);
  37049. },
  37050. /**
  37051. * @override
  37052. */
  37053. dispose: function (ecModel, api) {
  37054. disposeAxisPointer(this, api);
  37055. AxisView.superApply(this, 'dispose', arguments);
  37056. }
  37057. });
  37058. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  37059. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  37060. if (!Clazz) {
  37061. return;
  37062. }
  37063. var axisPointerModel = getAxisPointerModel(axisModel);
  37064. axisPointerModel
  37065. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  37066. .render(axisModel, axisPointerModel, api, forceRender)
  37067. : disposeAxisPointer(axisView, api);
  37068. }
  37069. function disposeAxisPointer(axisView, ecModel, api) {
  37070. var axisPointer = axisView._axisPointer;
  37071. axisPointer && axisPointer.dispose(ecModel, api);
  37072. axisView._axisPointer = null;
  37073. }
  37074. var axisPointerClazz = [];
  37075. AxisView.registerAxisPointerClass = function (type, clazz) {
  37076. if (__DEV__) {
  37077. if (axisPointerClazz[type]) {
  37078. throw new Error('axisPointer ' + type + ' exists');
  37079. }
  37080. }
  37081. axisPointerClazz[type] = clazz;
  37082. };
  37083. AxisView.getAxisPointerClass = function (type) {
  37084. return type && axisPointerClazz[type];
  37085. };
  37086. /*
  37087. * Licensed to the Apache Software Foundation (ASF) under one
  37088. * or more contributor license agreements. See the NOTICE file
  37089. * distributed with this work for additional information
  37090. * regarding copyright ownership. The ASF licenses this file
  37091. * to you under the Apache License, Version 2.0 (the
  37092. * "License"); you may not use this file except in compliance
  37093. * with the License. You may obtain a copy of the License at
  37094. *
  37095. * http://www.apache.org/licenses/LICENSE-2.0
  37096. *
  37097. * Unless required by applicable law or agreed to in writing,
  37098. * software distributed under the License is distributed on an
  37099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37100. * KIND, either express or implied. See the License for the
  37101. * specific language governing permissions and limitations
  37102. * under the License.
  37103. */
  37104. /**
  37105. * Can only be called after coordinate system creation stage.
  37106. * (Can be called before coordinate system update stage).
  37107. *
  37108. * @param {Object} opt {labelInside}
  37109. * @return {Object} {
  37110. * position, rotation, labelDirection, labelOffset,
  37111. * tickDirection, labelRotate, z2
  37112. * }
  37113. */
  37114. function layout$1(gridModel, axisModel, opt) {
  37115. opt = opt || {};
  37116. var grid = gridModel.coordinateSystem;
  37117. var axis = axisModel.axis;
  37118. var layout = {};
  37119. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  37120. var rawAxisPosition = axis.position;
  37121. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  37122. var axisDim = axis.dim;
  37123. var rect = grid.getRect();
  37124. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  37125. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  37126. var axisOffset = axisModel.get('offset') || 0;
  37127. var posBound = axisDim === 'x'
  37128. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  37129. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  37130. if (otherAxisOnZeroOf) {
  37131. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  37132. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  37133. }
  37134. // Axis position
  37135. layout.position = [
  37136. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  37137. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  37138. ];
  37139. // Axis rotation
  37140. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  37141. // Tick and label direction, x y is axisDim
  37142. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  37143. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  37144. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  37145. if (axisModel.get('axisTick.inside')) {
  37146. layout.tickDirection = -layout.tickDirection;
  37147. }
  37148. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  37149. layout.labelDirection = -layout.labelDirection;
  37150. }
  37151. // Special label rotation
  37152. var labelRotate = axisModel.get('axisLabel.rotate');
  37153. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  37154. // Over splitLine and splitArea
  37155. layout.z2 = 1;
  37156. return layout;
  37157. }
  37158. /*
  37159. * Licensed to the Apache Software Foundation (ASF) under one
  37160. * or more contributor license agreements. See the NOTICE file
  37161. * distributed with this work for additional information
  37162. * regarding copyright ownership. The ASF licenses this file
  37163. * to you under the Apache License, Version 2.0 (the
  37164. * "License"); you may not use this file except in compliance
  37165. * with the License. You may obtain a copy of the License at
  37166. *
  37167. * http://www.apache.org/licenses/LICENSE-2.0
  37168. *
  37169. * Unless required by applicable law or agreed to in writing,
  37170. * software distributed under the License is distributed on an
  37171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37172. * KIND, either express or implied. See the License for the
  37173. * specific language governing permissions and limitations
  37174. * under the License.
  37175. */
  37176. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  37177. var axis = axisModel.axis;
  37178. if (axis.scale.isBlank()) {
  37179. return;
  37180. }
  37181. var splitAreaModel = axisModel.getModel('splitArea');
  37182. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  37183. var areaColors = areaStyleModel.get('color');
  37184. var gridRect = gridModel.coordinateSystem.getRect();
  37185. var ticksCoords = axis.getTicksCoords({
  37186. tickModel: splitAreaModel,
  37187. clamp: true
  37188. });
  37189. if (!ticksCoords.length) {
  37190. return;
  37191. }
  37192. // For Making appropriate splitArea animation, the color and anid
  37193. // should be corresponding to previous one if possible.
  37194. var areaColorsLen = areaColors.length;
  37195. var lastSplitAreaColors = axisView.__splitAreaColors;
  37196. var newSplitAreaColors = createHashMap();
  37197. var colorIndex = 0;
  37198. if (lastSplitAreaColors) {
  37199. for (var i = 0; i < ticksCoords.length; i++) {
  37200. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  37201. if (cIndex != null) {
  37202. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  37203. break;
  37204. }
  37205. }
  37206. }
  37207. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  37208. var areaStyle = areaStyleModel.getAreaStyle();
  37209. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  37210. for (var i = 1; i < ticksCoords.length; i++) {
  37211. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37212. var x;
  37213. var y;
  37214. var width;
  37215. var height;
  37216. if (axis.isHorizontal()) {
  37217. x = prev;
  37218. y = gridRect.y;
  37219. width = tickCoord - x;
  37220. height = gridRect.height;
  37221. prev = x + width;
  37222. }
  37223. else {
  37224. x = gridRect.x;
  37225. y = prev;
  37226. width = gridRect.width;
  37227. height = tickCoord - y;
  37228. prev = y + height;
  37229. }
  37230. var tickValue = ticksCoords[i - 1].tickValue;
  37231. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  37232. axisGroup.add(new Rect({
  37233. anid: tickValue != null ? 'area_' + tickValue : null,
  37234. shape: {
  37235. x: x,
  37236. y: y,
  37237. width: width,
  37238. height: height
  37239. },
  37240. style: defaults({
  37241. fill: areaColors[colorIndex]
  37242. }, areaStyle),
  37243. silent: true
  37244. }));
  37245. colorIndex = (colorIndex + 1) % areaColorsLen;
  37246. }
  37247. axisView.__splitAreaColors = newSplitAreaColors;
  37248. }
  37249. function rectCoordAxisHandleRemove(axisView) {
  37250. axisView.__splitAreaColors = null;
  37251. }
  37252. /*
  37253. * Licensed to the Apache Software Foundation (ASF) under one
  37254. * or more contributor license agreements. See the NOTICE file
  37255. * distributed with this work for additional information
  37256. * regarding copyright ownership. The ASF licenses this file
  37257. * to you under the Apache License, Version 2.0 (the
  37258. * "License"); you may not use this file except in compliance
  37259. * with the License. You may obtain a copy of the License at
  37260. *
  37261. * http://www.apache.org/licenses/LICENSE-2.0
  37262. *
  37263. * Unless required by applicable law or agreed to in writing,
  37264. * software distributed under the License is distributed on an
  37265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37266. * KIND, either express or implied. See the License for the
  37267. * specific language governing permissions and limitations
  37268. * under the License.
  37269. */
  37270. var axisBuilderAttrs = [
  37271. 'axisLine', 'axisTickLabel', 'axisName'
  37272. ];
  37273. var selfBuilderAttrs = [
  37274. 'splitArea', 'splitLine', 'minorSplitLine'
  37275. ];
  37276. var CartesianAxisView = AxisView.extend({
  37277. type: 'cartesianAxis',
  37278. axisPointerClass: 'CartesianAxisPointer',
  37279. /**
  37280. * @override
  37281. */
  37282. render: function (axisModel, ecModel, api, payload) {
  37283. this.group.removeAll();
  37284. var oldAxisGroup = this._axisGroup;
  37285. this._axisGroup = new Group();
  37286. this.group.add(this._axisGroup);
  37287. if (!axisModel.get('show')) {
  37288. return;
  37289. }
  37290. var gridModel = axisModel.getCoordSysModel();
  37291. var layout = layout$1(gridModel, axisModel);
  37292. var axisBuilder = new AxisBuilder(axisModel, layout);
  37293. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  37294. this._axisGroup.add(axisBuilder.getGroup());
  37295. each$1(selfBuilderAttrs, function (name) {
  37296. if (axisModel.get(name + '.show')) {
  37297. this['_' + name](axisModel, gridModel);
  37298. }
  37299. }, this);
  37300. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  37301. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  37302. },
  37303. remove: function () {
  37304. rectCoordAxisHandleRemove(this);
  37305. },
  37306. /**
  37307. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37308. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37309. * @private
  37310. */
  37311. _splitLine: function (axisModel, gridModel) {
  37312. var axis = axisModel.axis;
  37313. if (axis.scale.isBlank()) {
  37314. return;
  37315. }
  37316. var splitLineModel = axisModel.getModel('splitLine');
  37317. var lineStyleModel = splitLineModel.getModel('lineStyle');
  37318. var lineColors = lineStyleModel.get('color');
  37319. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  37320. var gridRect = gridModel.coordinateSystem.getRect();
  37321. var isHorizontal = axis.isHorizontal();
  37322. var lineCount = 0;
  37323. var ticksCoords = axis.getTicksCoords({
  37324. tickModel: splitLineModel
  37325. });
  37326. var p1 = [];
  37327. var p2 = [];
  37328. var lineStyle = lineStyleModel.getLineStyle();
  37329. for (var i = 0; i < ticksCoords.length; i++) {
  37330. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  37331. if (isHorizontal) {
  37332. p1[0] = tickCoord;
  37333. p1[1] = gridRect.y;
  37334. p2[0] = tickCoord;
  37335. p2[1] = gridRect.y + gridRect.height;
  37336. }
  37337. else {
  37338. p1[0] = gridRect.x;
  37339. p1[1] = tickCoord;
  37340. p2[0] = gridRect.x + gridRect.width;
  37341. p2[1] = tickCoord;
  37342. }
  37343. var colorIndex = (lineCount++) % lineColors.length;
  37344. var tickValue = ticksCoords[i].tickValue;
  37345. this._axisGroup.add(new Line({
  37346. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  37347. subPixelOptimize: true,
  37348. shape: {
  37349. x1: p1[0],
  37350. y1: p1[1],
  37351. x2: p2[0],
  37352. y2: p2[1]
  37353. },
  37354. style: defaults({
  37355. stroke: lineColors[colorIndex]
  37356. }, lineStyle),
  37357. silent: true
  37358. }));
  37359. }
  37360. },
  37361. /**
  37362. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37363. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37364. * @private
  37365. */
  37366. _minorSplitLine: function (axisModel, gridModel) {
  37367. var axis = axisModel.axis;
  37368. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  37369. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  37370. var gridRect = gridModel.coordinateSystem.getRect();
  37371. var isHorizontal = axis.isHorizontal();
  37372. var minorTicksCoords = axis.getMinorTicksCoords();
  37373. if (!minorTicksCoords.length) {
  37374. return;
  37375. }
  37376. var p1 = [];
  37377. var p2 = [];
  37378. var lineStyle = lineStyleModel.getLineStyle();
  37379. for (var i = 0; i < minorTicksCoords.length; i++) {
  37380. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  37381. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  37382. if (isHorizontal) {
  37383. p1[0] = tickCoord;
  37384. p1[1] = gridRect.y;
  37385. p2[0] = tickCoord;
  37386. p2[1] = gridRect.y + gridRect.height;
  37387. }
  37388. else {
  37389. p1[0] = gridRect.x;
  37390. p1[1] = tickCoord;
  37391. p2[0] = gridRect.x + gridRect.width;
  37392. p2[1] = tickCoord;
  37393. }
  37394. this._axisGroup.add(new Line({
  37395. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  37396. subPixelOptimize: true,
  37397. shape: {
  37398. x1: p1[0],
  37399. y1: p1[1],
  37400. x2: p2[0],
  37401. y2: p2[1]
  37402. },
  37403. style: lineStyle,
  37404. silent: true
  37405. }));
  37406. }
  37407. }
  37408. },
  37409. /**
  37410. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  37411. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  37412. * @private
  37413. */
  37414. _splitArea: function (axisModel, gridModel) {
  37415. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  37416. }
  37417. });
  37418. CartesianAxisView.extend({
  37419. type: 'xAxis'
  37420. });
  37421. CartesianAxisView.extend({
  37422. type: 'yAxis'
  37423. });
  37424. /*
  37425. * Licensed to the Apache Software Foundation (ASF) under one
  37426. * or more contributor license agreements. See the NOTICE file
  37427. * distributed with this work for additional information
  37428. * regarding copyright ownership. The ASF licenses this file
  37429. * to you under the Apache License, Version 2.0 (the
  37430. * "License"); you may not use this file except in compliance
  37431. * with the License. You may obtain a copy of the License at
  37432. *
  37433. * http://www.apache.org/licenses/LICENSE-2.0
  37434. *
  37435. * Unless required by applicable law or agreed to in writing,
  37436. * software distributed under the License is distributed on an
  37437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37438. * KIND, either express or implied. See the License for the
  37439. * specific language governing permissions and limitations
  37440. * under the License.
  37441. */
  37442. /*
  37443. * Licensed to the Apache Software Foundation (ASF) under one
  37444. * or more contributor license agreements. See the NOTICE file
  37445. * distributed with this work for additional information
  37446. * regarding copyright ownership. The ASF licenses this file
  37447. * to you under the Apache License, Version 2.0 (the
  37448. * "License"); you may not use this file except in compliance
  37449. * with the License. You may obtain a copy of the License at
  37450. *
  37451. * http://www.apache.org/licenses/LICENSE-2.0
  37452. *
  37453. * Unless required by applicable law or agreed to in writing,
  37454. * software distributed under the License is distributed on an
  37455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37456. * KIND, either express or implied. See the License for the
  37457. * specific language governing permissions and limitations
  37458. * under the License.
  37459. */
  37460. // Grid view
  37461. extendComponentView({
  37462. type: 'grid',
  37463. render: function (gridModel, ecModel) {
  37464. this.group.removeAll();
  37465. if (gridModel.get('show')) {
  37466. this.group.add(new Rect({
  37467. shape: gridModel.coordinateSystem.getRect(),
  37468. style: defaults({
  37469. fill: gridModel.get('backgroundColor')
  37470. }, gridModel.getItemStyle()),
  37471. silent: true,
  37472. z2: -1
  37473. }));
  37474. }
  37475. }
  37476. });
  37477. registerPreprocessor(function (option) {
  37478. // Only create grid when need
  37479. if (option.xAxis && option.yAxis && !option.grid) {
  37480. option.grid = {};
  37481. }
  37482. });
  37483. /*
  37484. * Licensed to the Apache Software Foundation (ASF) under one
  37485. * or more contributor license agreements. See the NOTICE file
  37486. * distributed with this work for additional information
  37487. * regarding copyright ownership. The ASF licenses this file
  37488. * to you under the Apache License, Version 2.0 (the
  37489. * "License"); you may not use this file except in compliance
  37490. * with the License. You may obtain a copy of the License at
  37491. *
  37492. * http://www.apache.org/licenses/LICENSE-2.0
  37493. *
  37494. * Unless required by applicable law or agreed to in writing,
  37495. * software distributed under the License is distributed on an
  37496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37497. * KIND, either express or implied. See the License for the
  37498. * specific language governing permissions and limitations
  37499. * under the License.
  37500. */
  37501. // In case developer forget to include grid component
  37502. registerVisual(visualSymbol('line', 'circle', 'line'));
  37503. registerLayout(pointsLayout('line'));
  37504. // Down sample after filter
  37505. registerProcessor(
  37506. PRIORITY.PROCESSOR.STATISTIC,
  37507. dataSample('line')
  37508. );
  37509. /*
  37510. * Licensed to the Apache Software Foundation (ASF) under one
  37511. * or more contributor license agreements. See the NOTICE file
  37512. * distributed with this work for additional information
  37513. * regarding copyright ownership. The ASF licenses this file
  37514. * to you under the Apache License, Version 2.0 (the
  37515. * "License"); you may not use this file except in compliance
  37516. * with the License. You may obtain a copy of the License at
  37517. *
  37518. * http://www.apache.org/licenses/LICENSE-2.0
  37519. *
  37520. * Unless required by applicable law or agreed to in writing,
  37521. * software distributed under the License is distributed on an
  37522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37523. * KIND, either express or implied. See the License for the
  37524. * specific language governing permissions and limitations
  37525. * under the License.
  37526. */
  37527. var BaseBarSeries = SeriesModel.extend({
  37528. type: 'series.__base_bar__',
  37529. getInitialData: function (option, ecModel) {
  37530. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  37531. },
  37532. getMarkerPosition: function (value) {
  37533. var coordSys = this.coordinateSystem;
  37534. if (coordSys) {
  37535. // PENDING if clamp ?
  37536. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  37537. var data = this.getData();
  37538. var offset = data.getLayout('offset');
  37539. var size = data.getLayout('size');
  37540. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  37541. pt[offsetIndex] += offset + size / 2;
  37542. return pt;
  37543. }
  37544. return [NaN, NaN];
  37545. },
  37546. defaultOption: {
  37547. zlevel: 0, // 一级层叠
  37548. z: 2, // 二级层叠
  37549. coordinateSystem: 'cartesian2d',
  37550. legendHoverLink: true,
  37551. // stack: null
  37552. // Cartesian coordinate system
  37553. // xAxisIndex: 0,
  37554. // yAxisIndex: 0,
  37555. // 最小高度改为0
  37556. barMinHeight: 0,
  37557. // 最小角度为0,仅对极坐标系下的柱状图有效
  37558. barMinAngle: 0,
  37559. // cursor: null,
  37560. large: false,
  37561. largeThreshold: 400,
  37562. progressive: 3e3,
  37563. progressiveChunkMode: 'mod',
  37564. // barMaxWidth: null,
  37565. // In cartesian, the default value is 1. Otherwise null.
  37566. // barMinWidth: null,
  37567. // 默认自适应
  37568. // barWidth: null,
  37569. // 柱间距离,默认为柱形宽度的30%,可设固定值
  37570. // barGap: '30%',
  37571. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  37572. // barCategoryGap: '20%',
  37573. // label: {
  37574. // show: false
  37575. // },
  37576. itemStyle: {},
  37577. emphasis: {}
  37578. }
  37579. });
  37580. /*
  37581. * Licensed to the Apache Software Foundation (ASF) under one
  37582. * or more contributor license agreements. See the NOTICE file
  37583. * distributed with this work for additional information
  37584. * regarding copyright ownership. The ASF licenses this file
  37585. * to you under the Apache License, Version 2.0 (the
  37586. * "License"); you may not use this file except in compliance
  37587. * with the License. You may obtain a copy of the License at
  37588. *
  37589. * http://www.apache.org/licenses/LICENSE-2.0
  37590. *
  37591. * Unless required by applicable law or agreed to in writing,
  37592. * software distributed under the License is distributed on an
  37593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37594. * KIND, either express or implied. See the License for the
  37595. * specific language governing permissions and limitations
  37596. * under the License.
  37597. */
  37598. BaseBarSeries.extend({
  37599. type: 'series.bar',
  37600. dependencies: ['grid', 'polar'],
  37601. brushSelector: 'rect',
  37602. /**
  37603. * @override
  37604. */
  37605. getProgressive: function () {
  37606. // Do not support progressive in normal mode.
  37607. return this.get('large')
  37608. ? this.get('progressive')
  37609. : false;
  37610. },
  37611. /**
  37612. * @override
  37613. */
  37614. getProgressiveThreshold: function () {
  37615. // Do not support progressive in normal mode.
  37616. var progressiveThreshold = this.get('progressiveThreshold');
  37617. var largeThreshold = this.get('largeThreshold');
  37618. if (largeThreshold > progressiveThreshold) {
  37619. progressiveThreshold = largeThreshold;
  37620. }
  37621. return progressiveThreshold;
  37622. },
  37623. defaultOption: {
  37624. // If clipped
  37625. // Only available on cartesian2d
  37626. clip: true,
  37627. // If use caps on two sides of bars
  37628. // Only available on tangential polar bar
  37629. roundCap: false,
  37630. showBackground: false,
  37631. backgroundStyle: {
  37632. color: 'rgba(180, 180, 180, 0.2)',
  37633. borderColor: null,
  37634. borderWidth: 0,
  37635. borderType: 'solid',
  37636. borderRadius: 0,
  37637. shadowBlur: 0,
  37638. shadowColor: null,
  37639. shadowOffsetX: 0,
  37640. shadowOffsetY: 0,
  37641. opacity: 1
  37642. }
  37643. }
  37644. });
  37645. /*
  37646. * Licensed to the Apache Software Foundation (ASF) under one
  37647. * or more contributor license agreements. See the NOTICE file
  37648. * distributed with this work for additional information
  37649. * regarding copyright ownership. The ASF licenses this file
  37650. * to you under the Apache License, Version 2.0 (the
  37651. * "License"); you may not use this file except in compliance
  37652. * with the License. You may obtain a copy of the License at
  37653. *
  37654. * http://www.apache.org/licenses/LICENSE-2.0
  37655. *
  37656. * Unless required by applicable law or agreed to in writing,
  37657. * software distributed under the License is distributed on an
  37658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37659. * KIND, either express or implied. See the License for the
  37660. * specific language governing permissions and limitations
  37661. * under the License.
  37662. */
  37663. function setLabel(
  37664. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  37665. ) {
  37666. var labelModel = itemModel.getModel('label');
  37667. var hoverLabelModel = itemModel.getModel('emphasis.label');
  37668. setLabelStyle(
  37669. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  37670. {
  37671. labelFetcher: seriesModel,
  37672. labelDataIndex: dataIndex,
  37673. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37674. isRectText: true,
  37675. autoColor: color
  37676. }
  37677. );
  37678. fixPosition(normalStyle);
  37679. fixPosition(hoverStyle);
  37680. }
  37681. function fixPosition(style, labelPositionOutside) {
  37682. if (style.textPosition === 'outside') {
  37683. style.textPosition = labelPositionOutside;
  37684. }
  37685. }
  37686. /*
  37687. * Licensed to the Apache Software Foundation (ASF) under one
  37688. * or more contributor license agreements. See the NOTICE file
  37689. * distributed with this work for additional information
  37690. * regarding copyright ownership. The ASF licenses this file
  37691. * to you under the Apache License, Version 2.0 (the
  37692. * "License"); you may not use this file except in compliance
  37693. * with the License. You may obtain a copy of the License at
  37694. *
  37695. * http://www.apache.org/licenses/LICENSE-2.0
  37696. *
  37697. * Unless required by applicable law or agreed to in writing,
  37698. * software distributed under the License is distributed on an
  37699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37700. * KIND, either express or implied. See the License for the
  37701. * specific language governing permissions and limitations
  37702. * under the License.
  37703. */
  37704. var getBarItemStyle = makeStyleMapper(
  37705. [
  37706. ['fill', 'color'],
  37707. ['stroke', 'borderColor'],
  37708. ['lineWidth', 'borderWidth'],
  37709. // Compatitable with 2
  37710. ['stroke', 'barBorderColor'],
  37711. ['lineWidth', 'barBorderWidth'],
  37712. ['opacity'],
  37713. ['shadowBlur'],
  37714. ['shadowOffsetX'],
  37715. ['shadowOffsetY'],
  37716. ['shadowColor']
  37717. ]
  37718. );
  37719. var barItemStyle = {
  37720. getBarItemStyle: function (excludes) {
  37721. var style = getBarItemStyle(this, excludes);
  37722. if (this.getBorderLineDash) {
  37723. var lineDash = this.getBorderLineDash();
  37724. lineDash && (style.lineDash = lineDash);
  37725. }
  37726. return style;
  37727. }
  37728. };
  37729. /*
  37730. * Licensed to the Apache Software Foundation (ASF) under one
  37731. * or more contributor license agreements. See the NOTICE file
  37732. * distributed with this work for additional information
  37733. * regarding copyright ownership. The ASF licenses this file
  37734. * to you under the Apache License, Version 2.0 (the
  37735. * "License"); you may not use this file except in compliance
  37736. * with the License. You may obtain a copy of the License at
  37737. *
  37738. * http://www.apache.org/licenses/LICENSE-2.0
  37739. *
  37740. * Unless required by applicable law or agreed to in writing,
  37741. * software distributed under the License is distributed on an
  37742. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37743. * KIND, either express or implied. See the License for the
  37744. * specific language governing permissions and limitations
  37745. * under the License.
  37746. */
  37747. /**
  37748. * Sausage: similar to sector, but have half circle on both sides
  37749. * @public
  37750. */
  37751. var Sausage = extendShape({
  37752. type: 'sausage',
  37753. shape: {
  37754. cx: 0,
  37755. cy: 0,
  37756. r0: 0,
  37757. r: 0,
  37758. startAngle: 0,
  37759. endAngle: Math.PI * 2,
  37760. clockwise: true
  37761. },
  37762. buildPath: function (ctx, shape) {
  37763. var x = shape.cx;
  37764. var y = shape.cy;
  37765. var r0 = Math.max(shape.r0 || 0, 0);
  37766. var r = Math.max(shape.r, 0);
  37767. var dr = (r - r0) * 0.5;
  37768. var rCenter = r0 + dr;
  37769. var startAngle = shape.startAngle;
  37770. var endAngle = shape.endAngle;
  37771. var clockwise = shape.clockwise;
  37772. var unitStartX = Math.cos(startAngle);
  37773. var unitStartY = Math.sin(startAngle);
  37774. var unitEndX = Math.cos(endAngle);
  37775. var unitEndY = Math.sin(endAngle);
  37776. var lessThanCircle = clockwise
  37777. ? endAngle - startAngle < Math.PI * 2
  37778. : startAngle - endAngle < Math.PI * 2;
  37779. if (lessThanCircle) {
  37780. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37781. ctx.arc(
  37782. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  37783. -Math.PI + startAngle, startAngle, !clockwise
  37784. );
  37785. }
  37786. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37787. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37788. ctx.arc(
  37789. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  37790. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  37791. );
  37792. if (r0 !== 0) {
  37793. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37794. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37795. }
  37796. ctx.closePath();
  37797. }
  37798. });
  37799. /*
  37800. * Licensed to the Apache Software Foundation (ASF) under one
  37801. * or more contributor license agreements. See the NOTICE file
  37802. * distributed with this work for additional information
  37803. * regarding copyright ownership. The ASF licenses this file
  37804. * to you under the Apache License, Version 2.0 (the
  37805. * "License"); you may not use this file except in compliance
  37806. * with the License. You may obtain a copy of the License at
  37807. *
  37808. * http://www.apache.org/licenses/LICENSE-2.0
  37809. *
  37810. * Unless required by applicable law or agreed to in writing,
  37811. * software distributed under the License is distributed on an
  37812. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37813. * KIND, either express or implied. See the License for the
  37814. * specific language governing permissions and limitations
  37815. * under the License.
  37816. */
  37817. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  37818. var _eventPos = [0, 0];
  37819. // FIXME
  37820. // Just for compatible with ec2.
  37821. extend(Model.prototype, barItemStyle);
  37822. function getClipArea(coord, data) {
  37823. var coordSysClipArea = coord.getArea && coord.getArea();
  37824. if (coord.type === 'cartesian2d') {
  37825. var baseAxis = coord.getBaseAxis();
  37826. // When boundaryGap is false or using time axis. bar may exceed the grid.
  37827. // We should not clip this part.
  37828. // See test/bar2.html
  37829. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37830. var expandWidth = data.getLayout('bandWidth');
  37831. if (baseAxis.isHorizontal()) {
  37832. coordSysClipArea.x -= expandWidth;
  37833. coordSysClipArea.width += expandWidth * 2;
  37834. }
  37835. else {
  37836. coordSysClipArea.y -= expandWidth;
  37837. coordSysClipArea.height += expandWidth * 2;
  37838. }
  37839. }
  37840. }
  37841. return coordSysClipArea;
  37842. }
  37843. extendChartView({
  37844. type: 'bar',
  37845. render: function (seriesModel, ecModel, api) {
  37846. this._updateDrawMode(seriesModel);
  37847. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37848. if (coordinateSystemType === 'cartesian2d'
  37849. || coordinateSystemType === 'polar'
  37850. ) {
  37851. this._isLargeDraw
  37852. ? this._renderLarge(seriesModel, ecModel, api)
  37853. : this._renderNormal(seriesModel, ecModel, api);
  37854. }
  37855. else if (__DEV__) {
  37856. console.warn('Only cartesian2d and polar supported for bar.');
  37857. }
  37858. return this.group;
  37859. },
  37860. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37861. this._clear();
  37862. this._updateDrawMode(seriesModel);
  37863. },
  37864. incrementalRender: function (params, seriesModel, ecModel, api) {
  37865. // Do not support progressive in normal mode.
  37866. this._incrementalRenderLarge(params, seriesModel);
  37867. },
  37868. _updateDrawMode: function (seriesModel) {
  37869. var isLargeDraw = seriesModel.pipelineContext.large;
  37870. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37871. this._isLargeDraw = isLargeDraw;
  37872. this._clear();
  37873. }
  37874. },
  37875. _renderNormal: function (seriesModel, ecModel, api) {
  37876. var group = this.group;
  37877. var data = seriesModel.getData();
  37878. var oldData = this._data;
  37879. var coord = seriesModel.coordinateSystem;
  37880. var baseAxis = coord.getBaseAxis();
  37881. var isHorizontalOrRadial;
  37882. if (coord.type === 'cartesian2d') {
  37883. isHorizontalOrRadial = baseAxis.isHorizontal();
  37884. }
  37885. else if (coord.type === 'polar') {
  37886. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37887. }
  37888. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37889. var needsClip = seriesModel.get('clip', true);
  37890. var coordSysClipArea = getClipArea(coord, data);
  37891. // If there is clipPath created in large mode. Remove it.
  37892. group.removeClipPath();
  37893. // We don't use clipPath in normal mode because we needs a perfect animation
  37894. // And don't want the label are clipped.
  37895. var roundCap = seriesModel.get('roundCap', true);
  37896. var drawBackground = seriesModel.get('showBackground', true);
  37897. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37898. var barBorderRadius = backgroundModel.get('barBorderRadius') || 0;
  37899. var bgEls = [];
  37900. var oldBgEls = this._backgroundEls || [];
  37901. data.diff(oldData)
  37902. .add(function (dataIndex) {
  37903. var itemModel = data.getItemModel(dataIndex);
  37904. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37905. if (drawBackground) {
  37906. var bgLayout = getLayout[coord.type](data, dataIndex);
  37907. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  37908. bgEl.useStyle(backgroundModel.getBarItemStyle());
  37909. // Only cartesian2d support borderRadius.
  37910. if (coord.type === 'cartesian2d') {
  37911. bgEl.setShape('r', barBorderRadius);
  37912. }
  37913. bgEls[dataIndex] = bgEl;
  37914. }
  37915. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  37916. if (!data.hasValue(dataIndex)) {
  37917. return;
  37918. }
  37919. if (needsClip) {
  37920. // Clip will modify the layout params.
  37921. // And return a boolean to determine if the shape are fully clipped.
  37922. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37923. if (isClipped) {
  37924. group.remove(el);
  37925. return;
  37926. }
  37927. }
  37928. var el = elementCreator[coord.type](
  37929. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  37930. );
  37931. data.setItemGraphicEl(dataIndex, el);
  37932. group.add(el);
  37933. updateStyle(
  37934. el, data, dataIndex, itemModel, layout,
  37935. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37936. );
  37937. })
  37938. .update(function (newIndex, oldIndex) {
  37939. var itemModel = data.getItemModel(newIndex);
  37940. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37941. if (drawBackground) {
  37942. var bgEl = oldBgEls[oldIndex];
  37943. bgEl.useStyle(backgroundModel.getBarItemStyle());
  37944. // Only cartesian2d support borderRadius.
  37945. if (coord.type === 'cartesian2d') {
  37946. bgEl.setShape('r', barBorderRadius);
  37947. }
  37948. bgEls[newIndex] = bgEl;
  37949. var bgLayout = getLayout[coord.type](data, newIndex);
  37950. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  37951. updateProps(bgEl, { shape: shape }, animationModel, newIndex);
  37952. }
  37953. var el = oldData.getItemGraphicEl(oldIndex);
  37954. if (!data.hasValue(newIndex)) {
  37955. group.remove(el);
  37956. return;
  37957. }
  37958. if (needsClip) {
  37959. var isClipped = clip[coord.type](coordSysClipArea, layout);
  37960. if (isClipped) {
  37961. group.remove(el);
  37962. return;
  37963. }
  37964. }
  37965. if (el) {
  37966. updateProps(el, {shape: layout}, animationModel, newIndex);
  37967. }
  37968. else {
  37969. el = elementCreator[coord.type](
  37970. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  37971. );
  37972. }
  37973. data.setItemGraphicEl(newIndex, el);
  37974. // Add back
  37975. group.add(el);
  37976. updateStyle(
  37977. el, data, newIndex, itemModel, layout,
  37978. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  37979. );
  37980. })
  37981. .remove(function (dataIndex) {
  37982. var el = oldData.getItemGraphicEl(dataIndex);
  37983. if (coord.type === 'cartesian2d') {
  37984. el && removeRect(dataIndex, animationModel, el);
  37985. }
  37986. else {
  37987. el && removeSector(dataIndex, animationModel, el);
  37988. }
  37989. })
  37990. .execute();
  37991. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  37992. bgGroup.removeAll();
  37993. for (var i = 0; i < bgEls.length; ++i) {
  37994. bgGroup.add(bgEls[i]);
  37995. }
  37996. group.add(bgGroup);
  37997. this._backgroundEls = bgEls;
  37998. this._data = data;
  37999. },
  38000. _renderLarge: function (seriesModel, ecModel, api) {
  38001. this._clear();
  38002. createLarge(seriesModel, this.group);
  38003. // Use clipPath in large mode.
  38004. var clipPath = seriesModel.get('clip', true)
  38005. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  38006. : null;
  38007. if (clipPath) {
  38008. this.group.setClipPath(clipPath);
  38009. }
  38010. else {
  38011. this.group.removeClipPath();
  38012. }
  38013. },
  38014. _incrementalRenderLarge: function (params, seriesModel) {
  38015. this._removeBackground();
  38016. createLarge(seriesModel, this.group, true);
  38017. },
  38018. dispose: noop,
  38019. remove: function (ecModel) {
  38020. this._clear(ecModel);
  38021. },
  38022. _clear: function (ecModel) {
  38023. var group = this.group;
  38024. var data = this._data;
  38025. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  38026. this._removeBackground();
  38027. this._backgroundEls = [];
  38028. data.eachItemGraphicEl(function (el) {
  38029. if (el.type === 'sector') {
  38030. removeSector(el.dataIndex, ecModel, el);
  38031. }
  38032. else {
  38033. removeRect(el.dataIndex, ecModel, el);
  38034. }
  38035. });
  38036. }
  38037. else {
  38038. group.removeAll();
  38039. }
  38040. this._data = null;
  38041. },
  38042. _removeBackground: function () {
  38043. this.group.remove(this._backgroundGroup);
  38044. this._backgroundGroup = null;
  38045. }
  38046. });
  38047. var mathMax$4 = Math.max;
  38048. var mathMin$4 = Math.min;
  38049. var clip = {
  38050. cartesian2d: function (coordSysBoundingRect, layout) {
  38051. var signWidth = layout.width < 0 ? -1 : 1;
  38052. var signHeight = layout.height < 0 ? -1 : 1;
  38053. // Needs positive width and height
  38054. if (signWidth < 0) {
  38055. layout.x += layout.width;
  38056. layout.width = -layout.width;
  38057. }
  38058. if (signHeight < 0) {
  38059. layout.y += layout.height;
  38060. layout.height = -layout.height;
  38061. }
  38062. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  38063. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  38064. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  38065. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  38066. layout.x = x;
  38067. layout.y = y;
  38068. layout.width = x2 - x;
  38069. layout.height = y2 - y;
  38070. var clipped = layout.width < 0 || layout.height < 0;
  38071. // Reverse back
  38072. if (signWidth < 0) {
  38073. layout.x += layout.width;
  38074. layout.width = -layout.width;
  38075. }
  38076. if (signHeight < 0) {
  38077. layout.y += layout.height;
  38078. layout.height = -layout.height;
  38079. }
  38080. return clipped;
  38081. },
  38082. polar: function (coordSysClipArea) {
  38083. return false;
  38084. }
  38085. };
  38086. var elementCreator = {
  38087. cartesian2d: function (
  38088. dataIndex, layout, isHorizontal,
  38089. animationModel, isUpdate
  38090. ) {
  38091. var rect = new Rect({
  38092. shape: extend({}, layout),
  38093. z2: 1
  38094. });
  38095. rect.name = 'item';
  38096. // Animation
  38097. if (animationModel) {
  38098. var rectShape = rect.shape;
  38099. var animateProperty = isHorizontal ? 'height' : 'width';
  38100. var animateTarget = {};
  38101. rectShape[animateProperty] = 0;
  38102. animateTarget[animateProperty] = layout[animateProperty];
  38103. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  38104. shape: animateTarget
  38105. }, animationModel, dataIndex);
  38106. }
  38107. return rect;
  38108. },
  38109. polar: function (
  38110. dataIndex, layout, isRadial,
  38111. animationModel, isUpdate, roundCap
  38112. ) {
  38113. // Keep the same logic with bar in catesion: use end value to control
  38114. // direction. Notice that if clockwise is true (by default), the sector
  38115. // will always draw clockwisely, no matter whether endAngle is greater
  38116. // or less than startAngle.
  38117. var clockwise = layout.startAngle < layout.endAngle;
  38118. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  38119. var sector = new ShapeClass({
  38120. shape: defaults({clockwise: clockwise}, layout),
  38121. z2: 1
  38122. });
  38123. sector.name = 'item';
  38124. // Animation
  38125. if (animationModel) {
  38126. var sectorShape = sector.shape;
  38127. var animateProperty = isRadial ? 'r' : 'endAngle';
  38128. var animateTarget = {};
  38129. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  38130. animateTarget[animateProperty] = layout[animateProperty];
  38131. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  38132. shape: animateTarget
  38133. }, animationModel, dataIndex);
  38134. }
  38135. return sector;
  38136. }
  38137. };
  38138. function removeRect(dataIndex, animationModel, el) {
  38139. // Not show text when animating
  38140. el.style.text = null;
  38141. updateProps(el, {
  38142. shape: {
  38143. width: 0
  38144. }
  38145. }, animationModel, dataIndex, function () {
  38146. el.parent && el.parent.remove(el);
  38147. });
  38148. }
  38149. function removeSector(dataIndex, animationModel, el) {
  38150. // Not show text when animating
  38151. el.style.text = null;
  38152. updateProps(el, {
  38153. shape: {
  38154. r: el.shape.r0
  38155. }
  38156. }, animationModel, dataIndex, function () {
  38157. el.parent && el.parent.remove(el);
  38158. });
  38159. }
  38160. var getLayout = {
  38161. // itemModel is only used to get borderWidth, which is not needed
  38162. // when calculating bar background layout.
  38163. cartesian2d: function (data, dataIndex, itemModel) {
  38164. var layout = data.getItemLayout(dataIndex);
  38165. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
  38166. // fix layout with lineWidth
  38167. var signX = layout.width > 0 ? 1 : -1;
  38168. var signY = layout.height > 0 ? 1 : -1;
  38169. return {
  38170. x: layout.x + signX * fixedLineWidth / 2,
  38171. y: layout.y + signY * fixedLineWidth / 2,
  38172. width: layout.width - signX * fixedLineWidth,
  38173. height: layout.height - signY * fixedLineWidth
  38174. };
  38175. },
  38176. polar: function (data, dataIndex, itemModel) {
  38177. var layout = data.getItemLayout(dataIndex);
  38178. return {
  38179. cx: layout.cx,
  38180. cy: layout.cy,
  38181. r0: layout.r0,
  38182. r: layout.r,
  38183. startAngle: layout.startAngle,
  38184. endAngle: layout.endAngle
  38185. };
  38186. }
  38187. };
  38188. function isZeroOnPolar(layout) {
  38189. return layout.startAngle != null
  38190. && layout.endAngle != null
  38191. && layout.startAngle === layout.endAngle;
  38192. }
  38193. function updateStyle(
  38194. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  38195. ) {
  38196. var color = data.getItemVisual(dataIndex, 'color');
  38197. var opacity = data.getItemVisual(dataIndex, 'opacity');
  38198. var stroke = data.getVisual('borderColor');
  38199. var itemStyleModel = itemModel.getModel('itemStyle');
  38200. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  38201. if (!isPolar) {
  38202. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  38203. }
  38204. el.useStyle(defaults(
  38205. {
  38206. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  38207. fill: isZeroOnPolar(layout) ? 'none' : color,
  38208. opacity: opacity
  38209. },
  38210. itemStyleModel.getBarItemStyle()
  38211. ));
  38212. var cursorStyle = itemModel.getShallow('cursor');
  38213. cursorStyle && el.attr('cursor', cursorStyle);
  38214. var labelPositionOutside = isHorizontal
  38215. ? (layout.height > 0 ? 'bottom' : 'top')
  38216. : (layout.width > 0 ? 'left' : 'right');
  38217. if (!isPolar) {
  38218. setLabel(
  38219. el.style, hoverStyle, itemModel, color,
  38220. seriesModel, dataIndex, labelPositionOutside
  38221. );
  38222. }
  38223. if (isZeroOnPolar(layout)) {
  38224. hoverStyle.fill = hoverStyle.stroke = 'none';
  38225. }
  38226. setHoverStyle(el, hoverStyle);
  38227. }
  38228. // In case width or height are too small.
  38229. function getLineWidth(itemModel, rawLayout) {
  38230. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  38231. // width or height may be NaN for empty data
  38232. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  38233. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  38234. return Math.min(lineWidth, width, height);
  38235. }
  38236. var LargePath = Path.extend({
  38237. type: 'largeBar',
  38238. shape: {points: []},
  38239. buildPath: function (ctx, shape) {
  38240. // Drawing lines is more efficient than drawing
  38241. // a whole line or drawing rects.
  38242. var points = shape.points;
  38243. var startPoint = this.__startPoint;
  38244. var baseDimIdx = this.__baseDimIdx;
  38245. for (var i = 0; i < points.length; i += 2) {
  38246. startPoint[baseDimIdx] = points[i + baseDimIdx];
  38247. ctx.moveTo(startPoint[0], startPoint[1]);
  38248. ctx.lineTo(points[i], points[i + 1]);
  38249. }
  38250. }
  38251. });
  38252. function createLarge(seriesModel, group, incremental) {
  38253. // TODO support polar
  38254. var data = seriesModel.getData();
  38255. var startPoint = [];
  38256. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  38257. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  38258. var largeDataIndices = data.getLayout('largeDataIndices');
  38259. var barWidth = data.getLayout('barWidth');
  38260. var backgroundModel = seriesModel.getModel('backgroundStyle');
  38261. var drawBackground = seriesModel.get('showBackground', true);
  38262. if (drawBackground) {
  38263. var points = data.getLayout('largeBackgroundPoints');
  38264. var backgroundStartPoint = [];
  38265. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  38266. var bgEl = new LargePath({
  38267. shape: {points: points},
  38268. incremental: !!incremental,
  38269. __startPoint: backgroundStartPoint,
  38270. __baseDimIdx: baseDimIdx,
  38271. __largeDataIndices: largeDataIndices,
  38272. __barWidth: barWidth,
  38273. silent: true,
  38274. z2: 0
  38275. });
  38276. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  38277. group.add(bgEl);
  38278. }
  38279. var el = new LargePath({
  38280. shape: {points: data.getLayout('largePoints')},
  38281. incremental: !!incremental,
  38282. __startPoint: startPoint,
  38283. __baseDimIdx: baseDimIdx,
  38284. __largeDataIndices: largeDataIndices,
  38285. __barWidth: barWidth
  38286. });
  38287. group.add(el);
  38288. setLargeStyle(el, seriesModel, data);
  38289. // Enable tooltip and user mouse/touch event handlers.
  38290. el.seriesIndex = seriesModel.seriesIndex;
  38291. if (!seriesModel.get('silent')) {
  38292. el.on('mousedown', largePathUpdateDataIndex);
  38293. el.on('mousemove', largePathUpdateDataIndex);
  38294. }
  38295. }
  38296. // Use throttle to avoid frequently traverse to find dataIndex.
  38297. var largePathUpdateDataIndex = throttle(function (event) {
  38298. var largePath = this;
  38299. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  38300. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  38301. }, 30, false);
  38302. function largePathFindDataIndex(largePath, x, y) {
  38303. var baseDimIdx = largePath.__baseDimIdx;
  38304. var valueDimIdx = 1 - baseDimIdx;
  38305. var points = largePath.shape.points;
  38306. var largeDataIndices = largePath.__largeDataIndices;
  38307. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  38308. var startValueVal = largePath.__startPoint[valueDimIdx];
  38309. _eventPos[0] = x;
  38310. _eventPos[1] = y;
  38311. var pointerBaseVal = _eventPos[baseDimIdx];
  38312. var pointerValueVal = _eventPos[1 - baseDimIdx];
  38313. var baseLowerBound = pointerBaseVal - barWidthHalf;
  38314. var baseUpperBound = pointerBaseVal + barWidthHalf;
  38315. for (var i = 0, len = points.length / 2; i < len; i++) {
  38316. var ii = i * 2;
  38317. var barBaseVal = points[ii + baseDimIdx];
  38318. var barValueVal = points[ii + valueDimIdx];
  38319. if (
  38320. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  38321. && (
  38322. startValueVal <= barValueVal
  38323. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  38324. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  38325. )
  38326. ) {
  38327. return largeDataIndices[i];
  38328. }
  38329. }
  38330. return -1;
  38331. }
  38332. function setLargeStyle(el, seriesModel, data) {
  38333. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  38334. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  38335. el.useStyle(itemStyle);
  38336. el.style.fill = null;
  38337. el.style.stroke = borderColor;
  38338. el.style.lineWidth = data.getLayout('barWidth');
  38339. }
  38340. function setLargeBackgroundStyle(el, backgroundModel, data) {
  38341. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  38342. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  38343. el.useStyle(itemStyle);
  38344. el.style.fill = null;
  38345. el.style.stroke = borderColor;
  38346. el.style.lineWidth = data.getLayout('barWidth');
  38347. }
  38348. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  38349. var coordLayout;
  38350. var isPolar = coord.type === 'polar';
  38351. if (isPolar) {
  38352. coordLayout = coord.getArea();
  38353. }
  38354. else {
  38355. coordLayout = coord.grid.getRect();
  38356. }
  38357. if (isPolar) {
  38358. return {
  38359. cx: coordLayout.cx,
  38360. cy: coordLayout.cy,
  38361. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  38362. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  38363. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  38364. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  38365. };
  38366. }
  38367. else {
  38368. return {
  38369. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  38370. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  38371. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  38372. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  38373. };
  38374. }
  38375. }
  38376. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  38377. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  38378. return new ElementClz({
  38379. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  38380. silent: true,
  38381. z2: 0
  38382. });
  38383. }
  38384. /*
  38385. * Licensed to the Apache Software Foundation (ASF) under one
  38386. * or more contributor license agreements. See the NOTICE file
  38387. * distributed with this work for additional information
  38388. * regarding copyright ownership. The ASF licenses this file
  38389. * to you under the Apache License, Version 2.0 (the
  38390. * "License"); you may not use this file except in compliance
  38391. * with the License. You may obtain a copy of the License at
  38392. *
  38393. * http://www.apache.org/licenses/LICENSE-2.0
  38394. *
  38395. * Unless required by applicable law or agreed to in writing,
  38396. * software distributed under the License is distributed on an
  38397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38398. * KIND, either express or implied. See the License for the
  38399. * specific language governing permissions and limitations
  38400. * under the License.
  38401. */
  38402. // In case developer forget to include grid component
  38403. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  38404. // Use higher prority to avoid to be blocked by other overall layout, which do not
  38405. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  38406. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  38407. registerVisual({
  38408. seriesType: 'bar',
  38409. reset: function (seriesModel) {
  38410. // Visual coding for legend
  38411. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  38412. }
  38413. });
  38414. /*
  38415. * Licensed to the Apache Software Foundation (ASF) under one
  38416. * or more contributor license agreements. See the NOTICE file
  38417. * distributed with this work for additional information
  38418. * regarding copyright ownership. The ASF licenses this file
  38419. * to you under the Apache License, Version 2.0 (the
  38420. * "License"); you may not use this file except in compliance
  38421. * with the License. You may obtain a copy of the License at
  38422. *
  38423. * http://www.apache.org/licenses/LICENSE-2.0
  38424. *
  38425. * Unless required by applicable law or agreed to in writing,
  38426. * software distributed under the License is distributed on an
  38427. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38428. * KIND, either express or implied. See the License for the
  38429. * specific language governing permissions and limitations
  38430. * under the License.
  38431. */
  38432. /**
  38433. * [Usage]:
  38434. * (1)
  38435. * createListSimply(seriesModel, ['value']);
  38436. * (2)
  38437. * createListSimply(seriesModel, {
  38438. * coordDimensions: ['value'],
  38439. * dimensionsCount: 5
  38440. * });
  38441. *
  38442. * @param {module:echarts/model/Series} seriesModel
  38443. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  38444. * The options in opt, see `echarts/data/helper/createDimensions`
  38445. * @param {Array.<string>} [nameList]
  38446. * @return {module:echarts/data/List}
  38447. */
  38448. var createListSimply = function (seriesModel, opt, nameList) {
  38449. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  38450. var source = seriesModel.getSource();
  38451. var dimensionsInfo = createDimensions(source, opt);
  38452. var list = new List(dimensionsInfo, seriesModel);
  38453. list.initData(source, nameList);
  38454. return list;
  38455. };
  38456. /*
  38457. * Licensed to the Apache Software Foundation (ASF) under one
  38458. * or more contributor license agreements. See the NOTICE file
  38459. * distributed with this work for additional information
  38460. * regarding copyright ownership. The ASF licenses this file
  38461. * to you under the Apache License, Version 2.0 (the
  38462. * "License"); you may not use this file except in compliance
  38463. * with the License. You may obtain a copy of the License at
  38464. *
  38465. * http://www.apache.org/licenses/LICENSE-2.0
  38466. *
  38467. * Unless required by applicable law or agreed to in writing,
  38468. * software distributed under the License is distributed on an
  38469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38470. * KIND, either express or implied. See the License for the
  38471. * specific language governing permissions and limitations
  38472. * under the License.
  38473. */
  38474. /**
  38475. * Data selectable mixin for chart series.
  38476. * To eanble data select, option of series must have `selectedMode`.
  38477. * And each data item will use `selected` to toggle itself selected status
  38478. */
  38479. var dataSelectableMixin = {
  38480. /**
  38481. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  38482. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  38483. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  38484. */
  38485. updateSelectedMap: function (targetList) {
  38486. this._targetList = isArray(targetList) ? targetList.slice() : [];
  38487. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  38488. targetMap.set(target.name, target);
  38489. return targetMap;
  38490. }, createHashMap());
  38491. },
  38492. /**
  38493. * Either name or id should be passed as input here.
  38494. * If both of them are defined, id is used.
  38495. *
  38496. * @param {string|undefined} name name of data
  38497. * @param {number|undefined} id dataIndex of data
  38498. */
  38499. // PENGING If selectedMode is null ?
  38500. select: function (name, id) {
  38501. var target = id != null
  38502. ? this._targetList[id]
  38503. : this._selectTargetMap.get(name);
  38504. var selectedMode = this.get('selectedMode');
  38505. if (selectedMode === 'single') {
  38506. this._selectTargetMap.each(function (target) {
  38507. target.selected = false;
  38508. });
  38509. }
  38510. target && (target.selected = true);
  38511. },
  38512. /**
  38513. * Either name or id should be passed as input here.
  38514. * If both of them are defined, id is used.
  38515. *
  38516. * @param {string|undefined} name name of data
  38517. * @param {number|undefined} id dataIndex of data
  38518. */
  38519. unSelect: function (name, id) {
  38520. var target = id != null
  38521. ? this._targetList[id]
  38522. : this._selectTargetMap.get(name);
  38523. // var selectedMode = this.get('selectedMode');
  38524. // selectedMode !== 'single' && target && (target.selected = false);
  38525. target && (target.selected = false);
  38526. },
  38527. /**
  38528. * Either name or id should be passed as input here.
  38529. * If both of them are defined, id is used.
  38530. *
  38531. * @param {string|undefined} name name of data
  38532. * @param {number|undefined} id dataIndex of data
  38533. */
  38534. toggleSelected: function (name, id) {
  38535. var target = id != null
  38536. ? this._targetList[id]
  38537. : this._selectTargetMap.get(name);
  38538. if (target != null) {
  38539. this[target.selected ? 'unSelect' : 'select'](name, id);
  38540. return target.selected;
  38541. }
  38542. },
  38543. /**
  38544. * Either name or id should be passed as input here.
  38545. * If both of them are defined, id is used.
  38546. *
  38547. * @param {string|undefined} name name of data
  38548. * @param {number|undefined} id dataIndex of data
  38549. */
  38550. isSelected: function (name, id) {
  38551. var target = id != null
  38552. ? this._targetList[id]
  38553. : this._selectTargetMap.get(name);
  38554. return target && target.selected;
  38555. }
  38556. };
  38557. /*
  38558. * Licensed to the Apache Software Foundation (ASF) under one
  38559. * or more contributor license agreements. See the NOTICE file
  38560. * distributed with this work for additional information
  38561. * regarding copyright ownership. The ASF licenses this file
  38562. * to you under the Apache License, Version 2.0 (the
  38563. * "License"); you may not use this file except in compliance
  38564. * with the License. You may obtain a copy of the License at
  38565. *
  38566. * http://www.apache.org/licenses/LICENSE-2.0
  38567. *
  38568. * Unless required by applicable law or agreed to in writing,
  38569. * software distributed under the License is distributed on an
  38570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38571. * KIND, either express or implied. See the License for the
  38572. * specific language governing permissions and limitations
  38573. * under the License.
  38574. */
  38575. /**
  38576. * LegendVisualProvider is an bridge that pick encoded color from data and
  38577. * provide to the legend component.
  38578. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  38579. * @param {Function} getRawData Function to get raw data before filtered.
  38580. */
  38581. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  38582. this.getAllNames = function () {
  38583. var rawData = getRawData();
  38584. // We find the name from the raw data. In case it's filtered by the legend component.
  38585. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38586. return rawData.mapArray(rawData.getName);
  38587. };
  38588. this.containName = function (name) {
  38589. var rawData = getRawData();
  38590. return rawData.indexOfName(name) >= 0;
  38591. };
  38592. this.indexOfName = function (name) {
  38593. // Only get data when necessary.
  38594. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38595. // Invoking Series#getData immediately will throw an error.
  38596. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38597. return dataWithEncodedVisual.indexOfName(name);
  38598. };
  38599. this.getItemVisual = function (dataIndex, key) {
  38600. // Get encoded visual properties from final filtered data.
  38601. var dataWithEncodedVisual = getDataWithEncodedVisual();
  38602. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38603. };
  38604. }
  38605. /*
  38606. * Licensed to the Apache Software Foundation (ASF) under one
  38607. * or more contributor license agreements. See the NOTICE file
  38608. * distributed with this work for additional information
  38609. * regarding copyright ownership. The ASF licenses this file
  38610. * to you under the Apache License, Version 2.0 (the
  38611. * "License"); you may not use this file except in compliance
  38612. * with the License. You may obtain a copy of the License at
  38613. *
  38614. * http://www.apache.org/licenses/LICENSE-2.0
  38615. *
  38616. * Unless required by applicable law or agreed to in writing,
  38617. * software distributed under the License is distributed on an
  38618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38619. * KIND, either express or implied. See the License for the
  38620. * specific language governing permissions and limitations
  38621. * under the License.
  38622. */
  38623. var PieSeries = extendSeriesModel({
  38624. type: 'series.pie',
  38625. // Overwrite
  38626. init: function (option) {
  38627. PieSeries.superApply(this, 'init', arguments);
  38628. // Enable legend selection for each data item
  38629. // Use a function instead of direct access because data reference may changed
  38630. this.legendVisualProvider = new LegendVisualProvider(
  38631. bind(this.getData, this), bind(this.getRawData, this)
  38632. );
  38633. this.updateSelectedMap(this._createSelectableList());
  38634. this._defaultLabelLine(option);
  38635. },
  38636. // Overwrite
  38637. mergeOption: function (newOption) {
  38638. PieSeries.superCall(this, 'mergeOption', newOption);
  38639. this.updateSelectedMap(this._createSelectableList());
  38640. },
  38641. getInitialData: function (option, ecModel) {
  38642. return createListSimply(this, {
  38643. coordDimensions: ['value'],
  38644. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38645. });
  38646. },
  38647. _createSelectableList: function () {
  38648. var data = this.getRawData();
  38649. var valueDim = data.mapDimension('value');
  38650. var targetList = [];
  38651. for (var i = 0, len = data.count(); i < len; i++) {
  38652. targetList.push({
  38653. name: data.getName(i),
  38654. value: data.get(valueDim, i),
  38655. selected: retrieveRawAttr(data, i, 'selected')
  38656. });
  38657. }
  38658. return targetList;
  38659. },
  38660. // Overwrite
  38661. getDataParams: function (dataIndex) {
  38662. var data = this.getData();
  38663. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  38664. // FIXME toFixed?
  38665. var valueList = [];
  38666. data.each(data.mapDimension('value'), function (value) {
  38667. valueList.push(value);
  38668. });
  38669. params.percent = getPercentWithPrecision(
  38670. valueList,
  38671. dataIndex,
  38672. data.hostModel.get('percentPrecision')
  38673. );
  38674. params.$vars.push('percent');
  38675. return params;
  38676. },
  38677. _defaultLabelLine: function (option) {
  38678. // Extend labelLine emphasis
  38679. defaultEmphasis(option, 'labelLine', ['show']);
  38680. var labelLineNormalOpt = option.labelLine;
  38681. var labelLineEmphasisOpt = option.emphasis.labelLine;
  38682. // Not show label line if `label.normal.show = false`
  38683. labelLineNormalOpt.show = labelLineNormalOpt.show
  38684. && option.label.show;
  38685. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38686. && option.emphasis.label.show;
  38687. },
  38688. defaultOption: {
  38689. zlevel: 0,
  38690. z: 2,
  38691. legendHoverLink: true,
  38692. hoverAnimation: true,
  38693. // 默认全局居中
  38694. center: ['50%', '50%'],
  38695. radius: [0, '75%'],
  38696. // 默认顺时针
  38697. clockwise: true,
  38698. startAngle: 90,
  38699. // 最小角度改为0
  38700. minAngle: 0,
  38701. // If the angle of a sector less than `minShowLabelAngle`,
  38702. // the label will not be displayed.
  38703. minShowLabelAngle: 0,
  38704. // 选中时扇区偏移量
  38705. selectedOffset: 10,
  38706. // 高亮扇区偏移量
  38707. hoverOffset: 10,
  38708. // If use strategy to avoid label overlapping
  38709. avoidLabelOverlap: true,
  38710. // 选择模式,默认关闭,可选single,multiple
  38711. // selectedMode: false,
  38712. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38713. // roseType: null,
  38714. percentPrecision: 2,
  38715. // If still show when all data zero.
  38716. stillShowZeroSum: true,
  38717. // cursor: null,
  38718. left: 0,
  38719. top: 0,
  38720. right: 0,
  38721. bottom: 0,
  38722. width: null,
  38723. height: null,
  38724. label: {
  38725. // If rotate around circle
  38726. rotate: false,
  38727. show: true,
  38728. // 'outer', 'inside', 'center'
  38729. position: 'outer',
  38730. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38731. alignTo: 'none',
  38732. // Closest distance between label and chart edge.
  38733. // Works only position is 'outer' and alignTo is 'edge'.
  38734. margin: '25%',
  38735. // Works only position is 'outer' and alignTo is not 'edge'.
  38736. bleedMargin: 10,
  38737. // Distance between text and label line.
  38738. distanceToLabelLine: 5
  38739. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38740. // 默认使用全局文本样式,详见TEXTSTYLE
  38741. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38742. },
  38743. // Enabled when label.normal.position is 'outer'
  38744. labelLine: {
  38745. show: true,
  38746. // 引导线两段中的第一段长度
  38747. length: 15,
  38748. // 引导线两段中的第二段长度
  38749. length2: 15,
  38750. smooth: false,
  38751. lineStyle: {
  38752. // color: 各异,
  38753. width: 1,
  38754. type: 'solid'
  38755. }
  38756. },
  38757. itemStyle: {
  38758. borderWidth: 1
  38759. },
  38760. // Animation type. Valid values: expansion, scale
  38761. animationType: 'expansion',
  38762. // Animation type when update. Valid values: transition, expansion
  38763. animationTypeUpdate: 'transition',
  38764. animationEasing: 'cubicOut'
  38765. }
  38766. });
  38767. mixin(PieSeries, dataSelectableMixin);
  38768. /*
  38769. * Licensed to the Apache Software Foundation (ASF) under one
  38770. * or more contributor license agreements. See the NOTICE file
  38771. * distributed with this work for additional information
  38772. * regarding copyright ownership. The ASF licenses this file
  38773. * to you under the Apache License, Version 2.0 (the
  38774. * "License"); you may not use this file except in compliance
  38775. * with the License. You may obtain a copy of the License at
  38776. *
  38777. * http://www.apache.org/licenses/LICENSE-2.0
  38778. *
  38779. * Unless required by applicable law or agreed to in writing,
  38780. * software distributed under the License is distributed on an
  38781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38782. * KIND, either express or implied. See the License for the
  38783. * specific language governing permissions and limitations
  38784. * under the License.
  38785. */
  38786. /**
  38787. * @param {module:echarts/model/Series} seriesModel
  38788. * @param {boolean} hasAnimation
  38789. * @inner
  38790. */
  38791. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  38792. var data = seriesModel.getData();
  38793. var dataIndex = this.dataIndex;
  38794. var name = data.getName(dataIndex);
  38795. var selectedOffset = seriesModel.get('selectedOffset');
  38796. api.dispatchAction({
  38797. type: 'pieToggleSelect',
  38798. from: uid,
  38799. name: name,
  38800. seriesId: seriesModel.id
  38801. });
  38802. data.each(function (idx) {
  38803. toggleItemSelected(
  38804. data.getItemGraphicEl(idx),
  38805. data.getItemLayout(idx),
  38806. seriesModel.isSelected(data.getName(idx)),
  38807. selectedOffset,
  38808. hasAnimation
  38809. );
  38810. });
  38811. }
  38812. /**
  38813. * @param {module:zrender/graphic/Sector} el
  38814. * @param {Object} layout
  38815. * @param {boolean} isSelected
  38816. * @param {number} selectedOffset
  38817. * @param {boolean} hasAnimation
  38818. * @inner
  38819. */
  38820. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  38821. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38822. var dx = Math.cos(midAngle);
  38823. var dy = Math.sin(midAngle);
  38824. var offset = isSelected ? selectedOffset : 0;
  38825. var position = [dx * offset, dy * offset];
  38826. hasAnimation
  38827. // animateTo will stop revious animation like update transition
  38828. ? el.animate()
  38829. .when(200, {
  38830. position: position
  38831. })
  38832. .start('bounceOut')
  38833. : el.attr('position', position);
  38834. }
  38835. /**
  38836. * Piece of pie including Sector, Label, LabelLine
  38837. * @constructor
  38838. * @extends {module:zrender/graphic/Group}
  38839. */
  38840. function PiePiece(data, idx) {
  38841. Group.call(this);
  38842. var sector = new Sector({
  38843. z2: 2
  38844. });
  38845. var polyline = new Polyline();
  38846. var text = new Text();
  38847. this.add(sector);
  38848. this.add(polyline);
  38849. this.add(text);
  38850. this.updateData(data, idx, true);
  38851. }
  38852. var piePieceProto = PiePiece.prototype;
  38853. piePieceProto.updateData = function (data, idx, firstCreate) {
  38854. var sector = this.childAt(0);
  38855. var labelLine = this.childAt(1);
  38856. var labelText = this.childAt(2);
  38857. var seriesModel = data.hostModel;
  38858. var itemModel = data.getItemModel(idx);
  38859. var layout = data.getItemLayout(idx);
  38860. var sectorShape = extend({}, layout);
  38861. sectorShape.label = null;
  38862. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  38863. if (firstCreate) {
  38864. sector.setShape(sectorShape);
  38865. var animationType = seriesModel.getShallow('animationType');
  38866. if (animationType === 'scale') {
  38867. sector.shape.r = layout.r0;
  38868. initProps(sector, {
  38869. shape: {
  38870. r: layout.r
  38871. }
  38872. }, seriesModel, idx);
  38873. }
  38874. // Expansion
  38875. else {
  38876. sector.shape.endAngle = layout.startAngle;
  38877. updateProps(sector, {
  38878. shape: {
  38879. endAngle: layout.endAngle
  38880. }
  38881. }, seriesModel, idx);
  38882. }
  38883. }
  38884. else {
  38885. if (animationTypeUpdate === 'expansion') {
  38886. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  38887. sector.setShape(sectorShape);
  38888. }
  38889. else {
  38890. // Transition animation from the old shape
  38891. updateProps(sector, {
  38892. shape: sectorShape
  38893. }, seriesModel, idx);
  38894. }
  38895. }
  38896. // Update common style
  38897. var visualColor = data.getItemVisual(idx, 'color');
  38898. sector.useStyle(
  38899. defaults(
  38900. {
  38901. lineJoin: 'bevel',
  38902. fill: visualColor
  38903. },
  38904. itemModel.getModel('itemStyle').getItemStyle()
  38905. )
  38906. );
  38907. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38908. var cursorStyle = itemModel.getShallow('cursor');
  38909. cursorStyle && sector.attr('cursor', cursorStyle);
  38910. // Toggle selected
  38911. toggleItemSelected(
  38912. this,
  38913. data.getItemLayout(idx),
  38914. seriesModel.isSelected(data.getName(idx)),
  38915. seriesModel.get('selectedOffset'),
  38916. seriesModel.get('animation')
  38917. );
  38918. // Label and text animation should be applied only for transition type animation when update
  38919. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  38920. this._updateLabel(data, idx, withAnimation);
  38921. this.highDownOnUpdate = !seriesModel.get('silent')
  38922. ? function (fromState, toState) {
  38923. var hasAnimation = seriesModel.isAnimationEnabled() && itemModel.get('hoverAnimation');
  38924. if (toState === 'emphasis') {
  38925. labelLine.ignore = labelLine.hoverIgnore;
  38926. labelText.ignore = labelText.hoverIgnore;
  38927. // Sector may has animation of updating data. Force to move to the last frame
  38928. // Or it may stopped on the wrong shape
  38929. if (hasAnimation) {
  38930. sector.stopAnimation(true);
  38931. sector.animateTo({
  38932. shape: {
  38933. r: layout.r + seriesModel.get('hoverOffset')
  38934. }
  38935. }, 300, 'elasticOut');
  38936. }
  38937. }
  38938. else {
  38939. labelLine.ignore = labelLine.normalIgnore;
  38940. labelText.ignore = labelText.normalIgnore;
  38941. if (hasAnimation) {
  38942. sector.stopAnimation(true);
  38943. sector.animateTo({
  38944. shape: {
  38945. r: layout.r
  38946. }
  38947. }, 300, 'elasticOut');
  38948. }
  38949. }
  38950. }
  38951. : null;
  38952. setHoverStyle(this);
  38953. };
  38954. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  38955. var labelLine = this.childAt(1);
  38956. var labelText = this.childAt(2);
  38957. var seriesModel = data.hostModel;
  38958. var itemModel = data.getItemModel(idx);
  38959. var layout = data.getItemLayout(idx);
  38960. var labelLayout = layout.label;
  38961. var visualColor = data.getItemVisual(idx, 'color');
  38962. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  38963. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  38964. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  38965. return;
  38966. }
  38967. var targetLineShape = {
  38968. points: labelLayout.linePoints || [
  38969. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  38970. ]
  38971. };
  38972. var targetTextStyle = {
  38973. x: labelLayout.x,
  38974. y: labelLayout.y
  38975. };
  38976. if (withAnimation) {
  38977. updateProps(labelLine, {
  38978. shape: targetLineShape
  38979. }, seriesModel, idx);
  38980. updateProps(labelText, {
  38981. style: targetTextStyle
  38982. }, seriesModel, idx);
  38983. }
  38984. else {
  38985. labelLine.attr({
  38986. shape: targetLineShape
  38987. });
  38988. labelText.attr({
  38989. style: targetTextStyle
  38990. });
  38991. }
  38992. labelText.attr({
  38993. rotation: labelLayout.rotation,
  38994. origin: [labelLayout.x, labelLayout.y],
  38995. z2: 10
  38996. });
  38997. var labelModel = itemModel.getModel('label');
  38998. var labelHoverModel = itemModel.getModel('emphasis.label');
  38999. var labelLineModel = itemModel.getModel('labelLine');
  39000. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  39001. var visualColor = data.getItemVisual(idx, 'color');
  39002. setLabelStyle(
  39003. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  39004. {
  39005. labelFetcher: data.hostModel,
  39006. labelDataIndex: idx,
  39007. defaultText: labelLayout.text,
  39008. autoColor: visualColor,
  39009. useInsideStyle: !!labelLayout.inside
  39010. },
  39011. {
  39012. textAlign: labelLayout.textAlign,
  39013. textVerticalAlign: labelLayout.verticalAlign,
  39014. opacity: data.getItemVisual(idx, 'opacity')
  39015. }
  39016. );
  39017. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  39018. labelText.hoverIgnore = !labelHoverModel.get('show');
  39019. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  39020. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  39021. // Default use item visual color
  39022. labelLine.setStyle({
  39023. stroke: visualColor,
  39024. opacity: data.getItemVisual(idx, 'opacity')
  39025. });
  39026. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  39027. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  39028. var smooth = labelLineModel.get('smooth');
  39029. if (smooth && smooth === true) {
  39030. smooth = 0.4;
  39031. }
  39032. labelLine.setShape({
  39033. smooth: smooth
  39034. });
  39035. };
  39036. inherits(PiePiece, Group);
  39037. // Pie view
  39038. var PieView = Chart.extend({
  39039. type: 'pie',
  39040. init: function () {
  39041. var sectorGroup = new Group();
  39042. this._sectorGroup = sectorGroup;
  39043. },
  39044. render: function (seriesModel, ecModel, api, payload) {
  39045. if (payload && (payload.from === this.uid)) {
  39046. return;
  39047. }
  39048. var data = seriesModel.getData();
  39049. var oldData = this._data;
  39050. var group = this.group;
  39051. var hasAnimation = ecModel.get('animation');
  39052. var isFirstRender = !oldData;
  39053. var animationType = seriesModel.get('animationType');
  39054. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  39055. var onSectorClick = curry(
  39056. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  39057. );
  39058. var selectedMode = seriesModel.get('selectedMode');
  39059. data.diff(oldData)
  39060. .add(function (idx) {
  39061. var piePiece = new PiePiece(data, idx);
  39062. // Default expansion animation
  39063. if (isFirstRender && animationType !== 'scale') {
  39064. piePiece.eachChild(function (child) {
  39065. child.stopAnimation(true);
  39066. });
  39067. }
  39068. selectedMode && piePiece.on('click', onSectorClick);
  39069. data.setItemGraphicEl(idx, piePiece);
  39070. group.add(piePiece);
  39071. })
  39072. .update(function (newIdx, oldIdx) {
  39073. var piePiece = oldData.getItemGraphicEl(oldIdx);
  39074. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  39075. piePiece.eachChild(function (child) {
  39076. child.stopAnimation(true);
  39077. });
  39078. }
  39079. piePiece.updateData(data, newIdx);
  39080. piePiece.off('click');
  39081. selectedMode && piePiece.on('click', onSectorClick);
  39082. group.add(piePiece);
  39083. data.setItemGraphicEl(newIdx, piePiece);
  39084. })
  39085. .remove(function (idx) {
  39086. var piePiece = oldData.getItemGraphicEl(idx);
  39087. group.remove(piePiece);
  39088. })
  39089. .execute();
  39090. if (
  39091. hasAnimation && data.count() > 0
  39092. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  39093. ) {
  39094. var shape = data.getItemLayout(0);
  39095. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  39096. shape = data.getItemLayout(s);
  39097. }
  39098. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  39099. var removeClipPath = bind(group.removeClipPath, group);
  39100. group.setClipPath(this._createClipPath(
  39101. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  39102. ));
  39103. }
  39104. else {
  39105. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  39106. group.removeClipPath();
  39107. }
  39108. this._data = data;
  39109. },
  39110. dispose: function () {},
  39111. _createClipPath: function (
  39112. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  39113. ) {
  39114. var clipPath = new Sector({
  39115. shape: {
  39116. cx: cx,
  39117. cy: cy,
  39118. r0: 0,
  39119. r: r,
  39120. startAngle: startAngle,
  39121. endAngle: startAngle,
  39122. clockwise: clockwise
  39123. }
  39124. });
  39125. var initOrUpdate = isFirstRender ? initProps : updateProps;
  39126. initOrUpdate(clipPath, {
  39127. shape: {
  39128. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  39129. }
  39130. }, seriesModel, cb);
  39131. return clipPath;
  39132. },
  39133. /**
  39134. * @implement
  39135. */
  39136. containPoint: function (point, seriesModel) {
  39137. var data = seriesModel.getData();
  39138. var itemLayout = data.getItemLayout(0);
  39139. if (itemLayout) {
  39140. var dx = point[0] - itemLayout.cx;
  39141. var dy = point[1] - itemLayout.cy;
  39142. var radius = Math.sqrt(dx * dx + dy * dy);
  39143. return radius <= itemLayout.r && radius >= itemLayout.r0;
  39144. }
  39145. }
  39146. });
  39147. /*
  39148. * Licensed to the Apache Software Foundation (ASF) under one
  39149. * or more contributor license agreements. See the NOTICE file
  39150. * distributed with this work for additional information
  39151. * regarding copyright ownership. The ASF licenses this file
  39152. * to you under the Apache License, Version 2.0 (the
  39153. * "License"); you may not use this file except in compliance
  39154. * with the License. You may obtain a copy of the License at
  39155. *
  39156. * http://www.apache.org/licenses/LICENSE-2.0
  39157. *
  39158. * Unless required by applicable law or agreed to in writing,
  39159. * software distributed under the License is distributed on an
  39160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39161. * KIND, either express or implied. See the License for the
  39162. * specific language governing permissions and limitations
  39163. * under the License.
  39164. */
  39165. var createDataSelectAction = function (seriesType, actionInfos) {
  39166. each$1(actionInfos, function (actionInfo) {
  39167. actionInfo.update = 'updateView';
  39168. /**
  39169. * @payload
  39170. * @property {string} seriesName
  39171. * @property {string} name
  39172. */
  39173. registerAction(actionInfo, function (payload, ecModel) {
  39174. var selected = {};
  39175. ecModel.eachComponent(
  39176. {mainType: 'series', subType: seriesType, query: payload},
  39177. function (seriesModel) {
  39178. if (seriesModel[actionInfo.method]) {
  39179. seriesModel[actionInfo.method](
  39180. payload.name,
  39181. payload.dataIndex
  39182. );
  39183. }
  39184. var data = seriesModel.getData();
  39185. // Create selected map
  39186. data.each(function (idx) {
  39187. var name = data.getName(idx);
  39188. selected[name] = seriesModel.isSelected(name)
  39189. || false;
  39190. });
  39191. }
  39192. );
  39193. return {
  39194. name: payload.name,
  39195. selected: selected,
  39196. seriesId: payload.seriesId
  39197. };
  39198. });
  39199. });
  39200. };
  39201. /*
  39202. * Licensed to the Apache Software Foundation (ASF) under one
  39203. * or more contributor license agreements. See the NOTICE file
  39204. * distributed with this work for additional information
  39205. * regarding copyright ownership. The ASF licenses this file
  39206. * to you under the Apache License, Version 2.0 (the
  39207. * "License"); you may not use this file except in compliance
  39208. * with the License. You may obtain a copy of the License at
  39209. *
  39210. * http://www.apache.org/licenses/LICENSE-2.0
  39211. *
  39212. * Unless required by applicable law or agreed to in writing,
  39213. * software distributed under the License is distributed on an
  39214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39215. * KIND, either express or implied. See the License for the
  39216. * specific language governing permissions and limitations
  39217. * under the License.
  39218. */
  39219. // Pick color from palette for each data item.
  39220. // Applicable for charts that require applying color palette
  39221. // in data level (like pie, funnel, chord).
  39222. var dataColor = function (seriesType) {
  39223. return {
  39224. getTargetSeries: function (ecModel) {
  39225. // Pie and funnel may use diferrent scope
  39226. var paletteScope = {};
  39227. var seiresModelMap = createHashMap();
  39228. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39229. seriesModel.__paletteScope = paletteScope;
  39230. seiresModelMap.set(seriesModel.uid, seriesModel);
  39231. });
  39232. return seiresModelMap;
  39233. },
  39234. reset: function (seriesModel, ecModel) {
  39235. var dataAll = seriesModel.getRawData();
  39236. var idxMap = {};
  39237. var data = seriesModel.getData();
  39238. data.each(function (idx) {
  39239. var rawIdx = data.getRawIndex(idx);
  39240. idxMap[rawIdx] = idx;
  39241. });
  39242. dataAll.each(function (rawIdx) {
  39243. var filteredIdx = idxMap[rawIdx];
  39244. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  39245. var singleDataColor = filteredIdx != null
  39246. && data.getItemVisual(filteredIdx, 'color', true);
  39247. var singleDataBorderColor = filteredIdx != null
  39248. && data.getItemVisual(filteredIdx, 'borderColor', true);
  39249. var itemModel;
  39250. if (!singleDataColor || !singleDataBorderColor) {
  39251. // FIXME Performance
  39252. itemModel = dataAll.getItemModel(rawIdx);
  39253. }
  39254. if (!singleDataColor) {
  39255. var color = itemModel.get('itemStyle.color')
  39256. || seriesModel.getColorFromPalette(
  39257. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  39258. dataAll.count()
  39259. );
  39260. // Data is not filtered
  39261. if (filteredIdx != null) {
  39262. data.setItemVisual(filteredIdx, 'color', color);
  39263. }
  39264. }
  39265. if (!singleDataBorderColor) {
  39266. var borderColor = itemModel.get('itemStyle.borderColor');
  39267. // Data is not filtered
  39268. if (filteredIdx != null) {
  39269. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  39270. }
  39271. }
  39272. });
  39273. }
  39274. };
  39275. };
  39276. /*
  39277. * Licensed to the Apache Software Foundation (ASF) under one
  39278. * or more contributor license agreements. See the NOTICE file
  39279. * distributed with this work for additional information
  39280. * regarding copyright ownership. The ASF licenses this file
  39281. * to you under the Apache License, Version 2.0 (the
  39282. * "License"); you may not use this file except in compliance
  39283. * with the License. You may obtain a copy of the License at
  39284. *
  39285. * http://www.apache.org/licenses/LICENSE-2.0
  39286. *
  39287. * Unless required by applicable law or agreed to in writing,
  39288. * software distributed under the License is distributed on an
  39289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39290. * KIND, either express or implied. See the License for the
  39291. * specific language governing permissions and limitations
  39292. * under the License.
  39293. */
  39294. // FIXME emphasis label position is not same with normal label position
  39295. var RADIAN$1 = Math.PI / 180;
  39296. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  39297. list.sort(function (a, b) {
  39298. return a.y - b.y;
  39299. });
  39300. function shiftDown(start, end, delta, dir) {
  39301. for (var j = start; j < end; j++) {
  39302. if (list[j].y + delta > viewTop + viewHeight) {
  39303. break;
  39304. }
  39305. list[j].y += delta;
  39306. if (j > start
  39307. && j + 1 < end
  39308. && list[j + 1].y > list[j].y + list[j].height
  39309. ) {
  39310. shiftUp(j, delta / 2);
  39311. return;
  39312. }
  39313. }
  39314. shiftUp(end - 1, delta / 2);
  39315. }
  39316. function shiftUp(end, delta) {
  39317. for (var j = end; j >= 0; j--) {
  39318. if (list[j].y - delta < viewTop) {
  39319. break;
  39320. }
  39321. list[j].y -= delta;
  39322. if (j > 0
  39323. && list[j].y > list[j - 1].y + list[j - 1].height
  39324. ) {
  39325. break;
  39326. }
  39327. }
  39328. }
  39329. function changeX(list, isDownList, cx, cy, r, dir) {
  39330. var lastDeltaX = dir > 0
  39331. ? isDownList // right-side
  39332. ? Number.MAX_VALUE // down
  39333. : 0 // up
  39334. : isDownList // left-side
  39335. ? Number.MAX_VALUE // down
  39336. : 0; // up
  39337. for (var i = 0, l = list.length; i < l; i++) {
  39338. if (list[i].labelAlignTo !== 'none') {
  39339. continue;
  39340. }
  39341. var deltaY = Math.abs(list[i].y - cy);
  39342. var length = list[i].len;
  39343. var length2 = list[i].len2;
  39344. var deltaX = (deltaY < r + length)
  39345. ? Math.sqrt(
  39346. (r + length + length2) * (r + length + length2)
  39347. - deltaY * deltaY
  39348. )
  39349. : Math.abs(list[i].x - cx);
  39350. if (isDownList && deltaX >= lastDeltaX) {
  39351. // right-down, left-down
  39352. deltaX = lastDeltaX - 10;
  39353. }
  39354. if (!isDownList && deltaX <= lastDeltaX) {
  39355. // right-up, left-up
  39356. deltaX = lastDeltaX + 10;
  39357. }
  39358. list[i].x = cx + deltaX * dir;
  39359. lastDeltaX = deltaX;
  39360. }
  39361. }
  39362. var lastY = 0;
  39363. var delta;
  39364. var len = list.length;
  39365. var upList = [];
  39366. var downList = [];
  39367. for (var i = 0; i < len; i++) {
  39368. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  39369. var dx = list[i].x - farthestX;
  39370. list[i].linePoints[1][0] += dx;
  39371. list[i].x = farthestX;
  39372. }
  39373. delta = list[i].y - lastY;
  39374. if (delta < 0) {
  39375. shiftDown(i, len, -delta, dir);
  39376. }
  39377. lastY = list[i].y + list[i].height;
  39378. }
  39379. if (viewHeight - lastY < 0) {
  39380. shiftUp(len - 1, lastY - viewHeight);
  39381. }
  39382. for (var i = 0; i < len; i++) {
  39383. if (list[i].y >= cy) {
  39384. downList.push(list[i]);
  39385. }
  39386. else {
  39387. upList.push(list[i]);
  39388. }
  39389. }
  39390. changeX(upList, false, cx, cy, r, dir);
  39391. changeX(downList, true, cx, cy, r, dir);
  39392. }
  39393. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39394. var leftList = [];
  39395. var rightList = [];
  39396. var leftmostX = Number.MAX_VALUE;
  39397. var rightmostX = -Number.MAX_VALUE;
  39398. for (var i = 0; i < labelLayoutList.length; i++) {
  39399. if (isPositionCenter(labelLayoutList[i])) {
  39400. continue;
  39401. }
  39402. if (labelLayoutList[i].x < cx) {
  39403. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  39404. leftList.push(labelLayoutList[i]);
  39405. }
  39406. else {
  39407. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  39408. rightList.push(labelLayoutList[i]);
  39409. }
  39410. }
  39411. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  39412. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  39413. for (var i = 0; i < labelLayoutList.length; i++) {
  39414. var layout = labelLayoutList[i];
  39415. if (isPositionCenter(layout)) {
  39416. continue;
  39417. }
  39418. var linePoints = layout.linePoints;
  39419. if (linePoints) {
  39420. var isAlignToEdge = layout.labelAlignTo === 'edge';
  39421. var realTextWidth = layout.textRect.width;
  39422. var targetTextWidth;
  39423. if (isAlignToEdge) {
  39424. if (layout.x < cx) {
  39425. targetTextWidth = linePoints[2][0] - layout.labelDistance
  39426. - viewLeft - layout.labelMargin;
  39427. }
  39428. else {
  39429. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  39430. - linePoints[2][0] - layout.labelDistance;
  39431. }
  39432. }
  39433. else {
  39434. if (layout.x < cx) {
  39435. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  39436. }
  39437. else {
  39438. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  39439. }
  39440. }
  39441. if (targetTextWidth < layout.textRect.width) {
  39442. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  39443. if (layout.labelAlignTo === 'edge') {
  39444. realTextWidth = getWidth(layout.text, layout.font);
  39445. }
  39446. }
  39447. var dist = linePoints[1][0] - linePoints[2][0];
  39448. if (isAlignToEdge) {
  39449. if (layout.x < cx) {
  39450. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  39451. }
  39452. else {
  39453. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  39454. - realTextWidth - layout.labelDistance;
  39455. }
  39456. }
  39457. else {
  39458. if (layout.x < cx) {
  39459. linePoints[2][0] = layout.x + layout.labelDistance;
  39460. }
  39461. else {
  39462. linePoints[2][0] = layout.x - layout.labelDistance;
  39463. }
  39464. linePoints[1][0] = linePoints[2][0] + dist;
  39465. }
  39466. linePoints[1][1] = linePoints[2][1] = layout.y;
  39467. }
  39468. }
  39469. }
  39470. function isPositionCenter(layout) {
  39471. // Not change x for center label
  39472. return layout.position === 'center';
  39473. }
  39474. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  39475. var data = seriesModel.getData();
  39476. var labelLayoutList = [];
  39477. var cx;
  39478. var cy;
  39479. var hasLabelRotate = false;
  39480. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  39481. data.each(function (idx) {
  39482. var layout = data.getItemLayout(idx);
  39483. var itemModel = data.getItemModel(idx);
  39484. var labelModel = itemModel.getModel('label');
  39485. // Use position in normal or emphasis
  39486. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  39487. var labelDistance = labelModel.get('distanceToLabelLine');
  39488. var labelAlignTo = labelModel.get('alignTo');
  39489. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  39490. var bleedMargin = labelModel.get('bleedMargin');
  39491. var font = labelModel.getFont();
  39492. var labelLineModel = itemModel.getModel('labelLine');
  39493. var labelLineLen = labelLineModel.get('length');
  39494. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  39495. var labelLineLen2 = labelLineModel.get('length2');
  39496. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  39497. if (layout.angle < minShowLabelRadian) {
  39498. return;
  39499. }
  39500. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  39501. var dx = Math.cos(midAngle);
  39502. var dy = Math.sin(midAngle);
  39503. var textX;
  39504. var textY;
  39505. var linePoints;
  39506. var textAlign;
  39507. cx = layout.cx;
  39508. cy = layout.cy;
  39509. var text = seriesModel.getFormattedLabel(idx, 'normal')
  39510. || data.getName(idx);
  39511. var textRect = getBoundingRect(
  39512. text, font, textAlign, 'top'
  39513. );
  39514. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  39515. if (labelPosition === 'center') {
  39516. textX = layout.cx;
  39517. textY = layout.cy;
  39518. textAlign = 'center';
  39519. }
  39520. else {
  39521. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  39522. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  39523. textX = x1 + dx * 3;
  39524. textY = y1 + dy * 3;
  39525. if (!isLabelInside) {
  39526. // For roseType
  39527. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  39528. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  39529. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  39530. var y3 = y2;
  39531. if (labelAlignTo === 'edge') {
  39532. // Adjust textX because text align of edge is opposite
  39533. textX = dx < 0
  39534. ? viewLeft + labelMargin
  39535. : viewLeft + viewWidth - labelMargin;
  39536. }
  39537. else {
  39538. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  39539. }
  39540. textY = y3;
  39541. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  39542. }
  39543. textAlign = isLabelInside
  39544. ? 'center'
  39545. : (labelAlignTo === 'edge'
  39546. ? (dx > 0 ? 'right' : 'left')
  39547. : (dx > 0 ? 'left' : 'right'));
  39548. }
  39549. var labelRotate;
  39550. var rotate = labelModel.get('rotate');
  39551. if (typeof rotate === 'number') {
  39552. labelRotate = rotate * (Math.PI / 180);
  39553. }
  39554. else {
  39555. labelRotate = rotate
  39556. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  39557. : 0;
  39558. }
  39559. hasLabelRotate = !!labelRotate;
  39560. layout.label = {
  39561. x: textX,
  39562. y: textY,
  39563. position: labelPosition,
  39564. height: textRect.height,
  39565. len: labelLineLen,
  39566. len2: labelLineLen2,
  39567. linePoints: linePoints,
  39568. textAlign: textAlign,
  39569. verticalAlign: 'middle',
  39570. rotation: labelRotate,
  39571. inside: isLabelInside,
  39572. labelDistance: labelDistance,
  39573. labelAlignTo: labelAlignTo,
  39574. labelMargin: labelMargin,
  39575. bleedMargin: bleedMargin,
  39576. textRect: textRect,
  39577. text: text,
  39578. font: font
  39579. };
  39580. // Not layout the inside label
  39581. if (!isLabelInside) {
  39582. labelLayoutList.push(layout.label);
  39583. }
  39584. });
  39585. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  39586. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  39587. }
  39588. };
  39589. /*
  39590. * Licensed to the Apache Software Foundation (ASF) under one
  39591. * or more contributor license agreements. See the NOTICE file
  39592. * distributed with this work for additional information
  39593. * regarding copyright ownership. The ASF licenses this file
  39594. * to you under the Apache License, Version 2.0 (the
  39595. * "License"); you may not use this file except in compliance
  39596. * with the License. You may obtain a copy of the License at
  39597. *
  39598. * http://www.apache.org/licenses/LICENSE-2.0
  39599. *
  39600. * Unless required by applicable law or agreed to in writing,
  39601. * software distributed under the License is distributed on an
  39602. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39603. * KIND, either express or implied. See the License for the
  39604. * specific language governing permissions and limitations
  39605. * under the License.
  39606. */
  39607. var PI2$4 = Math.PI * 2;
  39608. var RADIAN = Math.PI / 180;
  39609. function getViewRect(seriesModel, api) {
  39610. return getLayoutRect(
  39611. seriesModel.getBoxLayoutParams(), {
  39612. width: api.getWidth(),
  39613. height: api.getHeight()
  39614. }
  39615. );
  39616. }
  39617. var pieLayout = function (seriesType, ecModel, api, payload) {
  39618. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  39619. var data = seriesModel.getData();
  39620. var valueDim = data.mapDimension('value');
  39621. var viewRect = getViewRect(seriesModel, api);
  39622. var center = seriesModel.get('center');
  39623. var radius = seriesModel.get('radius');
  39624. if (!isArray(radius)) {
  39625. radius = [0, radius];
  39626. }
  39627. if (!isArray(center)) {
  39628. center = [center, center];
  39629. }
  39630. var width = parsePercent$1(viewRect.width, api.getWidth());
  39631. var height = parsePercent$1(viewRect.height, api.getHeight());
  39632. var size = Math.min(width, height);
  39633. var cx = parsePercent$1(center[0], width) + viewRect.x;
  39634. var cy = parsePercent$1(center[1], height) + viewRect.y;
  39635. var r0 = parsePercent$1(radius[0], size / 2);
  39636. var r = parsePercent$1(radius[1], size / 2);
  39637. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  39638. var minAngle = seriesModel.get('minAngle') * RADIAN;
  39639. var validDataCount = 0;
  39640. data.each(valueDim, function (value) {
  39641. !isNaN(value) && validDataCount++;
  39642. });
  39643. var sum = data.getSum(valueDim);
  39644. // Sum may be 0
  39645. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  39646. var clockwise = seriesModel.get('clockwise');
  39647. var roseType = seriesModel.get('roseType');
  39648. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  39649. // [0...max]
  39650. var extent = data.getDataExtent(valueDim);
  39651. extent[0] = 0;
  39652. // In the case some sector angle is smaller than minAngle
  39653. var restAngle = PI2$4;
  39654. var valueSumLargerThanMinAngle = 0;
  39655. var currentAngle = startAngle;
  39656. var dir = clockwise ? 1 : -1;
  39657. data.each(valueDim, function (value, idx) {
  39658. var angle;
  39659. if (isNaN(value)) {
  39660. data.setItemLayout(idx, {
  39661. angle: NaN,
  39662. startAngle: NaN,
  39663. endAngle: NaN,
  39664. clockwise: clockwise,
  39665. cx: cx,
  39666. cy: cy,
  39667. r0: r0,
  39668. r: roseType
  39669. ? NaN
  39670. : r,
  39671. viewRect: viewRect
  39672. });
  39673. return;
  39674. }
  39675. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  39676. if (roseType !== 'area') {
  39677. angle = (sum === 0 && stillShowZeroSum)
  39678. ? unitRadian : (value * unitRadian);
  39679. }
  39680. else {
  39681. angle = PI2$4 / validDataCount;
  39682. }
  39683. if (angle < minAngle) {
  39684. angle = minAngle;
  39685. restAngle -= minAngle;
  39686. }
  39687. else {
  39688. valueSumLargerThanMinAngle += value;
  39689. }
  39690. var endAngle = currentAngle + dir * angle;
  39691. data.setItemLayout(idx, {
  39692. angle: angle,
  39693. startAngle: currentAngle,
  39694. endAngle: endAngle,
  39695. clockwise: clockwise,
  39696. cx: cx,
  39697. cy: cy,
  39698. r0: r0,
  39699. r: roseType
  39700. ? linearMap(value, extent, [r0, r])
  39701. : r,
  39702. viewRect: viewRect
  39703. });
  39704. currentAngle = endAngle;
  39705. });
  39706. // Some sector is constrained by minAngle
  39707. // Rest sectors needs recalculate angle
  39708. if (restAngle < PI2$4 && validDataCount) {
  39709. // Average the angle if rest angle is not enough after all angles is
  39710. // Constrained by minAngle
  39711. if (restAngle <= 1e-3) {
  39712. var angle = PI2$4 / validDataCount;
  39713. data.each(valueDim, function (value, idx) {
  39714. if (!isNaN(value)) {
  39715. var layout = data.getItemLayout(idx);
  39716. layout.angle = angle;
  39717. layout.startAngle = startAngle + dir * idx * angle;
  39718. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  39719. }
  39720. });
  39721. }
  39722. else {
  39723. unitRadian = restAngle / valueSumLargerThanMinAngle;
  39724. currentAngle = startAngle;
  39725. data.each(valueDim, function (value, idx) {
  39726. if (!isNaN(value)) {
  39727. var layout = data.getItemLayout(idx);
  39728. var angle = layout.angle === minAngle
  39729. ? minAngle : value * unitRadian;
  39730. layout.startAngle = currentAngle;
  39731. layout.endAngle = currentAngle + dir * angle;
  39732. currentAngle += dir * angle;
  39733. }
  39734. });
  39735. }
  39736. }
  39737. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  39738. });
  39739. };
  39740. /*
  39741. * Licensed to the Apache Software Foundation (ASF) under one
  39742. * or more contributor license agreements. See the NOTICE file
  39743. * distributed with this work for additional information
  39744. * regarding copyright ownership. The ASF licenses this file
  39745. * to you under the Apache License, Version 2.0 (the
  39746. * "License"); you may not use this file except in compliance
  39747. * with the License. You may obtain a copy of the License at
  39748. *
  39749. * http://www.apache.org/licenses/LICENSE-2.0
  39750. *
  39751. * Unless required by applicable law or agreed to in writing,
  39752. * software distributed under the License is distributed on an
  39753. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39754. * KIND, either express or implied. See the License for the
  39755. * specific language governing permissions and limitations
  39756. * under the License.
  39757. */
  39758. var dataFilter = function (seriesType) {
  39759. return {
  39760. seriesType: seriesType,
  39761. reset: function (seriesModel, ecModel) {
  39762. var legendModels = ecModel.findComponents({
  39763. mainType: 'legend'
  39764. });
  39765. if (!legendModels || !legendModels.length) {
  39766. return;
  39767. }
  39768. var data = seriesModel.getData();
  39769. data.filterSelf(function (idx) {
  39770. var name = data.getName(idx);
  39771. // If in any legend component the status is not selected.
  39772. for (var i = 0; i < legendModels.length; i++) {
  39773. if (!legendModels[i].isSelected(name)) {
  39774. return false;
  39775. }
  39776. }
  39777. return true;
  39778. });
  39779. }
  39780. };
  39781. };
  39782. /*
  39783. * Licensed to the Apache Software Foundation (ASF) under one
  39784. * or more contributor license agreements. See the NOTICE file
  39785. * distributed with this work for additional information
  39786. * regarding copyright ownership. The ASF licenses this file
  39787. * to you under the Apache License, Version 2.0 (the
  39788. * "License"); you may not use this file except in compliance
  39789. * with the License. You may obtain a copy of the License at
  39790. *
  39791. * http://www.apache.org/licenses/LICENSE-2.0
  39792. *
  39793. * Unless required by applicable law or agreed to in writing,
  39794. * software distributed under the License is distributed on an
  39795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39796. * KIND, either express or implied. See the License for the
  39797. * specific language governing permissions and limitations
  39798. * under the License.
  39799. */
  39800. createDataSelectAction('pie', [{
  39801. type: 'pieToggleSelect',
  39802. event: 'pieselectchanged',
  39803. method: 'toggleSelected'
  39804. }, {
  39805. type: 'pieSelect',
  39806. event: 'pieselected',
  39807. method: 'select'
  39808. }, {
  39809. type: 'pieUnSelect',
  39810. event: 'pieunselected',
  39811. method: 'unSelect'
  39812. }]);
  39813. registerVisual(dataColor('pie'));
  39814. registerLayout(curry(pieLayout, 'pie'));
  39815. registerProcessor(dataFilter('pie'));
  39816. /*
  39817. * Licensed to the Apache Software Foundation (ASF) under one
  39818. * or more contributor license agreements. See the NOTICE file
  39819. * distributed with this work for additional information
  39820. * regarding copyright ownership. The ASF licenses this file
  39821. * to you under the Apache License, Version 2.0 (the
  39822. * "License"); you may not use this file except in compliance
  39823. * with the License. You may obtain a copy of the License at
  39824. *
  39825. * http://www.apache.org/licenses/LICENSE-2.0
  39826. *
  39827. * Unless required by applicable law or agreed to in writing,
  39828. * software distributed under the License is distributed on an
  39829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39830. * KIND, either express or implied. See the License for the
  39831. * specific language governing permissions and limitations
  39832. * under the License.
  39833. */
  39834. SeriesModel.extend({
  39835. type: 'series.scatter',
  39836. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  39837. getInitialData: function (option, ecModel) {
  39838. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  39839. },
  39840. brushSelector: 'point',
  39841. getProgressive: function () {
  39842. var progressive = this.option.progressive;
  39843. if (progressive == null) {
  39844. // PENDING
  39845. return this.option.large ? 5e3 : this.get('progressive');
  39846. }
  39847. return progressive;
  39848. },
  39849. getProgressiveThreshold: function () {
  39850. var progressiveThreshold = this.option.progressiveThreshold;
  39851. if (progressiveThreshold == null) {
  39852. // PENDING
  39853. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  39854. }
  39855. return progressiveThreshold;
  39856. },
  39857. defaultOption: {
  39858. coordinateSystem: 'cartesian2d',
  39859. zlevel: 0,
  39860. z: 2,
  39861. legendHoverLink: true,
  39862. hoverAnimation: true,
  39863. // Cartesian coordinate system
  39864. // xAxisIndex: 0,
  39865. // yAxisIndex: 0,
  39866. // Polar coordinate system
  39867. // polarIndex: 0,
  39868. // Geo coordinate system
  39869. // geoIndex: 0,
  39870. // symbol: null, // 图形类型
  39871. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  39872. // symbolRotate: null, // 图形旋转控制
  39873. large: false,
  39874. // Available when large is true
  39875. largeThreshold: 2000,
  39876. // cursor: null,
  39877. // label: {
  39878. // show: false
  39879. // distance: 5,
  39880. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  39881. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  39882. // 'inside'|'left'|'right'|'top'|'bottom'
  39883. // 默认使用全局文本样式,详见TEXTSTYLE
  39884. // },
  39885. itemStyle: {
  39886. opacity: 0.8
  39887. // color: 各异
  39888. },
  39889. // If clip the overflow graphics
  39890. // Works on cartesian / polar series
  39891. clip: true
  39892. // progressive: null
  39893. }
  39894. });
  39895. /*
  39896. * Licensed to the Apache Software Foundation (ASF) under one
  39897. * or more contributor license agreements. See the NOTICE file
  39898. * distributed with this work for additional information
  39899. * regarding copyright ownership. The ASF licenses this file
  39900. * to you under the Apache License, Version 2.0 (the
  39901. * "License"); you may not use this file except in compliance
  39902. * with the License. You may obtain a copy of the License at
  39903. *
  39904. * http://www.apache.org/licenses/LICENSE-2.0
  39905. *
  39906. * Unless required by applicable law or agreed to in writing,
  39907. * software distributed under the License is distributed on an
  39908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39909. * KIND, either express or implied. See the License for the
  39910. * specific language governing permissions and limitations
  39911. * under the License.
  39912. */
  39913. /* global Float32Array */
  39914. // TODO Batch by color
  39915. var BOOST_SIZE_THRESHOLD = 4;
  39916. var LargeSymbolPath = extendShape({
  39917. shape: {
  39918. points: null
  39919. },
  39920. symbolProxy: null,
  39921. softClipShape: null,
  39922. buildPath: function (path, shape) {
  39923. var points = shape.points;
  39924. var size = shape.size;
  39925. var symbolProxy = this.symbolProxy;
  39926. var symbolProxyShape = symbolProxy.shape;
  39927. var ctx = path.getContext ? path.getContext() : path;
  39928. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  39929. // Do draw in afterBrush.
  39930. if (canBoost) {
  39931. return;
  39932. }
  39933. for (var i = 0; i < points.length;) {
  39934. var x = points[i++];
  39935. var y = points[i++];
  39936. if (isNaN(x) || isNaN(y)) {
  39937. continue;
  39938. }
  39939. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39940. continue;
  39941. }
  39942. symbolProxyShape.x = x - size[0] / 2;
  39943. symbolProxyShape.y = y - size[1] / 2;
  39944. symbolProxyShape.width = size[0];
  39945. symbolProxyShape.height = size[1];
  39946. symbolProxy.buildPath(path, symbolProxyShape, true);
  39947. }
  39948. },
  39949. afterBrush: function (ctx) {
  39950. var shape = this.shape;
  39951. var points = shape.points;
  39952. var size = shape.size;
  39953. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  39954. if (!canBoost) {
  39955. return;
  39956. }
  39957. this.setTransform(ctx);
  39958. // PENDING If style or other canvas status changed?
  39959. for (var i = 0; i < points.length;) {
  39960. var x = points[i++];
  39961. var y = points[i++];
  39962. if (isNaN(x) || isNaN(y)) {
  39963. continue;
  39964. }
  39965. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  39966. continue;
  39967. }
  39968. // fillRect is faster than building a rect path and draw.
  39969. // And it support light globalCompositeOperation.
  39970. ctx.fillRect(
  39971. x - size[0] / 2, y - size[1] / 2,
  39972. size[0], size[1]
  39973. );
  39974. }
  39975. this.restoreTransform(ctx);
  39976. },
  39977. findDataIndex: function (x, y) {
  39978. // TODO ???
  39979. // Consider transform
  39980. var shape = this.shape;
  39981. var points = shape.points;
  39982. var size = shape.size;
  39983. var w = Math.max(size[0], 4);
  39984. var h = Math.max(size[1], 4);
  39985. // Not consider transform
  39986. // Treat each element as a rect
  39987. // top down traverse
  39988. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  39989. var i = idx * 2;
  39990. var x0 = points[i] - w / 2;
  39991. var y0 = points[i + 1] - h / 2;
  39992. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  39993. return idx;
  39994. }
  39995. }
  39996. return -1;
  39997. }
  39998. });
  39999. function LargeSymbolDraw() {
  40000. this.group = new Group();
  40001. }
  40002. var largeSymbolProto = LargeSymbolDraw.prototype;
  40003. largeSymbolProto.isPersistent = function () {
  40004. return !this._incremental;
  40005. };
  40006. /**
  40007. * Update symbols draw by new data
  40008. * @param {module:echarts/data/List} data
  40009. * @param {Object} opt
  40010. * @param {Object} [opt.clipShape]
  40011. */
  40012. largeSymbolProto.updateData = function (data, opt) {
  40013. this.group.removeAll();
  40014. var symbolEl = new LargeSymbolPath({
  40015. rectHover: true,
  40016. cursor: 'default'
  40017. });
  40018. symbolEl.setShape({
  40019. points: data.getLayout('symbolPoints')
  40020. });
  40021. this._setCommon(symbolEl, data, false, opt);
  40022. this.group.add(symbolEl);
  40023. this._incremental = null;
  40024. };
  40025. largeSymbolProto.updateLayout = function (data) {
  40026. if (this._incremental) {
  40027. return;
  40028. }
  40029. var points = data.getLayout('symbolPoints');
  40030. this.group.eachChild(function (child) {
  40031. if (child.startIndex != null) {
  40032. var len = (child.endIndex - child.startIndex) * 2;
  40033. var byteOffset = child.startIndex * 4 * 2;
  40034. points = new Float32Array(points.buffer, byteOffset, len);
  40035. }
  40036. child.setShape('points', points);
  40037. });
  40038. };
  40039. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  40040. this.group.removeAll();
  40041. this._clearIncremental();
  40042. // Only use incremental displayables when data amount is larger than 2 million.
  40043. // PENDING Incremental data?
  40044. if (data.count() > 2e6) {
  40045. if (!this._incremental) {
  40046. this._incremental = new IncrementalDisplayble({
  40047. silent: true
  40048. });
  40049. }
  40050. this.group.add(this._incremental);
  40051. }
  40052. else {
  40053. this._incremental = null;
  40054. }
  40055. };
  40056. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  40057. var symbolEl;
  40058. if (this._incremental) {
  40059. symbolEl = new LargeSymbolPath();
  40060. this._incremental.addDisplayable(symbolEl, true);
  40061. }
  40062. else {
  40063. symbolEl = new LargeSymbolPath({
  40064. rectHover: true,
  40065. cursor: 'default',
  40066. startIndex: taskParams.start,
  40067. endIndex: taskParams.end
  40068. });
  40069. symbolEl.incremental = true;
  40070. this.group.add(symbolEl);
  40071. }
  40072. symbolEl.setShape({
  40073. points: data.getLayout('symbolPoints')
  40074. });
  40075. this._setCommon(symbolEl, data, !!this._incremental, opt);
  40076. };
  40077. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  40078. var hostModel = data.hostModel;
  40079. opt = opt || {};
  40080. // TODO
  40081. // if (data.hasItemVisual.symbolSize) {
  40082. // // TODO typed array?
  40083. // symbolEl.setShape('sizes', data.mapArray(
  40084. // function (idx) {
  40085. // var size = data.getItemVisual(idx, 'symbolSize');
  40086. // return (size instanceof Array) ? size : [size, size];
  40087. // }
  40088. // ));
  40089. // }
  40090. // else {
  40091. var size = data.getVisual('symbolSize');
  40092. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  40093. // }
  40094. symbolEl.softClipShape = opt.clipShape || null;
  40095. // Create symbolProxy to build path for each data
  40096. symbolEl.symbolProxy = createSymbol(
  40097. data.getVisual('symbol'), 0, 0, 0, 0
  40098. );
  40099. // Use symbolProxy setColor method
  40100. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  40101. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  40102. symbolEl.useStyle(
  40103. // Draw shadow when doing fillRect is extremely slow.
  40104. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  40105. );
  40106. var visualColor = data.getVisual('color');
  40107. if (visualColor) {
  40108. symbolEl.setColor(visualColor);
  40109. }
  40110. if (!isIncremental) {
  40111. // Enable tooltip
  40112. // PENDING May have performance issue when path is extremely large
  40113. symbolEl.seriesIndex = hostModel.seriesIndex;
  40114. symbolEl.on('mousemove', function (e) {
  40115. symbolEl.dataIndex = null;
  40116. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  40117. if (dataIndex >= 0) {
  40118. // Provide dataIndex for tooltip
  40119. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  40120. }
  40121. });
  40122. }
  40123. };
  40124. largeSymbolProto.remove = function () {
  40125. this._clearIncremental();
  40126. this._incremental = null;
  40127. this.group.removeAll();
  40128. };
  40129. largeSymbolProto._clearIncremental = function () {
  40130. var incremental = this._incremental;
  40131. if (incremental) {
  40132. incremental.clearDisplaybles();
  40133. }
  40134. };
  40135. /*
  40136. * Licensed to the Apache Software Foundation (ASF) under one
  40137. * or more contributor license agreements. See the NOTICE file
  40138. * distributed with this work for additional information
  40139. * regarding copyright ownership. The ASF licenses this file
  40140. * to you under the Apache License, Version 2.0 (the
  40141. * "License"); you may not use this file except in compliance
  40142. * with the License. You may obtain a copy of the License at
  40143. *
  40144. * http://www.apache.org/licenses/LICENSE-2.0
  40145. *
  40146. * Unless required by applicable law or agreed to in writing,
  40147. * software distributed under the License is distributed on an
  40148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40149. * KIND, either express or implied. See the License for the
  40150. * specific language governing permissions and limitations
  40151. * under the License.
  40152. */
  40153. extendChartView({
  40154. type: 'scatter',
  40155. render: function (seriesModel, ecModel, api) {
  40156. var data = seriesModel.getData();
  40157. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40158. symbolDraw.updateData(data, {
  40159. // TODO
  40160. // If this parameter should be a shape or a bounding volume
  40161. // shape will be more general.
  40162. // But bounding volume like bounding rect will be much faster in the contain calculation
  40163. clipShape: this._getClipShape(seriesModel)
  40164. });
  40165. this._finished = true;
  40166. },
  40167. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  40168. var data = seriesModel.getData();
  40169. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  40170. symbolDraw.incrementalPrepareUpdate(data);
  40171. this._finished = false;
  40172. },
  40173. incrementalRender: function (taskParams, seriesModel, ecModel) {
  40174. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  40175. clipShape: this._getClipShape(seriesModel)
  40176. });
  40177. this._finished = taskParams.end === seriesModel.getData().count();
  40178. },
  40179. updateTransform: function (seriesModel, ecModel, api) {
  40180. var data = seriesModel.getData();
  40181. // Must mark group dirty and make sure the incremental layer will be cleared
  40182. // PENDING
  40183. this.group.dirty();
  40184. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  40185. return {
  40186. update: true
  40187. };
  40188. }
  40189. else {
  40190. var res = pointsLayout().reset(seriesModel);
  40191. if (res.progress) {
  40192. res.progress({ start: 0, end: data.count() }, data);
  40193. }
  40194. this._symbolDraw.updateLayout(data);
  40195. }
  40196. },
  40197. _getClipShape: function (seriesModel) {
  40198. var coordSys = seriesModel.coordinateSystem;
  40199. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  40200. return seriesModel.get('clip', true) ? clipArea : null;
  40201. },
  40202. _updateSymbolDraw: function (data, seriesModel) {
  40203. var symbolDraw = this._symbolDraw;
  40204. var pipelineContext = seriesModel.pipelineContext;
  40205. var isLargeDraw = pipelineContext.large;
  40206. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  40207. symbolDraw && symbolDraw.remove();
  40208. symbolDraw = this._symbolDraw = isLargeDraw
  40209. ? new LargeSymbolDraw()
  40210. : new SymbolDraw();
  40211. this._isLargeDraw = isLargeDraw;
  40212. this.group.removeAll();
  40213. }
  40214. this.group.add(symbolDraw.group);
  40215. return symbolDraw;
  40216. },
  40217. remove: function (ecModel, api) {
  40218. this._symbolDraw && this._symbolDraw.remove(true);
  40219. this._symbolDraw = null;
  40220. },
  40221. dispose: function () {}
  40222. });
  40223. /*
  40224. * Licensed to the Apache Software Foundation (ASF) under one
  40225. * or more contributor license agreements. See the NOTICE file
  40226. * distributed with this work for additional information
  40227. * regarding copyright ownership. The ASF licenses this file
  40228. * to you under the Apache License, Version 2.0 (the
  40229. * "License"); you may not use this file except in compliance
  40230. * with the License. You may obtain a copy of the License at
  40231. *
  40232. * http://www.apache.org/licenses/LICENSE-2.0
  40233. *
  40234. * Unless required by applicable law or agreed to in writing,
  40235. * software distributed under the License is distributed on an
  40236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40237. * KIND, either express or implied. See the License for the
  40238. * specific language governing permissions and limitations
  40239. * under the License.
  40240. */
  40241. // import * as zrUtil from 'zrender/src/core/util';
  40242. // In case developer forget to include grid component
  40243. registerVisual(visualSymbol('scatter', 'circle'));
  40244. registerLayout(pointsLayout('scatter'));
  40245. // echarts.registerProcessor(function (ecModel, api) {
  40246. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  40247. // var data = seriesModel.getData();
  40248. // var coordSys = seriesModel.coordinateSystem;
  40249. // if (coordSys.type !== 'geo') {
  40250. // return;
  40251. // }
  40252. // var startPt = coordSys.pointToData([0, 0]);
  40253. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  40254. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  40255. // return data.mapDimension(dim);
  40256. // });
  40257. // var range = {};
  40258. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  40259. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  40260. // data.selectRange(range);
  40261. // });
  40262. // });
  40263. /*
  40264. * Licensed to the Apache Software Foundation (ASF) under one
  40265. * or more contributor license agreements. See the NOTICE file
  40266. * distributed with this work for additional information
  40267. * regarding copyright ownership. The ASF licenses this file
  40268. * to you under the Apache License, Version 2.0 (the
  40269. * "License"); you may not use this file except in compliance
  40270. * with the License. You may obtain a copy of the License at
  40271. *
  40272. * http://www.apache.org/licenses/LICENSE-2.0
  40273. *
  40274. * Unless required by applicable law or agreed to in writing,
  40275. * software distributed under the License is distributed on an
  40276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40277. * KIND, either express or implied. See the License for the
  40278. * specific language governing permissions and limitations
  40279. * under the License.
  40280. */
  40281. var _nonShapeGraphicElements = {
  40282. // Reserved but not supported in graphic component.
  40283. path: null,
  40284. compoundPath: null,
  40285. // Supported in graphic component.
  40286. group: Group,
  40287. image: ZImage,
  40288. text: Text
  40289. };
  40290. // -------------
  40291. // Preprocessor
  40292. // -------------
  40293. registerPreprocessor(function (option) {
  40294. var graphicOption = option.graphic;
  40295. // Convert
  40296. // {graphic: [{left: 10, type: 'circle'}, ...]}
  40297. // or
  40298. // {graphic: {left: 10, type: 'circle'}}
  40299. // to
  40300. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  40301. if (isArray(graphicOption)) {
  40302. if (!graphicOption[0] || !graphicOption[0].elements) {
  40303. option.graphic = [{elements: graphicOption}];
  40304. }
  40305. else {
  40306. // Only one graphic instance can be instantiated. (We dont
  40307. // want that too many views are created in echarts._viewMap)
  40308. option.graphic = [option.graphic[0]];
  40309. }
  40310. }
  40311. else if (graphicOption && !graphicOption.elements) {
  40312. option.graphic = [{elements: [graphicOption]}];
  40313. }
  40314. });
  40315. // ------
  40316. // Model
  40317. // ------
  40318. var GraphicModel = extendComponentModel({
  40319. type: 'graphic',
  40320. defaultOption: {
  40321. // Extra properties for each elements:
  40322. //
  40323. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  40324. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  40325. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  40326. // This mechanism is useful when you want to position a group/element
  40327. // against the right side or the center of this container.
  40328. //
  40329. // width/height: (can only be pixel value, default 0)
  40330. // Only be used to specify contianer(group) size, if needed. And
  40331. // can not be percentage value (like '33%'). See the reason in the
  40332. // layout algorithm below.
  40333. //
  40334. // bounding: (enum: 'all' (default) | 'raw')
  40335. // Specify how to calculate boundingRect when locating.
  40336. // 'all': Get uioned and transformed boundingRect
  40337. // from both itself and its descendants.
  40338. // This mode simplies confining a group of elements in the bounding
  40339. // of their ancester container (e.g., using 'right: 0').
  40340. // 'raw': Only use the boundingRect of itself and before transformed.
  40341. // This mode is similar to css behavior, which is useful when you
  40342. // want an element to be able to overflow its container. (Consider
  40343. // a rotated circle needs to be located in a corner.)
  40344. // info: custom info. enables user to mount some info on elements and use them
  40345. // in event handlers. Update them only when user specified, otherwise, remain.
  40346. // Note: elements is always behind its ancestors in this elements array.
  40347. elements: [],
  40348. parentId: null
  40349. },
  40350. /**
  40351. * Save el options for the sake of the performance (only update modified graphics).
  40352. * The order is the same as those in option. (ancesters -> descendants)
  40353. *
  40354. * @private
  40355. * @type {Array.<Object>}
  40356. */
  40357. _elOptionsToUpdate: null,
  40358. /**
  40359. * @override
  40360. */
  40361. mergeOption: function (option) {
  40362. // Prevent default merge to elements
  40363. var elements = this.option.elements;
  40364. this.option.elements = null;
  40365. GraphicModel.superApply(this, 'mergeOption', arguments);
  40366. this.option.elements = elements;
  40367. },
  40368. /**
  40369. * @override
  40370. */
  40371. optionUpdated: function (newOption, isInit) {
  40372. var thisOption = this.option;
  40373. var newList = (isInit ? thisOption : newOption).elements;
  40374. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  40375. var flattenedList = [];
  40376. this._flatten(newList, flattenedList);
  40377. var mappingResult = mappingToExists(existList, flattenedList);
  40378. makeIdAndName(mappingResult);
  40379. // Clear elOptionsToUpdate
  40380. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  40381. each$1(mappingResult, function (resultItem, index) {
  40382. var newElOption = resultItem.option;
  40383. if (__DEV__) {
  40384. assert$1(
  40385. isObject$1(newElOption) || resultItem.exist,
  40386. 'Empty graphic option definition'
  40387. );
  40388. }
  40389. if (!newElOption) {
  40390. return;
  40391. }
  40392. elOptionsToUpdate.push(newElOption);
  40393. setKeyInfoToNewElOption(resultItem, newElOption);
  40394. mergeNewElOptionToExist(existList, index, newElOption);
  40395. setLayoutInfoToExist(existList[index], newElOption);
  40396. }, this);
  40397. // Clean
  40398. for (var i = existList.length - 1; i >= 0; i--) {
  40399. if (existList[i] == null) {
  40400. existList.splice(i, 1);
  40401. }
  40402. else {
  40403. // $action should be volatile, otherwise option gotten from
  40404. // `getOption` will contain unexpected $action.
  40405. delete existList[i].$action;
  40406. }
  40407. }
  40408. },
  40409. /**
  40410. * Convert
  40411. * [{
  40412. * type: 'group',
  40413. * id: 'xx',
  40414. * children: [{type: 'circle'}, {type: 'polygon'}]
  40415. * }]
  40416. * to
  40417. * [
  40418. * {type: 'group', id: 'xx'},
  40419. * {type: 'circle', parentId: 'xx'},
  40420. * {type: 'polygon', parentId: 'xx'}
  40421. * ]
  40422. *
  40423. * @private
  40424. * @param {Array.<Object>} optionList option list
  40425. * @param {Array.<Object>} result result of flatten
  40426. * @param {Object} parentOption parent option
  40427. */
  40428. _flatten: function (optionList, result, parentOption) {
  40429. each$1(optionList, function (option) {
  40430. if (!option) {
  40431. return;
  40432. }
  40433. if (parentOption) {
  40434. option.parentOption = parentOption;
  40435. }
  40436. result.push(option);
  40437. var children = option.children;
  40438. if (option.type === 'group' && children) {
  40439. this._flatten(children, result, option);
  40440. }
  40441. // Deleting for JSON output, and for not affecting group creation.
  40442. delete option.children;
  40443. }, this);
  40444. },
  40445. // FIXME
  40446. // Pass to view using payload? setOption has a payload?
  40447. useElOptionsToUpdate: function () {
  40448. var els = this._elOptionsToUpdate;
  40449. // Clear to avoid render duplicately when zooming.
  40450. this._elOptionsToUpdate = null;
  40451. return els;
  40452. }
  40453. });
  40454. // -----
  40455. // View
  40456. // -----
  40457. extendComponentView({
  40458. type: 'graphic',
  40459. /**
  40460. * @override
  40461. */
  40462. init: function (ecModel, api) {
  40463. /**
  40464. * @private
  40465. * @type {module:zrender/core/util.HashMap}
  40466. */
  40467. this._elMap = createHashMap();
  40468. /**
  40469. * @private
  40470. * @type {module:echarts/graphic/GraphicModel}
  40471. */
  40472. this._lastGraphicModel;
  40473. },
  40474. /**
  40475. * @override
  40476. */
  40477. render: function (graphicModel, ecModel, api) {
  40478. // Having leveraged between use cases and algorithm complexity, a very
  40479. // simple layout mechanism is used:
  40480. // The size(width/height) can be determined by itself or its parent (not
  40481. // implemented yet), but can not by its children. (Top-down travel)
  40482. // The location(x/y) can be determined by the bounding rect of itself
  40483. // (can including its descendants or not) and the size of its parent.
  40484. // (Bottom-up travel)
  40485. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  40486. // view will be reused.
  40487. if (graphicModel !== this._lastGraphicModel) {
  40488. this._clear();
  40489. }
  40490. this._lastGraphicModel = graphicModel;
  40491. this._updateElements(graphicModel);
  40492. this._relocate(graphicModel, api);
  40493. },
  40494. /**
  40495. * Update graphic elements.
  40496. *
  40497. * @private
  40498. * @param {Object} graphicModel graphic model
  40499. */
  40500. _updateElements: function (graphicModel) {
  40501. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  40502. if (!elOptionsToUpdate) {
  40503. return;
  40504. }
  40505. var elMap = this._elMap;
  40506. var rootGroup = this.group;
  40507. // Top-down tranverse to assign graphic settings to each elements.
  40508. each$1(elOptionsToUpdate, function (elOption) {
  40509. var $action = elOption.$action;
  40510. var id = elOption.id;
  40511. var existEl = elMap.get(id);
  40512. var parentId = elOption.parentId;
  40513. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  40514. var elOptionStyle = elOption.style;
  40515. if (elOption.type === 'text' && elOptionStyle) {
  40516. // In top/bottom mode, textVerticalAlign should not be used, which cause
  40517. // inaccurately locating.
  40518. if (elOption.hv && elOption.hv[1]) {
  40519. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  40520. }
  40521. // Compatible with previous setting: both support fill and textFill,
  40522. // stroke and textStroke.
  40523. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  40524. elOptionStyle.textFill = elOptionStyle.fill
  40525. );
  40526. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  40527. elOptionStyle.textStroke = elOptionStyle.stroke
  40528. );
  40529. }
  40530. // Remove unnecessary props to avoid potential problems.
  40531. var elOptionCleaned = getCleanedElOption(elOption);
  40532. // For simple, do not support parent change, otherwise reorder is needed.
  40533. if (__DEV__) {
  40534. existEl && assert$1(
  40535. targetElParent === existEl.parent,
  40536. 'Changing parent is not supported.'
  40537. );
  40538. }
  40539. if (!$action || $action === 'merge') {
  40540. existEl
  40541. ? existEl.attr(elOptionCleaned)
  40542. : createEl(id, targetElParent, elOptionCleaned, elMap);
  40543. }
  40544. else if ($action === 'replace') {
  40545. removeEl(existEl, elMap);
  40546. createEl(id, targetElParent, elOptionCleaned, elMap);
  40547. }
  40548. else if ($action === 'remove') {
  40549. removeEl(existEl, elMap);
  40550. }
  40551. var el = elMap.get(id);
  40552. if (el) {
  40553. el.__ecGraphicWidthOption = elOption.width;
  40554. el.__ecGraphicHeightOption = elOption.height;
  40555. setEventData(el, graphicModel, elOption);
  40556. }
  40557. });
  40558. },
  40559. /**
  40560. * Locate graphic elements.
  40561. *
  40562. * @private
  40563. * @param {Object} graphicModel graphic model
  40564. * @param {module:echarts/ExtensionAPI} api extension API
  40565. */
  40566. _relocate: function (graphicModel, api) {
  40567. var elOptions = graphicModel.option.elements;
  40568. var rootGroup = this.group;
  40569. var elMap = this._elMap;
  40570. var apiWidth = api.getWidth();
  40571. var apiHeight = api.getHeight();
  40572. // Top-down to calculate percentage width/height of group
  40573. for (var i = 0; i < elOptions.length; i++) {
  40574. var elOption = elOptions[i];
  40575. var el = elMap.get(elOption.id);
  40576. if (!el || !el.isGroup) {
  40577. continue;
  40578. }
  40579. var parentEl = el.parent;
  40580. var isParentRoot = parentEl === rootGroup;
  40581. // Like 'position:absolut' in css, default 0.
  40582. el.__ecGraphicWidth = parsePercent$1(
  40583. el.__ecGraphicWidthOption,
  40584. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  40585. ) || 0;
  40586. el.__ecGraphicHeight = parsePercent$1(
  40587. el.__ecGraphicHeightOption,
  40588. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  40589. ) || 0;
  40590. }
  40591. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  40592. for (var i = elOptions.length - 1; i >= 0; i--) {
  40593. var elOption = elOptions[i];
  40594. var el = elMap.get(elOption.id);
  40595. if (!el) {
  40596. continue;
  40597. }
  40598. var parentEl = el.parent;
  40599. var containerInfo = parentEl === rootGroup
  40600. ? {
  40601. width: apiWidth,
  40602. height: apiHeight
  40603. }
  40604. : {
  40605. width: parentEl.__ecGraphicWidth,
  40606. height: parentEl.__ecGraphicHeight
  40607. };
  40608. // PENDING
  40609. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  40610. // does not include the rect of [0, 0, group.width, group.height], which
  40611. // is probably weird for users. Should we make a break change for it?
  40612. positionElement(
  40613. el, elOption, containerInfo, null,
  40614. {hv: elOption.hv, boundingMode: elOption.bounding}
  40615. );
  40616. }
  40617. },
  40618. /**
  40619. * Clear all elements.
  40620. *
  40621. * @private
  40622. */
  40623. _clear: function () {
  40624. var elMap = this._elMap;
  40625. elMap.each(function (el) {
  40626. removeEl(el, elMap);
  40627. });
  40628. this._elMap = createHashMap();
  40629. },
  40630. /**
  40631. * @override
  40632. */
  40633. dispose: function () {
  40634. this._clear();
  40635. }
  40636. });
  40637. function createEl(id, targetElParent, elOption, elMap) {
  40638. var graphicType = elOption.type;
  40639. if (__DEV__) {
  40640. assert$1(graphicType, 'graphic type MUST be set');
  40641. }
  40642. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  40643. // Those graphic elements are not shapes. They should not be
  40644. // overwritten by users, so do them first.
  40645. ? _nonShapeGraphicElements[graphicType]
  40646. : getShapeClass(graphicType);
  40647. if (__DEV__) {
  40648. assert$1(Clz, 'graphic type can not be found');
  40649. }
  40650. var el = new Clz(elOption);
  40651. targetElParent.add(el);
  40652. elMap.set(id, el);
  40653. el.__ecGraphicId = id;
  40654. }
  40655. function removeEl(existEl, elMap) {
  40656. var existElParent = existEl && existEl.parent;
  40657. if (existElParent) {
  40658. existEl.type === 'group' && existEl.traverse(function (el) {
  40659. removeEl(el, elMap);
  40660. });
  40661. elMap.removeKey(existEl.__ecGraphicId);
  40662. existElParent.remove(existEl);
  40663. }
  40664. }
  40665. // Remove unnecessary props to avoid potential problems.
  40666. function getCleanedElOption(elOption) {
  40667. elOption = extend({}, elOption);
  40668. each$1(
  40669. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  40670. function (name) {
  40671. delete elOption[name];
  40672. }
  40673. );
  40674. return elOption;
  40675. }
  40676. function isSetLoc(obj, props) {
  40677. var isSet;
  40678. each$1(props, function (prop) {
  40679. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  40680. });
  40681. return isSet;
  40682. }
  40683. function setKeyInfoToNewElOption(resultItem, newElOption) {
  40684. var existElOption = resultItem.exist;
  40685. // Set id and type after id assigned.
  40686. newElOption.id = resultItem.keyInfo.id;
  40687. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  40688. // Set parent id if not specified
  40689. if (newElOption.parentId == null) {
  40690. var newElParentOption = newElOption.parentOption;
  40691. if (newElParentOption) {
  40692. newElOption.parentId = newElParentOption.id;
  40693. }
  40694. else if (existElOption) {
  40695. newElOption.parentId = existElOption.parentId;
  40696. }
  40697. }
  40698. // Clear
  40699. newElOption.parentOption = null;
  40700. }
  40701. function mergeNewElOptionToExist(existList, index, newElOption) {
  40702. // Update existing options, for `getOption` feature.
  40703. var newElOptCopy = extend({}, newElOption);
  40704. var existElOption = existList[index];
  40705. var $action = newElOption.$action || 'merge';
  40706. if ($action === 'merge') {
  40707. if (existElOption) {
  40708. if (__DEV__) {
  40709. var newType = newElOption.type;
  40710. assert$1(
  40711. !newType || existElOption.type === newType,
  40712. 'Please set $action: "replace" to change `type`'
  40713. );
  40714. }
  40715. // We can ensure that newElOptCopy and existElOption are not
  40716. // the same object, so `merge` will not change newElOptCopy.
  40717. merge(existElOption, newElOptCopy, true);
  40718. // Rigid body, use ignoreSize.
  40719. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  40720. // Will be used in render.
  40721. copyLayoutParams(newElOption, existElOption);
  40722. }
  40723. else {
  40724. existList[index] = newElOptCopy;
  40725. }
  40726. }
  40727. else if ($action === 'replace') {
  40728. existList[index] = newElOptCopy;
  40729. }
  40730. else if ($action === 'remove') {
  40731. // null will be cleaned later.
  40732. existElOption && (existList[index] = null);
  40733. }
  40734. }
  40735. function setLayoutInfoToExist(existItem, newElOption) {
  40736. if (!existItem) {
  40737. return;
  40738. }
  40739. existItem.hv = newElOption.hv = [
  40740. // Rigid body, dont care `width`.
  40741. isSetLoc(newElOption, ['left', 'right']),
  40742. // Rigid body, dont care `height`.
  40743. isSetLoc(newElOption, ['top', 'bottom'])
  40744. ];
  40745. // Give default group size. Otherwise layout error may occur.
  40746. if (existItem.type === 'group') {
  40747. existItem.width == null && (existItem.width = newElOption.width = 0);
  40748. existItem.height == null && (existItem.height = newElOption.height = 0);
  40749. }
  40750. }
  40751. function setEventData(el, graphicModel, elOption) {
  40752. var eventData = el.eventData;
  40753. // Simple optimize for large amount of elements that no need event.
  40754. if (!el.silent && !el.ignore && !eventData) {
  40755. eventData = el.eventData = {
  40756. componentType: 'graphic',
  40757. componentIndex: graphicModel.componentIndex,
  40758. name: el.name
  40759. };
  40760. }
  40761. // `elOption.info` enables user to mount some info on
  40762. // elements and use them in event handlers.
  40763. if (eventData) {
  40764. eventData.info = el.info;
  40765. }
  40766. }
  40767. /*
  40768. * Licensed to the Apache Software Foundation (ASF) under one
  40769. * or more contributor license agreements. See the NOTICE file
  40770. * distributed with this work for additional information
  40771. * regarding copyright ownership. The ASF licenses this file
  40772. * to you under the Apache License, Version 2.0 (the
  40773. * "License"); you may not use this file except in compliance
  40774. * with the License. You may obtain a copy of the License at
  40775. *
  40776. * http://www.apache.org/licenses/LICENSE-2.0
  40777. *
  40778. * Unless required by applicable law or agreed to in writing,
  40779. * software distributed under the License is distributed on an
  40780. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40781. * KIND, either express or implied. See the License for the
  40782. * specific language governing permissions and limitations
  40783. * under the License.
  40784. */
  40785. /**
  40786. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  40787. * @param {module:echarts/model/Global} ecModel
  40788. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  40789. */
  40790. var findPointFromSeries = function (finder, ecModel) {
  40791. var point = [];
  40792. var seriesIndex = finder.seriesIndex;
  40793. var seriesModel;
  40794. if (seriesIndex == null || !(
  40795. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  40796. )) {
  40797. return {point: []};
  40798. }
  40799. var data = seriesModel.getData();
  40800. var dataIndex = queryDataIndex(data, finder);
  40801. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  40802. return {point: []};
  40803. }
  40804. var el = data.getItemGraphicEl(dataIndex);
  40805. var coordSys = seriesModel.coordinateSystem;
  40806. if (seriesModel.getTooltipPosition) {
  40807. point = seriesModel.getTooltipPosition(dataIndex) || [];
  40808. }
  40809. else if (coordSys && coordSys.dataToPoint) {
  40810. point = coordSys.dataToPoint(
  40811. data.getValues(
  40812. map(coordSys.dimensions, function (dim) {
  40813. return data.mapDimension(dim);
  40814. }), dataIndex, true
  40815. )
  40816. ) || [];
  40817. }
  40818. else if (el) {
  40819. // Use graphic bounding rect
  40820. var rect = el.getBoundingRect().clone();
  40821. rect.applyTransform(el.transform);
  40822. point = [
  40823. rect.x + rect.width / 2,
  40824. rect.y + rect.height / 2
  40825. ];
  40826. }
  40827. return {point: point, el: el};
  40828. };
  40829. /*
  40830. * Licensed to the Apache Software Foundation (ASF) under one
  40831. * or more contributor license agreements. See the NOTICE file
  40832. * distributed with this work for additional information
  40833. * regarding copyright ownership. The ASF licenses this file
  40834. * to you under the Apache License, Version 2.0 (the
  40835. * "License"); you may not use this file except in compliance
  40836. * with the License. You may obtain a copy of the License at
  40837. *
  40838. * http://www.apache.org/licenses/LICENSE-2.0
  40839. *
  40840. * Unless required by applicable law or agreed to in writing,
  40841. * software distributed under the License is distributed on an
  40842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40843. * KIND, either express or implied. See the License for the
  40844. * specific language governing permissions and limitations
  40845. * under the License.
  40846. */
  40847. var each$7 = each$1;
  40848. var curry$2 = curry;
  40849. var inner$7 = makeInner();
  40850. /**
  40851. * Basic logic: check all axis, if they do not demand show/highlight,
  40852. * then hide/downplay them.
  40853. *
  40854. * @param {Object} coordSysAxesInfo
  40855. * @param {Object} payload
  40856. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  40857. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  40858. * trigger axisPointer and tooltip.
  40859. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  40860. * trigger axisPointer and tooltip.
  40861. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  40862. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  40863. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  40864. * [{
  40865. * axisDim: 'x'|'y'|'angle'|...,
  40866. * axisIndex: ...,
  40867. * value: ...
  40868. * }, ...]
  40869. * @param {Function} [payload.dispatchAction]
  40870. * @param {Object} [payload.tooltipOption]
  40871. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  40872. * which can be specified in dispatchAction
  40873. * @param {module:echarts/model/Global} ecModel
  40874. * @param {module:echarts/ExtensionAPI} api
  40875. * @return {Object} content of event obj for echarts.connect.
  40876. */
  40877. var axisTrigger = function (payload, ecModel, api) {
  40878. var currTrigger = payload.currTrigger;
  40879. var point = [payload.x, payload.y];
  40880. var finder = payload;
  40881. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  40882. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40883. // Pending
  40884. // See #6121. But we are not able to reproduce it yet.
  40885. if (!coordSysAxesInfo) {
  40886. return;
  40887. }
  40888. if (illegalPoint(point)) {
  40889. // Used in the default behavior of `connection`: use the sample seriesIndex
  40890. // and dataIndex. And also used in the tooltipView trigger.
  40891. point = findPointFromSeries({
  40892. seriesIndex: finder.seriesIndex,
  40893. // Do not use dataIndexInside from other ec instance.
  40894. // FIXME: auto detect it?
  40895. dataIndex: finder.dataIndex
  40896. }, ecModel).point;
  40897. }
  40898. var isIllegalPoint = illegalPoint(point);
  40899. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  40900. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  40901. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  40902. // and dataIndex.
  40903. var inputAxesInfo = finder.axesInfo;
  40904. var axesInfo = coordSysAxesInfo.axesInfo;
  40905. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  40906. var outputFinder = {};
  40907. var showValueMap = {};
  40908. var dataByCoordSys = {list: [], map: {}};
  40909. var updaters = {
  40910. showPointer: curry$2(showPointer, showValueMap),
  40911. showTooltip: curry$2(showTooltip, dataByCoordSys)
  40912. };
  40913. // Process for triggered axes.
  40914. each$7(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  40915. // If a point given, it must be contained by the coordinate system.
  40916. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  40917. each$7(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  40918. var axis = axisInfo.axis;
  40919. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  40920. // If no inputAxesInfo, no axis is restricted.
  40921. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  40922. var val = inputAxisInfo && inputAxisInfo.value;
  40923. if (val == null && !isIllegalPoint) {
  40924. val = axis.pointToData(point);
  40925. }
  40926. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  40927. }
  40928. });
  40929. });
  40930. // Process for linked axes.
  40931. var linkTriggers = {};
  40932. each$7(axesInfo, function (tarAxisInfo, tarKey) {
  40933. var linkGroup = tarAxisInfo.linkGroup;
  40934. // If axis has been triggered in the previous stage, it should not be triggered by link.
  40935. if (linkGroup && !showValueMap[tarKey]) {
  40936. each$7(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  40937. var srcValItem = showValueMap[srcKey];
  40938. // If srcValItem exist, source axis is triggered, so link to target axis.
  40939. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  40940. var val = srcValItem.value;
  40941. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  40942. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  40943. )));
  40944. linkTriggers[tarAxisInfo.key] = val;
  40945. }
  40946. });
  40947. }
  40948. });
  40949. each$7(linkTriggers, function (val, tarKey) {
  40950. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  40951. });
  40952. updateModelActually(showValueMap, axesInfo, outputFinder);
  40953. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  40954. dispatchHighDownActually(axesInfo, dispatchAction, api);
  40955. return outputFinder;
  40956. };
  40957. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  40958. var axis = axisInfo.axis;
  40959. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  40960. return;
  40961. }
  40962. if (!axisInfo.involveSeries) {
  40963. updaters.showPointer(axisInfo, newValue);
  40964. return;
  40965. }
  40966. // Heavy calculation. So put it after axis.containData checking.
  40967. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  40968. var payloadBatch = payloadInfo.payloadBatch;
  40969. var snapToValue = payloadInfo.snapToValue;
  40970. // Fill content of event obj for echarts.connect.
  40971. // By defualt use the first involved series data as a sample to connect.
  40972. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  40973. extend(outputFinder, payloadBatch[0]);
  40974. }
  40975. // If no linkSource input, this process is for collecting link
  40976. // target, where snap should not be accepted.
  40977. if (!dontSnap && axisInfo.snap) {
  40978. if (axis.containData(snapToValue) && snapToValue != null) {
  40979. newValue = snapToValue;
  40980. }
  40981. }
  40982. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  40983. // Tooltip should always be snapToValue, otherwise there will be
  40984. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  40985. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  40986. }
  40987. function buildPayloadsBySeries(value, axisInfo) {
  40988. var axis = axisInfo.axis;
  40989. var dim = axis.dim;
  40990. var snapToValue = value;
  40991. var payloadBatch = [];
  40992. var minDist = Number.MAX_VALUE;
  40993. var minDiff = -1;
  40994. each$7(axisInfo.seriesModels, function (series, idx) {
  40995. var dataDim = series.getData().mapDimension(dim, true);
  40996. var seriesNestestValue;
  40997. var dataIndices;
  40998. if (series.getAxisTooltipData) {
  40999. var result = series.getAxisTooltipData(dataDim, value, axis);
  41000. dataIndices = result.dataIndices;
  41001. seriesNestestValue = result.nestestValue;
  41002. }
  41003. else {
  41004. dataIndices = series.getData().indicesOfNearest(
  41005. dataDim[0],
  41006. value,
  41007. // Add a threshold to avoid find the wrong dataIndex
  41008. // when data length is not same.
  41009. // false,
  41010. axis.type === 'category' ? 0.5 : null
  41011. );
  41012. if (!dataIndices.length) {
  41013. return;
  41014. }
  41015. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  41016. }
  41017. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  41018. return;
  41019. }
  41020. var diff = value - seriesNestestValue;
  41021. var dist = Math.abs(diff);
  41022. // Consider category case
  41023. if (dist <= minDist) {
  41024. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  41025. minDist = dist;
  41026. minDiff = diff;
  41027. snapToValue = seriesNestestValue;
  41028. payloadBatch.length = 0;
  41029. }
  41030. each$7(dataIndices, function (dataIndex) {
  41031. payloadBatch.push({
  41032. seriesIndex: series.seriesIndex,
  41033. dataIndexInside: dataIndex,
  41034. dataIndex: series.getData().getRawIndex(dataIndex)
  41035. });
  41036. });
  41037. }
  41038. });
  41039. return {
  41040. payloadBatch: payloadBatch,
  41041. snapToValue: snapToValue
  41042. };
  41043. }
  41044. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  41045. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  41046. }
  41047. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  41048. var payloadBatch = payloadInfo.payloadBatch;
  41049. var axis = axisInfo.axis;
  41050. var axisModel = axis.model;
  41051. var axisPointerModel = axisInfo.axisPointerModel;
  41052. // If no data, do not create anything in dataByCoordSys,
  41053. // whose length will be used to judge whether dispatch action.
  41054. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  41055. return;
  41056. }
  41057. var coordSysModel = axisInfo.coordSys.model;
  41058. var coordSysKey = makeKey(coordSysModel);
  41059. var coordSysItem = dataByCoordSys.map[coordSysKey];
  41060. if (!coordSysItem) {
  41061. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  41062. coordSysId: coordSysModel.id,
  41063. coordSysIndex: coordSysModel.componentIndex,
  41064. coordSysType: coordSysModel.type,
  41065. coordSysMainType: coordSysModel.mainType,
  41066. dataByAxis: []
  41067. };
  41068. dataByCoordSys.list.push(coordSysItem);
  41069. }
  41070. coordSysItem.dataByAxis.push({
  41071. axisDim: axis.dim,
  41072. axisIndex: axisModel.componentIndex,
  41073. axisType: axisModel.type,
  41074. axisId: axisModel.id,
  41075. value: value,
  41076. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  41077. // depends that all models have been updated. So it should not be performed
  41078. // here. Considering axisPointerModel used here is volatile, which is hard
  41079. // to be retrieve in TooltipView, we prepare parameters here.
  41080. valueLabelOpt: {
  41081. precision: axisPointerModel.get('label.precision'),
  41082. formatter: axisPointerModel.get('label.formatter')
  41083. },
  41084. seriesDataIndices: payloadBatch.slice()
  41085. });
  41086. }
  41087. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  41088. var outputAxesInfo = outputFinder.axesInfo = [];
  41089. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  41090. each$7(axesInfo, function (axisInfo, key) {
  41091. var option = axisInfo.axisPointerModel.option;
  41092. var valItem = showValueMap[key];
  41093. if (valItem) {
  41094. !axisInfo.useHandle && (option.status = 'show');
  41095. option.value = valItem.value;
  41096. // For label formatter param and highlight.
  41097. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  41098. }
  41099. // When always show (e.g., handle used), remain
  41100. // original value and status.
  41101. else {
  41102. // If hide, value still need to be set, consider
  41103. // click legend to toggle axis blank.
  41104. !axisInfo.useHandle && (option.status = 'hide');
  41105. }
  41106. // If status is 'hide', should be no info in payload.
  41107. option.status === 'show' && outputAxesInfo.push({
  41108. axisDim: axisInfo.axis.dim,
  41109. axisIndex: axisInfo.axis.model.componentIndex,
  41110. value: option.value
  41111. });
  41112. });
  41113. }
  41114. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  41115. // Basic logic: If no showTip required, hideTip will be dispatched.
  41116. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  41117. dispatchAction({type: 'hideTip'});
  41118. return;
  41119. }
  41120. // In most case only one axis (or event one series is used). It is
  41121. // convinient to fetch payload.seriesIndex and payload.dataIndex
  41122. // dirtectly. So put the first seriesIndex and dataIndex of the first
  41123. // axis on the payload.
  41124. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  41125. dispatchAction({
  41126. type: 'showTip',
  41127. escapeConnect: true,
  41128. x: point[0],
  41129. y: point[1],
  41130. tooltipOption: payload.tooltipOption,
  41131. position: payload.position,
  41132. dataIndexInside: sampleItem.dataIndexInside,
  41133. dataIndex: sampleItem.dataIndex,
  41134. seriesIndex: sampleItem.seriesIndex,
  41135. dataByCoordSys: dataByCoordSys.list
  41136. });
  41137. }
  41138. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  41139. // FIXME
  41140. // highlight status modification shoule be a stage of main process?
  41141. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  41142. var zr = api.getZr();
  41143. var highDownKey = 'axisPointerLastHighlights';
  41144. var lastHighlights = inner$7(zr)[highDownKey] || {};
  41145. var newHighlights = inner$7(zr)[highDownKey] = {};
  41146. // Update highlight/downplay status according to axisPointer model.
  41147. // Build hash map and remove duplicate incidentally.
  41148. each$7(axesInfo, function (axisInfo, key) {
  41149. var option = axisInfo.axisPointerModel.option;
  41150. option.status === 'show' && each$7(option.seriesDataIndices, function (batchItem) {
  41151. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  41152. newHighlights[key] = batchItem;
  41153. });
  41154. });
  41155. // Diff.
  41156. var toHighlight = [];
  41157. var toDownplay = [];
  41158. each$1(lastHighlights, function (batchItem, key) {
  41159. !newHighlights[key] && toDownplay.push(batchItem);
  41160. });
  41161. each$1(newHighlights, function (batchItem, key) {
  41162. !lastHighlights[key] && toHighlight.push(batchItem);
  41163. });
  41164. toDownplay.length && api.dispatchAction({
  41165. type: 'downplay', escapeConnect: true, batch: toDownplay
  41166. });
  41167. toHighlight.length && api.dispatchAction({
  41168. type: 'highlight', escapeConnect: true, batch: toHighlight
  41169. });
  41170. }
  41171. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  41172. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  41173. var inputAxisInfo = inputAxesInfo[i];
  41174. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  41175. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  41176. ) {
  41177. return inputAxisInfo;
  41178. }
  41179. }
  41180. }
  41181. function makeMapperParam(axisInfo) {
  41182. var axisModel = axisInfo.axis.model;
  41183. var item = {};
  41184. var dim = item.axisDim = axisInfo.axis.dim;
  41185. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  41186. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  41187. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  41188. return item;
  41189. }
  41190. function illegalPoint(point) {
  41191. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  41192. }
  41193. /*
  41194. * Licensed to the Apache Software Foundation (ASF) under one
  41195. * or more contributor license agreements. See the NOTICE file
  41196. * distributed with this work for additional information
  41197. * regarding copyright ownership. The ASF licenses this file
  41198. * to you under the Apache License, Version 2.0 (the
  41199. * "License"); you may not use this file except in compliance
  41200. * with the License. You may obtain a copy of the License at
  41201. *
  41202. * http://www.apache.org/licenses/LICENSE-2.0
  41203. *
  41204. * Unless required by applicable law or agreed to in writing,
  41205. * software distributed under the License is distributed on an
  41206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41207. * KIND, either express or implied. See the License for the
  41208. * specific language governing permissions and limitations
  41209. * under the License.
  41210. */
  41211. var AxisPointerModel = extendComponentModel({
  41212. type: 'axisPointer',
  41213. coordSysAxesInfo: null,
  41214. defaultOption: {
  41215. // 'auto' means that show when triggered by tooltip or handle.
  41216. show: 'auto',
  41217. // 'click' | 'mousemove' | 'none'
  41218. triggerOn: null, // set default in AxisPonterView.js
  41219. zlevel: 0,
  41220. z: 50,
  41221. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  41222. // axispointer triggered by tootip determine snap automatically,
  41223. // see `modelHelper`.
  41224. snap: false,
  41225. triggerTooltip: true,
  41226. value: null,
  41227. status: null, // Init value depends on whether handle is used.
  41228. // [group0, group1, ...]
  41229. // Each group can be: {
  41230. // mapper: function () {},
  41231. // singleTooltip: 'multiple', // 'multiple' or 'single'
  41232. // xAxisId: ...,
  41233. // yAxisName: ...,
  41234. // angleAxisIndex: ...
  41235. // }
  41236. // mapper: can be ignored.
  41237. // input: {axisInfo, value}
  41238. // output: {axisInfo, value}
  41239. link: [],
  41240. // Do not set 'auto' here, otherwise global animation: false
  41241. // will not effect at this axispointer.
  41242. animation: null,
  41243. animationDurationUpdate: 200,
  41244. lineStyle: {
  41245. color: '#aaa',
  41246. width: 1,
  41247. type: 'solid'
  41248. },
  41249. shadowStyle: {
  41250. color: 'rgba(150,150,150,0.3)'
  41251. },
  41252. label: {
  41253. show: true,
  41254. formatter: null, // string | Function
  41255. precision: 'auto', // Or a number like 0, 1, 2 ...
  41256. margin: 3,
  41257. color: '#fff',
  41258. padding: [5, 7, 5, 7],
  41259. backgroundColor: 'auto', // default: axis line color
  41260. borderColor: null,
  41261. borderWidth: 0,
  41262. shadowBlur: 3,
  41263. shadowColor: '#aaa'
  41264. // Considering applicability, common style should
  41265. // better not have shadowOffset.
  41266. // shadowOffsetX: 0,
  41267. // shadowOffsetY: 2
  41268. },
  41269. handle: {
  41270. show: false,
  41271. /* eslint-disable */
  41272. 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
  41273. /* eslint-enable */
  41274. size: 45,
  41275. // handle margin is from symbol center to axis, which is stable when circular move.
  41276. margin: 50,
  41277. // color: '#1b8bbd'
  41278. // color: '#2f4554'
  41279. color: '#333',
  41280. shadowBlur: 3,
  41281. shadowColor: '#aaa',
  41282. shadowOffsetX: 0,
  41283. shadowOffsetY: 2,
  41284. // For mobile performance
  41285. throttle: 40
  41286. }
  41287. }
  41288. });
  41289. /*
  41290. * Licensed to the Apache Software Foundation (ASF) under one
  41291. * or more contributor license agreements. See the NOTICE file
  41292. * distributed with this work for additional information
  41293. * regarding copyright ownership. The ASF licenses this file
  41294. * to you under the Apache License, Version 2.0 (the
  41295. * "License"); you may not use this file except in compliance
  41296. * with the License. You may obtain a copy of the License at
  41297. *
  41298. * http://www.apache.org/licenses/LICENSE-2.0
  41299. *
  41300. * Unless required by applicable law or agreed to in writing,
  41301. * software distributed under the License is distributed on an
  41302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41303. * KIND, either express or implied. See the License for the
  41304. * specific language governing permissions and limitations
  41305. * under the License.
  41306. */
  41307. var inner$8 = makeInner();
  41308. var each$8 = each$1;
  41309. /**
  41310. * @param {string} key
  41311. * @param {module:echarts/ExtensionAPI} api
  41312. * @param {Function} handler
  41313. * param: {string} currTrigger
  41314. * param: {Array.<number>} point
  41315. */
  41316. function register(key, api, handler) {
  41317. if (env$1.node) {
  41318. return;
  41319. }
  41320. var zr = api.getZr();
  41321. inner$8(zr).records || (inner$8(zr).records = {});
  41322. initGlobalListeners(zr, api);
  41323. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  41324. record.handler = handler;
  41325. }
  41326. function initGlobalListeners(zr, api) {
  41327. if (inner$8(zr).initialized) {
  41328. return;
  41329. }
  41330. inner$8(zr).initialized = true;
  41331. useHandler('click', curry(doEnter, 'click'));
  41332. useHandler('mousemove', curry(doEnter, 'mousemove'));
  41333. // useHandler('mouseout', onLeave);
  41334. useHandler('globalout', onLeave);
  41335. function useHandler(eventType, cb) {
  41336. zr.on(eventType, function (e) {
  41337. var dis = makeDispatchAction(api);
  41338. each$8(inner$8(zr).records, function (record) {
  41339. record && cb(record, e, dis.dispatchAction);
  41340. });
  41341. dispatchTooltipFinally(dis.pendings, api);
  41342. });
  41343. }
  41344. }
  41345. function dispatchTooltipFinally(pendings, api) {
  41346. var showLen = pendings.showTip.length;
  41347. var hideLen = pendings.hideTip.length;
  41348. var actuallyPayload;
  41349. if (showLen) {
  41350. actuallyPayload = pendings.showTip[showLen - 1];
  41351. }
  41352. else if (hideLen) {
  41353. actuallyPayload = pendings.hideTip[hideLen - 1];
  41354. }
  41355. if (actuallyPayload) {
  41356. actuallyPayload.dispatchAction = null;
  41357. api.dispatchAction(actuallyPayload);
  41358. }
  41359. }
  41360. function onLeave(record, e, dispatchAction) {
  41361. record.handler('leave', null, dispatchAction);
  41362. }
  41363. function doEnter(currTrigger, record, e, dispatchAction) {
  41364. record.handler(currTrigger, e, dispatchAction);
  41365. }
  41366. function makeDispatchAction(api) {
  41367. var pendings = {
  41368. showTip: [],
  41369. hideTip: []
  41370. };
  41371. // FIXME
  41372. // better approach?
  41373. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  41374. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  41375. // So we have to add "final stage" to merge those dispatched actions.
  41376. var dispatchAction = function (payload) {
  41377. var pendingList = pendings[payload.type];
  41378. if (pendingList) {
  41379. pendingList.push(payload);
  41380. }
  41381. else {
  41382. payload.dispatchAction = dispatchAction;
  41383. api.dispatchAction(payload);
  41384. }
  41385. };
  41386. return {
  41387. dispatchAction: dispatchAction,
  41388. pendings: pendings
  41389. };
  41390. }
  41391. /**
  41392. * @param {string} key
  41393. * @param {module:echarts/ExtensionAPI} api
  41394. */
  41395. function unregister(key, api) {
  41396. if (env$1.node) {
  41397. return;
  41398. }
  41399. var zr = api.getZr();
  41400. var record = (inner$8(zr).records || {})[key];
  41401. if (record) {
  41402. inner$8(zr).records[key] = null;
  41403. }
  41404. }
  41405. /*
  41406. * Licensed to the Apache Software Foundation (ASF) under one
  41407. * or more contributor license agreements. See the NOTICE file
  41408. * distributed with this work for additional information
  41409. * regarding copyright ownership. The ASF licenses this file
  41410. * to you under the Apache License, Version 2.0 (the
  41411. * "License"); you may not use this file except in compliance
  41412. * with the License. You may obtain a copy of the License at
  41413. *
  41414. * http://www.apache.org/licenses/LICENSE-2.0
  41415. *
  41416. * Unless required by applicable law or agreed to in writing,
  41417. * software distributed under the License is distributed on an
  41418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41419. * KIND, either express or implied. See the License for the
  41420. * specific language governing permissions and limitations
  41421. * under the License.
  41422. */
  41423. var AxisPointerView = extendComponentView({
  41424. type: 'axisPointer',
  41425. render: function (globalAxisPointerModel, ecModel, api) {
  41426. var globalTooltipModel = ecModel.getComponent('tooltip');
  41427. var triggerOn = globalAxisPointerModel.get('triggerOn')
  41428. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  41429. // Register global listener in AxisPointerView to enable
  41430. // AxisPointerView to be independent to Tooltip.
  41431. register(
  41432. 'axisPointer',
  41433. api,
  41434. function (currTrigger, e, dispatchAction) {
  41435. // If 'none', it is not controlled by mouse totally.
  41436. if (triggerOn !== 'none'
  41437. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  41438. ) {
  41439. dispatchAction({
  41440. type: 'updateAxisPointer',
  41441. currTrigger: currTrigger,
  41442. x: e && e.offsetX,
  41443. y: e && e.offsetY
  41444. });
  41445. }
  41446. }
  41447. );
  41448. },
  41449. /**
  41450. * @override
  41451. */
  41452. remove: function (ecModel, api) {
  41453. unregister(api.getZr(), 'axisPointer');
  41454. AxisPointerView.superApply(this._model, 'remove', arguments);
  41455. },
  41456. /**
  41457. * @override
  41458. */
  41459. dispose: function (ecModel, api) {
  41460. unregister('axisPointer', api);
  41461. AxisPointerView.superApply(this._model, 'dispose', arguments);
  41462. }
  41463. });
  41464. /*
  41465. * Licensed to the Apache Software Foundation (ASF) under one
  41466. * or more contributor license agreements. See the NOTICE file
  41467. * distributed with this work for additional information
  41468. * regarding copyright ownership. The ASF licenses this file
  41469. * to you under the Apache License, Version 2.0 (the
  41470. * "License"); you may not use this file except in compliance
  41471. * with the License. You may obtain a copy of the License at
  41472. *
  41473. * http://www.apache.org/licenses/LICENSE-2.0
  41474. *
  41475. * Unless required by applicable law or agreed to in writing,
  41476. * software distributed under the License is distributed on an
  41477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41478. * KIND, either express or implied. See the License for the
  41479. * specific language governing permissions and limitations
  41480. * under the License.
  41481. */
  41482. var inner$9 = makeInner();
  41483. var clone$4 = clone;
  41484. var bind$1 = bind;
  41485. /**
  41486. * Base axis pointer class in 2D.
  41487. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  41488. */
  41489. function BaseAxisPointer() {
  41490. }
  41491. BaseAxisPointer.prototype = {
  41492. /**
  41493. * @private
  41494. */
  41495. _group: null,
  41496. /**
  41497. * @private
  41498. */
  41499. _lastGraphicKey: null,
  41500. /**
  41501. * @private
  41502. */
  41503. _handle: null,
  41504. /**
  41505. * @private
  41506. */
  41507. _dragging: false,
  41508. /**
  41509. * @private
  41510. */
  41511. _lastValue: null,
  41512. /**
  41513. * @private
  41514. */
  41515. _lastStatus: null,
  41516. /**
  41517. * @private
  41518. */
  41519. _payloadInfo: null,
  41520. /**
  41521. * In px, arbitrary value. Do not set too small,
  41522. * no animation is ok for most cases.
  41523. * @protected
  41524. */
  41525. animationThreshold: 15,
  41526. /**
  41527. * @implement
  41528. */
  41529. render: function (axisModel, axisPointerModel, api, forceRender) {
  41530. var value = axisPointerModel.get('value');
  41531. var status = axisPointerModel.get('status');
  41532. // Bind them to `this`, not in closure, otherwise they will not
  41533. // be replaced when user calling setOption in not merge mode.
  41534. this._axisModel = axisModel;
  41535. this._axisPointerModel = axisPointerModel;
  41536. this._api = api;
  41537. // Optimize: `render` will be called repeatly during mouse move.
  41538. // So it is power consuming if performing `render` each time,
  41539. // especially on mobile device.
  41540. if (!forceRender
  41541. && this._lastValue === value
  41542. && this._lastStatus === status
  41543. ) {
  41544. return;
  41545. }
  41546. this._lastValue = value;
  41547. this._lastStatus = status;
  41548. var group = this._group;
  41549. var handle = this._handle;
  41550. if (!status || status === 'hide') {
  41551. // Do not clear here, for animation better.
  41552. group && group.hide();
  41553. handle && handle.hide();
  41554. return;
  41555. }
  41556. group && group.show();
  41557. handle && handle.show();
  41558. // Otherwise status is 'show'
  41559. var elOption = {};
  41560. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  41561. // Enable change axis pointer type.
  41562. var graphicKey = elOption.graphicKey;
  41563. if (graphicKey !== this._lastGraphicKey) {
  41564. this.clear(api);
  41565. }
  41566. this._lastGraphicKey = graphicKey;
  41567. var moveAnimation = this._moveAnimation =
  41568. this.determineAnimation(axisModel, axisPointerModel);
  41569. if (!group) {
  41570. group = this._group = new Group();
  41571. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  41572. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  41573. api.getZr().add(group);
  41574. }
  41575. else {
  41576. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  41577. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  41578. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  41579. }
  41580. updateMandatoryProps(group, axisPointerModel, true);
  41581. this._renderHandle(value);
  41582. },
  41583. /**
  41584. * @implement
  41585. */
  41586. remove: function (api) {
  41587. this.clear(api);
  41588. },
  41589. /**
  41590. * @implement
  41591. */
  41592. dispose: function (api) {
  41593. this.clear(api);
  41594. },
  41595. /**
  41596. * @protected
  41597. */
  41598. determineAnimation: function (axisModel, axisPointerModel) {
  41599. var animation = axisPointerModel.get('animation');
  41600. var axis = axisModel.axis;
  41601. var isCategoryAxis = axis.type === 'category';
  41602. var useSnap = axisPointerModel.get('snap');
  41603. // Value axis without snap always do not snap.
  41604. if (!useSnap && !isCategoryAxis) {
  41605. return false;
  41606. }
  41607. if (animation === 'auto' || animation == null) {
  41608. var animationThreshold = this.animationThreshold;
  41609. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  41610. return true;
  41611. }
  41612. // It is important to auto animation when snap used. Consider if there is
  41613. // a dataZoom, animation will be disabled when too many points exist, while
  41614. // it will be enabled for better visual effect when little points exist.
  41615. if (useSnap) {
  41616. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  41617. var axisExtent = axis.getExtent();
  41618. // Approximate band width
  41619. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  41620. }
  41621. return false;
  41622. }
  41623. return animation === true;
  41624. },
  41625. /**
  41626. * add {pointer, label, graphicKey} to elOption
  41627. * @protected
  41628. */
  41629. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  41630. // Shoule be implemenented by sub-class.
  41631. },
  41632. /**
  41633. * @protected
  41634. */
  41635. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  41636. var pointerOption = elOption.pointer;
  41637. if (pointerOption) {
  41638. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  41639. clone$4(elOption.pointer)
  41640. );
  41641. group.add(pointerEl);
  41642. }
  41643. },
  41644. /**
  41645. * @protected
  41646. */
  41647. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  41648. if (elOption.label) {
  41649. var labelEl = inner$9(group).labelEl = new Rect(
  41650. clone$4(elOption.label)
  41651. );
  41652. group.add(labelEl);
  41653. updateLabelShowHide(labelEl, axisPointerModel);
  41654. }
  41655. },
  41656. /**
  41657. * @protected
  41658. */
  41659. updatePointerEl: function (group, elOption, updateProps$$1) {
  41660. var pointerEl = inner$9(group).pointerEl;
  41661. if (pointerEl && elOption.pointer) {
  41662. pointerEl.setStyle(elOption.pointer.style);
  41663. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  41664. }
  41665. },
  41666. /**
  41667. * @protected
  41668. */
  41669. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  41670. var labelEl = inner$9(group).labelEl;
  41671. if (labelEl) {
  41672. labelEl.setStyle(elOption.label.style);
  41673. updateProps$$1(labelEl, {
  41674. // Consider text length change in vertical axis, animation should
  41675. // be used on shape, otherwise the effect will be weird.
  41676. shape: elOption.label.shape,
  41677. position: elOption.label.position
  41678. });
  41679. updateLabelShowHide(labelEl, axisPointerModel);
  41680. }
  41681. },
  41682. /**
  41683. * @private
  41684. */
  41685. _renderHandle: function (value) {
  41686. if (this._dragging || !this.updateHandleTransform) {
  41687. return;
  41688. }
  41689. var axisPointerModel = this._axisPointerModel;
  41690. var zr = this._api.getZr();
  41691. var handle = this._handle;
  41692. var handleModel = axisPointerModel.getModel('handle');
  41693. var status = axisPointerModel.get('status');
  41694. if (!handleModel.get('show') || !status || status === 'hide') {
  41695. handle && zr.remove(handle);
  41696. this._handle = null;
  41697. return;
  41698. }
  41699. var isInit;
  41700. if (!this._handle) {
  41701. isInit = true;
  41702. handle = this._handle = createIcon(
  41703. handleModel.get('icon'),
  41704. {
  41705. cursor: 'move',
  41706. draggable: true,
  41707. onmousemove: function (e) {
  41708. // Fot mobile devicem, prevent screen slider on the button.
  41709. stop(e.event);
  41710. },
  41711. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  41712. drift: bind$1(this._onHandleDragMove, this),
  41713. ondragend: bind$1(this._onHandleDragEnd, this)
  41714. }
  41715. );
  41716. zr.add(handle);
  41717. }
  41718. updateMandatoryProps(handle, axisPointerModel, false);
  41719. // update style
  41720. var includeStyles = [
  41721. 'color', 'borderColor', 'borderWidth', 'opacity',
  41722. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  41723. ];
  41724. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  41725. // update position
  41726. var handleSize = handleModel.get('size');
  41727. if (!isArray(handleSize)) {
  41728. handleSize = [handleSize, handleSize];
  41729. }
  41730. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  41731. createOrUpdate(
  41732. this,
  41733. '_doDispatchAxisPointer',
  41734. handleModel.get('throttle') || 0,
  41735. 'fixRate'
  41736. );
  41737. this._moveHandleToValue(value, isInit);
  41738. },
  41739. /**
  41740. * @private
  41741. */
  41742. _moveHandleToValue: function (value, isInit) {
  41743. updateProps$1(
  41744. this._axisPointerModel,
  41745. !isInit && this._moveAnimation,
  41746. this._handle,
  41747. getHandleTransProps(this.getHandleTransform(
  41748. value, this._axisModel, this._axisPointerModel
  41749. ))
  41750. );
  41751. },
  41752. /**
  41753. * @private
  41754. */
  41755. _onHandleDragMove: function (dx, dy) {
  41756. var handle = this._handle;
  41757. if (!handle) {
  41758. return;
  41759. }
  41760. this._dragging = true;
  41761. // Persistent for throttle.
  41762. var trans = this.updateHandleTransform(
  41763. getHandleTransProps(handle),
  41764. [dx, dy],
  41765. this._axisModel,
  41766. this._axisPointerModel
  41767. );
  41768. this._payloadInfo = trans;
  41769. handle.stopAnimation();
  41770. handle.attr(getHandleTransProps(trans));
  41771. inner$9(handle).lastProp = null;
  41772. this._doDispatchAxisPointer();
  41773. },
  41774. /**
  41775. * Throttled method.
  41776. * @private
  41777. */
  41778. _doDispatchAxisPointer: function () {
  41779. var handle = this._handle;
  41780. if (!handle) {
  41781. return;
  41782. }
  41783. var payloadInfo = this._payloadInfo;
  41784. var axisModel = this._axisModel;
  41785. this._api.dispatchAction({
  41786. type: 'updateAxisPointer',
  41787. x: payloadInfo.cursorPoint[0],
  41788. y: payloadInfo.cursorPoint[1],
  41789. tooltipOption: payloadInfo.tooltipOption,
  41790. axesInfo: [{
  41791. axisDim: axisModel.axis.dim,
  41792. axisIndex: axisModel.componentIndex
  41793. }]
  41794. });
  41795. },
  41796. /**
  41797. * @private
  41798. */
  41799. _onHandleDragEnd: function (moveAnimation) {
  41800. this._dragging = false;
  41801. var handle = this._handle;
  41802. if (!handle) {
  41803. return;
  41804. }
  41805. var value = this._axisPointerModel.get('value');
  41806. // Consider snap or categroy axis, handle may be not consistent with
  41807. // axisPointer. So move handle to align the exact value position when
  41808. // drag ended.
  41809. this._moveHandleToValue(value);
  41810. // For the effect: tooltip will be shown when finger holding on handle
  41811. // button, and will be hidden after finger left handle button.
  41812. this._api.dispatchAction({
  41813. type: 'hideTip'
  41814. });
  41815. },
  41816. /**
  41817. * Should be implemenented by sub-class if support `handle`.
  41818. * @protected
  41819. * @param {number} value
  41820. * @param {module:echarts/model/Model} axisModel
  41821. * @param {module:echarts/model/Model} axisPointerModel
  41822. * @return {Object} {position: [x, y], rotation: 0}
  41823. */
  41824. getHandleTransform: null,
  41825. /**
  41826. * * Should be implemenented by sub-class if support `handle`.
  41827. * @protected
  41828. * @param {Object} transform {position, rotation}
  41829. * @param {Array.<number>} delta [dx, dy]
  41830. * @param {module:echarts/model/Model} axisModel
  41831. * @param {module:echarts/model/Model} axisPointerModel
  41832. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  41833. */
  41834. updateHandleTransform: null,
  41835. /**
  41836. * @private
  41837. */
  41838. clear: function (api) {
  41839. this._lastValue = null;
  41840. this._lastStatus = null;
  41841. var zr = api.getZr();
  41842. var group = this._group;
  41843. var handle = this._handle;
  41844. if (zr && group) {
  41845. this._lastGraphicKey = null;
  41846. group && zr.remove(group);
  41847. handle && zr.remove(handle);
  41848. this._group = null;
  41849. this._handle = null;
  41850. this._payloadInfo = null;
  41851. }
  41852. },
  41853. /**
  41854. * @protected
  41855. */
  41856. doClear: function () {
  41857. // Implemented by sub-class if necessary.
  41858. },
  41859. /**
  41860. * @protected
  41861. * @param {Array.<number>} xy
  41862. * @param {Array.<number>} wh
  41863. * @param {number} [xDimIndex=0] or 1
  41864. */
  41865. buildLabel: function (xy, wh, xDimIndex) {
  41866. xDimIndex = xDimIndex || 0;
  41867. return {
  41868. x: xy[xDimIndex],
  41869. y: xy[1 - xDimIndex],
  41870. width: wh[xDimIndex],
  41871. height: wh[1 - xDimIndex]
  41872. };
  41873. }
  41874. };
  41875. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  41876. function updateProps$1(animationModel, moveAnimation, el, props) {
  41877. // Animation optimize.
  41878. if (!propsEqual(inner$9(el).lastProp, props)) {
  41879. inner$9(el).lastProp = props;
  41880. moveAnimation
  41881. ? updateProps(el, props, animationModel)
  41882. : (el.stopAnimation(), el.attr(props));
  41883. }
  41884. }
  41885. function propsEqual(lastProps, newProps) {
  41886. if (isObject$1(lastProps) && isObject$1(newProps)) {
  41887. var equals = true;
  41888. each$1(newProps, function (item, key) {
  41889. equals = equals && propsEqual(lastProps[key], item);
  41890. });
  41891. return !!equals;
  41892. }
  41893. else {
  41894. return lastProps === newProps;
  41895. }
  41896. }
  41897. function updateLabelShowHide(labelEl, axisPointerModel) {
  41898. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  41899. }
  41900. function getHandleTransProps(trans) {
  41901. return {
  41902. position: trans.position.slice(),
  41903. rotation: trans.rotation || 0
  41904. };
  41905. }
  41906. function updateMandatoryProps(group, axisPointerModel, silent) {
  41907. var z = axisPointerModel.get('z');
  41908. var zlevel = axisPointerModel.get('zlevel');
  41909. group && group.traverse(function (el) {
  41910. if (el.type !== 'group') {
  41911. z != null && (el.z = z);
  41912. zlevel != null && (el.zlevel = zlevel);
  41913. el.silent = silent;
  41914. }
  41915. });
  41916. }
  41917. enableClassExtend(BaseAxisPointer);
  41918. /*
  41919. * Licensed to the Apache Software Foundation (ASF) under one
  41920. * or more contributor license agreements. See the NOTICE file
  41921. * distributed with this work for additional information
  41922. * regarding copyright ownership. The ASF licenses this file
  41923. * to you under the Apache License, Version 2.0 (the
  41924. * "License"); you may not use this file except in compliance
  41925. * with the License. You may obtain a copy of the License at
  41926. *
  41927. * http://www.apache.org/licenses/LICENSE-2.0
  41928. *
  41929. * Unless required by applicable law or agreed to in writing,
  41930. * software distributed under the License is distributed on an
  41931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41932. * KIND, either express or implied. See the License for the
  41933. * specific language governing permissions and limitations
  41934. * under the License.
  41935. */
  41936. /**
  41937. * @param {module:echarts/model/Model} axisPointerModel
  41938. */
  41939. function buildElStyle(axisPointerModel) {
  41940. var axisPointerType = axisPointerModel.get('type');
  41941. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  41942. var style;
  41943. if (axisPointerType === 'line') {
  41944. style = styleModel.getLineStyle();
  41945. style.fill = null;
  41946. }
  41947. else if (axisPointerType === 'shadow') {
  41948. style = styleModel.getAreaStyle();
  41949. style.stroke = null;
  41950. }
  41951. return style;
  41952. }
  41953. /**
  41954. * @param {Function} labelPos {align, verticalAlign, position}
  41955. */
  41956. function buildLabelElOption(
  41957. elOption, axisModel, axisPointerModel, api, labelPos
  41958. ) {
  41959. var value = axisPointerModel.get('value');
  41960. var text = getValueLabel(
  41961. value, axisModel.axis, axisModel.ecModel,
  41962. axisPointerModel.get('seriesDataIndices'),
  41963. {
  41964. precision: axisPointerModel.get('label.precision'),
  41965. formatter: axisPointerModel.get('label.formatter')
  41966. }
  41967. );
  41968. var labelModel = axisPointerModel.getModel('label');
  41969. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  41970. var font = labelModel.getFont();
  41971. var textRect = getBoundingRect(text, font);
  41972. var position = labelPos.position;
  41973. var width = textRect.width + paddings[1] + paddings[3];
  41974. var height = textRect.height + paddings[0] + paddings[2];
  41975. // Adjust by align.
  41976. var align = labelPos.align;
  41977. align === 'right' && (position[0] -= width);
  41978. align === 'center' && (position[0] -= width / 2);
  41979. var verticalAlign = labelPos.verticalAlign;
  41980. verticalAlign === 'bottom' && (position[1] -= height);
  41981. verticalAlign === 'middle' && (position[1] -= height / 2);
  41982. // Not overflow ec container
  41983. confineInContainer(position, width, height, api);
  41984. var bgColor = labelModel.get('backgroundColor');
  41985. if (!bgColor || bgColor === 'auto') {
  41986. bgColor = axisModel.get('axisLine.lineStyle.color');
  41987. }
  41988. elOption.label = {
  41989. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  41990. position: position.slice(),
  41991. // TODO: rich
  41992. style: {
  41993. text: text,
  41994. textFont: font,
  41995. textFill: labelModel.getTextColor(),
  41996. textPosition: 'inside',
  41997. textPadding: paddings,
  41998. fill: bgColor,
  41999. stroke: labelModel.get('borderColor') || 'transparent',
  42000. lineWidth: labelModel.get('borderWidth') || 0,
  42001. shadowBlur: labelModel.get('shadowBlur'),
  42002. shadowColor: labelModel.get('shadowColor'),
  42003. shadowOffsetX: labelModel.get('shadowOffsetX'),
  42004. shadowOffsetY: labelModel.get('shadowOffsetY')
  42005. },
  42006. // Lable should be over axisPointer.
  42007. z2: 10
  42008. };
  42009. }
  42010. // Do not overflow ec container
  42011. function confineInContainer(position, width, height, api) {
  42012. var viewWidth = api.getWidth();
  42013. var viewHeight = api.getHeight();
  42014. position[0] = Math.min(position[0] + width, viewWidth) - width;
  42015. position[1] = Math.min(position[1] + height, viewHeight) - height;
  42016. position[0] = Math.max(position[0], 0);
  42017. position[1] = Math.max(position[1], 0);
  42018. }
  42019. /**
  42020. * @param {number} value
  42021. * @param {module:echarts/coord/Axis} axis
  42022. * @param {module:echarts/model/Global} ecModel
  42023. * @param {Object} opt
  42024. * @param {Array.<Object>} seriesDataIndices
  42025. * @param {number|string} opt.precision 'auto' or a number
  42026. * @param {string|Function} opt.formatter label formatter
  42027. */
  42028. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  42029. value = axis.scale.parse(value);
  42030. var text = axis.scale.getLabel(
  42031. // If `precision` is set, width can be fixed (like '12.00500'), which
  42032. // helps to debounce when when moving label.
  42033. value, {precision: opt.precision}
  42034. );
  42035. var formatter = opt.formatter;
  42036. if (formatter) {
  42037. var params = {
  42038. value: getAxisRawValue(axis, value),
  42039. axisDimension: axis.dim,
  42040. axisIndex: axis.index,
  42041. seriesData: []
  42042. };
  42043. each$1(seriesDataIndices, function (idxItem) {
  42044. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  42045. var dataIndex = idxItem.dataIndexInside;
  42046. var dataParams = series && series.getDataParams(dataIndex);
  42047. dataParams && params.seriesData.push(dataParams);
  42048. });
  42049. if (isString(formatter)) {
  42050. text = formatter.replace('{value}', text);
  42051. }
  42052. else if (isFunction$1(formatter)) {
  42053. text = formatter(params);
  42054. }
  42055. }
  42056. return text;
  42057. }
  42058. /**
  42059. * @param {module:echarts/coord/Axis} axis
  42060. * @param {number} value
  42061. * @param {Object} layoutInfo {
  42062. * rotation, position, labelOffset, labelDirection, labelMargin
  42063. * }
  42064. */
  42065. function getTransformedPosition(axis, value, layoutInfo) {
  42066. var transform = create$1();
  42067. rotate(transform, transform, layoutInfo.rotation);
  42068. translate(transform, transform, layoutInfo.position);
  42069. return applyTransform$1([
  42070. axis.dataToCoord(value),
  42071. (layoutInfo.labelOffset || 0)
  42072. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  42073. ], transform);
  42074. }
  42075. function buildCartesianSingleLabelElOption(
  42076. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  42077. ) {
  42078. var textLayout = AxisBuilder.innerTextLayout(
  42079. layoutInfo.rotation, 0, layoutInfo.labelDirection
  42080. );
  42081. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  42082. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  42083. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  42084. align: textLayout.textAlign,
  42085. verticalAlign: textLayout.textVerticalAlign
  42086. });
  42087. }
  42088. /**
  42089. * @param {Array.<number>} p1
  42090. * @param {Array.<number>} p2
  42091. * @param {number} [xDimIndex=0] or 1
  42092. */
  42093. function makeLineShape(p1, p2, xDimIndex) {
  42094. xDimIndex = xDimIndex || 0;
  42095. return {
  42096. x1: p1[xDimIndex],
  42097. y1: p1[1 - xDimIndex],
  42098. x2: p2[xDimIndex],
  42099. y2: p2[1 - xDimIndex]
  42100. };
  42101. }
  42102. /**
  42103. * @param {Array.<number>} xy
  42104. * @param {Array.<number>} wh
  42105. * @param {number} [xDimIndex=0] or 1
  42106. */
  42107. function makeRectShape(xy, wh, xDimIndex) {
  42108. xDimIndex = xDimIndex || 0;
  42109. return {
  42110. x: xy[xDimIndex],
  42111. y: xy[1 - xDimIndex],
  42112. width: wh[xDimIndex],
  42113. height: wh[1 - xDimIndex]
  42114. };
  42115. }
  42116. /*
  42117. * Licensed to the Apache Software Foundation (ASF) under one
  42118. * or more contributor license agreements. See the NOTICE file
  42119. * distributed with this work for additional information
  42120. * regarding copyright ownership. The ASF licenses this file
  42121. * to you under the Apache License, Version 2.0 (the
  42122. * "License"); you may not use this file except in compliance
  42123. * with the License. You may obtain a copy of the License at
  42124. *
  42125. * http://www.apache.org/licenses/LICENSE-2.0
  42126. *
  42127. * Unless required by applicable law or agreed to in writing,
  42128. * software distributed under the License is distributed on an
  42129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42130. * KIND, either express or implied. See the License for the
  42131. * specific language governing permissions and limitations
  42132. * under the License.
  42133. */
  42134. var CartesianAxisPointer = BaseAxisPointer.extend({
  42135. /**
  42136. * @override
  42137. */
  42138. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  42139. var axis = axisModel.axis;
  42140. var grid = axis.grid;
  42141. var axisPointerType = axisPointerModel.get('type');
  42142. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42143. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  42144. if (axisPointerType && axisPointerType !== 'none') {
  42145. var elStyle = buildElStyle(axisPointerModel);
  42146. var pointerOption = pointerShapeBuilder[axisPointerType](
  42147. axis, pixelValue, otherExtent
  42148. );
  42149. pointerOption.style = elStyle;
  42150. elOption.graphicKey = pointerOption.type;
  42151. elOption.pointer = pointerOption;
  42152. }
  42153. var layoutInfo = layout$1(grid.model, axisModel);
  42154. buildCartesianSingleLabelElOption(
  42155. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  42156. );
  42157. },
  42158. /**
  42159. * @override
  42160. */
  42161. getHandleTransform: function (value, axisModel, axisPointerModel) {
  42162. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  42163. labelInside: false
  42164. });
  42165. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  42166. return {
  42167. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  42168. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  42169. };
  42170. },
  42171. /**
  42172. * @override
  42173. */
  42174. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  42175. var axis = axisModel.axis;
  42176. var grid = axis.grid;
  42177. var axisExtent = axis.getGlobalExtent(true);
  42178. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  42179. var dimIndex = axis.dim === 'x' ? 0 : 1;
  42180. var currPosition = transform.position;
  42181. currPosition[dimIndex] += delta[dimIndex];
  42182. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  42183. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  42184. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  42185. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  42186. cursorPoint[dimIndex] = currPosition[dimIndex];
  42187. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  42188. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  42189. return {
  42190. position: currPosition,
  42191. rotation: transform.rotation,
  42192. cursorPoint: cursorPoint,
  42193. tooltipOption: tooltipOptions[dimIndex]
  42194. };
  42195. }
  42196. });
  42197. function getCartesian(grid, axis) {
  42198. var opt = {};
  42199. opt[axis.dim + 'AxisIndex'] = axis.index;
  42200. return grid.getCartesian(opt);
  42201. }
  42202. var pointerShapeBuilder = {
  42203. line: function (axis, pixelValue, otherExtent) {
  42204. var targetShape = makeLineShape(
  42205. [pixelValue, otherExtent[0]],
  42206. [pixelValue, otherExtent[1]],
  42207. getAxisDimIndex(axis)
  42208. );
  42209. return {
  42210. type: 'Line',
  42211. subPixelOptimize: true,
  42212. shape: targetShape
  42213. };
  42214. },
  42215. shadow: function (axis, pixelValue, otherExtent) {
  42216. var bandWidth = Math.max(1, axis.getBandWidth());
  42217. var span = otherExtent[1] - otherExtent[0];
  42218. return {
  42219. type: 'Rect',
  42220. shape: makeRectShape(
  42221. [pixelValue - bandWidth / 2, otherExtent[0]],
  42222. [bandWidth, span],
  42223. getAxisDimIndex(axis)
  42224. )
  42225. };
  42226. }
  42227. };
  42228. function getAxisDimIndex(axis) {
  42229. return axis.dim === 'x' ? 0 : 1;
  42230. }
  42231. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  42232. /*
  42233. * Licensed to the Apache Software Foundation (ASF) under one
  42234. * or more contributor license agreements. See the NOTICE file
  42235. * distributed with this work for additional information
  42236. * regarding copyright ownership. The ASF licenses this file
  42237. * to you under the Apache License, Version 2.0 (the
  42238. * "License"); you may not use this file except in compliance
  42239. * with the License. You may obtain a copy of the License at
  42240. *
  42241. * http://www.apache.org/licenses/LICENSE-2.0
  42242. *
  42243. * Unless required by applicable law or agreed to in writing,
  42244. * software distributed under the License is distributed on an
  42245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42246. * KIND, either express or implied. See the License for the
  42247. * specific language governing permissions and limitations
  42248. * under the License.
  42249. */
  42250. // CartesianAxisPointer is not supposed to be required here. But consider
  42251. // echarts.simple.js and online build tooltip, which only require gridSimple,
  42252. // CartesianAxisPointer should be able to required somewhere.
  42253. registerPreprocessor(function (option) {
  42254. // Always has a global axisPointerModel for default setting.
  42255. if (option) {
  42256. (!option.axisPointer || option.axisPointer.length === 0)
  42257. && (option.axisPointer = {});
  42258. var link = option.axisPointer.link;
  42259. // Normalize to array to avoid object mergin. But if link
  42260. // is not set, remain null/undefined, otherwise it will
  42261. // override existent link setting.
  42262. if (link && !isArray(link)) {
  42263. option.axisPointer.link = [link];
  42264. }
  42265. }
  42266. });
  42267. // This process should proformed after coordinate systems created
  42268. // and series data processed. So put it on statistic processing stage.
  42269. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  42270. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  42271. // allAxesInfo should be updated when setOption performed.
  42272. ecModel.getComponent('axisPointer').coordSysAxesInfo =
  42273. collect(ecModel, api);
  42274. });
  42275. // Broadcast to all views.
  42276. registerAction({
  42277. type: 'updateAxisPointer',
  42278. event: 'updateAxisPointer',
  42279. update: ':updateAxisPointer'
  42280. }, axisTrigger);
  42281. /*
  42282. * Licensed to the Apache Software Foundation (ASF) under one
  42283. * or more contributor license agreements. See the NOTICE file
  42284. * distributed with this work for additional information
  42285. * regarding copyright ownership. The ASF licenses this file
  42286. * to you under the Apache License, Version 2.0 (the
  42287. * "License"); you may not use this file except in compliance
  42288. * with the License. You may obtain a copy of the License at
  42289. *
  42290. * http://www.apache.org/licenses/LICENSE-2.0
  42291. *
  42292. * Unless required by applicable law or agreed to in writing,
  42293. * software distributed under the License is distributed on an
  42294. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42295. * KIND, either express or implied. See the License for the
  42296. * specific language governing permissions and limitations
  42297. * under the License.
  42298. */
  42299. extendComponentModel({
  42300. type: 'tooltip',
  42301. dependencies: ['axisPointer'],
  42302. defaultOption: {
  42303. zlevel: 0,
  42304. z: 60,
  42305. show: true,
  42306. // tooltip主体内容
  42307. showContent: true,
  42308. // 'trigger' only works on coordinate system.
  42309. // 'item' | 'axis' | 'none'
  42310. trigger: 'item',
  42311. // 'click' | 'mousemove' | 'none'
  42312. triggerOn: 'mousemove|click',
  42313. alwaysShowContent: false,
  42314. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  42315. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  42316. // 'auto': use html by default, and use non-html if `document` is not defined
  42317. // 'html': use html for tooltip
  42318. // 'richText': use canvas, svg, and etc. for tooltip
  42319. // 位置 {Array} | {Function}
  42320. // position: null
  42321. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  42322. // align: null,
  42323. // verticalAlign: null,
  42324. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  42325. confine: false,
  42326. // 内容格式器:{string}(Template) ¦ {Function}
  42327. // formatter: null
  42328. showDelay: 0,
  42329. // 隐藏延迟,单位ms
  42330. hideDelay: 100,
  42331. // 动画变换时间,单位s
  42332. transitionDuration: 0.4,
  42333. enterable: false,
  42334. // 提示背景颜色,默认为透明度为0.7的黑色
  42335. backgroundColor: 'rgba(50,50,50,0.7)',
  42336. // 提示边框颜色
  42337. borderColor: '#333',
  42338. // 提示边框圆角,单位px,默认为4
  42339. borderRadius: 4,
  42340. // 提示边框线宽,单位px,默认为0(无边框)
  42341. borderWidth: 0,
  42342. // 提示内边距,单位px,默认各方向内边距为5,
  42343. // 接受数组分别设定上右下左边距,同css
  42344. padding: 5,
  42345. // Extra css text
  42346. extraCssText: '',
  42347. // 坐标轴指示器,坐标轴触发有效
  42348. axisPointer: {
  42349. // 默认为直线
  42350. // 可选为:'line' | 'shadow' | 'cross'
  42351. type: 'line',
  42352. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  42353. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  42354. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  42355. // 极坐标系会默认选择 angle 轴
  42356. axis: 'auto',
  42357. animation: 'auto',
  42358. animationDurationUpdate: 200,
  42359. animationEasingUpdate: 'exponentialOut',
  42360. crossStyle: {
  42361. color: '#999',
  42362. width: 1,
  42363. type: 'dashed',
  42364. // TODO formatter
  42365. textStyle: {}
  42366. }
  42367. // lineStyle and shadowStyle should not be specified here,
  42368. // otherwise it will always override those styles on option.axisPointer.
  42369. },
  42370. textStyle: {
  42371. color: '#fff',
  42372. fontSize: 14
  42373. }
  42374. }
  42375. });
  42376. /*
  42377. * Licensed to the Apache Software Foundation (ASF) under one
  42378. * or more contributor license agreements. See the NOTICE file
  42379. * distributed with this work for additional information
  42380. * regarding copyright ownership. The ASF licenses this file
  42381. * to you under the Apache License, Version 2.0 (the
  42382. * "License"); you may not use this file except in compliance
  42383. * with the License. You may obtain a copy of the License at
  42384. *
  42385. * http://www.apache.org/licenses/LICENSE-2.0
  42386. *
  42387. * Unless required by applicable law or agreed to in writing,
  42388. * software distributed under the License is distributed on an
  42389. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42390. * KIND, either express or implied. See the License for the
  42391. * specific language governing permissions and limitations
  42392. * under the License.
  42393. */
  42394. var each$10 = each$1;
  42395. var toCamelCase$1 = toCamelCase;
  42396. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  42397. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  42398. /**
  42399. * @param {number} duration
  42400. * @return {string}
  42401. * @inner
  42402. */
  42403. function assembleTransition(duration) {
  42404. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  42405. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  42406. + 'top ' + duration + 's ' + transitionCurve;
  42407. return map(vendors, function (vendorPrefix) {
  42408. return vendorPrefix + 'transition:' + transitionText;
  42409. }).join(';');
  42410. }
  42411. /**
  42412. * @param {Object} textStyle
  42413. * @return {string}
  42414. * @inner
  42415. */
  42416. function assembleFont(textStyleModel) {
  42417. var cssText = [];
  42418. var fontSize = textStyleModel.get('fontSize');
  42419. var color = textStyleModel.getTextColor();
  42420. color && cssText.push('color:' + color);
  42421. cssText.push('font:' + textStyleModel.getFont());
  42422. fontSize
  42423. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  42424. each$10(['decoration', 'align'], function (name) {
  42425. var val = textStyleModel.get(name);
  42426. val && cssText.push('text-' + name + ':' + val);
  42427. });
  42428. return cssText.join(';');
  42429. }
  42430. /**
  42431. * @param {Object} tooltipModel
  42432. * @return {string}
  42433. * @inner
  42434. */
  42435. function assembleCssText(tooltipModel) {
  42436. var cssText = [];
  42437. var transitionDuration = tooltipModel.get('transitionDuration');
  42438. var backgroundColor = tooltipModel.get('backgroundColor');
  42439. var textStyleModel = tooltipModel.getModel('textStyle');
  42440. var padding = tooltipModel.get('padding');
  42441. // Animation transition. Do not animate when transitionDuration is 0.
  42442. transitionDuration
  42443. && cssText.push(assembleTransition(transitionDuration));
  42444. if (backgroundColor) {
  42445. if (env$1.canvasSupported) {
  42446. cssText.push('background-Color:' + backgroundColor);
  42447. }
  42448. else {
  42449. // for ie
  42450. cssText.push(
  42451. 'background-Color:#' + toHex(backgroundColor)
  42452. );
  42453. cssText.push('filter:alpha(opacity=70)');
  42454. }
  42455. }
  42456. // Border style
  42457. each$10(['width', 'color', 'radius'], function (name) {
  42458. var borderName = 'border-' + name;
  42459. var camelCase = toCamelCase$1(borderName);
  42460. var val = tooltipModel.get(camelCase);
  42461. val != null
  42462. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  42463. });
  42464. // Text style
  42465. cssText.push(assembleFont(textStyleModel));
  42466. // Padding
  42467. if (padding != null) {
  42468. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  42469. }
  42470. return cssText.join(';') + ';';
  42471. }
  42472. // If not able to make, do not modify the input `out`.
  42473. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  42474. var zrPainter = zr && zr.painter;
  42475. if (appendToBody) {
  42476. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  42477. if (zrViewportRoot) {
  42478. // Some APPs might use scale on body, so we support CSS transform here.
  42479. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  42480. }
  42481. }
  42482. else {
  42483. out[0] = zrX;
  42484. out[1] = zrY;
  42485. // xy should be based on canvas root. But tooltipContent is
  42486. // the sibling of canvas root. So padding of ec container
  42487. // should be considered here.
  42488. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  42489. if (viewportRootOffset) {
  42490. out[0] += viewportRootOffset.offsetLeft;
  42491. out[1] += viewportRootOffset.offsetTop;
  42492. }
  42493. }
  42494. }
  42495. /**
  42496. * @alias module:echarts/component/tooltip/TooltipContent
  42497. * @param {HTMLElement} container
  42498. * @param {ExtensionAPI} api
  42499. * @param {Object} [opt]
  42500. * @param {boolean} [opt.appendToBody]
  42501. * `false`: the DOM element will be inside the container. Default value.
  42502. * `true`: the DOM element will be appended to HTML body, which avoid
  42503. * some overflow clip but intrude outside of the container.
  42504. * @constructor
  42505. */
  42506. function TooltipContent(container, api, opt) {
  42507. if (env$1.wxa) {
  42508. return null;
  42509. }
  42510. var el = document.createElement('div');
  42511. el.domBelongToZr = true;
  42512. this.el = el;
  42513. var zr = this._zr = api.getZr();
  42514. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  42515. this._styleCoord = [0, 0];
  42516. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  42517. if (appendToBody) {
  42518. document.body.appendChild(el);
  42519. }
  42520. else {
  42521. container.appendChild(el);
  42522. }
  42523. this._container = container;
  42524. this._show = false;
  42525. /**
  42526. * @private
  42527. */
  42528. this._hideTimeout;
  42529. // FIXME
  42530. // Is it needed to trigger zr event manually if
  42531. // the browser do not support `pointer-events: none`.
  42532. var self = this;
  42533. el.onmouseenter = function () {
  42534. // clear the timeout in hideLater and keep showing tooltip
  42535. if (self._enterable) {
  42536. clearTimeout(self._hideTimeout);
  42537. self._show = true;
  42538. }
  42539. self._inContent = true;
  42540. };
  42541. el.onmousemove = function (e) {
  42542. e = e || window.event;
  42543. if (!self._enterable) {
  42544. // `pointer-events: none` is set to tooltip content div
  42545. // if `enterable` is set as `false`, and `el.onmousemove`
  42546. // can not be triggered. But in browser that do not
  42547. // support `pointer-events`, we need to do this:
  42548. // Try trigger zrender event to avoid mouse
  42549. // in and out shape too frequently
  42550. var handler = zr.handler;
  42551. var zrViewportRoot = zr.painter.getViewportRoot();
  42552. normalizeEvent(zrViewportRoot, e, true);
  42553. handler.dispatch('mousemove', e);
  42554. }
  42555. };
  42556. el.onmouseleave = function () {
  42557. if (self._enterable) {
  42558. if (self._show) {
  42559. self.hideLater(self._hideDelay);
  42560. }
  42561. }
  42562. self._inContent = false;
  42563. };
  42564. }
  42565. TooltipContent.prototype = {
  42566. constructor: TooltipContent,
  42567. /**
  42568. * @private
  42569. * @type {boolean}
  42570. */
  42571. _enterable: true,
  42572. /**
  42573. * Update when tooltip is rendered
  42574. */
  42575. update: function () {
  42576. // FIXME
  42577. // Move this logic to ec main?
  42578. var container = this._container;
  42579. var stl = container.currentStyle
  42580. || document.defaultView.getComputedStyle(container);
  42581. var domStyle = container.style;
  42582. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  42583. domStyle.position = 'relative';
  42584. }
  42585. // Hide the tooltip
  42586. // PENDING
  42587. // this.hide();
  42588. },
  42589. show: function (tooltipModel) {
  42590. clearTimeout(this._hideTimeout);
  42591. var el = this.el;
  42592. var styleCoord = this._styleCoord;
  42593. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  42594. // Because of the reason described in:
  42595. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  42596. // we should set initial value to `left` and `top`.
  42597. + ';left:' + styleCoord[0] + 'px;top:' + styleCoord[1] + 'px;'
  42598. + (tooltipModel.get('extraCssText') || '');
  42599. el.style.display = el.innerHTML ? 'block' : 'none';
  42600. // If mouse occsionally move over the tooltip, a mouseout event will be
  42601. // triggered by canvas, and cuase some unexpectable result like dragging
  42602. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  42603. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  42604. // scenario.
  42605. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  42606. this._show = true;
  42607. },
  42608. setContent: function (content) {
  42609. this.el.innerHTML = content == null ? '' : content;
  42610. },
  42611. setEnterable: function (enterable) {
  42612. this._enterable = enterable;
  42613. },
  42614. getSize: function () {
  42615. var el = this.el;
  42616. return [el.clientWidth, el.clientHeight];
  42617. },
  42618. moveTo: function (zrX, zrY) {
  42619. var styleCoord = this._styleCoord;
  42620. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  42621. var style = this.el.style;
  42622. style.left = styleCoord[0] + 'px';
  42623. style.top = styleCoord[1] + 'px';
  42624. },
  42625. hide: function () {
  42626. this.el.style.display = 'none';
  42627. this._show = false;
  42628. },
  42629. hideLater: function (time) {
  42630. if (this._show && !(this._inContent && this._enterable)) {
  42631. if (time) {
  42632. this._hideDelay = time;
  42633. // Set show false to avoid invoke hideLater mutiple times
  42634. this._show = false;
  42635. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42636. }
  42637. else {
  42638. this.hide();
  42639. }
  42640. }
  42641. },
  42642. isShow: function () {
  42643. return this._show;
  42644. },
  42645. dispose: function () {
  42646. this.el.parentNode.removeChild(this.el);
  42647. },
  42648. getOuterSize: function () {
  42649. var width = this.el.clientWidth;
  42650. var height = this.el.clientHeight;
  42651. // Consider browser compatibility.
  42652. // IE8 does not support getComputedStyle.
  42653. if (document.defaultView && document.defaultView.getComputedStyle) {
  42654. var stl = document.defaultView.getComputedStyle(this.el);
  42655. if (stl) {
  42656. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  42657. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  42658. }
  42659. }
  42660. return {width: width, height: height};
  42661. }
  42662. };
  42663. /*
  42664. * Licensed to the Apache Software Foundation (ASF) under one
  42665. * or more contributor license agreements. See the NOTICE file
  42666. * distributed with this work for additional information
  42667. * regarding copyright ownership. The ASF licenses this file
  42668. * to you under the Apache License, Version 2.0 (the
  42669. * "License"); you may not use this file except in compliance
  42670. * with the License. You may obtain a copy of the License at
  42671. *
  42672. * http://www.apache.org/licenses/LICENSE-2.0
  42673. *
  42674. * Unless required by applicable law or agreed to in writing,
  42675. * software distributed under the License is distributed on an
  42676. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42677. * KIND, either express or implied. See the License for the
  42678. * specific language governing permissions and limitations
  42679. * under the License.
  42680. */
  42681. // import Group from 'zrender/src/container/Group';
  42682. /**
  42683. * @alias module:echarts/component/tooltip/TooltipRichContent
  42684. * @constructor
  42685. */
  42686. function TooltipRichContent(api) {
  42687. this._zr = api.getZr();
  42688. this._show = false;
  42689. /**
  42690. * @private
  42691. */
  42692. this._hideTimeout;
  42693. }
  42694. TooltipRichContent.prototype = {
  42695. constructor: TooltipRichContent,
  42696. /**
  42697. * @private
  42698. * @type {boolean}
  42699. */
  42700. _enterable: true,
  42701. /**
  42702. * Update when tooltip is rendered
  42703. */
  42704. update: function () {
  42705. // noop
  42706. },
  42707. show: function (tooltipModel) {
  42708. if (this._hideTimeout) {
  42709. clearTimeout(this._hideTimeout);
  42710. }
  42711. this.el.attr('show', true);
  42712. this._show = true;
  42713. },
  42714. /**
  42715. * Set tooltip content
  42716. *
  42717. * @param {string} content rich text string of content
  42718. * @param {Object} markerRich rich text style
  42719. * @param {Object} tooltipModel tooltip model
  42720. */
  42721. setContent: function (content, markerRich, tooltipModel) {
  42722. if (this.el) {
  42723. this._zr.remove(this.el);
  42724. }
  42725. var markers = {};
  42726. var text = content;
  42727. var prefix = '{marker';
  42728. var suffix = '|}';
  42729. var startId = text.indexOf(prefix);
  42730. while (startId >= 0) {
  42731. var endId = text.indexOf(suffix);
  42732. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  42733. if (name.indexOf('sub') > -1) {
  42734. markers['marker' + name] = {
  42735. textWidth: 4,
  42736. textHeight: 4,
  42737. textBorderRadius: 2,
  42738. textBackgroundColor: markerRich[name],
  42739. // TODO: textOffset is not implemented for rich text
  42740. textOffset: [3, 0]
  42741. };
  42742. }
  42743. else {
  42744. markers['marker' + name] = {
  42745. textWidth: 10,
  42746. textHeight: 10,
  42747. textBorderRadius: 5,
  42748. textBackgroundColor: markerRich[name]
  42749. };
  42750. }
  42751. text = text.substr(endId + 1);
  42752. startId = text.indexOf('{marker');
  42753. }
  42754. this.el = new Text({
  42755. style: {
  42756. rich: markers,
  42757. text: content,
  42758. textLineHeight: 20,
  42759. textBackgroundColor: tooltipModel.get('backgroundColor'),
  42760. textBorderRadius: tooltipModel.get('borderRadius'),
  42761. textFill: tooltipModel.get('textStyle.color'),
  42762. textPadding: tooltipModel.get('padding')
  42763. },
  42764. z: tooltipModel.get('z')
  42765. });
  42766. this._zr.add(this.el);
  42767. var self = this;
  42768. this.el.on('mouseover', function () {
  42769. // clear the timeout in hideLater and keep showing tooltip
  42770. if (self._enterable) {
  42771. clearTimeout(self._hideTimeout);
  42772. self._show = true;
  42773. }
  42774. self._inContent = true;
  42775. });
  42776. this.el.on('mouseout', function () {
  42777. if (self._enterable) {
  42778. if (self._show) {
  42779. self.hideLater(self._hideDelay);
  42780. }
  42781. }
  42782. self._inContent = false;
  42783. });
  42784. },
  42785. setEnterable: function (enterable) {
  42786. this._enterable = enterable;
  42787. },
  42788. getSize: function () {
  42789. var bounding = this.el.getBoundingRect();
  42790. return [bounding.width, bounding.height];
  42791. },
  42792. moveTo: function (x, y) {
  42793. if (this.el) {
  42794. this.el.attr('position', [x, y]);
  42795. }
  42796. },
  42797. hide: function () {
  42798. if (this.el) {
  42799. this.el.hide();
  42800. }
  42801. this._show = false;
  42802. },
  42803. hideLater: function (time) {
  42804. if (this._show && !(this._inContent && this._enterable)) {
  42805. if (time) {
  42806. this._hideDelay = time;
  42807. // Set show false to avoid invoke hideLater mutiple times
  42808. this._show = false;
  42809. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  42810. }
  42811. else {
  42812. this.hide();
  42813. }
  42814. }
  42815. },
  42816. isShow: function () {
  42817. return this._show;
  42818. },
  42819. getOuterSize: function () {
  42820. var size = this.getSize();
  42821. return {
  42822. width: size[0],
  42823. height: size[1]
  42824. };
  42825. }
  42826. };
  42827. /*
  42828. * Licensed to the Apache Software Foundation (ASF) under one
  42829. * or more contributor license agreements. See the NOTICE file
  42830. * distributed with this work for additional information
  42831. * regarding copyright ownership. The ASF licenses this file
  42832. * to you under the Apache License, Version 2.0 (the
  42833. * "License"); you may not use this file except in compliance
  42834. * with the License. You may obtain a copy of the License at
  42835. *
  42836. * http://www.apache.org/licenses/LICENSE-2.0
  42837. *
  42838. * Unless required by applicable law or agreed to in writing,
  42839. * software distributed under the License is distributed on an
  42840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42841. * KIND, either express or implied. See the License for the
  42842. * specific language governing permissions and limitations
  42843. * under the License.
  42844. */
  42845. var bind$2 = bind;
  42846. var each$9 = each$1;
  42847. var parsePercent$2 = parsePercent$1;
  42848. var proxyRect = new Rect({
  42849. shape: {x: -1, y: -1, width: 2, height: 2}
  42850. });
  42851. extendComponentView({
  42852. type: 'tooltip',
  42853. init: function (ecModel, api) {
  42854. if (env$1.node) {
  42855. return;
  42856. }
  42857. var tooltipModel = ecModel.getComponent('tooltip');
  42858. var renderMode = tooltipModel.get('renderMode');
  42859. this._renderMode = getTooltipRenderMode(renderMode);
  42860. var tooltipContent;
  42861. if (this._renderMode === 'html') {
  42862. tooltipContent = new TooltipContent(api.getDom(), api, {
  42863. appendToBody: tooltipModel.get('appendToBody', true)
  42864. });
  42865. this._newLine = '<br/>';
  42866. }
  42867. else {
  42868. tooltipContent = new TooltipRichContent(api);
  42869. this._newLine = '\n';
  42870. }
  42871. this._tooltipContent = tooltipContent;
  42872. },
  42873. render: function (tooltipModel, ecModel, api) {
  42874. if (env$1.node) {
  42875. return;
  42876. }
  42877. // Reset
  42878. this.group.removeAll();
  42879. /**
  42880. * @private
  42881. * @type {module:echarts/component/tooltip/TooltipModel}
  42882. */
  42883. this._tooltipModel = tooltipModel;
  42884. /**
  42885. * @private
  42886. * @type {module:echarts/model/Global}
  42887. */
  42888. this._ecModel = ecModel;
  42889. /**
  42890. * @private
  42891. * @type {module:echarts/ExtensionAPI}
  42892. */
  42893. this._api = api;
  42894. /**
  42895. * Should be cleaned when render.
  42896. * @private
  42897. * @type {Array.<Array.<Object>>}
  42898. */
  42899. this._lastDataByCoordSys = null;
  42900. /**
  42901. * @private
  42902. * @type {boolean}
  42903. */
  42904. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  42905. var tooltipContent = this._tooltipContent;
  42906. tooltipContent.update();
  42907. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  42908. this._initGlobalListener();
  42909. this._keepShow();
  42910. },
  42911. _initGlobalListener: function () {
  42912. var tooltipModel = this._tooltipModel;
  42913. var triggerOn = tooltipModel.get('triggerOn');
  42914. register(
  42915. 'itemTooltip',
  42916. this._api,
  42917. bind$2(function (currTrigger, e, dispatchAction) {
  42918. // If 'none', it is not controlled by mouse totally.
  42919. if (triggerOn !== 'none') {
  42920. if (triggerOn.indexOf(currTrigger) >= 0) {
  42921. this._tryShow(e, dispatchAction);
  42922. }
  42923. else if (currTrigger === 'leave') {
  42924. this._hide(dispatchAction);
  42925. }
  42926. }
  42927. }, this)
  42928. );
  42929. },
  42930. _keepShow: function () {
  42931. var tooltipModel = this._tooltipModel;
  42932. var ecModel = this._ecModel;
  42933. var api = this._api;
  42934. // Try to keep the tooltip show when refreshing
  42935. if (this._lastX != null
  42936. && this._lastY != null
  42937. // When user is willing to control tooltip totally using API,
  42938. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  42939. // which is not expected.
  42940. && tooltipModel.get('triggerOn') !== 'none'
  42941. ) {
  42942. var self = this;
  42943. clearTimeout(this._refreshUpdateTimeout);
  42944. this._refreshUpdateTimeout = setTimeout(function () {
  42945. // Show tip next tick after other charts are rendered
  42946. // In case highlight action has wrong result
  42947. // FIXME
  42948. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  42949. x: self._lastX,
  42950. y: self._lastY
  42951. });
  42952. });
  42953. }
  42954. },
  42955. /**
  42956. * Show tip manually by
  42957. * dispatchAction({
  42958. * type: 'showTip',
  42959. * x: 10,
  42960. * y: 10
  42961. * });
  42962. * Or
  42963. * dispatchAction({
  42964. * type: 'showTip',
  42965. * seriesIndex: 0,
  42966. * dataIndex or dataIndexInside or name
  42967. * });
  42968. *
  42969. * TODO Batch
  42970. */
  42971. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  42972. if (payload.from === this.uid || env$1.node) {
  42973. return;
  42974. }
  42975. var dispatchAction = makeDispatchAction$1(payload, api);
  42976. // Reset ticket
  42977. this._ticket = '';
  42978. // When triggered from axisPointer.
  42979. var dataByCoordSys = payload.dataByCoordSys;
  42980. if (payload.tooltip && payload.x != null && payload.y != null) {
  42981. var el = proxyRect;
  42982. el.position = [payload.x, payload.y];
  42983. el.update();
  42984. el.tooltip = payload.tooltip;
  42985. // Manually show tooltip while view is not using zrender elements.
  42986. this._tryShow({
  42987. offsetX: payload.x,
  42988. offsetY: payload.y,
  42989. target: el
  42990. }, dispatchAction);
  42991. }
  42992. else if (dataByCoordSys) {
  42993. this._tryShow({
  42994. offsetX: payload.x,
  42995. offsetY: payload.y,
  42996. position: payload.position,
  42997. dataByCoordSys: payload.dataByCoordSys,
  42998. tooltipOption: payload.tooltipOption
  42999. }, dispatchAction);
  43000. }
  43001. else if (payload.seriesIndex != null) {
  43002. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  43003. return;
  43004. }
  43005. var pointInfo = findPointFromSeries(payload, ecModel);
  43006. var cx = pointInfo.point[0];
  43007. var cy = pointInfo.point[1];
  43008. if (cx != null && cy != null) {
  43009. this._tryShow({
  43010. offsetX: cx,
  43011. offsetY: cy,
  43012. position: payload.position,
  43013. target: pointInfo.el
  43014. }, dispatchAction);
  43015. }
  43016. }
  43017. else if (payload.x != null && payload.y != null) {
  43018. // FIXME
  43019. // should wrap dispatchAction like `axisPointer/globalListener` ?
  43020. api.dispatchAction({
  43021. type: 'updateAxisPointer',
  43022. x: payload.x,
  43023. y: payload.y
  43024. });
  43025. this._tryShow({
  43026. offsetX: payload.x,
  43027. offsetY: payload.y,
  43028. position: payload.position,
  43029. target: api.getZr().findHover(payload.x, payload.y).target
  43030. }, dispatchAction);
  43031. }
  43032. },
  43033. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  43034. var tooltipContent = this._tooltipContent;
  43035. if (!this._alwaysShowContent && this._tooltipModel) {
  43036. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  43037. }
  43038. this._lastX = this._lastY = null;
  43039. if (payload.from !== this.uid) {
  43040. this._hide(makeDispatchAction$1(payload, api));
  43041. }
  43042. },
  43043. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  43044. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  43045. // and tooltip.
  43046. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  43047. var seriesIndex = payload.seriesIndex;
  43048. var dataIndex = payload.dataIndex;
  43049. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  43050. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  43051. return;
  43052. }
  43053. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  43054. if (!seriesModel) {
  43055. return;
  43056. }
  43057. var data = seriesModel.getData();
  43058. var tooltipModel = buildTooltipModel([
  43059. data.getItemModel(dataIndex),
  43060. seriesModel,
  43061. (seriesModel.coordinateSystem || {}).model,
  43062. tooltipModel
  43063. ]);
  43064. if (tooltipModel.get('trigger') !== 'axis') {
  43065. return;
  43066. }
  43067. api.dispatchAction({
  43068. type: 'updateAxisPointer',
  43069. seriesIndex: seriesIndex,
  43070. dataIndex: dataIndex,
  43071. position: payload.position
  43072. });
  43073. return true;
  43074. },
  43075. _tryShow: function (e, dispatchAction) {
  43076. var el = e.target;
  43077. var tooltipModel = this._tooltipModel;
  43078. if (!tooltipModel) {
  43079. return;
  43080. }
  43081. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  43082. this._lastX = e.offsetX;
  43083. this._lastY = e.offsetY;
  43084. var dataByCoordSys = e.dataByCoordSys;
  43085. if (dataByCoordSys && dataByCoordSys.length) {
  43086. this._showAxisTooltip(dataByCoordSys, e);
  43087. }
  43088. // Always show item tooltip if mouse is on the element with dataIndex
  43089. else if (el && el.dataIndex != null) {
  43090. this._lastDataByCoordSys = null;
  43091. this._showSeriesItemTooltip(e, el, dispatchAction);
  43092. }
  43093. // Tooltip provided directly. Like legend.
  43094. else if (el && el.tooltip) {
  43095. this._lastDataByCoordSys = null;
  43096. this._showComponentItemTooltip(e, el, dispatchAction);
  43097. }
  43098. else {
  43099. this._lastDataByCoordSys = null;
  43100. this._hide(dispatchAction);
  43101. }
  43102. },
  43103. _showOrMove: function (tooltipModel, cb) {
  43104. // showDelay is used in this case: tooltip.enterable is set
  43105. // as true. User intent to move mouse into tooltip and click
  43106. // something. `showDelay` makes it easyer to enter the content
  43107. // but tooltip do not move immediately.
  43108. var delay = tooltipModel.get('showDelay');
  43109. cb = bind(cb, this);
  43110. clearTimeout(this._showTimout);
  43111. delay > 0
  43112. ? (this._showTimout = setTimeout(cb, delay))
  43113. : cb();
  43114. },
  43115. _showAxisTooltip: function (dataByCoordSys, e) {
  43116. var ecModel = this._ecModel;
  43117. var globalTooltipModel = this._tooltipModel;
  43118. var point = [e.offsetX, e.offsetY];
  43119. var singleDefaultHTML = [];
  43120. var singleParamsList = [];
  43121. var singleTooltipModel = buildTooltipModel([
  43122. e.tooltipOption,
  43123. globalTooltipModel
  43124. ]);
  43125. var renderMode = this._renderMode;
  43126. var newLine = this._newLine;
  43127. var markers = {};
  43128. each$9(dataByCoordSys, function (itemCoordSys) {
  43129. // var coordParamList = [];
  43130. // var coordDefaultHTML = [];
  43131. // var coordTooltipModel = buildTooltipModel([
  43132. // e.tooltipOption,
  43133. // itemCoordSys.tooltipOption,
  43134. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  43135. // globalTooltipModel
  43136. // ]);
  43137. // var displayMode = coordTooltipModel.get('displayMode');
  43138. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  43139. each$9(itemCoordSys.dataByAxis, function (item) {
  43140. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  43141. var axisValue = item.value;
  43142. var seriesDefaultHTML = [];
  43143. if (!axisModel || axisValue == null) {
  43144. return;
  43145. }
  43146. var valueLabel = getValueLabel(
  43147. axisValue, axisModel.axis, ecModel,
  43148. item.seriesDataIndices,
  43149. item.valueLabelOpt
  43150. );
  43151. each$1(item.seriesDataIndices, function (idxItem) {
  43152. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  43153. var dataIndex = idxItem.dataIndexInside;
  43154. var dataParams = series && series.getDataParams(dataIndex);
  43155. dataParams.axisDim = item.axisDim;
  43156. dataParams.axisIndex = item.axisIndex;
  43157. dataParams.axisType = item.axisType;
  43158. dataParams.axisId = item.axisId;
  43159. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  43160. dataParams.axisValueLabel = valueLabel;
  43161. if (dataParams) {
  43162. singleParamsList.push(dataParams);
  43163. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  43164. var html;
  43165. if (isObject$1(seriesTooltip)) {
  43166. html = seriesTooltip.html;
  43167. var newMarkers = seriesTooltip.markers;
  43168. merge(markers, newMarkers);
  43169. }
  43170. else {
  43171. html = seriesTooltip;
  43172. }
  43173. seriesDefaultHTML.push(html);
  43174. }
  43175. });
  43176. // Default tooltip content
  43177. // FIXME
  43178. // (1) shold be the first data which has name?
  43179. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  43180. var firstLine = valueLabel;
  43181. if (renderMode !== 'html') {
  43182. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  43183. }
  43184. else {
  43185. singleDefaultHTML.push(
  43186. (firstLine ? encodeHTML(firstLine) + newLine : '')
  43187. + seriesDefaultHTML.join(newLine)
  43188. );
  43189. }
  43190. });
  43191. }, this);
  43192. // In most case, the second axis is shown upper than the first one.
  43193. singleDefaultHTML.reverse();
  43194. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  43195. var positionExpr = e.position;
  43196. this._showOrMove(singleTooltipModel, function () {
  43197. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  43198. this._updatePosition(
  43199. singleTooltipModel,
  43200. positionExpr,
  43201. point[0], point[1],
  43202. this._tooltipContent,
  43203. singleParamsList
  43204. );
  43205. }
  43206. else {
  43207. this._showTooltipContent(
  43208. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  43209. point[0], point[1], positionExpr, undefined, markers
  43210. );
  43211. }
  43212. });
  43213. // Do not trigger events here, because this branch only be entered
  43214. // from dispatchAction.
  43215. },
  43216. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  43217. var ecModel = this._ecModel;
  43218. // Use dataModel in element if possible
  43219. // Used when mouseover on a element like markPoint or edge
  43220. // In which case, the data is not main data in series.
  43221. var seriesIndex = el.seriesIndex;
  43222. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  43223. // For example, graph link.
  43224. var dataModel = el.dataModel || seriesModel;
  43225. var dataIndex = el.dataIndex;
  43226. var dataType = el.dataType;
  43227. var data = dataModel.getData(dataType);
  43228. var tooltipModel = buildTooltipModel([
  43229. data.getItemModel(dataIndex),
  43230. dataModel,
  43231. seriesModel && (seriesModel.coordinateSystem || {}).model,
  43232. this._tooltipModel
  43233. ]);
  43234. var tooltipTrigger = tooltipModel.get('trigger');
  43235. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  43236. return;
  43237. }
  43238. var params = dataModel.getDataParams(dataIndex, dataType);
  43239. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  43240. var defaultHtml;
  43241. var markers;
  43242. if (isObject$1(seriesTooltip)) {
  43243. defaultHtml = seriesTooltip.html;
  43244. markers = seriesTooltip.markers;
  43245. }
  43246. else {
  43247. defaultHtml = seriesTooltip;
  43248. markers = null;
  43249. }
  43250. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  43251. this._showOrMove(tooltipModel, function () {
  43252. this._showTooltipContent(
  43253. tooltipModel, defaultHtml, params, asyncTicket,
  43254. e.offsetX, e.offsetY, e.position, e.target, markers
  43255. );
  43256. });
  43257. // FIXME
  43258. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  43259. dispatchAction({
  43260. type: 'showTip',
  43261. dataIndexInside: dataIndex,
  43262. dataIndex: data.getRawIndex(dataIndex),
  43263. seriesIndex: seriesIndex,
  43264. from: this.uid
  43265. });
  43266. },
  43267. _showComponentItemTooltip: function (e, el, dispatchAction) {
  43268. var tooltipOpt = el.tooltip;
  43269. if (typeof tooltipOpt === 'string') {
  43270. var content = tooltipOpt;
  43271. tooltipOpt = {
  43272. content: content,
  43273. // Fixed formatter
  43274. formatter: content
  43275. };
  43276. }
  43277. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  43278. var defaultHtml = subTooltipModel.get('content');
  43279. var asyncTicket = Math.random();
  43280. // Do not check whether `trigger` is 'none' here, because `trigger`
  43281. // only works on cooridinate system. In fact, we have not found case
  43282. // that requires setting `trigger` nothing on component yet.
  43283. this._showOrMove(subTooltipModel, function () {
  43284. this._showTooltipContent(
  43285. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  43286. asyncTicket, e.offsetX, e.offsetY, e.position, el
  43287. );
  43288. });
  43289. // If not dispatch showTip, tip may be hide triggered by axis.
  43290. dispatchAction({
  43291. type: 'showTip',
  43292. from: this.uid
  43293. });
  43294. },
  43295. _showTooltipContent: function (
  43296. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  43297. ) {
  43298. // Reset ticket
  43299. this._ticket = '';
  43300. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  43301. return;
  43302. }
  43303. var tooltipContent = this._tooltipContent;
  43304. var formatter = tooltipModel.get('formatter');
  43305. positionExpr = positionExpr || tooltipModel.get('position');
  43306. var html = defaultHtml;
  43307. if (formatter && typeof formatter === 'string') {
  43308. html = formatTpl(formatter, params, true);
  43309. }
  43310. else if (typeof formatter === 'function') {
  43311. var callback = bind$2(function (cbTicket, html) {
  43312. if (cbTicket === this._ticket) {
  43313. tooltipContent.setContent(html, markers, tooltipModel);
  43314. this._updatePosition(
  43315. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  43316. );
  43317. }
  43318. }, this);
  43319. this._ticket = asyncTicket;
  43320. html = formatter(params, asyncTicket, callback);
  43321. }
  43322. tooltipContent.setContent(html, markers, tooltipModel);
  43323. tooltipContent.show(tooltipModel);
  43324. this._updatePosition(
  43325. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  43326. );
  43327. },
  43328. /**
  43329. * @param {string|Function|Array.<number>|Object} positionExpr
  43330. * @param {number} x Mouse x
  43331. * @param {number} y Mouse y
  43332. * @param {boolean} confine Whether confine tooltip content in view rect.
  43333. * @param {Object|<Array.<Object>} params
  43334. * @param {module:zrender/Element} el target element
  43335. * @param {module:echarts/ExtensionAPI} api
  43336. * @return {Array.<number>}
  43337. */
  43338. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  43339. var viewWidth = this._api.getWidth();
  43340. var viewHeight = this._api.getHeight();
  43341. positionExpr = positionExpr || tooltipModel.get('position');
  43342. var contentSize = content.getSize();
  43343. var align = tooltipModel.get('align');
  43344. var vAlign = tooltipModel.get('verticalAlign');
  43345. var rect = el && el.getBoundingRect().clone();
  43346. el && rect.applyTransform(el.transform);
  43347. if (typeof positionExpr === 'function') {
  43348. // Callback of position can be an array or a string specify the position
  43349. positionExpr = positionExpr([x, y], params, content.el, rect, {
  43350. viewSize: [viewWidth, viewHeight],
  43351. contentSize: contentSize.slice()
  43352. });
  43353. }
  43354. if (isArray(positionExpr)) {
  43355. x = parsePercent$2(positionExpr[0], viewWidth);
  43356. y = parsePercent$2(positionExpr[1], viewHeight);
  43357. }
  43358. else if (isObject$1(positionExpr)) {
  43359. positionExpr.width = contentSize[0];
  43360. positionExpr.height = contentSize[1];
  43361. var layoutRect = getLayoutRect(
  43362. positionExpr, {width: viewWidth, height: viewHeight}
  43363. );
  43364. x = layoutRect.x;
  43365. y = layoutRect.y;
  43366. align = null;
  43367. // When positionExpr is left/top/right/bottom,
  43368. // align and verticalAlign will not work.
  43369. vAlign = null;
  43370. }
  43371. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  43372. else if (typeof positionExpr === 'string' && el) {
  43373. var pos = calcTooltipPosition(
  43374. positionExpr, rect, contentSize
  43375. );
  43376. x = pos[0];
  43377. y = pos[1];
  43378. }
  43379. else {
  43380. var pos = refixTooltipPosition(
  43381. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  43382. );
  43383. x = pos[0];
  43384. y = pos[1];
  43385. }
  43386. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  43387. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  43388. if (tooltipModel.get('confine')) {
  43389. var pos = confineTooltipPosition(
  43390. x, y, content, viewWidth, viewHeight
  43391. );
  43392. x = pos[0];
  43393. y = pos[1];
  43394. }
  43395. content.moveTo(x, y);
  43396. },
  43397. // FIXME
  43398. // Should we remove this but leave this to user?
  43399. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  43400. var lastCoordSys = this._lastDataByCoordSys;
  43401. var contentNotChanged = !!lastCoordSys
  43402. && lastCoordSys.length === dataByCoordSys.length;
  43403. contentNotChanged && each$9(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  43404. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  43405. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  43406. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  43407. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  43408. contentNotChanged && each$9(lastDataByAxis, function (lastItem, indexAxis) {
  43409. var thisItem = thisDataByAxis[indexAxis] || {};
  43410. var lastIndices = lastItem.seriesDataIndices || [];
  43411. var newIndices = thisItem.seriesDataIndices || [];
  43412. contentNotChanged
  43413. &= lastItem.value === thisItem.value
  43414. && lastItem.axisType === thisItem.axisType
  43415. && lastItem.axisId === thisItem.axisId
  43416. && lastIndices.length === newIndices.length;
  43417. contentNotChanged && each$9(lastIndices, function (lastIdxItem, j) {
  43418. var newIdxItem = newIndices[j];
  43419. contentNotChanged
  43420. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  43421. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  43422. });
  43423. });
  43424. });
  43425. this._lastDataByCoordSys = dataByCoordSys;
  43426. return !!contentNotChanged;
  43427. },
  43428. _hide: function (dispatchAction) {
  43429. // Do not directly hideLater here, because this behavior may be prevented
  43430. // in dispatchAction when showTip is dispatched.
  43431. // FIXME
  43432. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  43433. this._lastDataByCoordSys = null;
  43434. dispatchAction({
  43435. type: 'hideTip',
  43436. from: this.uid
  43437. });
  43438. },
  43439. dispose: function (ecModel, api) {
  43440. if (env$1.node) {
  43441. return;
  43442. }
  43443. this._tooltipContent.dispose();
  43444. unregister('itemTooltip', api);
  43445. }
  43446. });
  43447. /**
  43448. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  43449. * From top to bottom. (the last one should be globalTooltipModel);
  43450. */
  43451. function buildTooltipModel(modelCascade) {
  43452. var resultModel = modelCascade.pop();
  43453. while (modelCascade.length) {
  43454. var tooltipOpt = modelCascade.pop();
  43455. if (tooltipOpt) {
  43456. if (Model.isInstance(tooltipOpt)) {
  43457. tooltipOpt = tooltipOpt.get('tooltip', true);
  43458. }
  43459. // In each data item tooltip can be simply write:
  43460. // {
  43461. // value: 10,
  43462. // tooltip: 'Something you need to know'
  43463. // }
  43464. if (typeof tooltipOpt === 'string') {
  43465. tooltipOpt = {formatter: tooltipOpt};
  43466. }
  43467. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  43468. }
  43469. }
  43470. return resultModel;
  43471. }
  43472. function makeDispatchAction$1(payload, api) {
  43473. return payload.dispatchAction || bind(api.dispatchAction, api);
  43474. }
  43475. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  43476. var size = content.getOuterSize();
  43477. var width = size.width;
  43478. var height = size.height;
  43479. if (gapH != null) {
  43480. if (x + width + gapH > viewWidth) {
  43481. x -= width + gapH;
  43482. }
  43483. else {
  43484. x += gapH;
  43485. }
  43486. }
  43487. if (gapV != null) {
  43488. if (y + height + gapV > viewHeight) {
  43489. y -= height + gapV;
  43490. }
  43491. else {
  43492. y += gapV;
  43493. }
  43494. }
  43495. return [x, y];
  43496. }
  43497. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  43498. var size = content.getOuterSize();
  43499. var width = size.width;
  43500. var height = size.height;
  43501. x = Math.min(x + width, viewWidth) - width;
  43502. y = Math.min(y + height, viewHeight) - height;
  43503. x = Math.max(x, 0);
  43504. y = Math.max(y, 0);
  43505. return [x, y];
  43506. }
  43507. function calcTooltipPosition(position, rect, contentSize) {
  43508. var domWidth = contentSize[0];
  43509. var domHeight = contentSize[1];
  43510. var gap = 5;
  43511. var x = 0;
  43512. var y = 0;
  43513. var rectWidth = rect.width;
  43514. var rectHeight = rect.height;
  43515. switch (position) {
  43516. case 'inside':
  43517. x = rect.x + rectWidth / 2 - domWidth / 2;
  43518. y = rect.y + rectHeight / 2 - domHeight / 2;
  43519. break;
  43520. case 'top':
  43521. x = rect.x + rectWidth / 2 - domWidth / 2;
  43522. y = rect.y - domHeight - gap;
  43523. break;
  43524. case 'bottom':
  43525. x = rect.x + rectWidth / 2 - domWidth / 2;
  43526. y = rect.y + rectHeight + gap;
  43527. break;
  43528. case 'left':
  43529. x = rect.x - domWidth - gap;
  43530. y = rect.y + rectHeight / 2 - domHeight / 2;
  43531. break;
  43532. case 'right':
  43533. x = rect.x + rectWidth + gap;
  43534. y = rect.y + rectHeight / 2 - domHeight / 2;
  43535. }
  43536. return [x, y];
  43537. }
  43538. function isCenterAlign(align) {
  43539. return align === 'center' || align === 'middle';
  43540. }
  43541. /*
  43542. * Licensed to the Apache Software Foundation (ASF) under one
  43543. * or more contributor license agreements. See the NOTICE file
  43544. * distributed with this work for additional information
  43545. * regarding copyright ownership. The ASF licenses this file
  43546. * to you under the Apache License, Version 2.0 (the
  43547. * "License"); you may not use this file except in compliance
  43548. * with the License. You may obtain a copy of the License at
  43549. *
  43550. * http://www.apache.org/licenses/LICENSE-2.0
  43551. *
  43552. * Unless required by applicable law or agreed to in writing,
  43553. * software distributed under the License is distributed on an
  43554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43555. * KIND, either express or implied. See the License for the
  43556. * specific language governing permissions and limitations
  43557. * under the License.
  43558. */
  43559. // FIXME Better way to pack data in graphic element
  43560. /**
  43561. * @action
  43562. * @property {string} type
  43563. * @property {number} seriesIndex
  43564. * @property {number} dataIndex
  43565. * @property {number} [x]
  43566. * @property {number} [y]
  43567. */
  43568. registerAction(
  43569. {
  43570. type: 'showTip',
  43571. event: 'showTip',
  43572. update: 'tooltip:manuallyShowTip'
  43573. },
  43574. // noop
  43575. function () {}
  43576. );
  43577. registerAction(
  43578. {
  43579. type: 'hideTip',
  43580. event: 'hideTip',
  43581. update: 'tooltip:manuallyHideTip'
  43582. },
  43583. // noop
  43584. function () {}
  43585. );
  43586. /*
  43587. * Licensed to the Apache Software Foundation (ASF) under one
  43588. * or more contributor license agreements. See the NOTICE file
  43589. * distributed with this work for additional information
  43590. * regarding copyright ownership. The ASF licenses this file
  43591. * to you under the Apache License, Version 2.0 (the
  43592. * "License"); you may not use this file except in compliance
  43593. * with the License. You may obtain a copy of the License at
  43594. *
  43595. * http://www.apache.org/licenses/LICENSE-2.0
  43596. *
  43597. * Unless required by applicable law or agreed to in writing,
  43598. * software distributed under the License is distributed on an
  43599. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43600. * KIND, either express or implied. See the License for the
  43601. * specific language governing permissions and limitations
  43602. * under the License.
  43603. */
  43604. var langSelector = lang.legend.selector;
  43605. var defaultSelectorOption = {
  43606. all: {
  43607. type: 'all',
  43608. title: clone(langSelector.all)
  43609. },
  43610. inverse: {
  43611. type: 'inverse',
  43612. title: clone(langSelector.inverse)
  43613. }
  43614. };
  43615. var LegendModel = extendComponentModel({
  43616. type: 'legend.plain',
  43617. dependencies: ['series'],
  43618. layoutMode: {
  43619. type: 'box',
  43620. // legend.width/height are maxWidth/maxHeight actually,
  43621. // whereas realy width/height is calculated by its content.
  43622. // (Setting {left: 10, right: 10} does not make sense).
  43623. // So consider the case:
  43624. // `setOption({legend: {left: 10});`
  43625. // then `setOption({legend: {right: 10});`
  43626. // The previous `left` should be cleared by setting `ignoreSize`.
  43627. ignoreSize: true
  43628. },
  43629. init: function (option, parentModel, ecModel) {
  43630. this.mergeDefaultAndTheme(option, ecModel);
  43631. option.selected = option.selected || {};
  43632. this._updateSelector(option);
  43633. },
  43634. mergeOption: function (option) {
  43635. LegendModel.superCall(this, 'mergeOption', option);
  43636. this._updateSelector(option);
  43637. },
  43638. _updateSelector: function (option) {
  43639. var selector = option.selector;
  43640. if (selector === true) {
  43641. selector = option.selector = ['all', 'inverse'];
  43642. }
  43643. if (isArray(selector)) {
  43644. each$1(selector, function (item, index) {
  43645. isString(item) && (item = {type: item});
  43646. selector[index] = merge(item, defaultSelectorOption[item.type]);
  43647. });
  43648. }
  43649. },
  43650. optionUpdated: function () {
  43651. this._updateData(this.ecModel);
  43652. var legendData = this._data;
  43653. // If selectedMode is single, try to select one
  43654. if (legendData[0] && this.get('selectedMode') === 'single') {
  43655. var hasSelected = false;
  43656. // If has any selected in option.selected
  43657. for (var i = 0; i < legendData.length; i++) {
  43658. var name = legendData[i].get('name');
  43659. if (this.isSelected(name)) {
  43660. // Force to unselect others
  43661. this.select(name);
  43662. hasSelected = true;
  43663. break;
  43664. }
  43665. }
  43666. // Try select the first if selectedMode is single
  43667. !hasSelected && this.select(legendData[0].get('name'));
  43668. }
  43669. },
  43670. _updateData: function (ecModel) {
  43671. var potentialData = [];
  43672. var availableNames = [];
  43673. ecModel.eachRawSeries(function (seriesModel) {
  43674. var seriesName = seriesModel.name;
  43675. availableNames.push(seriesName);
  43676. var isPotential;
  43677. if (seriesModel.legendVisualProvider) {
  43678. var provider = seriesModel.legendVisualProvider;
  43679. var names = provider.getAllNames();
  43680. if (!ecModel.isSeriesFiltered(seriesModel)) {
  43681. availableNames = availableNames.concat(names);
  43682. }
  43683. if (names.length) {
  43684. potentialData = potentialData.concat(names);
  43685. }
  43686. else {
  43687. isPotential = true;
  43688. }
  43689. }
  43690. else {
  43691. isPotential = true;
  43692. }
  43693. if (isPotential && isNameSpecified(seriesModel)) {
  43694. potentialData.push(seriesModel.name);
  43695. }
  43696. });
  43697. /**
  43698. * @type {Array.<string>}
  43699. * @private
  43700. */
  43701. this._availableNames = availableNames;
  43702. // If legend.data not specified in option, use availableNames as data,
  43703. // which is convinient for user preparing option.
  43704. var rawData = this.get('data') || potentialData;
  43705. var legendData = map(rawData, function (dataItem) {
  43706. // Can be string or number
  43707. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  43708. dataItem = {
  43709. name: dataItem
  43710. };
  43711. }
  43712. return new Model(dataItem, this, this.ecModel);
  43713. }, this);
  43714. /**
  43715. * @type {Array.<module:echarts/model/Model>}
  43716. * @private
  43717. */
  43718. this._data = legendData;
  43719. },
  43720. /**
  43721. * @return {Array.<module:echarts/model/Model>}
  43722. */
  43723. getData: function () {
  43724. return this._data;
  43725. },
  43726. /**
  43727. * @param {string} name
  43728. */
  43729. select: function (name) {
  43730. var selected = this.option.selected;
  43731. var selectedMode = this.get('selectedMode');
  43732. if (selectedMode === 'single') {
  43733. var data = this._data;
  43734. each$1(data, function (dataItem) {
  43735. selected[dataItem.get('name')] = false;
  43736. });
  43737. }
  43738. selected[name] = true;
  43739. },
  43740. /**
  43741. * @param {string} name
  43742. */
  43743. unSelect: function (name) {
  43744. if (this.get('selectedMode') !== 'single') {
  43745. this.option.selected[name] = false;
  43746. }
  43747. },
  43748. /**
  43749. * @param {string} name
  43750. */
  43751. toggleSelected: function (name) {
  43752. var selected = this.option.selected;
  43753. // Default is true
  43754. if (!selected.hasOwnProperty(name)) {
  43755. selected[name] = true;
  43756. }
  43757. this[selected[name] ? 'unSelect' : 'select'](name);
  43758. },
  43759. allSelect: function () {
  43760. var data = this._data;
  43761. var selected = this.option.selected;
  43762. each$1(data, function (dataItem) {
  43763. selected[dataItem.get('name', true)] = true;
  43764. });
  43765. },
  43766. inverseSelect: function () {
  43767. var data = this._data;
  43768. var selected = this.option.selected;
  43769. each$1(data, function (dataItem) {
  43770. var name = dataItem.get('name', true);
  43771. // Initially, default value is true
  43772. if (!selected.hasOwnProperty(name)) {
  43773. selected[name] = true;
  43774. }
  43775. selected[name] = !selected[name];
  43776. });
  43777. },
  43778. /**
  43779. * @param {string} name
  43780. */
  43781. isSelected: function (name) {
  43782. var selected = this.option.selected;
  43783. return !(selected.hasOwnProperty(name) && !selected[name])
  43784. && indexOf(this._availableNames, name) >= 0;
  43785. },
  43786. getOrient: function () {
  43787. return this.get('orient') === 'vertical'
  43788. ? {index: 1, name: 'vertical'}
  43789. : {index: 0, name: 'horizontal'};
  43790. },
  43791. defaultOption: {
  43792. // 一级层叠
  43793. zlevel: 0,
  43794. // 二级层叠
  43795. z: 4,
  43796. show: true,
  43797. // 布局方式,默认为水平布局,可选为:
  43798. // 'horizontal' | 'vertical'
  43799. orient: 'horizontal',
  43800. left: 'center',
  43801. // right: 'center',
  43802. top: 0,
  43803. // bottom: null,
  43804. // 水平对齐
  43805. // 'auto' | 'left' | 'right'
  43806. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  43807. align: 'auto',
  43808. backgroundColor: 'rgba(0,0,0,0)',
  43809. // 图例边框颜色
  43810. borderColor: '#ccc',
  43811. borderRadius: 0,
  43812. // 图例边框线宽,单位px,默认为0(无边框)
  43813. borderWidth: 0,
  43814. // 图例内边距,单位px,默认各方向内边距为5,
  43815. // 接受数组分别设定上右下左边距,同css
  43816. padding: 5,
  43817. // 各个item之间的间隔,单位px,默认为10,
  43818. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  43819. itemGap: 10,
  43820. // the width of legend symbol
  43821. itemWidth: 25,
  43822. // the height of legend symbol
  43823. itemHeight: 14,
  43824. // the color of unselected legend symbol
  43825. inactiveColor: '#ccc',
  43826. // the borderColor of unselected legend symbol
  43827. inactiveBorderColor: '#ccc',
  43828. itemStyle: {
  43829. // the default borderWidth of legend symbol
  43830. borderWidth: 0
  43831. },
  43832. textStyle: {
  43833. // 图例文字颜色
  43834. color: '#333'
  43835. },
  43836. // formatter: '',
  43837. // 选择模式,默认开启图例开关
  43838. selectedMode: true,
  43839. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  43840. // selected: null,
  43841. // 图例内容(详见legend.data,数组中每一项代表一个item
  43842. // data: [],
  43843. // Usage:
  43844. // selector: [{type: 'all or inverse', title: xxx}]
  43845. // or
  43846. // selector: true
  43847. // or
  43848. // selector: ['all', 'inverse']
  43849. selector: false,
  43850. selectorLabel: {
  43851. show: true,
  43852. borderRadius: 10,
  43853. padding: [3, 5, 3, 5],
  43854. fontSize: 12,
  43855. fontFamily: ' sans-serif',
  43856. color: '#666',
  43857. borderWidth: 1,
  43858. borderColor: '#666'
  43859. },
  43860. emphasis: {
  43861. selectorLabel: {
  43862. show: true,
  43863. color: '#eee',
  43864. backgroundColor: '#666'
  43865. }
  43866. },
  43867. // Value can be 'start' or 'end'
  43868. selectorPosition: 'auto',
  43869. selectorItemGap: 7,
  43870. selectorButtonGap: 10,
  43871. // Tooltip 相关配置
  43872. tooltip: {
  43873. show: false
  43874. }
  43875. }
  43876. });
  43877. /*
  43878. * Licensed to the Apache Software Foundation (ASF) under one
  43879. * or more contributor license agreements. See the NOTICE file
  43880. * distributed with this work for additional information
  43881. * regarding copyright ownership. The ASF licenses this file
  43882. * to you under the Apache License, Version 2.0 (the
  43883. * "License"); you may not use this file except in compliance
  43884. * with the License. You may obtain a copy of the License at
  43885. *
  43886. * http://www.apache.org/licenses/LICENSE-2.0
  43887. *
  43888. * Unless required by applicable law or agreed to in writing,
  43889. * software distributed under the License is distributed on an
  43890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43891. * KIND, either express or implied. See the License for the
  43892. * specific language governing permissions and limitations
  43893. * under the License.
  43894. */
  43895. function legendSelectActionHandler(methodName, payload, ecModel) {
  43896. var selectedMap = {};
  43897. var isToggleSelect = methodName === 'toggleSelected';
  43898. var isSelected;
  43899. // Update all legend components
  43900. ecModel.eachComponent('legend', function (legendModel) {
  43901. if (isToggleSelect && isSelected != null) {
  43902. // Force other legend has same selected status
  43903. // Or the first is toggled to true and other are toggled to false
  43904. // In the case one legend has some item unSelected in option. And if other legend
  43905. // doesn't has the item, they will assume it is selected.
  43906. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  43907. }
  43908. else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  43909. legendModel[methodName]();
  43910. }
  43911. else {
  43912. legendModel[methodName](payload.name);
  43913. isSelected = legendModel.isSelected(payload.name);
  43914. }
  43915. var legendData = legendModel.getData();
  43916. each$1(legendData, function (model) {
  43917. var name = model.get('name');
  43918. // Wrap element
  43919. if (name === '\n' || name === '') {
  43920. return;
  43921. }
  43922. var isItemSelected = legendModel.isSelected(name);
  43923. if (selectedMap.hasOwnProperty(name)) {
  43924. // Unselected if any legend is unselected
  43925. selectedMap[name] = selectedMap[name] && isItemSelected;
  43926. }
  43927. else {
  43928. selectedMap[name] = isItemSelected;
  43929. }
  43930. });
  43931. });
  43932. // Return the event explicitly
  43933. return (methodName === 'allSelect' || methodName === 'inverseSelect')
  43934. ? {
  43935. selected: selectedMap
  43936. }
  43937. : {
  43938. name: payload.name,
  43939. selected: selectedMap
  43940. };
  43941. }
  43942. /**
  43943. * @event legendToggleSelect
  43944. * @type {Object}
  43945. * @property {string} type 'legendToggleSelect'
  43946. * @property {string} [from]
  43947. * @property {string} name Series name or data item name
  43948. */
  43949. registerAction(
  43950. 'legendToggleSelect', 'legendselectchanged',
  43951. curry(legendSelectActionHandler, 'toggleSelected')
  43952. );
  43953. registerAction(
  43954. 'legendAllSelect', 'legendselectall',
  43955. curry(legendSelectActionHandler, 'allSelect')
  43956. );
  43957. registerAction(
  43958. 'legendInverseSelect', 'legendinverseselect',
  43959. curry(legendSelectActionHandler, 'inverseSelect')
  43960. );
  43961. /**
  43962. * @event legendSelect
  43963. * @type {Object}
  43964. * @property {string} type 'legendSelect'
  43965. * @property {string} name Series name or data item name
  43966. */
  43967. registerAction(
  43968. 'legendSelect', 'legendselected',
  43969. curry(legendSelectActionHandler, 'select')
  43970. );
  43971. /**
  43972. * @event legendUnSelect
  43973. * @type {Object}
  43974. * @property {string} type 'legendUnSelect'
  43975. * @property {string} name Series name or data item name
  43976. */
  43977. registerAction(
  43978. 'legendUnSelect', 'legendunselected',
  43979. curry(legendSelectActionHandler, 'unSelect')
  43980. );
  43981. /*
  43982. * Licensed to the Apache Software Foundation (ASF) under one
  43983. * or more contributor license agreements. See the NOTICE file
  43984. * distributed with this work for additional information
  43985. * regarding copyright ownership. The ASF licenses this file
  43986. * to you under the Apache License, Version 2.0 (the
  43987. * "License"); you may not use this file except in compliance
  43988. * with the License. You may obtain a copy of the License at
  43989. *
  43990. * http://www.apache.org/licenses/LICENSE-2.0
  43991. *
  43992. * Unless required by applicable law or agreed to in writing,
  43993. * software distributed under the License is distributed on an
  43994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43995. * KIND, either express or implied. See the License for the
  43996. * specific language governing permissions and limitations
  43997. * under the License.
  43998. */
  43999. /**
  44000. * Layout list like component.
  44001. * It will box layout each items in group of component and then position the whole group in the viewport
  44002. * @param {module:zrender/group/Group} group
  44003. * @param {module:echarts/model/Component} componentModel
  44004. * @param {module:echarts/ExtensionAPI}
  44005. */
  44006. function layout$2(group, componentModel, api) {
  44007. var boxLayoutParams = componentModel.getBoxLayoutParams();
  44008. var padding = componentModel.get('padding');
  44009. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  44010. var rect = getLayoutRect(
  44011. boxLayoutParams,
  44012. viewportSize,
  44013. padding
  44014. );
  44015. box(
  44016. componentModel.get('orient'),
  44017. group,
  44018. componentModel.get('itemGap'),
  44019. rect.width,
  44020. rect.height
  44021. );
  44022. positionElement(
  44023. group,
  44024. boxLayoutParams,
  44025. viewportSize,
  44026. padding
  44027. );
  44028. }
  44029. function makeBackground(rect, componentModel) {
  44030. var padding = normalizeCssArray$1(
  44031. componentModel.get('padding')
  44032. );
  44033. var style = componentModel.getItemStyle(['color', 'opacity']);
  44034. style.fill = componentModel.get('backgroundColor');
  44035. var rect = new Rect({
  44036. shape: {
  44037. x: rect.x - padding[3],
  44038. y: rect.y - padding[0],
  44039. width: rect.width + padding[1] + padding[3],
  44040. height: rect.height + padding[0] + padding[2],
  44041. r: componentModel.get('borderRadius')
  44042. },
  44043. style: style,
  44044. silent: true,
  44045. z2: -1
  44046. });
  44047. // FIXME
  44048. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  44049. // and background rect when setting like `left: 0`, `top: 0`.
  44050. // graphic.subPixelOptimizeRect(rect);
  44051. return rect;
  44052. }
  44053. /*
  44054. * Licensed to the Apache Software Foundation (ASF) under one
  44055. * or more contributor license agreements. See the NOTICE file
  44056. * distributed with this work for additional information
  44057. * regarding copyright ownership. The ASF licenses this file
  44058. * to you under the Apache License, Version 2.0 (the
  44059. * "License"); you may not use this file except in compliance
  44060. * with the License. You may obtain a copy of the License at
  44061. *
  44062. * http://www.apache.org/licenses/LICENSE-2.0
  44063. *
  44064. * Unless required by applicable law or agreed to in writing,
  44065. * software distributed under the License is distributed on an
  44066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44067. * KIND, either express or implied. See the License for the
  44068. * specific language governing permissions and limitations
  44069. * under the License.
  44070. */
  44071. var curry$3 = curry;
  44072. var each$11 = each$1;
  44073. var Group$2 = Group;
  44074. var LegendView = extendComponentView({
  44075. type: 'legend.plain',
  44076. newlineDisabled: false,
  44077. /**
  44078. * @override
  44079. */
  44080. init: function () {
  44081. /**
  44082. * @private
  44083. * @type {module:zrender/container/Group}
  44084. */
  44085. this.group.add(this._contentGroup = new Group$2());
  44086. /**
  44087. * @private
  44088. * @type {module:zrender/Element}
  44089. */
  44090. this._backgroundEl;
  44091. /**
  44092. * @private
  44093. * @type {module:zrender/container/Group}
  44094. */
  44095. this.group.add(this._selectorGroup = new Group$2());
  44096. /**
  44097. * If first rendering, `contentGroup.position` is [0, 0], which
  44098. * does not make sense and may cause unexepcted animation if adopted.
  44099. * @private
  44100. * @type {boolean}
  44101. */
  44102. this._isFirstRender = true;
  44103. },
  44104. /**
  44105. * @protected
  44106. */
  44107. getContentGroup: function () {
  44108. return this._contentGroup;
  44109. },
  44110. /**
  44111. * @protected
  44112. */
  44113. getSelectorGroup: function () {
  44114. return this._selectorGroup;
  44115. },
  44116. /**
  44117. * @override
  44118. */
  44119. render: function (legendModel, ecModel, api) {
  44120. var isFirstRender = this._isFirstRender;
  44121. this._isFirstRender = false;
  44122. this.resetInner();
  44123. if (!legendModel.get('show', true)) {
  44124. return;
  44125. }
  44126. var itemAlign = legendModel.get('align');
  44127. var orient = legendModel.get('orient');
  44128. if (!itemAlign || itemAlign === 'auto') {
  44129. itemAlign = (
  44130. legendModel.get('left') === 'right'
  44131. && orient === 'vertical'
  44132. ) ? 'right' : 'left';
  44133. }
  44134. var selector = legendModel.get('selector', true);
  44135. var selectorPosition = legendModel.get('selectorPosition', true);
  44136. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  44137. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  44138. }
  44139. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  44140. // Perform layout.
  44141. var positionInfo = legendModel.getBoxLayoutParams();
  44142. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  44143. var padding = legendModel.get('padding');
  44144. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  44145. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition);
  44146. // Place mainGroup, based on the calculated `mainRect`.
  44147. var layoutRect = getLayoutRect(
  44148. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  44149. viewportSize,
  44150. padding
  44151. );
  44152. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  44153. // Render background after group is layout.
  44154. this.group.add(
  44155. this._backgroundEl = makeBackground(mainRect, legendModel)
  44156. );
  44157. },
  44158. /**
  44159. * @protected
  44160. */
  44161. resetInner: function () {
  44162. this.getContentGroup().removeAll();
  44163. this._backgroundEl && this.group.remove(this._backgroundEl);
  44164. this.getSelectorGroup().removeAll();
  44165. },
  44166. /**
  44167. * @protected
  44168. */
  44169. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44170. var contentGroup = this.getContentGroup();
  44171. var legendDrawnMap = createHashMap();
  44172. var selectMode = legendModel.get('selectedMode');
  44173. var excludeSeriesId = [];
  44174. ecModel.eachRawSeries(function (seriesModel) {
  44175. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  44176. });
  44177. each$11(legendModel.getData(), function (itemModel, dataIndex) {
  44178. var name = itemModel.get('name');
  44179. // Use empty string or \n as a newline string
  44180. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  44181. contentGroup.add(new Group$2({
  44182. newline: true
  44183. }));
  44184. return;
  44185. }
  44186. // Representitive series.
  44187. var seriesModel = ecModel.getSeriesByName(name)[0];
  44188. if (legendDrawnMap.get(name)) {
  44189. // Have been drawed
  44190. return;
  44191. }
  44192. // Legend to control series.
  44193. if (seriesModel) {
  44194. var data = seriesModel.getData();
  44195. var color = data.getVisual('color');
  44196. var borderColor = data.getVisual('borderColor');
  44197. // If color is a callback function
  44198. if (typeof color === 'function') {
  44199. // Use the first data
  44200. color = color(seriesModel.getDataParams(0));
  44201. }
  44202. // If borderColor is a callback function
  44203. if (typeof borderColor === 'function') {
  44204. // Use the first data
  44205. borderColor = borderColor(seriesModel.getDataParams(0));
  44206. }
  44207. // Using rect symbol defaultly
  44208. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  44209. var symbolType = data.getVisual('symbol');
  44210. var itemGroup = this._createItem(
  44211. name, dataIndex, itemModel, legendModel,
  44212. legendSymbolType, symbolType,
  44213. itemAlign, color, borderColor,
  44214. selectMode
  44215. );
  44216. itemGroup.on('click', curry$3(dispatchSelectAction, name, null, api, excludeSeriesId))
  44217. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  44218. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  44219. legendDrawnMap.set(name, true);
  44220. }
  44221. else {
  44222. // Legend to control data. In pie and funnel.
  44223. ecModel.eachRawSeries(function (seriesModel) {
  44224. // In case multiple series has same data name
  44225. if (legendDrawnMap.get(name)) {
  44226. return;
  44227. }
  44228. if (seriesModel.legendVisualProvider) {
  44229. var provider = seriesModel.legendVisualProvider;
  44230. if (!provider.containName(name)) {
  44231. return;
  44232. }
  44233. var idx = provider.indexOfName(name);
  44234. var color = provider.getItemVisual(idx, 'color');
  44235. var borderColor = provider.getItemVisual(idx, 'borderColor');
  44236. var legendSymbolType = 'roundRect';
  44237. var itemGroup = this._createItem(
  44238. name, dataIndex, itemModel, legendModel,
  44239. legendSymbolType, null,
  44240. itemAlign, color, borderColor,
  44241. selectMode
  44242. );
  44243. // FIXME: consider different series has items with the same name.
  44244. itemGroup.on('click', curry$3(dispatchSelectAction, null, name, api, excludeSeriesId))
  44245. // Should not specify the series name, consider legend controls
  44246. // more than one pie series.
  44247. .on('mouseover', curry$3(dispatchHighlightAction, null, name, api, excludeSeriesId))
  44248. .on('mouseout', curry$3(dispatchDownplayAction, null, name, api, excludeSeriesId));
  44249. legendDrawnMap.set(name, true);
  44250. }
  44251. }, this);
  44252. }
  44253. if (__DEV__) {
  44254. if (!legendDrawnMap.get(name)) {
  44255. console.warn(
  44256. name + ' series not exists. Legend data should be same with series name or data name.'
  44257. );
  44258. }
  44259. }
  44260. }, this);
  44261. if (selector) {
  44262. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  44263. }
  44264. },
  44265. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  44266. var selectorGroup = this.getSelectorGroup();
  44267. each$11(selector, function (selectorItem) {
  44268. createSelectorButton(selectorItem);
  44269. });
  44270. function createSelectorButton(selectorItem) {
  44271. var type = selectorItem.type;
  44272. var labelText = new Text({
  44273. style: {
  44274. x: 0,
  44275. y: 0,
  44276. align: 'center',
  44277. verticalAlign: 'middle'
  44278. },
  44279. onclick: function () {
  44280. api.dispatchAction({
  44281. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  44282. });
  44283. }
  44284. });
  44285. selectorGroup.add(labelText);
  44286. var labelModel = legendModel.getModel('selectorLabel');
  44287. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  44288. setLabelStyle(
  44289. labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel,
  44290. {
  44291. defaultText: selectorItem.title,
  44292. isRectText: false
  44293. }
  44294. );
  44295. setHoverStyle(labelText);
  44296. }
  44297. },
  44298. _createItem: function (
  44299. name, dataIndex, itemModel, legendModel,
  44300. legendSymbolType, symbolType,
  44301. itemAlign, color, borderColor, selectMode
  44302. ) {
  44303. var itemWidth = legendModel.get('itemWidth');
  44304. var itemHeight = legendModel.get('itemHeight');
  44305. var inactiveColor = legendModel.get('inactiveColor');
  44306. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  44307. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  44308. var legendModelItemStyle = legendModel.getModel('itemStyle');
  44309. var isSelected = legendModel.isSelected(name);
  44310. var itemGroup = new Group$2();
  44311. var textStyleModel = itemModel.getModel('textStyle');
  44312. var itemIcon = itemModel.get('icon');
  44313. var tooltipModel = itemModel.getModel('tooltip');
  44314. var legendGlobalTooltipModel = tooltipModel.parentModel;
  44315. // Use user given icon first
  44316. legendSymbolType = itemIcon || legendSymbolType;
  44317. var legendSymbol = createSymbol(
  44318. legendSymbolType,
  44319. 0,
  44320. 0,
  44321. itemWidth,
  44322. itemHeight,
  44323. isSelected ? color : inactiveColor,
  44324. // symbolKeepAspect default true for legend
  44325. symbolKeepAspect == null ? true : symbolKeepAspect
  44326. );
  44327. itemGroup.add(
  44328. setSymbolStyle(
  44329. legendSymbol, legendSymbolType, legendModelItemStyle,
  44330. borderColor, inactiveBorderColor, isSelected
  44331. )
  44332. );
  44333. // Compose symbols
  44334. // PENDING
  44335. if (!itemIcon && symbolType
  44336. // At least show one symbol, can't be all none
  44337. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  44338. ) {
  44339. var size = itemHeight * 0.8;
  44340. if (symbolType === 'none') {
  44341. symbolType = 'circle';
  44342. }
  44343. var legendSymbolCenter = createSymbol(
  44344. symbolType,
  44345. (itemWidth - size) / 2,
  44346. (itemHeight - size) / 2,
  44347. size,
  44348. size,
  44349. isSelected ? color : inactiveColor,
  44350. // symbolKeepAspect default true for legend
  44351. symbolKeepAspect == null ? true : symbolKeepAspect
  44352. );
  44353. // Put symbol in the center
  44354. itemGroup.add(
  44355. setSymbolStyle(
  44356. legendSymbolCenter, symbolType, legendModelItemStyle,
  44357. borderColor, inactiveBorderColor, isSelected
  44358. )
  44359. );
  44360. }
  44361. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  44362. var textAlign = itemAlign;
  44363. var formatter = legendModel.get('formatter');
  44364. var content = name;
  44365. if (typeof formatter === 'string' && formatter) {
  44366. content = formatter.replace('{name}', name != null ? name : '');
  44367. }
  44368. else if (typeof formatter === 'function') {
  44369. content = formatter(name);
  44370. }
  44371. itemGroup.add(new Text({
  44372. style: setTextStyle({}, textStyleModel, {
  44373. text: content,
  44374. x: textX,
  44375. y: itemHeight / 2,
  44376. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  44377. textAlign: textAlign,
  44378. textVerticalAlign: 'middle'
  44379. })
  44380. }));
  44381. // Add a invisible rect to increase the area of mouse hover
  44382. var hitRect = new Rect({
  44383. shape: itemGroup.getBoundingRect(),
  44384. invisible: true,
  44385. tooltip: tooltipModel.get('show') ? extend({
  44386. content: name,
  44387. // Defaul formatter
  44388. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  44389. return name;
  44390. },
  44391. formatterParams: {
  44392. componentType: 'legend',
  44393. legendIndex: legendModel.componentIndex,
  44394. name: name,
  44395. $vars: ['name']
  44396. }
  44397. }, tooltipModel.option) : null
  44398. });
  44399. itemGroup.add(hitRect);
  44400. itemGroup.eachChild(function (child) {
  44401. child.silent = true;
  44402. });
  44403. hitRect.silent = !selectMode;
  44404. this.getContentGroup().add(itemGroup);
  44405. setHoverStyle(itemGroup);
  44406. itemGroup.__legendDataIndex = dataIndex;
  44407. return itemGroup;
  44408. },
  44409. /**
  44410. * @protected
  44411. */
  44412. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44413. var contentGroup = this.getContentGroup();
  44414. var selectorGroup = this.getSelectorGroup();
  44415. // Place items in contentGroup.
  44416. box(
  44417. legendModel.get('orient'),
  44418. contentGroup,
  44419. legendModel.get('itemGap'),
  44420. maxSize.width,
  44421. maxSize.height
  44422. );
  44423. var contentRect = contentGroup.getBoundingRect();
  44424. var contentPos = [-contentRect.x, -contentRect.y];
  44425. if (selector) {
  44426. // Place buttons in selectorGroup
  44427. box(
  44428. // Buttons in selectorGroup always layout horizontally
  44429. 'horizontal',
  44430. selectorGroup,
  44431. legendModel.get('selectorItemGap', true)
  44432. );
  44433. var selectorRect = selectorGroup.getBoundingRect();
  44434. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44435. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44436. var orientIdx = legendModel.getOrient().index;
  44437. var wh = orientIdx === 0 ? 'width' : 'height';
  44438. var hw = orientIdx === 0 ? 'height' : 'width';
  44439. var yx = orientIdx === 0 ? 'y' : 'x';
  44440. if (selectorPosition === 'end') {
  44441. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  44442. }
  44443. else {
  44444. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  44445. }
  44446. //Always align selector to content as 'middle'
  44447. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  44448. selectorGroup.attr('position', selectorPos);
  44449. contentGroup.attr('position', contentPos);
  44450. var mainRect = {x: 0, y: 0};
  44451. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  44452. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  44453. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  44454. return mainRect;
  44455. }
  44456. else {
  44457. contentGroup.attr('position', contentPos);
  44458. return this.group.getBoundingRect();
  44459. }
  44460. },
  44461. /**
  44462. * @protected
  44463. */
  44464. remove: function () {
  44465. this.getContentGroup().removeAll();
  44466. this._isFirstRender = true;
  44467. }
  44468. });
  44469. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  44470. var itemStyle;
  44471. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  44472. itemStyle = legendModelItemStyle.getItemStyle();
  44473. symbol.style.stroke = borderColor;
  44474. if (!isSelected) {
  44475. itemStyle.stroke = inactiveBorderColor;
  44476. }
  44477. }
  44478. else {
  44479. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  44480. }
  44481. return symbol.setStyle(itemStyle);
  44482. }
  44483. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  44484. // downplay before unselect
  44485. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  44486. api.dispatchAction({
  44487. type: 'legendToggleSelect',
  44488. name: seriesName != null ? seriesName : dataName
  44489. });
  44490. // highlight after select
  44491. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  44492. }
  44493. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  44494. // If element hover will move to a hoverLayer.
  44495. var el = api.getZr().storage.getDisplayList()[0];
  44496. if (!(el && el.useHoverLayer)) {
  44497. api.dispatchAction({
  44498. type: 'highlight',
  44499. seriesName: seriesName,
  44500. name: dataName,
  44501. excludeSeriesId: excludeSeriesId
  44502. });
  44503. }
  44504. }
  44505. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  44506. // If element hover will move to a hoverLayer.
  44507. var el = api.getZr().storage.getDisplayList()[0];
  44508. if (!(el && el.useHoverLayer)) {
  44509. api.dispatchAction({
  44510. type: 'downplay',
  44511. seriesName: seriesName,
  44512. name: dataName,
  44513. excludeSeriesId: excludeSeriesId
  44514. });
  44515. }
  44516. }
  44517. /*
  44518. * Licensed to the Apache Software Foundation (ASF) under one
  44519. * or more contributor license agreements. See the NOTICE file
  44520. * distributed with this work for additional information
  44521. * regarding copyright ownership. The ASF licenses this file
  44522. * to you under the Apache License, Version 2.0 (the
  44523. * "License"); you may not use this file except in compliance
  44524. * with the License. You may obtain a copy of the License at
  44525. *
  44526. * http://www.apache.org/licenses/LICENSE-2.0
  44527. *
  44528. * Unless required by applicable law or agreed to in writing,
  44529. * software distributed under the License is distributed on an
  44530. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44531. * KIND, either express or implied. See the License for the
  44532. * specific language governing permissions and limitations
  44533. * under the License.
  44534. */
  44535. var legendFilter = function (ecModel) {
  44536. var legendModels = ecModel.findComponents({
  44537. mainType: 'legend'
  44538. });
  44539. if (legendModels && legendModels.length) {
  44540. ecModel.filterSeries(function (series) {
  44541. // If in any legend component the status is not selected.
  44542. // Because in legend series is assumed selected when it is not in the legend data.
  44543. for (var i = 0; i < legendModels.length; i++) {
  44544. if (!legendModels[i].isSelected(series.name)) {
  44545. return false;
  44546. }
  44547. }
  44548. return true;
  44549. });
  44550. }
  44551. };
  44552. /*
  44553. * Licensed to the Apache Software Foundation (ASF) under one
  44554. * or more contributor license agreements. See the NOTICE file
  44555. * distributed with this work for additional information
  44556. * regarding copyright ownership. The ASF licenses this file
  44557. * to you under the Apache License, Version 2.0 (the
  44558. * "License"); you may not use this file except in compliance
  44559. * with the License. You may obtain a copy of the License at
  44560. *
  44561. * http://www.apache.org/licenses/LICENSE-2.0
  44562. *
  44563. * Unless required by applicable law or agreed to in writing,
  44564. * software distributed under the License is distributed on an
  44565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44566. * KIND, either express or implied. See the License for the
  44567. * specific language governing permissions and limitations
  44568. * under the License.
  44569. */
  44570. // Do not contain scrollable legend, for sake of file size.
  44571. // Series Filter
  44572. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  44573. ComponentModel.registerSubTypeDefaulter('legend', function () {
  44574. // Default 'plain' when no type specified.
  44575. return 'plain';
  44576. });
  44577. /*
  44578. * Licensed to the Apache Software Foundation (ASF) under one
  44579. * or more contributor license agreements. See the NOTICE file
  44580. * distributed with this work for additional information
  44581. * regarding copyright ownership. The ASF licenses this file
  44582. * to you under the Apache License, Version 2.0 (the
  44583. * "License"); you may not use this file except in compliance
  44584. * with the License. You may obtain a copy of the License at
  44585. *
  44586. * http://www.apache.org/licenses/LICENSE-2.0
  44587. *
  44588. * Unless required by applicable law or agreed to in writing,
  44589. * software distributed under the License is distributed on an
  44590. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44591. * KIND, either express or implied. See the License for the
  44592. * specific language governing permissions and limitations
  44593. * under the License.
  44594. */
  44595. var ScrollableLegendModel = LegendModel.extend({
  44596. type: 'legend.scroll',
  44597. /**
  44598. * @param {number} scrollDataIndex
  44599. */
  44600. setScrollDataIndex: function (scrollDataIndex) {
  44601. this.option.scrollDataIndex = scrollDataIndex;
  44602. },
  44603. defaultOption: {
  44604. scrollDataIndex: 0,
  44605. pageButtonItemGap: 5,
  44606. pageButtonGap: null,
  44607. pageButtonPosition: 'end', // 'start' or 'end'
  44608. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  44609. pageIcons: {
  44610. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  44611. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  44612. },
  44613. pageIconColor: '#2f4554',
  44614. pageIconInactiveColor: '#aaa',
  44615. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  44616. pageTextStyle: {
  44617. color: '#333'
  44618. },
  44619. animationDurationUpdate: 800
  44620. },
  44621. /**
  44622. * @override
  44623. */
  44624. init: function (option, parentModel, ecModel, extraOpt) {
  44625. var inputPositionParams = getLayoutParams(option);
  44626. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  44627. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  44628. },
  44629. /**
  44630. * @override
  44631. */
  44632. mergeOption: function (option, extraOpt) {
  44633. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  44634. mergeAndNormalizeLayoutParams(this, this.option, option);
  44635. }
  44636. });
  44637. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  44638. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  44639. var orient = legendModel.getOrient();
  44640. var ignoreSize = [1, 1];
  44641. ignoreSize[orient.index] = 0;
  44642. mergeLayoutParam(target, raw, {
  44643. type: 'box', ignoreSize: ignoreSize
  44644. });
  44645. }
  44646. /*
  44647. * Licensed to the Apache Software Foundation (ASF) under one
  44648. * or more contributor license agreements. See the NOTICE file
  44649. * distributed with this work for additional information
  44650. * regarding copyright ownership. The ASF licenses this file
  44651. * to you under the Apache License, Version 2.0 (the
  44652. * "License"); you may not use this file except in compliance
  44653. * with the License. You may obtain a copy of the License at
  44654. *
  44655. * http://www.apache.org/licenses/LICENSE-2.0
  44656. *
  44657. * Unless required by applicable law or agreed to in writing,
  44658. * software distributed under the License is distributed on an
  44659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44660. * KIND, either express or implied. See the License for the
  44661. * specific language governing permissions and limitations
  44662. * under the License.
  44663. */
  44664. /**
  44665. * Separate legend and scrollable legend to reduce package size.
  44666. */
  44667. var Group$3 = Group;
  44668. var WH = ['width', 'height'];
  44669. var XY = ['x', 'y'];
  44670. var ScrollableLegendView = LegendView.extend({
  44671. type: 'legend.scroll',
  44672. newlineDisabled: true,
  44673. init: function () {
  44674. ScrollableLegendView.superCall(this, 'init');
  44675. /**
  44676. * @private
  44677. * @type {number} For `scroll`.
  44678. */
  44679. this._currentIndex = 0;
  44680. /**
  44681. * @private
  44682. * @type {module:zrender/container/Group}
  44683. */
  44684. this.group.add(this._containerGroup = new Group$3());
  44685. this._containerGroup.add(this.getContentGroup());
  44686. /**
  44687. * @private
  44688. * @type {module:zrender/container/Group}
  44689. */
  44690. this.group.add(this._controllerGroup = new Group$3());
  44691. /**
  44692. *
  44693. * @private
  44694. */
  44695. this._showController;
  44696. },
  44697. /**
  44698. * @override
  44699. */
  44700. resetInner: function () {
  44701. ScrollableLegendView.superCall(this, 'resetInner');
  44702. this._controllerGroup.removeAll();
  44703. this._containerGroup.removeClipPath();
  44704. this._containerGroup.__rectSize = null;
  44705. },
  44706. /**
  44707. * @override
  44708. */
  44709. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  44710. var me = this;
  44711. // Render content items.
  44712. ScrollableLegendView.superCall(this, 'renderInner', itemAlign,
  44713. legendModel, ecModel, api, selector, orient, selectorPosition);
  44714. var controllerGroup = this._controllerGroup;
  44715. // FIXME: support be 'auto' adapt to size number text length,
  44716. // e.g., '3/12345' should not overlap with the control arrow button.
  44717. var pageIconSize = legendModel.get('pageIconSize', true);
  44718. if (!isArray(pageIconSize)) {
  44719. pageIconSize = [pageIconSize, pageIconSize];
  44720. }
  44721. createPageButton('pagePrev', 0);
  44722. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  44723. controllerGroup.add(new Text({
  44724. name: 'pageText',
  44725. style: {
  44726. textFill: pageTextStyleModel.getTextColor(),
  44727. font: pageTextStyleModel.getFont(),
  44728. textVerticalAlign: 'middle',
  44729. textAlign: 'center'
  44730. },
  44731. silent: true
  44732. }));
  44733. createPageButton('pageNext', 1);
  44734. function createPageButton(name, iconIdx) {
  44735. var pageDataIndexName = name + 'DataIndex';
  44736. var icon = createIcon(
  44737. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  44738. {
  44739. // Buttons will be created in each render, so we do not need
  44740. // to worry about avoiding using legendModel kept in scope.
  44741. onclick: bind(
  44742. me._pageGo, me, pageDataIndexName, legendModel, api
  44743. )
  44744. },
  44745. {
  44746. x: -pageIconSize[0] / 2,
  44747. y: -pageIconSize[1] / 2,
  44748. width: pageIconSize[0],
  44749. height: pageIconSize[1]
  44750. }
  44751. );
  44752. icon.name = name;
  44753. controllerGroup.add(icon);
  44754. }
  44755. },
  44756. /**
  44757. * @override
  44758. */
  44759. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  44760. var selectorGroup = this.getSelectorGroup();
  44761. var orientIdx = legendModel.getOrient().index;
  44762. var wh = WH[orientIdx];
  44763. var xy = XY[orientIdx];
  44764. var hw = WH[1 - orientIdx];
  44765. var yx = XY[1 - orientIdx];
  44766. selector && box(
  44767. // Buttons in selectorGroup always layout horizontally
  44768. 'horizontal',
  44769. selectorGroup,
  44770. legendModel.get('selectorItemGap', true)
  44771. );
  44772. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  44773. var selectorRect = selectorGroup.getBoundingRect();
  44774. var selectorPos = [-selectorRect.x, -selectorRect.y];
  44775. var processMaxSize = clone(maxSize);
  44776. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  44777. var mainRect = this._layoutContentAndController(legendModel, isFirstRender,
  44778. processMaxSize, orientIdx, wh, hw, yx
  44779. );
  44780. if (selector) {
  44781. if (selectorPosition === 'end') {
  44782. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  44783. }
  44784. else {
  44785. var offset = selectorRect[wh] + selectorButtonGap;
  44786. selectorPos[orientIdx] -= offset;
  44787. mainRect[xy] -= offset;
  44788. }
  44789. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  44790. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  44791. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  44792. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  44793. selectorGroup.attr('position', selectorPos);
  44794. }
  44795. return mainRect;
  44796. },
  44797. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  44798. var contentGroup = this.getContentGroup();
  44799. var containerGroup = this._containerGroup;
  44800. var controllerGroup = this._controllerGroup;
  44801. // Place items in contentGroup.
  44802. box(
  44803. legendModel.get('orient'),
  44804. contentGroup,
  44805. legendModel.get('itemGap'),
  44806. !orientIdx ? null : maxSize.width,
  44807. orientIdx ? null : maxSize.height
  44808. );
  44809. box(
  44810. // Buttons in controller are layout always horizontally.
  44811. 'horizontal',
  44812. controllerGroup,
  44813. legendModel.get('pageButtonItemGap', true)
  44814. );
  44815. var contentRect = contentGroup.getBoundingRect();
  44816. var controllerRect = controllerGroup.getBoundingRect();
  44817. var showController = this._showController = contentRect[wh] > maxSize[wh];
  44818. var contentPos = [-contentRect.x, -contentRect.y];
  44819. // Remain contentPos when scroll animation perfroming.
  44820. // If first rendering, `contentGroup.position` is [0, 0], which
  44821. // does not make sense and may cause unexepcted animation if adopted.
  44822. if (!isFirstRender) {
  44823. contentPos[orientIdx] = contentGroup.position[orientIdx];
  44824. }
  44825. // Layout container group based on 0.
  44826. var containerPos = [0, 0];
  44827. var controllerPos = [-controllerRect.x, -controllerRect.y];
  44828. var pageButtonGap = retrieve2(
  44829. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  44830. );
  44831. // Place containerGroup and controllerGroup and contentGroup.
  44832. if (showController) {
  44833. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  44834. // controller is on the right / bottom.
  44835. if (pageButtonPosition === 'end') {
  44836. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  44837. }
  44838. // controller is on the left / top.
  44839. else {
  44840. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  44841. }
  44842. }
  44843. // Always align controller to content as 'middle'.
  44844. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  44845. contentGroup.attr('position', contentPos);
  44846. containerGroup.attr('position', containerPos);
  44847. controllerGroup.attr('position', controllerPos);
  44848. // Calculate `mainRect` and set `clipPath`.
  44849. // mainRect should not be calculated by `this.group.getBoundingRect()`
  44850. // for sake of the overflow.
  44851. var mainRect = {x: 0, y: 0};
  44852. // Consider content may be overflow (should be clipped).
  44853. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  44854. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  44855. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  44856. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  44857. containerGroup.__rectSize = maxSize[wh];
  44858. if (showController) {
  44859. var clipShape = {x: 0, y: 0};
  44860. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  44861. clipShape[hw] = mainRect[hw];
  44862. containerGroup.setClipPath(new Rect({shape: clipShape}));
  44863. // Consider content may be larger than container, container rect
  44864. // can not be obtained from `containerGroup.getBoundingRect()`.
  44865. containerGroup.__rectSize = clipShape[wh];
  44866. }
  44867. else {
  44868. // Do not remove or ignore controller. Keep them set as placeholders.
  44869. controllerGroup.eachChild(function (child) {
  44870. child.attr({invisible: true, silent: true});
  44871. });
  44872. }
  44873. // Content translate animation.
  44874. var pageInfo = this._getPageInfo(legendModel);
  44875. pageInfo.pageIndex != null && updateProps(
  44876. contentGroup,
  44877. {position: pageInfo.contentPosition},
  44878. // When switch from "show controller" to "not show controller", view should be
  44879. // updated immediately without animation, otherwise causes weird effect.
  44880. showController ? legendModel : false
  44881. );
  44882. this._updatePageInfoView(legendModel, pageInfo);
  44883. return mainRect;
  44884. },
  44885. _pageGo: function (to, legendModel, api) {
  44886. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  44887. scrollDataIndex != null && api.dispatchAction({
  44888. type: 'legendScroll',
  44889. scrollDataIndex: scrollDataIndex,
  44890. legendId: legendModel.id
  44891. });
  44892. },
  44893. _updatePageInfoView: function (legendModel, pageInfo) {
  44894. var controllerGroup = this._controllerGroup;
  44895. each$1(['pagePrev', 'pageNext'], function (name) {
  44896. var canJump = pageInfo[name + 'DataIndex'] != null;
  44897. var icon = controllerGroup.childOfName(name);
  44898. if (icon) {
  44899. icon.setStyle(
  44900. 'fill',
  44901. canJump
  44902. ? legendModel.get('pageIconColor', true)
  44903. : legendModel.get('pageIconInactiveColor', true)
  44904. );
  44905. icon.cursor = canJump ? 'pointer' : 'default';
  44906. }
  44907. });
  44908. var pageText = controllerGroup.childOfName('pageText');
  44909. var pageFormatter = legendModel.get('pageFormatter');
  44910. var pageIndex = pageInfo.pageIndex;
  44911. var current = pageIndex != null ? pageIndex + 1 : 0;
  44912. var total = pageInfo.pageCount;
  44913. pageText && pageFormatter && pageText.setStyle(
  44914. 'text',
  44915. isString(pageFormatter)
  44916. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  44917. : pageFormatter({current: current, total: total})
  44918. );
  44919. },
  44920. /**
  44921. * @param {module:echarts/model/Model} legendModel
  44922. * @return {Object} {
  44923. * contentPosition: Array.<number>, null when data item not found.
  44924. * pageIndex: number, null when data item not found.
  44925. * pageCount: number, always be a number, can be 0.
  44926. * pagePrevDataIndex: number, null when no previous page.
  44927. * pageNextDataIndex: number, null when no next page.
  44928. * }
  44929. */
  44930. _getPageInfo: function (legendModel) {
  44931. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  44932. var contentGroup = this.getContentGroup();
  44933. var containerRectSize = this._containerGroup.__rectSize;
  44934. var orientIdx = legendModel.getOrient().index;
  44935. var wh = WH[orientIdx];
  44936. var xy = XY[orientIdx];
  44937. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  44938. var children = contentGroup.children();
  44939. var targetItem = children[targetItemIndex];
  44940. var itemCount = children.length;
  44941. var pCount = !itemCount ? 0 : 1;
  44942. var result = {
  44943. contentPosition: contentGroup.position.slice(),
  44944. pageCount: pCount,
  44945. pageIndex: pCount - 1,
  44946. pagePrevDataIndex: null,
  44947. pageNextDataIndex: null
  44948. };
  44949. if (!targetItem) {
  44950. return result;
  44951. }
  44952. var targetItemInfo = getItemInfo(targetItem);
  44953. result.contentPosition[orientIdx] = -targetItemInfo.s;
  44954. // Strategy:
  44955. // (1) Always align based on the left/top most item.
  44956. // (2) It is user-friendly that the last item shown in the
  44957. // current window is shown at the begining of next window.
  44958. // Otherwise if half of the last item is cut by the window,
  44959. // it will have no chance to display entirely.
  44960. // (3) Consider that item size probably be different, we
  44961. // have calculate pageIndex by size rather than item index,
  44962. // and we can not get page index directly by division.
  44963. // (4) The window is to narrow to contain more than
  44964. // one item, we should make sure that the page can be fliped.
  44965. for (var i = targetItemIndex + 1,
  44966. winStartItemInfo = targetItemInfo,
  44967. winEndItemInfo = targetItemInfo,
  44968. currItemInfo = null;
  44969. i <= itemCount;
  44970. ++i
  44971. ) {
  44972. currItemInfo = getItemInfo(children[i]);
  44973. if (
  44974. // Half of the last item is out of the window.
  44975. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  44976. // If the current item does not intersect with the window, the new page
  44977. // can be started at the current item or the last item.
  44978. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  44979. ) {
  44980. if (winEndItemInfo.i > winStartItemInfo.i) {
  44981. winStartItemInfo = winEndItemInfo;
  44982. }
  44983. else { // e.g., when page size is smaller than item size.
  44984. winStartItemInfo = currItemInfo;
  44985. }
  44986. if (winStartItemInfo) {
  44987. if (result.pageNextDataIndex == null) {
  44988. result.pageNextDataIndex = winStartItemInfo.i;
  44989. }
  44990. ++result.pageCount;
  44991. }
  44992. }
  44993. winEndItemInfo = currItemInfo;
  44994. }
  44995. for (var i = targetItemIndex - 1,
  44996. winStartItemInfo = targetItemInfo,
  44997. winEndItemInfo = targetItemInfo,
  44998. currItemInfo = null;
  44999. i >= -1;
  45000. --i
  45001. ) {
  45002. currItemInfo = getItemInfo(children[i]);
  45003. if (
  45004. // If the the end item does not intersect with the window started
  45005. // from the current item, a page can be settled.
  45006. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  45007. // e.g., when page size is smaller than item size.
  45008. && winStartItemInfo.i < winEndItemInfo.i
  45009. ) {
  45010. winEndItemInfo = winStartItemInfo;
  45011. if (result.pagePrevDataIndex == null) {
  45012. result.pagePrevDataIndex = winStartItemInfo.i;
  45013. }
  45014. ++result.pageCount;
  45015. ++result.pageIndex;
  45016. }
  45017. winStartItemInfo = currItemInfo;
  45018. }
  45019. return result;
  45020. function getItemInfo(el) {
  45021. if (el) {
  45022. var itemRect = el.getBoundingRect();
  45023. var start = itemRect[xy] + el.position[orientIdx];
  45024. return {
  45025. s: start,
  45026. e: start + itemRect[wh],
  45027. i: el.__legendDataIndex
  45028. };
  45029. }
  45030. }
  45031. function intersect(itemInfo, winStart) {
  45032. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  45033. }
  45034. },
  45035. _findTargetItemIndex: function (targetDataIndex) {
  45036. if (!this._showController) {
  45037. return 0;
  45038. }
  45039. var index;
  45040. var contentGroup = this.getContentGroup();
  45041. var defaultIndex;
  45042. contentGroup.eachChild(function (child, idx) {
  45043. var legendDataIdx = child.__legendDataIndex;
  45044. // FIXME
  45045. // If the given targetDataIndex (from model) is illegal,
  45046. // we use defualtIndex. But the index on the legend model and
  45047. // action payload is still illegal. That case will not be
  45048. // changed until some scenario requires.
  45049. if (defaultIndex == null && legendDataIdx != null) {
  45050. defaultIndex = idx;
  45051. }
  45052. if (legendDataIdx === targetDataIndex) {
  45053. index = idx;
  45054. }
  45055. });
  45056. return index != null ? index : defaultIndex;
  45057. }
  45058. });
  45059. /*
  45060. * Licensed to the Apache Software Foundation (ASF) under one
  45061. * or more contributor license agreements. See the NOTICE file
  45062. * distributed with this work for additional information
  45063. * regarding copyright ownership. The ASF licenses this file
  45064. * to you under the Apache License, Version 2.0 (the
  45065. * "License"); you may not use this file except in compliance
  45066. * with the License. You may obtain a copy of the License at
  45067. *
  45068. * http://www.apache.org/licenses/LICENSE-2.0
  45069. *
  45070. * Unless required by applicable law or agreed to in writing,
  45071. * software distributed under the License is distributed on an
  45072. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45073. * KIND, either express or implied. See the License for the
  45074. * specific language governing permissions and limitations
  45075. * under the License.
  45076. */
  45077. /**
  45078. * @event legendScroll
  45079. * @type {Object}
  45080. * @property {string} type 'legendScroll'
  45081. * @property {string} scrollDataIndex
  45082. */
  45083. registerAction(
  45084. 'legendScroll', 'legendscroll',
  45085. function (payload, ecModel) {
  45086. var scrollDataIndex = payload.scrollDataIndex;
  45087. scrollDataIndex != null && ecModel.eachComponent(
  45088. {mainType: 'legend', subType: 'scroll', query: payload},
  45089. function (legendModel) {
  45090. legendModel.setScrollDataIndex(scrollDataIndex);
  45091. }
  45092. );
  45093. }
  45094. );
  45095. /*
  45096. * Licensed to the Apache Software Foundation (ASF) under one
  45097. * or more contributor license agreements. See the NOTICE file
  45098. * distributed with this work for additional information
  45099. * regarding copyright ownership. The ASF licenses this file
  45100. * to you under the Apache License, Version 2.0 (the
  45101. * "License"); you may not use this file except in compliance
  45102. * with the License. You may obtain a copy of the License at
  45103. *
  45104. * http://www.apache.org/licenses/LICENSE-2.0
  45105. *
  45106. * Unless required by applicable law or agreed to in writing,
  45107. * software distributed under the License is distributed on an
  45108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45109. * KIND, either express or implied. See the License for the
  45110. * specific language governing permissions and limitations
  45111. * under the License.
  45112. */
  45113. /**
  45114. * Legend component entry file8
  45115. */
  45116. /*
  45117. * Licensed to the Apache Software Foundation (ASF) under one
  45118. * or more contributor license agreements. See the NOTICE file
  45119. * distributed with this work for additional information
  45120. * regarding copyright ownership. The ASF licenses this file
  45121. * to you under the Apache License, Version 2.0 (the
  45122. * "License"); you may not use this file except in compliance
  45123. * with the License. You may obtain a copy of the License at
  45124. *
  45125. * http://www.apache.org/licenses/LICENSE-2.0
  45126. *
  45127. * Unless required by applicable law or agreed to in writing,
  45128. * software distributed under the License is distributed on an
  45129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45130. * KIND, either express or implied. See the License for the
  45131. * specific language governing permissions and limitations
  45132. * under the License.
  45133. */
  45134. /*
  45135. * Licensed to the Apache Software Foundation (ASF) under one
  45136. * or more contributor license agreements. See the NOTICE file
  45137. * distributed with this work for additional information
  45138. * regarding copyright ownership. The ASF licenses this file
  45139. * to you under the Apache License, Version 2.0 (the
  45140. * "License"); you may not use this file except in compliance
  45141. * with the License. You may obtain a copy of the License at
  45142. *
  45143. * http://www.apache.org/licenses/LICENSE-2.0
  45144. *
  45145. * Unless required by applicable law or agreed to in writing,
  45146. * software distributed under the License is distributed on an
  45147. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45148. * KIND, either express or implied. See the License for the
  45149. * specific language governing permissions and limitations
  45150. * under the License.
  45151. */
  45152. // Model
  45153. extendComponentModel({
  45154. type: 'title',
  45155. layoutMode: {type: 'box', ignoreSize: true},
  45156. defaultOption: {
  45157. // 一级层叠
  45158. zlevel: 0,
  45159. // 二级层叠
  45160. z: 6,
  45161. show: true,
  45162. text: '',
  45163. // 超链接跳转
  45164. // link: null,
  45165. // 仅支持self | blank
  45166. target: 'blank',
  45167. subtext: '',
  45168. // 超链接跳转
  45169. // sublink: null,
  45170. // 仅支持self | blank
  45171. subtarget: 'blank',
  45172. // 'center' ¦ 'left' ¦ 'right'
  45173. // ¦ {number}(x坐标,单位px)
  45174. left: 0,
  45175. // 'top' ¦ 'bottom' ¦ 'center'
  45176. // ¦ {number}(y坐标,单位px)
  45177. top: 0,
  45178. // 水平对齐
  45179. // 'auto' | 'left' | 'right' | 'center'
  45180. // 默认根据 left 的位置判断是左对齐还是右对齐
  45181. // textAlign: null
  45182. //
  45183. // 垂直对齐
  45184. // 'auto' | 'top' | 'bottom' | 'middle'
  45185. // 默认根据 top 位置判断是上对齐还是下对齐
  45186. // textVerticalAlign: null
  45187. // textBaseline: null // The same as textVerticalAlign.
  45188. backgroundColor: 'rgba(0,0,0,0)',
  45189. // 标题边框颜色
  45190. borderColor: '#ccc',
  45191. // 标题边框线宽,单位px,默认为0(无边框)
  45192. borderWidth: 0,
  45193. // 标题内边距,单位px,默认各方向内边距为5,
  45194. // 接受数组分别设定上右下左边距,同css
  45195. padding: 5,
  45196. // 主副标题纵向间隔,单位px,默认为10,
  45197. itemGap: 10,
  45198. textStyle: {
  45199. fontSize: 18,
  45200. fontWeight: 'bolder',
  45201. color: '#333'
  45202. },
  45203. subtextStyle: {
  45204. color: '#aaa'
  45205. }
  45206. }
  45207. });
  45208. // View
  45209. extendComponentView({
  45210. type: 'title',
  45211. render: function (titleModel, ecModel, api) {
  45212. this.group.removeAll();
  45213. if (!titleModel.get('show')) {
  45214. return;
  45215. }
  45216. var group = this.group;
  45217. var textStyleModel = titleModel.getModel('textStyle');
  45218. var subtextStyleModel = titleModel.getModel('subtextStyle');
  45219. var textAlign = titleModel.get('textAlign');
  45220. var textVerticalAlign = retrieve2(
  45221. titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')
  45222. );
  45223. var textEl = new Text({
  45224. style: setTextStyle({}, textStyleModel, {
  45225. text: titleModel.get('text'),
  45226. textFill: textStyleModel.getTextColor()
  45227. }, {disableBox: true}),
  45228. z2: 10
  45229. });
  45230. var textRect = textEl.getBoundingRect();
  45231. var subText = titleModel.get('subtext');
  45232. var subTextEl = new Text({
  45233. style: setTextStyle({}, subtextStyleModel, {
  45234. text: subText,
  45235. textFill: subtextStyleModel.getTextColor(),
  45236. y: textRect.height + titleModel.get('itemGap'),
  45237. textVerticalAlign: 'top'
  45238. }, {disableBox: true}),
  45239. z2: 10
  45240. });
  45241. var link = titleModel.get('link');
  45242. var sublink = titleModel.get('sublink');
  45243. var triggerEvent = titleModel.get('triggerEvent', true);
  45244. textEl.silent = !link && !triggerEvent;
  45245. subTextEl.silent = !sublink && !triggerEvent;
  45246. if (link) {
  45247. textEl.on('click', function () {
  45248. windowOpen(link, '_' + titleModel.get('target'));
  45249. });
  45250. }
  45251. if (sublink) {
  45252. subTextEl.on('click', function () {
  45253. windowOpen(link, '_' + titleModel.get('subtarget'));
  45254. });
  45255. }
  45256. textEl.eventData = subTextEl.eventData = triggerEvent
  45257. ? {
  45258. componentType: 'title',
  45259. componentIndex: titleModel.componentIndex
  45260. }
  45261. : null;
  45262. group.add(textEl);
  45263. subText && group.add(subTextEl);
  45264. // If no subText, but add subTextEl, there will be an empty line.
  45265. var groupRect = group.getBoundingRect();
  45266. var layoutOption = titleModel.getBoxLayoutParams();
  45267. layoutOption.width = groupRect.width;
  45268. layoutOption.height = groupRect.height;
  45269. var layoutRect = getLayoutRect(
  45270. layoutOption, {
  45271. width: api.getWidth(),
  45272. height: api.getHeight()
  45273. }, titleModel.get('padding')
  45274. );
  45275. // Adjust text align based on position
  45276. if (!textAlign) {
  45277. // Align left if title is on the left. center and right is same
  45278. textAlign = titleModel.get('left') || titleModel.get('right');
  45279. if (textAlign === 'middle') {
  45280. textAlign = 'center';
  45281. }
  45282. // Adjust layout by text align
  45283. if (textAlign === 'right') {
  45284. layoutRect.x += layoutRect.width;
  45285. }
  45286. else if (textAlign === 'center') {
  45287. layoutRect.x += layoutRect.width / 2;
  45288. }
  45289. }
  45290. if (!textVerticalAlign) {
  45291. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  45292. if (textVerticalAlign === 'center') {
  45293. textVerticalAlign = 'middle';
  45294. }
  45295. if (textVerticalAlign === 'bottom') {
  45296. layoutRect.y += layoutRect.height;
  45297. }
  45298. else if (textVerticalAlign === 'middle') {
  45299. layoutRect.y += layoutRect.height / 2;
  45300. }
  45301. textVerticalAlign = textVerticalAlign || 'top';
  45302. }
  45303. group.attr('position', [layoutRect.x, layoutRect.y]);
  45304. var alignStyle = {
  45305. textAlign: textAlign,
  45306. textVerticalAlign: textVerticalAlign
  45307. };
  45308. textEl.setStyle(alignStyle);
  45309. subTextEl.setStyle(alignStyle);
  45310. // Render background
  45311. // Get groupRect again because textAlign has been changed
  45312. groupRect = group.getBoundingRect();
  45313. var padding = layoutRect.margin;
  45314. var style = titleModel.getItemStyle(['color', 'opacity']);
  45315. style.fill = titleModel.get('backgroundColor');
  45316. var rect = new Rect({
  45317. shape: {
  45318. x: groupRect.x - padding[3],
  45319. y: groupRect.y - padding[0],
  45320. width: groupRect.width + padding[1] + padding[3],
  45321. height: groupRect.height + padding[0] + padding[2],
  45322. r: titleModel.get('borderRadius')
  45323. },
  45324. style: style,
  45325. subPixelOptimize: true,
  45326. silent: true
  45327. });
  45328. group.add(rect);
  45329. }
  45330. });
  45331. /*
  45332. * Licensed to the Apache Software Foundation (ASF) under one
  45333. * or more contributor license agreements. See the NOTICE file
  45334. * distributed with this work for additional information
  45335. * regarding copyright ownership. The ASF licenses this file
  45336. * to you under the Apache License, Version 2.0 (the
  45337. * "License"); you may not use this file except in compliance
  45338. * with the License. You may obtain a copy of the License at
  45339. *
  45340. * http://www.apache.org/licenses/LICENSE-2.0
  45341. *
  45342. * Unless required by applicable law or agreed to in writing,
  45343. * software distributed under the License is distributed on an
  45344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45345. * KIND, either express or implied. See the License for the
  45346. * specific language governing permissions and limitations
  45347. * under the License.
  45348. */
  45349. var addCommas$1 = addCommas;
  45350. var encodeHTML$1 = encodeHTML;
  45351. function fillLabel(opt) {
  45352. defaultEmphasis(opt, 'label', ['show']);
  45353. }
  45354. var MarkerModel = extendComponentModel({
  45355. type: 'marker',
  45356. dependencies: ['series', 'grid', 'polar', 'geo'],
  45357. /**
  45358. * @overrite
  45359. */
  45360. init: function (option, parentModel, ecModel) {
  45361. if (__DEV__) {
  45362. if (this.type === 'marker') {
  45363. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  45364. }
  45365. }
  45366. this.mergeDefaultAndTheme(option, ecModel);
  45367. this._mergeOption(option, ecModel, false, true);
  45368. },
  45369. /**
  45370. * @return {boolean}
  45371. */
  45372. isAnimationEnabled: function () {
  45373. if (env$1.node) {
  45374. return false;
  45375. }
  45376. var hostSeries = this.__hostSeries;
  45377. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  45378. },
  45379. /**
  45380. * @overrite
  45381. */
  45382. mergeOption: function (newOpt, ecModel) {
  45383. this._mergeOption(newOpt, ecModel, false, false);
  45384. },
  45385. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  45386. var MarkerModel = this.constructor;
  45387. var modelPropName = this.mainType + 'Model';
  45388. if (!createdBySelf) {
  45389. ecModel.eachSeries(function (seriesModel) {
  45390. var markerOpt = seriesModel.get(this.mainType, true);
  45391. var markerModel = seriesModel[modelPropName];
  45392. if (!markerOpt || !markerOpt.data) {
  45393. seriesModel[modelPropName] = null;
  45394. return;
  45395. }
  45396. if (!markerModel) {
  45397. if (isInit) {
  45398. // Default label emphasis `position` and `show`
  45399. fillLabel(markerOpt);
  45400. }
  45401. each$1(markerOpt.data, function (item) {
  45402. // FIXME Overwrite fillLabel method ?
  45403. if (item instanceof Array) {
  45404. fillLabel(item[0]);
  45405. fillLabel(item[1]);
  45406. }
  45407. else {
  45408. fillLabel(item);
  45409. }
  45410. });
  45411. markerModel = new MarkerModel(
  45412. markerOpt, this, ecModel
  45413. );
  45414. extend(markerModel, {
  45415. mainType: this.mainType,
  45416. // Use the same series index and name
  45417. seriesIndex: seriesModel.seriesIndex,
  45418. name: seriesModel.name,
  45419. createdBySelf: true
  45420. });
  45421. markerModel.__hostSeries = seriesModel;
  45422. }
  45423. else {
  45424. markerModel._mergeOption(markerOpt, ecModel, true);
  45425. }
  45426. seriesModel[modelPropName] = markerModel;
  45427. }, this);
  45428. }
  45429. },
  45430. formatTooltip: function (dataIndex) {
  45431. var data = this.getData();
  45432. var value = this.getRawValue(dataIndex);
  45433. var formattedValue = isArray(value)
  45434. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  45435. var name = data.getName(dataIndex);
  45436. var html = encodeHTML$1(this.name);
  45437. if (value != null || name) {
  45438. html += '<br />';
  45439. }
  45440. if (name) {
  45441. html += encodeHTML$1(name);
  45442. if (value != null) {
  45443. html += ' : ';
  45444. }
  45445. }
  45446. if (value != null) {
  45447. html += encodeHTML$1(formattedValue);
  45448. }
  45449. return html;
  45450. },
  45451. getData: function () {
  45452. return this._data;
  45453. },
  45454. setData: function (data) {
  45455. this._data = data;
  45456. }
  45457. });
  45458. mixin(MarkerModel, dataFormatMixin);
  45459. /*
  45460. * Licensed to the Apache Software Foundation (ASF) under one
  45461. * or more contributor license agreements. See the NOTICE file
  45462. * distributed with this work for additional information
  45463. * regarding copyright ownership. The ASF licenses this file
  45464. * to you under the Apache License, Version 2.0 (the
  45465. * "License"); you may not use this file except in compliance
  45466. * with the License. You may obtain a copy of the License at
  45467. *
  45468. * http://www.apache.org/licenses/LICENSE-2.0
  45469. *
  45470. * Unless required by applicable law or agreed to in writing,
  45471. * software distributed under the License is distributed on an
  45472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45473. * KIND, either express or implied. See the License for the
  45474. * specific language governing permissions and limitations
  45475. * under the License.
  45476. */
  45477. MarkerModel.extend({
  45478. type: 'markPoint',
  45479. defaultOption: {
  45480. zlevel: 0,
  45481. z: 5,
  45482. symbol: 'pin',
  45483. symbolSize: 50,
  45484. //symbolRotate: 0,
  45485. //symbolOffset: [0, 0]
  45486. tooltip: {
  45487. trigger: 'item'
  45488. },
  45489. label: {
  45490. show: true,
  45491. position: 'inside'
  45492. },
  45493. itemStyle: {
  45494. borderWidth: 2
  45495. },
  45496. emphasis: {
  45497. label: {
  45498. show: true
  45499. }
  45500. }
  45501. }
  45502. });
  45503. /*
  45504. * Licensed to the Apache Software Foundation (ASF) under one
  45505. * or more contributor license agreements. See the NOTICE file
  45506. * distributed with this work for additional information
  45507. * regarding copyright ownership. The ASF licenses this file
  45508. * to you under the Apache License, Version 2.0 (the
  45509. * "License"); you may not use this file except in compliance
  45510. * with the License. You may obtain a copy of the License at
  45511. *
  45512. * http://www.apache.org/licenses/LICENSE-2.0
  45513. *
  45514. * Unless required by applicable law or agreed to in writing,
  45515. * software distributed under the License is distributed on an
  45516. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45517. * KIND, either express or implied. See the License for the
  45518. * specific language governing permissions and limitations
  45519. * under the License.
  45520. */
  45521. var indexOf$1 = indexOf;
  45522. function hasXOrY(item) {
  45523. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  45524. }
  45525. function hasXAndY(item) {
  45526. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  45527. }
  45528. // Make it simple, do not visit all stacked value to count precision.
  45529. // function getPrecision(data, valueAxisDim, dataIndex) {
  45530. // var precision = -1;
  45531. // var stackedDim = data.mapDimension(valueAxisDim);
  45532. // do {
  45533. // precision = Math.max(
  45534. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  45535. // precision
  45536. // );
  45537. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  45538. // if (stackedOnSeries) {
  45539. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  45540. // data = stackedOnSeries.getData();
  45541. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  45542. // stackedDim = data.getCalculationInfo('stackedDimension');
  45543. // }
  45544. // else {
  45545. // data = null;
  45546. // }
  45547. // } while (data);
  45548. // return precision;
  45549. // }
  45550. function markerTypeCalculatorWithExtent(
  45551. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  45552. ) {
  45553. var coordArr = [];
  45554. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  45555. var calcDataDim = stacked
  45556. ? data.getCalculationInfo('stackResultDimension')
  45557. : targetDataDim;
  45558. var value = numCalculate(data, calcDataDim, mlType);
  45559. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  45560. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  45561. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  45562. var coordArrValue = data.get(targetDataDim, dataIndex);
  45563. // Make it simple, do not visit all stacked value to count precision.
  45564. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  45565. precision = Math.min(precision, 20);
  45566. if (precision >= 0) {
  45567. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  45568. }
  45569. return [coordArr, coordArrValue];
  45570. }
  45571. var curry$4 = curry;
  45572. // TODO Specified percent
  45573. var markerTypeCalculator = {
  45574. /**
  45575. * @method
  45576. * @param {module:echarts/data/List} data
  45577. * @param {string} baseAxisDim
  45578. * @param {string} valueAxisDim
  45579. */
  45580. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  45581. /**
  45582. * @method
  45583. * @param {module:echarts/data/List} data
  45584. * @param {string} baseAxisDim
  45585. * @param {string} valueAxisDim
  45586. */
  45587. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  45588. /**
  45589. * @method
  45590. * @param {module:echarts/data/List} data
  45591. * @param {string} baseAxisDim
  45592. * @param {string} valueAxisDim
  45593. */
  45594. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  45595. };
  45596. /**
  45597. * Transform markPoint data item to format used in List by do the following
  45598. * 1. Calculate statistic like `max`, `min`, `average`
  45599. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  45600. * @param {module:echarts/model/Series} seriesModel
  45601. * @param {module:echarts/coord/*} [coordSys]
  45602. * @param {Object} item
  45603. * @return {Object}
  45604. */
  45605. function dataTransform(seriesModel, item) {
  45606. var data = seriesModel.getData();
  45607. var coordSys = seriesModel.coordinateSystem;
  45608. // 1. If not specify the position with pixel directly
  45609. // 2. If `coord` is not a data array. Which uses `xAxis`,
  45610. // `yAxis` to specify the coord on each dimension
  45611. // parseFloat first because item.x and item.y can be percent string like '20%'
  45612. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  45613. var dims = coordSys.dimensions;
  45614. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  45615. // Clone the option
  45616. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  45617. item = clone(item);
  45618. if (item.type
  45619. && markerTypeCalculator[item.type]
  45620. && axisInfo.baseAxis && axisInfo.valueAxis
  45621. ) {
  45622. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  45623. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  45624. var coordInfo = markerTypeCalculator[item.type](
  45625. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  45626. otherCoordIndex, targetCoordIndex
  45627. );
  45628. item.coord = coordInfo[0];
  45629. // Force to use the value of calculated value.
  45630. // let item use the value without stack.
  45631. item.value = coordInfo[1];
  45632. }
  45633. else {
  45634. // FIXME Only has one of xAxis and yAxis.
  45635. var coord = [
  45636. item.xAxis != null ? item.xAxis : item.radiusAxis,
  45637. item.yAxis != null ? item.yAxis : item.angleAxis
  45638. ];
  45639. // Each coord support max, min, average
  45640. for (var i = 0; i < 2; i++) {
  45641. if (markerTypeCalculator[coord[i]]) {
  45642. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  45643. }
  45644. }
  45645. item.coord = coord;
  45646. }
  45647. }
  45648. return item;
  45649. }
  45650. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  45651. var ret = {};
  45652. if (item.valueIndex != null || item.valueDim != null) {
  45653. ret.valueDataDim = item.valueIndex != null
  45654. ? data.getDimension(item.valueIndex) : item.valueDim;
  45655. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  45656. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  45657. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45658. }
  45659. else {
  45660. ret.baseAxis = seriesModel.getBaseAxis();
  45661. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  45662. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  45663. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  45664. }
  45665. return ret;
  45666. }
  45667. function dataDimToCoordDim(seriesModel, dataDim) {
  45668. var data = seriesModel.getData();
  45669. var dimensions = data.dimensions;
  45670. dataDim = data.getDimension(dataDim);
  45671. for (var i = 0; i < dimensions.length; i++) {
  45672. var dimItem = data.getDimensionInfo(dimensions[i]);
  45673. if (dimItem.name === dataDim) {
  45674. return dimItem.coordDim;
  45675. }
  45676. }
  45677. }
  45678. /**
  45679. * Filter data which is out of coordinateSystem range
  45680. * [dataFilter description]
  45681. * @param {module:echarts/coord/*} [coordSys]
  45682. * @param {Object} item
  45683. * @return {boolean}
  45684. */
  45685. function dataFilter$1(coordSys, item) {
  45686. // Alwalys return true if there is no coordSys
  45687. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  45688. ? coordSys.containData(item.coord) : true;
  45689. }
  45690. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  45691. // x, y, radius, angle
  45692. if (dimIndex < 2) {
  45693. return item.coord && item.coord[dimIndex];
  45694. }
  45695. return item.value;
  45696. }
  45697. function numCalculate(data, valueDataDim, type) {
  45698. if (type === 'average') {
  45699. var sum = 0;
  45700. var count = 0;
  45701. data.each(valueDataDim, function (val, idx) {
  45702. if (!isNaN(val)) {
  45703. sum += val;
  45704. count++;
  45705. }
  45706. });
  45707. return sum / count;
  45708. }
  45709. else if (type === 'median') {
  45710. return data.getMedian(valueDataDim);
  45711. }
  45712. else {
  45713. // max & min
  45714. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  45715. }
  45716. }
  45717. /*
  45718. * Licensed to the Apache Software Foundation (ASF) under one
  45719. * or more contributor license agreements. See the NOTICE file
  45720. * distributed with this work for additional information
  45721. * regarding copyright ownership. The ASF licenses this file
  45722. * to you under the Apache License, Version 2.0 (the
  45723. * "License"); you may not use this file except in compliance
  45724. * with the License. You may obtain a copy of the License at
  45725. *
  45726. * http://www.apache.org/licenses/LICENSE-2.0
  45727. *
  45728. * Unless required by applicable law or agreed to in writing,
  45729. * software distributed under the License is distributed on an
  45730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45731. * KIND, either express or implied. See the License for the
  45732. * specific language governing permissions and limitations
  45733. * under the License.
  45734. */
  45735. var MarkerView = extendComponentView({
  45736. type: 'marker',
  45737. init: function () {
  45738. /**
  45739. * Markline grouped by series
  45740. * @private
  45741. * @type {module:zrender/core/util.HashMap}
  45742. */
  45743. this.markerGroupMap = createHashMap();
  45744. },
  45745. render: function (markerModel, ecModel, api) {
  45746. var markerGroupMap = this.markerGroupMap;
  45747. markerGroupMap.each(function (item) {
  45748. item.__keep = false;
  45749. });
  45750. var markerModelKey = this.type + 'Model';
  45751. ecModel.eachSeries(function (seriesModel) {
  45752. var markerModel = seriesModel[markerModelKey];
  45753. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  45754. }, this);
  45755. markerGroupMap.each(function (item) {
  45756. !item.__keep && this.group.remove(item.group);
  45757. }, this);
  45758. },
  45759. renderSeries: function () {}
  45760. });
  45761. /*
  45762. * Licensed to the Apache Software Foundation (ASF) under one
  45763. * or more contributor license agreements. See the NOTICE file
  45764. * distributed with this work for additional information
  45765. * regarding copyright ownership. The ASF licenses this file
  45766. * to you under the Apache License, Version 2.0 (the
  45767. * "License"); you may not use this file except in compliance
  45768. * with the License. You may obtain a copy of the License at
  45769. *
  45770. * http://www.apache.org/licenses/LICENSE-2.0
  45771. *
  45772. * Unless required by applicable law or agreed to in writing,
  45773. * software distributed under the License is distributed on an
  45774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45775. * KIND, either express or implied. See the License for the
  45776. * specific language governing permissions and limitations
  45777. * under the License.
  45778. */
  45779. function updateMarkerLayout(mpData, seriesModel, api) {
  45780. var coordSys = seriesModel.coordinateSystem;
  45781. mpData.each(function (idx) {
  45782. var itemModel = mpData.getItemModel(idx);
  45783. var point;
  45784. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  45785. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  45786. if (!isNaN(xPx) && !isNaN(yPx)) {
  45787. point = [xPx, yPx];
  45788. }
  45789. // Chart like bar may have there own marker positioning logic
  45790. else if (seriesModel.getMarkerPosition) {
  45791. // Use the getMarkerPoisition
  45792. point = seriesModel.getMarkerPosition(
  45793. mpData.getValues(mpData.dimensions, idx)
  45794. );
  45795. }
  45796. else if (coordSys) {
  45797. var x = mpData.get(coordSys.dimensions[0], idx);
  45798. var y = mpData.get(coordSys.dimensions[1], idx);
  45799. point = coordSys.dataToPoint([x, y]);
  45800. }
  45801. // Use x, y if has any
  45802. if (!isNaN(xPx)) {
  45803. point[0] = xPx;
  45804. }
  45805. if (!isNaN(yPx)) {
  45806. point[1] = yPx;
  45807. }
  45808. mpData.setItemLayout(idx, point);
  45809. });
  45810. }
  45811. MarkerView.extend({
  45812. type: 'markPoint',
  45813. // updateLayout: function (markPointModel, ecModel, api) {
  45814. // ecModel.eachSeries(function (seriesModel) {
  45815. // var mpModel = seriesModel.markPointModel;
  45816. // if (mpModel) {
  45817. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45818. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45819. // }
  45820. // }, this);
  45821. // },
  45822. updateTransform: function (markPointModel, ecModel, api) {
  45823. ecModel.eachSeries(function (seriesModel) {
  45824. var mpModel = seriesModel.markPointModel;
  45825. if (mpModel) {
  45826. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45827. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  45828. }
  45829. }, this);
  45830. },
  45831. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  45832. var coordSys = seriesModel.coordinateSystem;
  45833. var seriesId = seriesModel.id;
  45834. var seriesData = seriesModel.getData();
  45835. var symbolDrawMap = this.markerGroupMap;
  45836. var symbolDraw = symbolDrawMap.get(seriesId)
  45837. || symbolDrawMap.set(seriesId, new SymbolDraw());
  45838. var mpData = createList$1(coordSys, seriesModel, mpModel);
  45839. // FIXME
  45840. mpModel.setData(mpData);
  45841. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  45842. mpData.each(function (idx) {
  45843. var itemModel = mpData.getItemModel(idx);
  45844. var symbol = itemModel.getShallow('symbol');
  45845. var symbolSize = itemModel.getShallow('symbolSize');
  45846. var isFnSymbol = isFunction$1(symbol);
  45847. var isFnSymbolSize = isFunction$1(symbolSize);
  45848. if (isFnSymbol || isFnSymbolSize) {
  45849. var rawIdx = mpModel.getRawValue(idx);
  45850. var dataParams = mpModel.getDataParams(idx);
  45851. if (isFnSymbol) {
  45852. symbol = symbol(rawIdx, dataParams);
  45853. }
  45854. if (isFnSymbolSize) {
  45855. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  45856. symbolSize = symbolSize(rawIdx, dataParams);
  45857. }
  45858. }
  45859. mpData.setItemVisual(idx, {
  45860. symbol: symbol,
  45861. symbolSize: symbolSize,
  45862. color: itemModel.get('itemStyle.color')
  45863. || seriesData.getVisual('color')
  45864. });
  45865. });
  45866. // TODO Text are wrong
  45867. symbolDraw.updateData(mpData);
  45868. this.group.add(symbolDraw.group);
  45869. // Set host model for tooltip
  45870. // FIXME
  45871. mpData.eachItemGraphicEl(function (el) {
  45872. el.traverse(function (child) {
  45873. child.dataModel = mpModel;
  45874. });
  45875. });
  45876. symbolDraw.__keep = true;
  45877. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  45878. }
  45879. });
  45880. /**
  45881. * @inner
  45882. * @param {module:echarts/coord/*} [coordSys]
  45883. * @param {module:echarts/model/Series} seriesModel
  45884. * @param {module:echarts/model/Model} mpModel
  45885. */
  45886. function createList$1(coordSys, seriesModel, mpModel) {
  45887. var coordDimsInfos;
  45888. if (coordSys) {
  45889. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  45890. var info = seriesModel.getData().getDimensionInfo(
  45891. seriesModel.getData().mapDimension(coordDim)
  45892. ) || {};
  45893. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  45894. return defaults({name: coordDim}, info);
  45895. });
  45896. }
  45897. else {
  45898. coordDimsInfos = [{
  45899. name: 'value',
  45900. type: 'float'
  45901. }];
  45902. }
  45903. var mpData = new List(coordDimsInfos, mpModel);
  45904. var dataOpt = map(mpModel.get('data'), curry(
  45905. dataTransform, seriesModel
  45906. ));
  45907. if (coordSys) {
  45908. dataOpt = filter(
  45909. dataOpt, curry(dataFilter$1, coordSys)
  45910. );
  45911. }
  45912. mpData.initData(dataOpt, null,
  45913. coordSys ? dimValueGetter : function (item) {
  45914. return item.value;
  45915. }
  45916. );
  45917. return mpData;
  45918. }
  45919. /*
  45920. * Licensed to the Apache Software Foundation (ASF) under one
  45921. * or more contributor license agreements. See the NOTICE file
  45922. * distributed with this work for additional information
  45923. * regarding copyright ownership. The ASF licenses this file
  45924. * to you under the Apache License, Version 2.0 (the
  45925. * "License"); you may not use this file except in compliance
  45926. * with the License. You may obtain a copy of the License at
  45927. *
  45928. * http://www.apache.org/licenses/LICENSE-2.0
  45929. *
  45930. * Unless required by applicable law or agreed to in writing,
  45931. * software distributed under the License is distributed on an
  45932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45933. * KIND, either express or implied. See the License for the
  45934. * specific language governing permissions and limitations
  45935. * under the License.
  45936. */
  45937. // HINT Markpoint can't be used too much
  45938. registerPreprocessor(function (opt) {
  45939. // Make sure markPoint component is enabled
  45940. opt.markPoint = opt.markPoint || {};
  45941. });
  45942. /*
  45943. * Licensed to the Apache Software Foundation (ASF) under one
  45944. * or more contributor license agreements. See the NOTICE file
  45945. * distributed with this work for additional information
  45946. * regarding copyright ownership. The ASF licenses this file
  45947. * to you under the Apache License, Version 2.0 (the
  45948. * "License"); you may not use this file except in compliance
  45949. * with the License. You may obtain a copy of the License at
  45950. *
  45951. * http://www.apache.org/licenses/LICENSE-2.0
  45952. *
  45953. * Unless required by applicable law or agreed to in writing,
  45954. * software distributed under the License is distributed on an
  45955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45956. * KIND, either express or implied. See the License for the
  45957. * specific language governing permissions and limitations
  45958. * under the License.
  45959. */
  45960. MarkerModel.extend({
  45961. type: 'markLine',
  45962. defaultOption: {
  45963. zlevel: 0,
  45964. z: 5,
  45965. symbol: ['circle', 'arrow'],
  45966. symbolSize: [8, 16],
  45967. //symbolRotate: 0,
  45968. precision: 2,
  45969. tooltip: {
  45970. trigger: 'item'
  45971. },
  45972. label: {
  45973. show: true,
  45974. position: 'end',
  45975. distance: 5
  45976. },
  45977. lineStyle: {
  45978. type: 'dashed'
  45979. },
  45980. emphasis: {
  45981. label: {
  45982. show: true
  45983. },
  45984. lineStyle: {
  45985. width: 3
  45986. }
  45987. },
  45988. animationEasing: 'linear'
  45989. }
  45990. });
  45991. /*
  45992. * Licensed to the Apache Software Foundation (ASF) under one
  45993. * or more contributor license agreements. See the NOTICE file
  45994. * distributed with this work for additional information
  45995. * regarding copyright ownership. The ASF licenses this file
  45996. * to you under the Apache License, Version 2.0 (the
  45997. * "License"); you may not use this file except in compliance
  45998. * with the License. You may obtain a copy of the License at
  45999. *
  46000. * http://www.apache.org/licenses/LICENSE-2.0
  46001. *
  46002. * Unless required by applicable law or agreed to in writing,
  46003. * software distributed under the License is distributed on an
  46004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46005. * KIND, either express or implied. See the License for the
  46006. * specific language governing permissions and limitations
  46007. * under the License.
  46008. */
  46009. /**
  46010. * Line path for bezier and straight line draw
  46011. */
  46012. var straightLineProto = Line.prototype;
  46013. var bezierCurveProto = BezierCurve.prototype;
  46014. function isLine(shape) {
  46015. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  46016. }
  46017. var LinePath = extendShape({
  46018. type: 'ec-line',
  46019. style: {
  46020. stroke: '#000',
  46021. fill: null
  46022. },
  46023. shape: {
  46024. x1: 0,
  46025. y1: 0,
  46026. x2: 0,
  46027. y2: 0,
  46028. percent: 1,
  46029. cpx1: null,
  46030. cpy1: null
  46031. },
  46032. buildPath: function (ctx, shape) {
  46033. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  46034. },
  46035. _buildPathLine: straightLineProto.buildPath,
  46036. _buildPathCurve: bezierCurveProto.buildPath,
  46037. pointAt: function (t) {
  46038. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  46039. },
  46040. _pointAtLine: straightLineProto.pointAt,
  46041. _pointAtCurve: bezierCurveProto.pointAt,
  46042. tangentAt: function (t) {
  46043. var shape = this.shape;
  46044. var p = isLine(shape)
  46045. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  46046. : this._tangentAtCurve(t);
  46047. return normalize(p, p);
  46048. },
  46049. _tangentAtCurve: bezierCurveProto.tangentAt
  46050. });
  46051. /*
  46052. * Licensed to the Apache Software Foundation (ASF) under one
  46053. * or more contributor license agreements. See the NOTICE file
  46054. * distributed with this work for additional information
  46055. * regarding copyright ownership. The ASF licenses this file
  46056. * to you under the Apache License, Version 2.0 (the
  46057. * "License"); you may not use this file except in compliance
  46058. * with the License. You may obtain a copy of the License at
  46059. *
  46060. * http://www.apache.org/licenses/LICENSE-2.0
  46061. *
  46062. * Unless required by applicable law or agreed to in writing,
  46063. * software distributed under the License is distributed on an
  46064. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46065. * KIND, either express or implied. See the License for the
  46066. * specific language governing permissions and limitations
  46067. * under the License.
  46068. */
  46069. /**
  46070. * @module echarts/chart/helper/Line
  46071. */
  46072. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  46073. function makeSymbolTypeKey(symbolCategory) {
  46074. return '_' + symbolCategory + 'Type';
  46075. }
  46076. /**
  46077. * @inner
  46078. */
  46079. function createSymbol$1(name, lineData, idx) {
  46080. var color = lineData.getItemVisual(idx, 'color');
  46081. var symbolType = lineData.getItemVisual(idx, name);
  46082. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  46083. if (!symbolType || symbolType === 'none') {
  46084. return;
  46085. }
  46086. if (!isArray(symbolSize)) {
  46087. symbolSize = [symbolSize, symbolSize];
  46088. }
  46089. var symbolPath = createSymbol(
  46090. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  46091. symbolSize[0], symbolSize[1], color
  46092. );
  46093. symbolPath.name = name;
  46094. return symbolPath;
  46095. }
  46096. function createLine(points) {
  46097. var line = new LinePath({
  46098. name: 'line',
  46099. subPixelOptimize: true
  46100. });
  46101. setLinePoints(line.shape, points);
  46102. return line;
  46103. }
  46104. function setLinePoints(targetShape, points) {
  46105. targetShape.x1 = points[0][0];
  46106. targetShape.y1 = points[0][1];
  46107. targetShape.x2 = points[1][0];
  46108. targetShape.y2 = points[1][1];
  46109. targetShape.percent = 1;
  46110. var cp1 = points[2];
  46111. if (cp1) {
  46112. targetShape.cpx1 = cp1[0];
  46113. targetShape.cpy1 = cp1[1];
  46114. }
  46115. else {
  46116. targetShape.cpx1 = NaN;
  46117. targetShape.cpy1 = NaN;
  46118. }
  46119. }
  46120. function updateSymbolAndLabelBeforeLineUpdate() {
  46121. var lineGroup = this;
  46122. var symbolFrom = lineGroup.childOfName('fromSymbol');
  46123. var symbolTo = lineGroup.childOfName('toSymbol');
  46124. var label = lineGroup.childOfName('label');
  46125. // Quick reject
  46126. if (!symbolFrom && !symbolTo && label.ignore) {
  46127. return;
  46128. }
  46129. var invScale = 1;
  46130. var parentNode = this.parent;
  46131. while (parentNode) {
  46132. if (parentNode.scale) {
  46133. invScale /= parentNode.scale[0];
  46134. }
  46135. parentNode = parentNode.parent;
  46136. }
  46137. var line = lineGroup.childOfName('line');
  46138. // If line not changed
  46139. // FIXME Parent scale changed
  46140. if (!this.__dirty && !line.__dirty) {
  46141. return;
  46142. }
  46143. var percent = line.shape.percent;
  46144. var fromPos = line.pointAt(0);
  46145. var toPos = line.pointAt(percent);
  46146. var d = sub([], toPos, fromPos);
  46147. normalize(d, d);
  46148. if (symbolFrom) {
  46149. symbolFrom.attr('position', fromPos);
  46150. var tangent = line.tangentAt(0);
  46151. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  46152. tangent[1], tangent[0]
  46153. ));
  46154. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  46155. }
  46156. if (symbolTo) {
  46157. symbolTo.attr('position', toPos);
  46158. var tangent = line.tangentAt(1);
  46159. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  46160. tangent[1], tangent[0]
  46161. ));
  46162. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  46163. }
  46164. if (!label.ignore) {
  46165. label.attr('position', toPos);
  46166. var textPosition;
  46167. var textAlign;
  46168. var textVerticalAlign;
  46169. var textOrigin;
  46170. var distance$$1 = label.__labelDistance;
  46171. var distanceX = distance$$1[0] * invScale;
  46172. var distanceY = distance$$1[1] * invScale;
  46173. var halfPercent = percent / 2;
  46174. var tangent = line.tangentAt(halfPercent);
  46175. var n = [tangent[1], -tangent[0]];
  46176. var cp = line.pointAt(halfPercent);
  46177. if (n[1] > 0) {
  46178. n[0] = -n[0];
  46179. n[1] = -n[1];
  46180. }
  46181. var dir = tangent[0] < 0 ? -1 : 1;
  46182. if (label.__position !== 'start' && label.__position !== 'end') {
  46183. var rotation = -Math.atan2(tangent[1], tangent[0]);
  46184. if (toPos[0] < fromPos[0]) {
  46185. rotation = Math.PI + rotation;
  46186. }
  46187. label.attr('rotation', rotation);
  46188. }
  46189. var dy;
  46190. switch (label.__position) {
  46191. case 'insideStartTop':
  46192. case 'insideMiddleTop':
  46193. case 'insideEndTop':
  46194. case 'middle':
  46195. dy = -distanceY;
  46196. textVerticalAlign = 'bottom';
  46197. break;
  46198. case 'insideStartBottom':
  46199. case 'insideMiddleBottom':
  46200. case 'insideEndBottom':
  46201. dy = distanceY;
  46202. textVerticalAlign = 'top';
  46203. break;
  46204. default:
  46205. dy = 0;
  46206. textVerticalAlign = 'middle';
  46207. }
  46208. switch (label.__position) {
  46209. case 'end':
  46210. textPosition = [d[0] * distanceX + toPos[0], d[1] * distanceY + toPos[1]];
  46211. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  46212. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  46213. break;
  46214. case 'start':
  46215. textPosition = [-d[0] * distanceX + fromPos[0], -d[1] * distanceY + fromPos[1]];
  46216. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  46217. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  46218. break;
  46219. case 'insideStartTop':
  46220. case 'insideStart':
  46221. case 'insideStartBottom':
  46222. textPosition = [distanceX * dir + fromPos[0], fromPos[1] + dy];
  46223. textAlign = tangent[0] < 0 ? 'right' : 'left';
  46224. textOrigin = [-distanceX * dir, -dy];
  46225. break;
  46226. case 'insideMiddleTop':
  46227. case 'insideMiddle':
  46228. case 'insideMiddleBottom':
  46229. case 'middle':
  46230. textPosition = [cp[0], cp[1] + dy];
  46231. textAlign = 'center';
  46232. textOrigin = [0, -dy];
  46233. break;
  46234. case 'insideEndTop':
  46235. case 'insideEnd':
  46236. case 'insideEndBottom':
  46237. textPosition = [-distanceX * dir + toPos[0], toPos[1] + dy];
  46238. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  46239. textOrigin = [distanceX * dir, -dy];
  46240. break;
  46241. }
  46242. label.attr({
  46243. style: {
  46244. // Use the user specified text align and baseline first
  46245. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  46246. textAlign: label.__textAlign || textAlign
  46247. },
  46248. position: textPosition,
  46249. scale: [invScale, invScale],
  46250. origin: textOrigin
  46251. });
  46252. }
  46253. }
  46254. /**
  46255. * @constructor
  46256. * @extends {module:zrender/graphic/Group}
  46257. * @alias {module:echarts/chart/helper/Line}
  46258. */
  46259. function Line$1(lineData, idx, seriesScope) {
  46260. Group.call(this);
  46261. this._createLine(lineData, idx, seriesScope);
  46262. }
  46263. var lineProto = Line$1.prototype;
  46264. // Update symbol position and rotation
  46265. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  46266. lineProto._createLine = function (lineData, idx, seriesScope) {
  46267. var seriesModel = lineData.hostModel;
  46268. var linePoints = lineData.getItemLayout(idx);
  46269. var line = createLine(linePoints);
  46270. line.shape.percent = 0;
  46271. initProps(line, {
  46272. shape: {
  46273. percent: 1
  46274. }
  46275. }, seriesModel, idx);
  46276. this.add(line);
  46277. var label = new Text({
  46278. name: 'label',
  46279. // FIXME
  46280. // Temporary solution for `focusNodeAdjacency`.
  46281. // line label do not use the opacity of lineStyle.
  46282. lineLabelOriginalOpacity: 1
  46283. });
  46284. this.add(label);
  46285. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46286. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46287. // symbols must added after line to make sure
  46288. // it will be updated after line#update.
  46289. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  46290. this.add(symbol);
  46291. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  46292. }, this);
  46293. this._updateCommonStl(lineData, idx, seriesScope);
  46294. };
  46295. lineProto.updateData = function (lineData, idx, seriesScope) {
  46296. var seriesModel = lineData.hostModel;
  46297. var line = this.childOfName('line');
  46298. var linePoints = lineData.getItemLayout(idx);
  46299. var target = {
  46300. shape: {}
  46301. };
  46302. setLinePoints(target.shape, linePoints);
  46303. updateProps(line, target, seriesModel, idx);
  46304. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46305. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  46306. var key = makeSymbolTypeKey(symbolCategory);
  46307. // Symbol changed
  46308. if (this[key] !== symbolType) {
  46309. this.remove(this.childOfName(symbolCategory));
  46310. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46311. this.add(symbol);
  46312. }
  46313. this[key] = symbolType;
  46314. }, this);
  46315. this._updateCommonStl(lineData, idx, seriesScope);
  46316. };
  46317. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46318. var seriesModel = lineData.hostModel;
  46319. var line = this.childOfName('line');
  46320. var lineStyle = seriesScope && seriesScope.lineStyle;
  46321. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46322. var labelModel = seriesScope && seriesScope.labelModel;
  46323. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  46324. // Optimization for large dataset
  46325. if (!seriesScope || lineData.hasItemOption) {
  46326. var itemModel = lineData.getItemModel(idx);
  46327. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46328. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46329. labelModel = itemModel.getModel('label');
  46330. hoverLabelModel = itemModel.getModel('emphasis.label');
  46331. }
  46332. var visualColor = lineData.getItemVisual(idx, 'color');
  46333. var visualOpacity = retrieve3(
  46334. lineData.getItemVisual(idx, 'opacity'),
  46335. lineStyle.opacity,
  46336. 1
  46337. );
  46338. line.useStyle(defaults(
  46339. {
  46340. strokeNoScale: true,
  46341. fill: 'none',
  46342. stroke: visualColor,
  46343. opacity: visualOpacity
  46344. },
  46345. lineStyle
  46346. ));
  46347. line.hoverStyle = hoverLineStyle;
  46348. // Update symbol
  46349. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46350. var symbol = this.childOfName(symbolCategory);
  46351. if (symbol) {
  46352. symbol.setColor(visualColor);
  46353. symbol.setStyle({
  46354. opacity: visualOpacity
  46355. });
  46356. }
  46357. }, this);
  46358. var showLabel = labelModel.getShallow('show');
  46359. var hoverShowLabel = hoverLabelModel.getShallow('show');
  46360. var label = this.childOfName('label');
  46361. var defaultLabelColor;
  46362. var baseText;
  46363. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  46364. if (showLabel || hoverShowLabel) {
  46365. defaultLabelColor = visualColor || '#000';
  46366. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  46367. if (baseText == null) {
  46368. var rawVal = seriesModel.getRawValue(idx);
  46369. baseText = rawVal == null
  46370. ? lineData.getName(idx)
  46371. : isFinite(rawVal)
  46372. ? round$1(rawVal)
  46373. : rawVal;
  46374. }
  46375. }
  46376. var normalText = showLabel ? baseText : null;
  46377. var emphasisText = hoverShowLabel
  46378. ? retrieve2(
  46379. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  46380. baseText
  46381. )
  46382. : null;
  46383. var labelStyle = label.style;
  46384. // Always set `textStyle` even if `normalStyle.text` is null, because default
  46385. // values have to be set on `normalStyle`.
  46386. if (normalText != null || emphasisText != null) {
  46387. setTextStyle(label.style, labelModel, {
  46388. text: normalText
  46389. }, {
  46390. autoColor: defaultLabelColor
  46391. });
  46392. label.__textAlign = labelStyle.textAlign;
  46393. label.__verticalAlign = labelStyle.textVerticalAlign;
  46394. // 'start', 'middle', 'end'
  46395. label.__position = labelModel.get('position') || 'middle';
  46396. var distance$$1 = labelModel.get('distance');
  46397. if (!isArray(distance$$1)) {
  46398. distance$$1 = [distance$$1, distance$$1];
  46399. }
  46400. label.__labelDistance = distance$$1;
  46401. }
  46402. if (emphasisText != null) {
  46403. // Only these properties supported in this emphasis style here.
  46404. label.hoverStyle = {
  46405. text: emphasisText,
  46406. textFill: hoverLabelModel.getTextColor(true),
  46407. // For merging hover style to normal style, do not use
  46408. // `hoverLabelModel.getFont()` here.
  46409. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  46410. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  46411. fontSize: hoverLabelModel.getShallow('fontSize'),
  46412. fontFamily: hoverLabelModel.getShallow('fontFamily')
  46413. };
  46414. }
  46415. else {
  46416. label.hoverStyle = {
  46417. text: null
  46418. };
  46419. }
  46420. label.ignore = !showLabel && !hoverShowLabel;
  46421. setHoverStyle(this);
  46422. };
  46423. lineProto.highlight = function () {
  46424. this.trigger('emphasis');
  46425. };
  46426. lineProto.downplay = function () {
  46427. this.trigger('normal');
  46428. };
  46429. lineProto.updateLayout = function (lineData, idx) {
  46430. this.setLinePoints(lineData.getItemLayout(idx));
  46431. };
  46432. lineProto.setLinePoints = function (points) {
  46433. var linePath = this.childOfName('line');
  46434. setLinePoints(linePath.shape, points);
  46435. linePath.dirty();
  46436. };
  46437. inherits(Line$1, Group);
  46438. /*
  46439. * Licensed to the Apache Software Foundation (ASF) under one
  46440. * or more contributor license agreements. See the NOTICE file
  46441. * distributed with this work for additional information
  46442. * regarding copyright ownership. The ASF licenses this file
  46443. * to you under the Apache License, Version 2.0 (the
  46444. * "License"); you may not use this file except in compliance
  46445. * with the License. You may obtain a copy of the License at
  46446. *
  46447. * http://www.apache.org/licenses/LICENSE-2.0
  46448. *
  46449. * Unless required by applicable law or agreed to in writing,
  46450. * software distributed under the License is distributed on an
  46451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46452. * KIND, either express or implied. See the License for the
  46453. * specific language governing permissions and limitations
  46454. * under the License.
  46455. */
  46456. /**
  46457. * @module echarts/chart/helper/LineDraw
  46458. */
  46459. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  46460. /**
  46461. * @alias module:echarts/component/marker/LineDraw
  46462. * @constructor
  46463. */
  46464. function LineDraw(ctor) {
  46465. this._ctor = ctor || Line$1;
  46466. this.group = new Group();
  46467. }
  46468. var lineDrawProto = LineDraw.prototype;
  46469. lineDrawProto.isPersistent = function () {
  46470. return true;
  46471. };
  46472. /**
  46473. * @param {module:echarts/data/List} lineData
  46474. */
  46475. lineDrawProto.updateData = function (lineData) {
  46476. var lineDraw = this;
  46477. var group = lineDraw.group;
  46478. var oldLineData = lineDraw._lineData;
  46479. lineDraw._lineData = lineData;
  46480. // There is no oldLineData only when first rendering or switching from
  46481. // stream mode to normal mode, where previous elements should be removed.
  46482. if (!oldLineData) {
  46483. group.removeAll();
  46484. }
  46485. var seriesScope = makeSeriesScope$1(lineData);
  46486. lineData.diff(oldLineData)
  46487. .add(function (idx) {
  46488. doAdd(lineDraw, lineData, idx, seriesScope);
  46489. })
  46490. .update(function (newIdx, oldIdx) {
  46491. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  46492. })
  46493. .remove(function (idx) {
  46494. group.remove(oldLineData.getItemGraphicEl(idx));
  46495. })
  46496. .execute();
  46497. };
  46498. function doAdd(lineDraw, lineData, idx, seriesScope) {
  46499. var itemLayout = lineData.getItemLayout(idx);
  46500. if (!lineNeedsDraw(itemLayout)) {
  46501. return;
  46502. }
  46503. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  46504. lineData.setItemGraphicEl(idx, el);
  46505. lineDraw.group.add(el);
  46506. }
  46507. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  46508. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  46509. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  46510. lineDraw.group.remove(itemEl);
  46511. return;
  46512. }
  46513. if (!itemEl) {
  46514. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  46515. }
  46516. else {
  46517. itemEl.updateData(newLineData, newIdx, seriesScope);
  46518. }
  46519. newLineData.setItemGraphicEl(newIdx, itemEl);
  46520. lineDraw.group.add(itemEl);
  46521. }
  46522. lineDrawProto.updateLayout = function () {
  46523. var lineData = this._lineData;
  46524. // Do not support update layout in incremental mode.
  46525. if (!lineData) {
  46526. return;
  46527. }
  46528. lineData.eachItemGraphicEl(function (el, idx) {
  46529. el.updateLayout(lineData, idx);
  46530. }, this);
  46531. };
  46532. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  46533. this._seriesScope = makeSeriesScope$1(lineData);
  46534. this._lineData = null;
  46535. this.group.removeAll();
  46536. };
  46537. function isEffectObject(el) {
  46538. return el.animators && el.animators.length > 0;
  46539. }
  46540. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  46541. function updateIncrementalAndHover(el) {
  46542. if (!el.isGroup && !isEffectObject(el)) {
  46543. el.incremental = el.useHoverLayer = true;
  46544. }
  46545. }
  46546. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  46547. var itemLayout = lineData.getItemLayout(idx);
  46548. if (lineNeedsDraw(itemLayout)) {
  46549. var el = new this._ctor(lineData, idx, this._seriesScope);
  46550. el.traverse(updateIncrementalAndHover);
  46551. this.group.add(el);
  46552. lineData.setItemGraphicEl(idx, el);
  46553. }
  46554. }
  46555. };
  46556. function makeSeriesScope$1(lineData) {
  46557. var hostModel = lineData.hostModel;
  46558. return {
  46559. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  46560. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  46561. labelModel: hostModel.getModel('label'),
  46562. hoverLabelModel: hostModel.getModel('emphasis.label')
  46563. };
  46564. }
  46565. lineDrawProto.remove = function () {
  46566. this._clearIncremental();
  46567. this._incremental = null;
  46568. this.group.removeAll();
  46569. };
  46570. lineDrawProto._clearIncremental = function () {
  46571. var incremental = this._incremental;
  46572. if (incremental) {
  46573. incremental.clearDisplaybles();
  46574. }
  46575. };
  46576. function isPointNaN(pt) {
  46577. return isNaN(pt[0]) || isNaN(pt[1]);
  46578. }
  46579. function lineNeedsDraw(pts) {
  46580. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  46581. }
  46582. /*
  46583. * Licensed to the Apache Software Foundation (ASF) under one
  46584. * or more contributor license agreements. See the NOTICE file
  46585. * distributed with this work for additional information
  46586. * regarding copyright ownership. The ASF licenses this file
  46587. * to you under the Apache License, Version 2.0 (the
  46588. * "License"); you may not use this file except in compliance
  46589. * with the License. You may obtain a copy of the License at
  46590. *
  46591. * http://www.apache.org/licenses/LICENSE-2.0
  46592. *
  46593. * Unless required by applicable law or agreed to in writing,
  46594. * software distributed under the License is distributed on an
  46595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46596. * KIND, either express or implied. See the License for the
  46597. * specific language governing permissions and limitations
  46598. * under the License.
  46599. */
  46600. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  46601. var data = seriesModel.getData();
  46602. // Special type markLine like 'min', 'max', 'average', 'median'
  46603. var mlType = item.type;
  46604. if (!isArray(item)
  46605. && (
  46606. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  46607. // In case
  46608. // data: [{
  46609. // yAxis: 10
  46610. // }]
  46611. || (item.xAxis != null || item.yAxis != null)
  46612. )
  46613. ) {
  46614. var valueAxis;
  46615. var value;
  46616. if (item.yAxis != null || item.xAxis != null) {
  46617. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  46618. value = retrieve(item.yAxis, item.xAxis);
  46619. }
  46620. else {
  46621. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  46622. valueAxis = axisInfo.valueAxis;
  46623. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  46624. value = numCalculate(data, valueDataDim, mlType);
  46625. }
  46626. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  46627. var baseIndex = 1 - valueIndex;
  46628. var mlFrom = clone(item);
  46629. var mlTo = {};
  46630. mlFrom.type = null;
  46631. mlFrom.coord = [];
  46632. mlTo.coord = [];
  46633. mlFrom.coord[baseIndex] = -Infinity;
  46634. mlTo.coord[baseIndex] = Infinity;
  46635. var precision = mlModel.get('precision');
  46636. if (precision >= 0 && typeof value === 'number') {
  46637. value = +value.toFixed(Math.min(precision, 20));
  46638. }
  46639. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  46640. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  46641. type: mlType,
  46642. valueIndex: item.valueIndex,
  46643. // Force to use the value of calculated value.
  46644. value: value
  46645. }];
  46646. }
  46647. item = [
  46648. dataTransform(seriesModel, item[0]),
  46649. dataTransform(seriesModel, item[1]),
  46650. extend({}, item[2])
  46651. ];
  46652. // Avoid line data type is extended by from(to) data type
  46653. item[2].type = item[2].type || '';
  46654. // Merge from option and to option into line option
  46655. merge(item[2], item[0]);
  46656. merge(item[2], item[1]);
  46657. return item;
  46658. };
  46659. function isInifinity(val) {
  46660. return !isNaN(val) && !isFinite(val);
  46661. }
  46662. // If a markLine has one dim
  46663. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  46664. var otherDimIndex = 1 - dimIndex;
  46665. var dimName = coordSys.dimensions[dimIndex];
  46666. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  46667. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  46668. }
  46669. function markLineFilter(coordSys, item) {
  46670. if (coordSys.type === 'cartesian2d') {
  46671. var fromCoord = item[0].coord;
  46672. var toCoord = item[1].coord;
  46673. // In case
  46674. // {
  46675. // markLine: {
  46676. // data: [{ yAxis: 2 }]
  46677. // }
  46678. // }
  46679. if (
  46680. fromCoord && toCoord
  46681. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  46682. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  46683. ) {
  46684. return true;
  46685. }
  46686. }
  46687. return dataFilter$1(coordSys, item[0])
  46688. && dataFilter$1(coordSys, item[1]);
  46689. }
  46690. function updateSingleMarkerEndLayout(
  46691. data, idx, isFrom, seriesModel, api
  46692. ) {
  46693. var coordSys = seriesModel.coordinateSystem;
  46694. var itemModel = data.getItemModel(idx);
  46695. var point;
  46696. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  46697. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  46698. if (!isNaN(xPx) && !isNaN(yPx)) {
  46699. point = [xPx, yPx];
  46700. }
  46701. else {
  46702. // Chart like bar may have there own marker positioning logic
  46703. if (seriesModel.getMarkerPosition) {
  46704. // Use the getMarkerPoisition
  46705. point = seriesModel.getMarkerPosition(
  46706. data.getValues(data.dimensions, idx)
  46707. );
  46708. }
  46709. else {
  46710. var dims = coordSys.dimensions;
  46711. var x = data.get(dims[0], idx);
  46712. var y = data.get(dims[1], idx);
  46713. point = coordSys.dataToPoint([x, y]);
  46714. }
  46715. // Expand line to the edge of grid if value on one axis is Inifnity
  46716. // In case
  46717. // markLine: {
  46718. // data: [{
  46719. // yAxis: 2
  46720. // // or
  46721. // type: 'average'
  46722. // }]
  46723. // }
  46724. if (coordSys.type === 'cartesian2d') {
  46725. var xAxis = coordSys.getAxis('x');
  46726. var yAxis = coordSys.getAxis('y');
  46727. var dims = coordSys.dimensions;
  46728. if (isInifinity(data.get(dims[0], idx))) {
  46729. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  46730. }
  46731. else if (isInifinity(data.get(dims[1], idx))) {
  46732. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  46733. }
  46734. }
  46735. // Use x, y if has any
  46736. if (!isNaN(xPx)) {
  46737. point[0] = xPx;
  46738. }
  46739. if (!isNaN(yPx)) {
  46740. point[1] = yPx;
  46741. }
  46742. }
  46743. data.setItemLayout(idx, point);
  46744. }
  46745. MarkerView.extend({
  46746. type: 'markLine',
  46747. // updateLayout: function (markLineModel, ecModel, api) {
  46748. // ecModel.eachSeries(function (seriesModel) {
  46749. // var mlModel = seriesModel.markLineModel;
  46750. // if (mlModel) {
  46751. // var mlData = mlModel.getData();
  46752. // var fromData = mlModel.__from;
  46753. // var toData = mlModel.__to;
  46754. // // Update visual and layout of from symbol and to symbol
  46755. // fromData.each(function (idx) {
  46756. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46757. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46758. // });
  46759. // // Update layout of line
  46760. // mlData.each(function (idx) {
  46761. // mlData.setItemLayout(idx, [
  46762. // fromData.getItemLayout(idx),
  46763. // toData.getItemLayout(idx)
  46764. // ]);
  46765. // });
  46766. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  46767. // }
  46768. // }, this);
  46769. // },
  46770. updateTransform: function (markLineModel, ecModel, api) {
  46771. ecModel.eachSeries(function (seriesModel) {
  46772. var mlModel = seriesModel.markLineModel;
  46773. if (mlModel) {
  46774. var mlData = mlModel.getData();
  46775. var fromData = mlModel.__from;
  46776. var toData = mlModel.__to;
  46777. // Update visual and layout of from symbol and to symbol
  46778. fromData.each(function (idx) {
  46779. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  46780. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  46781. });
  46782. // Update layout of line
  46783. mlData.each(function (idx) {
  46784. mlData.setItemLayout(idx, [
  46785. fromData.getItemLayout(idx),
  46786. toData.getItemLayout(idx)
  46787. ]);
  46788. });
  46789. this.markerGroupMap.get(seriesModel.id).updateLayout();
  46790. }
  46791. }, this);
  46792. },
  46793. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  46794. var coordSys = seriesModel.coordinateSystem;
  46795. var seriesId = seriesModel.id;
  46796. var seriesData = seriesModel.getData();
  46797. var lineDrawMap = this.markerGroupMap;
  46798. var lineDraw = lineDrawMap.get(seriesId)
  46799. || lineDrawMap.set(seriesId, new LineDraw());
  46800. this.group.add(lineDraw.group);
  46801. var mlData = createList$2(coordSys, seriesModel, mlModel);
  46802. var fromData = mlData.from;
  46803. var toData = mlData.to;
  46804. var lineData = mlData.line;
  46805. mlModel.__from = fromData;
  46806. mlModel.__to = toData;
  46807. // Line data for tooltip and formatter
  46808. mlModel.setData(lineData);
  46809. var symbolType = mlModel.get('symbol');
  46810. var symbolSize = mlModel.get('symbolSize');
  46811. if (!isArray(symbolType)) {
  46812. symbolType = [symbolType, symbolType];
  46813. }
  46814. if (typeof symbolSize === 'number') {
  46815. symbolSize = [symbolSize, symbolSize];
  46816. }
  46817. // Update visual and layout of from symbol and to symbol
  46818. mlData.from.each(function (idx) {
  46819. updateDataVisualAndLayout(fromData, idx, true);
  46820. updateDataVisualAndLayout(toData, idx, false);
  46821. });
  46822. // Update visual and layout of line
  46823. lineData.each(function (idx) {
  46824. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  46825. lineData.setItemVisual(idx, {
  46826. color: lineColor || fromData.getItemVisual(idx, 'color')
  46827. });
  46828. lineData.setItemLayout(idx, [
  46829. fromData.getItemLayout(idx),
  46830. toData.getItemLayout(idx)
  46831. ]);
  46832. lineData.setItemVisual(idx, {
  46833. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  46834. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  46835. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  46836. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  46837. });
  46838. });
  46839. lineDraw.updateData(lineData);
  46840. // Set host model for tooltip
  46841. // FIXME
  46842. mlData.line.eachItemGraphicEl(function (el, idx) {
  46843. el.traverse(function (child) {
  46844. child.dataModel = mlModel;
  46845. });
  46846. });
  46847. function updateDataVisualAndLayout(data, idx, isFrom) {
  46848. var itemModel = data.getItemModel(idx);
  46849. updateSingleMarkerEndLayout(
  46850. data, idx, isFrom, seriesModel, api
  46851. );
  46852. data.setItemVisual(idx, {
  46853. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  46854. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  46855. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  46856. });
  46857. }
  46858. lineDraw.__keep = true;
  46859. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  46860. }
  46861. });
  46862. /**
  46863. * @inner
  46864. * @param {module:echarts/coord/*} coordSys
  46865. * @param {module:echarts/model/Series} seriesModel
  46866. * @param {module:echarts/model/Model} mpModel
  46867. */
  46868. function createList$2(coordSys, seriesModel, mlModel) {
  46869. var coordDimsInfos;
  46870. if (coordSys) {
  46871. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  46872. var info = seriesModel.getData().getDimensionInfo(
  46873. seriesModel.getData().mapDimension(coordDim)
  46874. ) || {};
  46875. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  46876. return defaults({name: coordDim}, info);
  46877. });
  46878. }
  46879. else {
  46880. coordDimsInfos = [{
  46881. name: 'value',
  46882. type: 'float'
  46883. }];
  46884. }
  46885. var fromData = new List(coordDimsInfos, mlModel);
  46886. var toData = new List(coordDimsInfos, mlModel);
  46887. // No dimensions
  46888. var lineData = new List([], mlModel);
  46889. var optData = map(mlModel.get('data'), curry(
  46890. markLineTransform, seriesModel, coordSys, mlModel
  46891. ));
  46892. if (coordSys) {
  46893. optData = filter(
  46894. optData, curry(markLineFilter, coordSys)
  46895. );
  46896. }
  46897. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  46898. return item.value;
  46899. };
  46900. fromData.initData(
  46901. map(optData, function (item) {
  46902. return item[0];
  46903. }),
  46904. null,
  46905. dimValueGetter$$1
  46906. );
  46907. toData.initData(
  46908. map(optData, function (item) {
  46909. return item[1];
  46910. }),
  46911. null,
  46912. dimValueGetter$$1
  46913. );
  46914. lineData.initData(
  46915. map(optData, function (item) {
  46916. return item[2];
  46917. })
  46918. );
  46919. lineData.hasItemOption = true;
  46920. return {
  46921. from: fromData,
  46922. to: toData,
  46923. line: lineData
  46924. };
  46925. }
  46926. /*
  46927. * Licensed to the Apache Software Foundation (ASF) under one
  46928. * or more contributor license agreements. See the NOTICE file
  46929. * distributed with this work for additional information
  46930. * regarding copyright ownership. The ASF licenses this file
  46931. * to you under the Apache License, Version 2.0 (the
  46932. * "License"); you may not use this file except in compliance
  46933. * with the License. You may obtain a copy of the License at
  46934. *
  46935. * http://www.apache.org/licenses/LICENSE-2.0
  46936. *
  46937. * Unless required by applicable law or agreed to in writing,
  46938. * software distributed under the License is distributed on an
  46939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46940. * KIND, either express or implied. See the License for the
  46941. * specific language governing permissions and limitations
  46942. * under the License.
  46943. */
  46944. registerPreprocessor(function (opt) {
  46945. // Make sure markLine component is enabled
  46946. opt.markLine = opt.markLine || {};
  46947. });
  46948. /*
  46949. * Licensed to the Apache Software Foundation (ASF) under one
  46950. * or more contributor license agreements. See the NOTICE file
  46951. * distributed with this work for additional information
  46952. * regarding copyright ownership. The ASF licenses this file
  46953. * to you under the Apache License, Version 2.0 (the
  46954. * "License"); you may not use this file except in compliance
  46955. * with the License. You may obtain a copy of the License at
  46956. *
  46957. * http://www.apache.org/licenses/LICENSE-2.0
  46958. *
  46959. * Unless required by applicable law or agreed to in writing,
  46960. * software distributed under the License is distributed on an
  46961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46962. * KIND, either express or implied. See the License for the
  46963. * specific language governing permissions and limitations
  46964. * under the License.
  46965. */
  46966. MarkerModel.extend({
  46967. type: 'markArea',
  46968. defaultOption: {
  46969. zlevel: 0,
  46970. // PENDING
  46971. z: 1,
  46972. tooltip: {
  46973. trigger: 'item'
  46974. },
  46975. // markArea should fixed on the coordinate system
  46976. animation: false,
  46977. label: {
  46978. show: true,
  46979. position: 'top'
  46980. },
  46981. itemStyle: {
  46982. // color and borderColor default to use color from series
  46983. // color: 'auto'
  46984. // borderColor: 'auto'
  46985. borderWidth: 0
  46986. },
  46987. emphasis: {
  46988. label: {
  46989. show: true,
  46990. position: 'top'
  46991. }
  46992. }
  46993. }
  46994. });
  46995. /*
  46996. * Licensed to the Apache Software Foundation (ASF) under one
  46997. * or more contributor license agreements. See the NOTICE file
  46998. * distributed with this work for additional information
  46999. * regarding copyright ownership. The ASF licenses this file
  47000. * to you under the Apache License, Version 2.0 (the
  47001. * "License"); you may not use this file except in compliance
  47002. * with the License. You may obtain a copy of the License at
  47003. *
  47004. * http://www.apache.org/licenses/LICENSE-2.0
  47005. *
  47006. * Unless required by applicable law or agreed to in writing,
  47007. * software distributed under the License is distributed on an
  47008. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47009. * KIND, either express or implied. See the License for the
  47010. * specific language governing permissions and limitations
  47011. * under the License.
  47012. */
  47013. // TODO Better on polar
  47014. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  47015. var lt = dataTransform(seriesModel, item[0]);
  47016. var rb = dataTransform(seriesModel, item[1]);
  47017. var retrieve$$1 = retrieve;
  47018. // FIXME make sure lt is less than rb
  47019. var ltCoord = lt.coord;
  47020. var rbCoord = rb.coord;
  47021. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  47022. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  47023. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  47024. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  47025. // Merge option into one
  47026. var result = mergeAll([{}, lt, rb]);
  47027. result.coord = [
  47028. lt.coord, rb.coord
  47029. ];
  47030. result.x0 = lt.x;
  47031. result.y0 = lt.y;
  47032. result.x1 = rb.x;
  47033. result.y1 = rb.y;
  47034. return result;
  47035. };
  47036. function isInifinity$1(val) {
  47037. return !isNaN(val) && !isFinite(val);
  47038. }
  47039. // If a markArea has one dim
  47040. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  47041. var otherDimIndex = 1 - dimIndex;
  47042. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  47043. }
  47044. function markAreaFilter(coordSys, item) {
  47045. var fromCoord = item.coord[0];
  47046. var toCoord = item.coord[1];
  47047. if (coordSys.type === 'cartesian2d') {
  47048. // In case
  47049. // {
  47050. // markArea: {
  47051. // data: [{ yAxis: 2 }]
  47052. // }
  47053. // }
  47054. if (
  47055. fromCoord && toCoord
  47056. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  47057. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  47058. ) {
  47059. return true;
  47060. }
  47061. }
  47062. return dataFilter$1(coordSys, {
  47063. coord: fromCoord,
  47064. x: item.x0,
  47065. y: item.y0
  47066. })
  47067. || dataFilter$1(coordSys, {
  47068. coord: toCoord,
  47069. x: item.x1,
  47070. y: item.y1
  47071. });
  47072. }
  47073. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  47074. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  47075. var coordSys = seriesModel.coordinateSystem;
  47076. var itemModel = data.getItemModel(idx);
  47077. var point;
  47078. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  47079. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  47080. if (!isNaN(xPx) && !isNaN(yPx)) {
  47081. point = [xPx, yPx];
  47082. }
  47083. else {
  47084. // Chart like bar may have there own marker positioning logic
  47085. if (seriesModel.getMarkerPosition) {
  47086. // Use the getMarkerPoisition
  47087. point = seriesModel.getMarkerPosition(
  47088. data.getValues(dims, idx)
  47089. );
  47090. }
  47091. else {
  47092. var x = data.get(dims[0], idx);
  47093. var y = data.get(dims[1], idx);
  47094. var pt = [x, y];
  47095. coordSys.clampData && coordSys.clampData(pt, pt);
  47096. point = coordSys.dataToPoint(pt, true);
  47097. }
  47098. if (coordSys.type === 'cartesian2d') {
  47099. var xAxis = coordSys.getAxis('x');
  47100. var yAxis = coordSys.getAxis('y');
  47101. var x = data.get(dims[0], idx);
  47102. var y = data.get(dims[1], idx);
  47103. if (isInifinity$1(x)) {
  47104. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  47105. }
  47106. else if (isInifinity$1(y)) {
  47107. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  47108. }
  47109. }
  47110. // Use x, y if has any
  47111. if (!isNaN(xPx)) {
  47112. point[0] = xPx;
  47113. }
  47114. if (!isNaN(yPx)) {
  47115. point[1] = yPx;
  47116. }
  47117. }
  47118. return point;
  47119. }
  47120. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  47121. MarkerView.extend({
  47122. type: 'markArea',
  47123. // updateLayout: function (markAreaModel, ecModel, api) {
  47124. // ecModel.eachSeries(function (seriesModel) {
  47125. // var maModel = seriesModel.markAreaModel;
  47126. // if (maModel) {
  47127. // var areaData = maModel.getData();
  47128. // areaData.each(function (idx) {
  47129. // var points = zrUtil.map(dimPermutations, function (dim) {
  47130. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47131. // });
  47132. // // Layout
  47133. // areaData.setItemLayout(idx, points);
  47134. // var el = areaData.getItemGraphicEl(idx);
  47135. // el.setShape('points', points);
  47136. // });
  47137. // }
  47138. // }, this);
  47139. // },
  47140. updateTransform: function (markAreaModel, ecModel, api) {
  47141. ecModel.eachSeries(function (seriesModel) {
  47142. var maModel = seriesModel.markAreaModel;
  47143. if (maModel) {
  47144. var areaData = maModel.getData();
  47145. areaData.each(function (idx) {
  47146. var points = map(dimPermutations, function (dim) {
  47147. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47148. });
  47149. // Layout
  47150. areaData.setItemLayout(idx, points);
  47151. var el = areaData.getItemGraphicEl(idx);
  47152. el.setShape('points', points);
  47153. });
  47154. }
  47155. }, this);
  47156. },
  47157. renderSeries: function (seriesModel, maModel, ecModel, api) {
  47158. var coordSys = seriesModel.coordinateSystem;
  47159. var seriesId = seriesModel.id;
  47160. var seriesData = seriesModel.getData();
  47161. var areaGroupMap = this.markerGroupMap;
  47162. var polygonGroup = areaGroupMap.get(seriesId)
  47163. || areaGroupMap.set(seriesId, {group: new Group()});
  47164. this.group.add(polygonGroup.group);
  47165. polygonGroup.__keep = true;
  47166. var areaData = createList$3(coordSys, seriesModel, maModel);
  47167. // Line data for tooltip and formatter
  47168. maModel.setData(areaData);
  47169. // Update visual and layout of line
  47170. areaData.each(function (idx) {
  47171. // Layout
  47172. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  47173. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  47174. }));
  47175. // Visual
  47176. areaData.setItemVisual(idx, {
  47177. color: seriesData.getVisual('color')
  47178. });
  47179. });
  47180. areaData.diff(polygonGroup.__data)
  47181. .add(function (idx) {
  47182. var polygon = new Polygon({
  47183. shape: {
  47184. points: areaData.getItemLayout(idx)
  47185. }
  47186. });
  47187. areaData.setItemGraphicEl(idx, polygon);
  47188. polygonGroup.group.add(polygon);
  47189. })
  47190. .update(function (newIdx, oldIdx) {
  47191. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  47192. updateProps(polygon, {
  47193. shape: {
  47194. points: areaData.getItemLayout(newIdx)
  47195. }
  47196. }, maModel, newIdx);
  47197. polygonGroup.group.add(polygon);
  47198. areaData.setItemGraphicEl(newIdx, polygon);
  47199. })
  47200. .remove(function (idx) {
  47201. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  47202. polygonGroup.group.remove(polygon);
  47203. })
  47204. .execute();
  47205. areaData.eachItemGraphicEl(function (polygon, idx) {
  47206. var itemModel = areaData.getItemModel(idx);
  47207. var labelModel = itemModel.getModel('label');
  47208. var labelHoverModel = itemModel.getModel('emphasis.label');
  47209. var color = areaData.getItemVisual(idx, 'color');
  47210. polygon.useStyle(
  47211. defaults(
  47212. itemModel.getModel('itemStyle').getItemStyle(),
  47213. {
  47214. fill: modifyAlpha(color, 0.4),
  47215. stroke: color
  47216. }
  47217. )
  47218. );
  47219. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  47220. setLabelStyle(
  47221. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  47222. {
  47223. labelFetcher: maModel,
  47224. labelDataIndex: idx,
  47225. defaultText: areaData.getName(idx) || '',
  47226. isRectText: true,
  47227. autoColor: color
  47228. }
  47229. );
  47230. setHoverStyle(polygon, {});
  47231. polygon.dataModel = maModel;
  47232. });
  47233. polygonGroup.__data = areaData;
  47234. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  47235. }
  47236. });
  47237. /**
  47238. * @inner
  47239. * @param {module:echarts/coord/*} coordSys
  47240. * @param {module:echarts/model/Series} seriesModel
  47241. * @param {module:echarts/model/Model} mpModel
  47242. */
  47243. function createList$3(coordSys, seriesModel, maModel) {
  47244. var coordDimsInfos;
  47245. var areaData;
  47246. var dims = ['x0', 'y0', 'x1', 'y1'];
  47247. if (coordSys) {
  47248. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  47249. var data = seriesModel.getData();
  47250. var info = data.getDimensionInfo(
  47251. data.mapDimension(coordDim)
  47252. ) || {};
  47253. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  47254. return defaults({name: coordDim}, info);
  47255. });
  47256. areaData = new List(map(dims, function (dim, idx) {
  47257. return {
  47258. name: dim,
  47259. type: coordDimsInfos[idx % 2].type
  47260. };
  47261. }), maModel);
  47262. }
  47263. else {
  47264. coordDimsInfos = [{
  47265. name: 'value',
  47266. type: 'float'
  47267. }];
  47268. areaData = new List(coordDimsInfos, maModel);
  47269. }
  47270. var optData = map(maModel.get('data'), curry(
  47271. markAreaTransform, seriesModel, coordSys, maModel
  47272. ));
  47273. if (coordSys) {
  47274. optData = filter(
  47275. optData, curry(markAreaFilter, coordSys)
  47276. );
  47277. }
  47278. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  47279. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  47280. } : function (item) {
  47281. return item.value;
  47282. };
  47283. areaData.initData(optData, null, dimValueGetter$$1);
  47284. areaData.hasItemOption = true;
  47285. return areaData;
  47286. }
  47287. /*
  47288. * Licensed to the Apache Software Foundation (ASF) under one
  47289. * or more contributor license agreements. See the NOTICE file
  47290. * distributed with this work for additional information
  47291. * regarding copyright ownership. The ASF licenses this file
  47292. * to you under the Apache License, Version 2.0 (the
  47293. * "License"); you may not use this file except in compliance
  47294. * with the License. You may obtain a copy of the License at
  47295. *
  47296. * http://www.apache.org/licenses/LICENSE-2.0
  47297. *
  47298. * Unless required by applicable law or agreed to in writing,
  47299. * software distributed under the License is distributed on an
  47300. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47301. * KIND, either express or implied. See the License for the
  47302. * specific language governing permissions and limitations
  47303. * under the License.
  47304. */
  47305. registerPreprocessor(function (opt) {
  47306. // Make sure markArea component is enabled
  47307. opt.markArea = opt.markArea || {};
  47308. });
  47309. /*
  47310. * Licensed to the Apache Software Foundation (ASF) under one
  47311. * or more contributor license agreements. See the NOTICE file
  47312. * distributed with this work for additional information
  47313. * regarding copyright ownership. The ASF licenses this file
  47314. * to you under the Apache License, Version 2.0 (the
  47315. * "License"); you may not use this file except in compliance
  47316. * with the License. You may obtain a copy of the License at
  47317. *
  47318. * http://www.apache.org/licenses/LICENSE-2.0
  47319. *
  47320. * Unless required by applicable law or agreed to in writing,
  47321. * software distributed under the License is distributed on an
  47322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47323. * KIND, either express or implied. See the License for the
  47324. * specific language governing permissions and limitations
  47325. * under the License.
  47326. */
  47327. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  47328. // Default 'slider' when no type specified.
  47329. return 'slider';
  47330. });
  47331. /*
  47332. * Licensed to the Apache Software Foundation (ASF) under one
  47333. * or more contributor license agreements. See the NOTICE file
  47334. * distributed with this work for additional information
  47335. * regarding copyright ownership. The ASF licenses this file
  47336. * to you under the Apache License, Version 2.0 (the
  47337. * "License"); you may not use this file except in compliance
  47338. * with the License. You may obtain a copy of the License at
  47339. *
  47340. * http://www.apache.org/licenses/LICENSE-2.0
  47341. *
  47342. * Unless required by applicable law or agreed to in writing,
  47343. * software distributed under the License is distributed on an
  47344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47345. * KIND, either express or implied. See the License for the
  47346. * specific language governing permissions and limitations
  47347. * under the License.
  47348. */
  47349. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  47350. // Supported coords.
  47351. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  47352. /**
  47353. * @param {string} coordType
  47354. * @return {boolean}
  47355. */
  47356. function isCoordSupported(coordType) {
  47357. return indexOf(COORDS, coordType) >= 0;
  47358. }
  47359. /**
  47360. * Create "each" method to iterate names.
  47361. *
  47362. * @pubilc
  47363. * @param {Array.<string>} names
  47364. * @param {Array.<string>=} attrs
  47365. * @return {Function}
  47366. */
  47367. function createNameEach(names, attrs) {
  47368. names = names.slice();
  47369. var capitalNames = map(names, capitalFirst);
  47370. attrs = (attrs || []).slice();
  47371. var capitalAttrs = map(attrs, capitalFirst);
  47372. return function (callback, context) {
  47373. each$1(names, function (name, index) {
  47374. var nameObj = {name: name, capital: capitalNames[index]};
  47375. for (var j = 0; j < attrs.length; j++) {
  47376. nameObj[attrs[j]] = name + capitalAttrs[j];
  47377. }
  47378. callback.call(context, nameObj);
  47379. });
  47380. };
  47381. }
  47382. /**
  47383. * Iterate each dimension name.
  47384. *
  47385. * @public
  47386. * @param {Function} callback The parameter is like:
  47387. * {
  47388. * name: 'angle',
  47389. * capital: 'Angle',
  47390. * axis: 'angleAxis',
  47391. * axisIndex: 'angleAixs',
  47392. * index: 'angleIndex'
  47393. * }
  47394. * @param {Object} context
  47395. */
  47396. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  47397. /**
  47398. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  47399. * dataZoomModels and 'links' make up one or more graphics.
  47400. * This function finds the graphic where the source dataZoomModel is in.
  47401. *
  47402. * @public
  47403. * @param {Function} forEachNode Node iterator.
  47404. * @param {Function} forEachEdgeType edgeType iterator
  47405. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  47406. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  47407. */
  47408. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  47409. return function (sourceNode) {
  47410. var result = {
  47411. nodes: [],
  47412. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  47413. };
  47414. forEachEdgeType(function (edgeType) {
  47415. result.records[edgeType.name] = {};
  47416. });
  47417. if (!sourceNode) {
  47418. return result;
  47419. }
  47420. absorb(sourceNode, result);
  47421. var existsLink;
  47422. do {
  47423. existsLink = false;
  47424. forEachNode(processSingleNode);
  47425. }
  47426. while (existsLink);
  47427. function processSingleNode(node) {
  47428. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  47429. absorb(node, result);
  47430. existsLink = true;
  47431. }
  47432. }
  47433. return result;
  47434. };
  47435. function isNodeAbsorded(node, result) {
  47436. return indexOf(result.nodes, node) >= 0;
  47437. }
  47438. function isLinked(node, result) {
  47439. var hasLink = false;
  47440. forEachEdgeType(function (edgeType) {
  47441. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  47442. result.records[edgeType.name][edgeId] && (hasLink = true);
  47443. });
  47444. });
  47445. return hasLink;
  47446. }
  47447. function absorb(node, result) {
  47448. result.nodes.push(node);
  47449. forEachEdgeType(function (edgeType) {
  47450. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  47451. result.records[edgeType.name][edgeId] = true;
  47452. });
  47453. });
  47454. }
  47455. }
  47456. /*
  47457. * Licensed to the Apache Software Foundation (ASF) under one
  47458. * or more contributor license agreements. See the NOTICE file
  47459. * distributed with this work for additional information
  47460. * regarding copyright ownership. The ASF licenses this file
  47461. * to you under the Apache License, Version 2.0 (the
  47462. * "License"); you may not use this file except in compliance
  47463. * with the License. You may obtain a copy of the License at
  47464. *
  47465. * http://www.apache.org/licenses/LICENSE-2.0
  47466. *
  47467. * Unless required by applicable law or agreed to in writing,
  47468. * software distributed under the License is distributed on an
  47469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47470. * KIND, either express or implied. See the License for the
  47471. * specific language governing permissions and limitations
  47472. * under the License.
  47473. */
  47474. /**
  47475. * Calculate slider move result.
  47476. * Usage:
  47477. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  47478. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  47479. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47480. *
  47481. * @param {number} delta Move length.
  47482. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47483. * handleEnds will be modified in this method.
  47484. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47485. * extent[0] should less or equals than extent[1].
  47486. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  47487. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47488. * If not set, handle0 and cross handle1. If set as a non-negative
  47489. * number (including `0`), handles will push each other when reaching
  47490. * the minSpan.
  47491. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47492. * @return {Array.<number>} The input handleEnds.
  47493. */
  47494. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47495. delta = delta || 0;
  47496. var extentSpan = extent[1] - extent[0];
  47497. // Notice maxSpan and minSpan can be null/undefined.
  47498. if (minSpan != null) {
  47499. minSpan = restrict(minSpan, [0, extentSpan]);
  47500. }
  47501. if (maxSpan != null) {
  47502. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47503. }
  47504. if (handleIndex === 'all') {
  47505. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47506. handleSpan = restrict(handleSpan, [0, extentSpan]);
  47507. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  47508. handleIndex = 0;
  47509. }
  47510. handleEnds[0] = restrict(handleEnds[0], extent);
  47511. handleEnds[1] = restrict(handleEnds[1], extent);
  47512. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47513. handleEnds[handleIndex] += delta;
  47514. // Restrict in extent.
  47515. var extentMinSpan = minSpan || 0;
  47516. var realExtent = extent.slice();
  47517. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47518. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  47519. // Expand span.
  47520. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47521. if (minSpan != null && (
  47522. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47523. )) {
  47524. // If minSpan exists, 'cross' is forbidden.
  47525. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47526. }
  47527. // Shrink span.
  47528. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47529. if (maxSpan != null && currDistSign.span > maxSpan) {
  47530. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47531. }
  47532. return handleEnds;
  47533. };
  47534. function getSpanSign(handleEnds, handleIndex) {
  47535. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47536. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47537. // is at left of handleEnds[1] for non-cross case.
  47538. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47539. }
  47540. function restrict(value, extend) {
  47541. return Math.min(
  47542. extend[1] != null ? extend[1] : Infinity,
  47543. Math.max(extend[0] != null ? extend[0] : -Infinity, value)
  47544. );
  47545. }
  47546. /*
  47547. * Licensed to the Apache Software Foundation (ASF) under one
  47548. * or more contributor license agreements. See the NOTICE file
  47549. * distributed with this work for additional information
  47550. * regarding copyright ownership. The ASF licenses this file
  47551. * to you under the Apache License, Version 2.0 (the
  47552. * "License"); you may not use this file except in compliance
  47553. * with the License. You may obtain a copy of the License at
  47554. *
  47555. * http://www.apache.org/licenses/LICENSE-2.0
  47556. *
  47557. * Unless required by applicable law or agreed to in writing,
  47558. * software distributed under the License is distributed on an
  47559. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47560. * KIND, either express or implied. See the License for the
  47561. * specific language governing permissions and limitations
  47562. * under the License.
  47563. */
  47564. var each$13 = each$1;
  47565. var asc$1 = asc;
  47566. /**
  47567. * Operate single axis.
  47568. * One axis can only operated by one axis operator.
  47569. * Different dataZoomModels may be defined to operate the same axis.
  47570. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  47571. * So dataZoomModels share one axisProxy in that case.
  47572. *
  47573. * @class
  47574. */
  47575. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  47576. /**
  47577. * @private
  47578. * @type {string}
  47579. */
  47580. this._dimName = dimName;
  47581. /**
  47582. * @private
  47583. */
  47584. this._axisIndex = axisIndex;
  47585. /**
  47586. * @private
  47587. * @type {Array.<number>}
  47588. */
  47589. this._valueWindow;
  47590. /**
  47591. * @private
  47592. * @type {Array.<number>}
  47593. */
  47594. this._percentWindow;
  47595. /**
  47596. * @private
  47597. * @type {Array.<number>}
  47598. */
  47599. this._dataExtent;
  47600. /**
  47601. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  47602. * @private
  47603. * @type {Object}
  47604. */
  47605. this._minMaxSpan;
  47606. /**
  47607. * @readOnly
  47608. * @type {module: echarts/model/Global}
  47609. */
  47610. this.ecModel = ecModel;
  47611. /**
  47612. * @private
  47613. * @type {module: echarts/component/dataZoom/DataZoomModel}
  47614. */
  47615. this._dataZoomModel = dataZoomModel;
  47616. // /**
  47617. // * @readOnly
  47618. // * @private
  47619. // */
  47620. // this.hasSeriesStacked;
  47621. };
  47622. AxisProxy.prototype = {
  47623. constructor: AxisProxy,
  47624. /**
  47625. * Whether the axisProxy is hosted by dataZoomModel.
  47626. *
  47627. * @public
  47628. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47629. * @return {boolean}
  47630. */
  47631. hostedBy: function (dataZoomModel) {
  47632. return this._dataZoomModel === dataZoomModel;
  47633. },
  47634. /**
  47635. * @return {Array.<number>} Value can only be NaN or finite value.
  47636. */
  47637. getDataValueWindow: function () {
  47638. return this._valueWindow.slice();
  47639. },
  47640. /**
  47641. * @return {Array.<number>}
  47642. */
  47643. getDataPercentWindow: function () {
  47644. return this._percentWindow.slice();
  47645. },
  47646. /**
  47647. * @public
  47648. * @param {number} axisIndex
  47649. * @return {Array} seriesModels
  47650. */
  47651. getTargetSeriesModels: function () {
  47652. var seriesModels = [];
  47653. var ecModel = this.ecModel;
  47654. ecModel.eachSeries(function (seriesModel) {
  47655. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  47656. var dimName = this._dimName;
  47657. var axisModel = ecModel.queryComponents({
  47658. mainType: dimName + 'Axis',
  47659. index: seriesModel.get(dimName + 'AxisIndex'),
  47660. id: seriesModel.get(dimName + 'AxisId')
  47661. })[0];
  47662. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  47663. seriesModels.push(seriesModel);
  47664. }
  47665. }
  47666. }, this);
  47667. return seriesModels;
  47668. },
  47669. getAxisModel: function () {
  47670. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  47671. },
  47672. getOtherAxisModel: function () {
  47673. var axisDim = this._dimName;
  47674. var ecModel = this.ecModel;
  47675. var axisModel = this.getAxisModel();
  47676. var isCartesian = axisDim === 'x' || axisDim === 'y';
  47677. var otherAxisDim;
  47678. var coordSysIndexName;
  47679. if (isCartesian) {
  47680. coordSysIndexName = 'gridIndex';
  47681. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  47682. }
  47683. else {
  47684. coordSysIndexName = 'polarIndex';
  47685. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  47686. }
  47687. var foundOtherAxisModel;
  47688. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  47689. if ((otherAxisModel.get(coordSysIndexName) || 0)
  47690. === (axisModel.get(coordSysIndexName) || 0)
  47691. ) {
  47692. foundOtherAxisModel = otherAxisModel;
  47693. }
  47694. });
  47695. return foundOtherAxisModel;
  47696. },
  47697. getMinMaxSpan: function () {
  47698. return clone(this._minMaxSpan);
  47699. },
  47700. /**
  47701. * Only calculate by given range and this._dataExtent, do not change anything.
  47702. *
  47703. * @param {Object} opt
  47704. * @param {number} [opt.start]
  47705. * @param {number} [opt.end]
  47706. * @param {number} [opt.startValue]
  47707. * @param {number} [opt.endValue]
  47708. */
  47709. calculateDataWindow: function (opt) {
  47710. var dataExtent = this._dataExtent;
  47711. var axisModel = this.getAxisModel();
  47712. var scale = axisModel.axis.scale;
  47713. var rangePropMode = this._dataZoomModel.getRangePropMode();
  47714. var percentExtent = [0, 100];
  47715. var percentWindow = [];
  47716. var valueWindow = [];
  47717. var hasPropModeValue;
  47718. each$13(['start', 'end'], function (prop, idx) {
  47719. var boundPercent = opt[prop];
  47720. var boundValue = opt[prop + 'Value'];
  47721. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  47722. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  47723. // but not min/max of axis, which will be calculated by data window then).
  47724. // The former one is suitable for cases that a dataZoom component controls multiple
  47725. // axes with different unit or extent, and the latter one is suitable for accurate
  47726. // zoom by pixel (e.g., in dataZoomSelect).
  47727. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  47728. // only when setOption or dispatchAction, otherwise it remains its original value.
  47729. // (Why not only record `percentProp` and always map to `valueProp`? Because
  47730. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  47731. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  47732. // data extent. All of values that are overflow the `dataExtent` will be calculated
  47733. // to percent '100%').
  47734. if (rangePropMode[idx] === 'percent') {
  47735. boundPercent == null && (boundPercent = percentExtent[idx]);
  47736. // Use scale.parse to math round for category or time axis.
  47737. boundValue = scale.parse(linearMap(
  47738. boundPercent, percentExtent, dataExtent
  47739. ));
  47740. }
  47741. else {
  47742. hasPropModeValue = true;
  47743. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
  47744. // Calculating `percent` from `value` may be not accurate, because
  47745. // This calculation can not be inversed, because all of values that
  47746. // are overflow the `dataExtent` will be calculated to percent '100%'
  47747. boundPercent = linearMap(
  47748. boundValue, dataExtent, percentExtent
  47749. );
  47750. }
  47751. // valueWindow[idx] = round(boundValue);
  47752. // percentWindow[idx] = round(boundPercent);
  47753. valueWindow[idx] = boundValue;
  47754. percentWindow[idx] = boundPercent;
  47755. });
  47756. asc$1(valueWindow);
  47757. asc$1(percentWindow);
  47758. // The windows from user calling of `dispatchAction` might be out of the extent,
  47759. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  47760. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  47761. // where API is able to initialize/modify the window size even though `zoomLock`
  47762. // specified.
  47763. var spans = this._minMaxSpan;
  47764. hasPropModeValue
  47765. ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
  47766. : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  47767. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  47768. var suffix = toValue ? 'Span' : 'ValueSpan';
  47769. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  47770. for (var i = 0; i < 2; i++) {
  47771. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  47772. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  47773. }
  47774. }
  47775. return {
  47776. valueWindow: valueWindow,
  47777. percentWindow: percentWindow
  47778. };
  47779. },
  47780. /**
  47781. * Notice: reset should not be called before series.restoreData() called,
  47782. * so it is recommanded to be called in "process stage" but not "model init
  47783. * stage".
  47784. *
  47785. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47786. */
  47787. reset: function (dataZoomModel) {
  47788. if (dataZoomModel !== this._dataZoomModel) {
  47789. return;
  47790. }
  47791. var targetSeries = this.getTargetSeriesModels();
  47792. // Culculate data window and data extent, and record them.
  47793. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  47794. // this.hasSeriesStacked = false;
  47795. // each(targetSeries, function (series) {
  47796. // var data = series.getData();
  47797. // var dataDim = data.mapDimension(this._dimName);
  47798. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  47799. // if (stackedDimension && stackedDimension === dataDim) {
  47800. // this.hasSeriesStacked = true;
  47801. // }
  47802. // }, this);
  47803. // `calculateDataWindow` uses min/maxSpan.
  47804. setMinMaxSpan(this);
  47805. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  47806. this._valueWindow = dataWindow.valueWindow;
  47807. this._percentWindow = dataWindow.percentWindow;
  47808. // Update axis setting then.
  47809. setAxisModel(this);
  47810. },
  47811. /**
  47812. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47813. */
  47814. restore: function (dataZoomModel) {
  47815. if (dataZoomModel !== this._dataZoomModel) {
  47816. return;
  47817. }
  47818. this._valueWindow = this._percentWindow = null;
  47819. setAxisModel(this, true);
  47820. },
  47821. /**
  47822. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  47823. */
  47824. filterData: function (dataZoomModel, api) {
  47825. if (dataZoomModel !== this._dataZoomModel) {
  47826. return;
  47827. }
  47828. var axisDim = this._dimName;
  47829. var seriesModels = this.getTargetSeriesModels();
  47830. var filterMode = dataZoomModel.get('filterMode');
  47831. var valueWindow = this._valueWindow;
  47832. if (filterMode === 'none') {
  47833. return;
  47834. }
  47835. // FIXME
  47836. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  47837. // with NaN data, NaN will be filtered and stack will be wrong.
  47838. // So we need to force the mode to be set empty.
  47839. // In fect, it is not a big deal that do not support filterMode-'filter'
  47840. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  47841. // selection" some day, which might need "adapt to data extent on the
  47842. // otherAxis", which is disabled by filterMode-'empty'.
  47843. // But currently, stack has been fixed to based on value but not index,
  47844. // so this is not an issue any more.
  47845. // var otherAxisModel = this.getOtherAxisModel();
  47846. // if (dataZoomModel.get('$fromToolbox')
  47847. // && otherAxisModel
  47848. // && otherAxisModel.hasSeriesStacked
  47849. // ) {
  47850. // filterMode = 'empty';
  47851. // }
  47852. // TODO
  47853. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  47854. each$13(seriesModels, function (seriesModel) {
  47855. var seriesData = seriesModel.getData();
  47856. var dataDims = seriesData.mapDimension(axisDim, true);
  47857. if (!dataDims.length) {
  47858. return;
  47859. }
  47860. if (filterMode === 'weakFilter') {
  47861. seriesData.filterSelf(function (dataIndex) {
  47862. var leftOut;
  47863. var rightOut;
  47864. var hasValue;
  47865. for (var i = 0; i < dataDims.length; i++) {
  47866. var value = seriesData.get(dataDims[i], dataIndex);
  47867. var thisHasValue = !isNaN(value);
  47868. var thisLeftOut = value < valueWindow[0];
  47869. var thisRightOut = value > valueWindow[1];
  47870. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  47871. return true;
  47872. }
  47873. thisHasValue && (hasValue = true);
  47874. thisLeftOut && (leftOut = true);
  47875. thisRightOut && (rightOut = true);
  47876. }
  47877. // If both left out and right out, do not filter.
  47878. return hasValue && leftOut && rightOut;
  47879. });
  47880. }
  47881. else {
  47882. each$13(dataDims, function (dim) {
  47883. if (filterMode === 'empty') {
  47884. seriesModel.setData(
  47885. seriesData = seriesData.map(dim, function (value) {
  47886. return !isInWindow(value) ? NaN : value;
  47887. })
  47888. );
  47889. }
  47890. else {
  47891. var range = {};
  47892. range[dim] = valueWindow;
  47893. // console.time('select');
  47894. seriesData.selectRange(range);
  47895. // console.timeEnd('select');
  47896. }
  47897. });
  47898. }
  47899. each$13(dataDims, function (dim) {
  47900. seriesData.setApproximateExtent(valueWindow, dim);
  47901. });
  47902. });
  47903. function isInWindow(value) {
  47904. return value >= valueWindow[0] && value <= valueWindow[1];
  47905. }
  47906. }
  47907. };
  47908. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  47909. var dataExtent = [Infinity, -Infinity];
  47910. each$13(seriesModels, function (seriesModel) {
  47911. var seriesData = seriesModel.getData();
  47912. if (seriesData) {
  47913. each$13(seriesData.mapDimension(axisDim, true), function (dim) {
  47914. var seriesExtent = seriesData.getApproximateExtent(dim);
  47915. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  47916. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  47917. });
  47918. }
  47919. });
  47920. if (dataExtent[1] < dataExtent[0]) {
  47921. dataExtent = [NaN, NaN];
  47922. }
  47923. // It is important to get "consistent" extent when more then one axes is
  47924. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  47925. // when zooming. But it is difficult to know what is "consistent", considering
  47926. // axes have different type or even different meanings (For example, two
  47927. // time axes are used to compare data of the same date in different years).
  47928. // So basically dataZoom just obtains extent by series.data (in category axis
  47929. // extent can be obtained from axis.data).
  47930. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  47931. // consistent.
  47932. fixExtentByAxis(axisProxy, dataExtent);
  47933. return dataExtent;
  47934. }
  47935. function fixExtentByAxis(axisProxy, dataExtent) {
  47936. var axisModel = axisProxy.getAxisModel();
  47937. var min = axisModel.getMin(true);
  47938. // For category axis, if min/max/scale are not set, extent is determined
  47939. // by axis.data by default.
  47940. var isCategoryAxis = axisModel.get('type') === 'category';
  47941. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  47942. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  47943. dataExtent[0] = min;
  47944. }
  47945. else if (isCategoryAxis) {
  47946. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  47947. }
  47948. var max = axisModel.getMax(true);
  47949. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  47950. dataExtent[1] = max;
  47951. }
  47952. else if (isCategoryAxis) {
  47953. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  47954. }
  47955. if (!axisModel.get('scale', true)) {
  47956. dataExtent[0] > 0 && (dataExtent[0] = 0);
  47957. dataExtent[1] < 0 && (dataExtent[1] = 0);
  47958. }
  47959. // For value axis, if min/max/scale are not set, we just use the extent obtained
  47960. // by series data, which may be a little different from the extent calculated by
  47961. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  47962. // little when zooming. So it will not be fixed until some users require it strongly.
  47963. return dataExtent;
  47964. }
  47965. function setAxisModel(axisProxy, isRestore) {
  47966. var axisModel = axisProxy.getAxisModel();
  47967. var percentWindow = axisProxy._percentWindow;
  47968. var valueWindow = axisProxy._valueWindow;
  47969. if (!percentWindow) {
  47970. return;
  47971. }
  47972. // [0, 500]: arbitrary value, guess axis extent.
  47973. var precision = getPixelPrecision(valueWindow, [0, 500]);
  47974. precision = Math.min(precision, 20);
  47975. // isRestore or isFull
  47976. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  47977. axisModel.setRange(
  47978. useOrigin ? null : +valueWindow[0].toFixed(precision),
  47979. useOrigin ? null : +valueWindow[1].toFixed(precision)
  47980. );
  47981. }
  47982. function setMinMaxSpan(axisProxy) {
  47983. var minMaxSpan = axisProxy._minMaxSpan = {};
  47984. var dataZoomModel = axisProxy._dataZoomModel;
  47985. var dataExtent = axisProxy._dataExtent;
  47986. each$13(['min', 'max'], function (minMax) {
  47987. var percentSpan = dataZoomModel.get(minMax + 'Span');
  47988. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  47989. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan));
  47990. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  47991. if (valueSpan != null) {
  47992. percentSpan = linearMap(
  47993. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  47994. );
  47995. }
  47996. else if (percentSpan != null) {
  47997. valueSpan = linearMap(
  47998. percentSpan, [0, 100], dataExtent, true
  47999. ) - dataExtent[0];
  48000. }
  48001. minMaxSpan[minMax + 'Span'] = percentSpan;
  48002. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  48003. });
  48004. }
  48005. /*
  48006. * Licensed to the Apache Software Foundation (ASF) under one
  48007. * or more contributor license agreements. See the NOTICE file
  48008. * distributed with this work for additional information
  48009. * regarding copyright ownership. The ASF licenses this file
  48010. * to you under the Apache License, Version 2.0 (the
  48011. * "License"); you may not use this file except in compliance
  48012. * with the License. You may obtain a copy of the License at
  48013. *
  48014. * http://www.apache.org/licenses/LICENSE-2.0
  48015. *
  48016. * Unless required by applicable law or agreed to in writing,
  48017. * software distributed under the License is distributed on an
  48018. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48019. * KIND, either express or implied. See the License for the
  48020. * specific language governing permissions and limitations
  48021. * under the License.
  48022. */
  48023. var each$12 = each$1;
  48024. var eachAxisDim = eachAxisDim$1;
  48025. var DataZoomModel = extendComponentModel({
  48026. type: 'dataZoom',
  48027. dependencies: [
  48028. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  48029. ],
  48030. /**
  48031. * @protected
  48032. */
  48033. defaultOption: {
  48034. zlevel: 0,
  48035. z: 4, // Higher than normal component (z: 2).
  48036. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  48037. xAxisIndex: null, // Default the first horizontal category axis.
  48038. yAxisIndex: null, // Default the first vertical category axis.
  48039. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  48040. // 'filter': data items which are out of window will be removed. This option is
  48041. // applicable when filtering outliers. For each data item, it will be
  48042. // filtered if one of the relevant dimensions is out of the window.
  48043. // 'weakFilter': data items which are out of window will be removed. This option
  48044. // is applicable when filtering outliers. For each data item, it will be
  48045. // filtered only if all of the relevant dimensions are out of the same
  48046. // side of the window.
  48047. // 'empty': data items which are out of window will be set to empty.
  48048. // This option is applicable when user should not neglect
  48049. // that there are some data items out of window.
  48050. // 'none': Do not filter.
  48051. // Taking line chart as an example, line will be broken in
  48052. // the filtered points when filterModel is set to 'empty', but
  48053. // be connected when set to 'filter'.
  48054. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  48055. // default 100. Do not throttle when use null/undefined.
  48056. // If animation === true and animationDurationUpdate > 0,
  48057. // default value is 100, otherwise 20.
  48058. start: 0, // Start percent. 0 ~ 100
  48059. end: 100, // End percent. 0 ~ 100
  48060. startValue: null, // Start value. If startValue specified, start is ignored.
  48061. endValue: null, // End value. If endValue specified, end is ignored.
  48062. minSpan: null, // 0 ~ 100
  48063. maxSpan: null, // 0 ~ 100
  48064. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  48065. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  48066. rangeMode: null // Array, can be 'value' or 'percent'.
  48067. },
  48068. /**
  48069. * @override
  48070. */
  48071. init: function (option, parentModel, ecModel) {
  48072. /**
  48073. * key like x_0, y_1
  48074. * @private
  48075. * @type {Object}
  48076. */
  48077. this._dataIntervalByAxis = {};
  48078. /**
  48079. * @private
  48080. */
  48081. this._dataInfo = {};
  48082. /**
  48083. * key like x_0, y_1
  48084. * @private
  48085. */
  48086. this._axisProxies = {};
  48087. /**
  48088. * @readOnly
  48089. */
  48090. this.textStyleModel;
  48091. /**
  48092. * @private
  48093. */
  48094. this._autoThrottle = true;
  48095. /**
  48096. * It is `[rangeModeForMin, rangeModeForMax]`.
  48097. * The optional values for `rangeMode`:
  48098. * + `'value'` mode: the axis extent will always be determined by
  48099. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  48100. * how data like and how `axis.min` and `axis.max` are.
  48101. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  48102. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  48103. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  48104. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  48105. *
  48106. * For example, when users are using dynamic data (update data periodically via `setOption`),
  48107. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  48108. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  48109. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  48110. *
  48111. * @private
  48112. */
  48113. this._rangePropMode = ['percent', 'percent'];
  48114. var inputRawOption = retrieveRawOption(option);
  48115. /**
  48116. * Suppose a "main process" start at the point that model prepared (that is,
  48117. * model initialized or merged or method called in `action`).
  48118. * We should keep the `main process` idempotent, that is, given a set of values
  48119. * on `option`, we get the same result.
  48120. *
  48121. * But sometimes, values on `option` will be updated for providing users
  48122. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  48123. * should not be the base/input of the `main process`.
  48124. *
  48125. * So in that case we should save and keep the input of the `main process`
  48126. * separately, called `settledOption`.
  48127. *
  48128. * For example, consider the case:
  48129. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  48130. * where the original input `option.startValue`, `option.endValue` are earsed by
  48131. * calculated value.
  48132. * (Step)2) click the legend to hide and show a series,
  48133. * where the new range is calculated by the earsed `startValue` and `endValue`,
  48134. * which brings incorrect result.
  48135. *
  48136. * @readOnly
  48137. */
  48138. this.settledOption = inputRawOption;
  48139. this.mergeDefaultAndTheme(option, ecModel);
  48140. this.doInit(inputRawOption);
  48141. },
  48142. /**
  48143. * @override
  48144. */
  48145. mergeOption: function (newOption) {
  48146. var inputRawOption = retrieveRawOption(newOption);
  48147. //FIX #2591
  48148. merge(this.option, newOption, true);
  48149. merge(this.settledOption, inputRawOption, true);
  48150. this.doInit(inputRawOption);
  48151. },
  48152. /**
  48153. * @protected
  48154. */
  48155. doInit: function (inputRawOption) {
  48156. var thisOption = this.option;
  48157. // Disable realtime view update if canvas is not supported.
  48158. if (!env$1.canvasSupported) {
  48159. thisOption.realtime = false;
  48160. }
  48161. this._setDefaultThrottle(inputRawOption);
  48162. updateRangeUse(this, inputRawOption);
  48163. var settledOption = this.settledOption;
  48164. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48165. // start/end has higher priority over startValue/endValue if they
  48166. // both set, but we should make chart.setOption({endValue: 1000})
  48167. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  48168. if (this._rangePropMode[index] === 'value') {
  48169. thisOption[names[0]] = settledOption[names[0]] = null;
  48170. }
  48171. // Otherwise do nothing and use the merge result.
  48172. }, this);
  48173. this.textStyleModel = this.getModel('textStyle');
  48174. this._resetTarget();
  48175. this._giveAxisProxies();
  48176. },
  48177. /**
  48178. * @private
  48179. */
  48180. _giveAxisProxies: function () {
  48181. var axisProxies = this._axisProxies;
  48182. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  48183. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  48184. // If exists, share axisProxy with other dataZoomModels.
  48185. var axisProxy = axisModel.__dzAxisProxy || (
  48186. // Use the first dataZoomModel as the main model of axisProxy.
  48187. axisModel.__dzAxisProxy = new AxisProxy(
  48188. dimNames.name, axisIndex, this, ecModel
  48189. )
  48190. );
  48191. // FIXME
  48192. // dispose __dzAxisProxy
  48193. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  48194. }, this);
  48195. },
  48196. /**
  48197. * @private
  48198. */
  48199. _resetTarget: function () {
  48200. var thisOption = this.option;
  48201. var autoMode = this._judgeAutoMode();
  48202. eachAxisDim(function (dimNames) {
  48203. var axisIndexName = dimNames.axisIndex;
  48204. thisOption[axisIndexName] = normalizeToArray(
  48205. thisOption[axisIndexName]
  48206. );
  48207. }, this);
  48208. if (autoMode === 'axisIndex') {
  48209. this._autoSetAxisIndex();
  48210. }
  48211. else if (autoMode === 'orient') {
  48212. this._autoSetOrient();
  48213. }
  48214. },
  48215. /**
  48216. * @private
  48217. */
  48218. _judgeAutoMode: function () {
  48219. // Auto set only works for setOption at the first time.
  48220. // The following is user's reponsibility. So using merged
  48221. // option is OK.
  48222. var thisOption = this.option;
  48223. var hasIndexSpecified = false;
  48224. eachAxisDim(function (dimNames) {
  48225. // When user set axisIndex as a empty array, we think that user specify axisIndex
  48226. // but do not want use auto mode. Because empty array may be encountered when
  48227. // some error occured.
  48228. if (thisOption[dimNames.axisIndex] != null) {
  48229. hasIndexSpecified = true;
  48230. }
  48231. }, this);
  48232. var orient = thisOption.orient;
  48233. if (orient == null && hasIndexSpecified) {
  48234. return 'orient';
  48235. }
  48236. else if (!hasIndexSpecified) {
  48237. if (orient == null) {
  48238. thisOption.orient = 'horizontal';
  48239. }
  48240. return 'axisIndex';
  48241. }
  48242. },
  48243. /**
  48244. * @private
  48245. */
  48246. _autoSetAxisIndex: function () {
  48247. var autoAxisIndex = true;
  48248. var orient = this.get('orient', true);
  48249. var thisOption = this.option;
  48250. var dependentModels = this.dependentModels;
  48251. if (autoAxisIndex) {
  48252. // Find axis that parallel to dataZoom as default.
  48253. var dimName = orient === 'vertical' ? 'y' : 'x';
  48254. if (dependentModels[dimName + 'Axis'].length) {
  48255. thisOption[dimName + 'AxisIndex'] = [0];
  48256. autoAxisIndex = false;
  48257. }
  48258. else {
  48259. each$12(dependentModels.singleAxis, function (singleAxisModel) {
  48260. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  48261. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  48262. autoAxisIndex = false;
  48263. }
  48264. });
  48265. }
  48266. }
  48267. if (autoAxisIndex) {
  48268. // Find the first category axis as default. (consider polar)
  48269. eachAxisDim(function (dimNames) {
  48270. if (!autoAxisIndex) {
  48271. return;
  48272. }
  48273. var axisIndices = [];
  48274. var axisModels = this.dependentModels[dimNames.axis];
  48275. if (axisModels.length && !axisIndices.length) {
  48276. for (var i = 0, len = axisModels.length; i < len; i++) {
  48277. if (axisModels[i].get('type') === 'category') {
  48278. axisIndices.push(i);
  48279. }
  48280. }
  48281. }
  48282. thisOption[dimNames.axisIndex] = axisIndices;
  48283. if (axisIndices.length) {
  48284. autoAxisIndex = false;
  48285. }
  48286. }, this);
  48287. }
  48288. if (autoAxisIndex) {
  48289. // FIXME
  48290. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  48291. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  48292. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  48293. // dataZoom component auto adopts series that reference to
  48294. // both xAxis and yAxis which type is 'value'.
  48295. this.ecModel.eachSeries(function (seriesModel) {
  48296. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  48297. eachAxisDim(function (dimNames) {
  48298. var axisIndices = thisOption[dimNames.axisIndex];
  48299. var axisIndex = seriesModel.get(dimNames.axisIndex);
  48300. var axisId = seriesModel.get(dimNames.axisId);
  48301. var axisModel = seriesModel.ecModel.queryComponents({
  48302. mainType: dimNames.axis,
  48303. index: axisIndex,
  48304. id: axisId
  48305. })[0];
  48306. if (__DEV__) {
  48307. if (!axisModel) {
  48308. throw new Error(
  48309. dimNames.axis + ' "' + retrieve(
  48310. axisIndex,
  48311. axisId,
  48312. 0
  48313. ) + '" not found'
  48314. );
  48315. }
  48316. }
  48317. axisIndex = axisModel.componentIndex;
  48318. if (indexOf(axisIndices, axisIndex) < 0) {
  48319. axisIndices.push(axisIndex);
  48320. }
  48321. });
  48322. }
  48323. }, this);
  48324. }
  48325. },
  48326. /**
  48327. * @private
  48328. */
  48329. _autoSetOrient: function () {
  48330. var dim;
  48331. // Find the first axis
  48332. this.eachTargetAxis(function (dimNames) {
  48333. !dim && (dim = dimNames.name);
  48334. }, this);
  48335. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  48336. },
  48337. /**
  48338. * @private
  48339. */
  48340. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  48341. // FIXME
  48342. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  48343. // 例如series.type === scatter时。
  48344. var is = true;
  48345. eachAxisDim(function (dimNames) {
  48346. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  48347. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  48348. if (!axisModel || axisModel.get('type') !== axisType) {
  48349. is = false;
  48350. }
  48351. }, this);
  48352. return is;
  48353. },
  48354. /**
  48355. * @private
  48356. */
  48357. _setDefaultThrottle: function (inputRawOption) {
  48358. // When first time user set throttle, auto throttle ends.
  48359. if (inputRawOption.hasOwnProperty('throttle')) {
  48360. this._autoThrottle = false;
  48361. }
  48362. if (this._autoThrottle) {
  48363. var globalOption = this.ecModel.option;
  48364. this.option.throttle = (
  48365. globalOption.animation && globalOption.animationDurationUpdate > 0
  48366. ) ? 100 : 20;
  48367. }
  48368. },
  48369. /**
  48370. * @public
  48371. */
  48372. getFirstTargetAxisModel: function () {
  48373. var firstAxisModel;
  48374. eachAxisDim(function (dimNames) {
  48375. if (firstAxisModel == null) {
  48376. var indices = this.get(dimNames.axisIndex);
  48377. if (indices.length) {
  48378. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  48379. }
  48380. }
  48381. }, this);
  48382. return firstAxisModel;
  48383. },
  48384. /**
  48385. * @public
  48386. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  48387. */
  48388. eachTargetAxis: function (callback, context) {
  48389. var ecModel = this.ecModel;
  48390. eachAxisDim(function (dimNames) {
  48391. each$12(
  48392. this.get(dimNames.axisIndex),
  48393. function (axisIndex) {
  48394. callback.call(context, dimNames, axisIndex, this, ecModel);
  48395. },
  48396. this
  48397. );
  48398. }, this);
  48399. },
  48400. /**
  48401. * @param {string} dimName
  48402. * @param {number} axisIndex
  48403. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  48404. */
  48405. getAxisProxy: function (dimName, axisIndex) {
  48406. return this._axisProxies[dimName + '_' + axisIndex];
  48407. },
  48408. /**
  48409. * @param {string} dimName
  48410. * @param {number} axisIndex
  48411. * @return {module:echarts/model/Model} If not found, return null/undefined.
  48412. */
  48413. getAxisModel: function (dimName, axisIndex) {
  48414. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  48415. return axisProxy && axisProxy.getAxisModel();
  48416. },
  48417. /**
  48418. * If not specified, set to undefined.
  48419. *
  48420. * @public
  48421. * @param {Object} opt
  48422. * @param {number} [opt.start]
  48423. * @param {number} [opt.end]
  48424. * @param {number} [opt.startValue]
  48425. * @param {number} [opt.endValue]
  48426. */
  48427. setRawRange: function (opt) {
  48428. var thisOption = this.option;
  48429. var settledOption = this.settledOption;
  48430. each$12([['start', 'startValue'], ['end', 'endValue']], function (names) {
  48431. // Consider the pair <start, startValue>:
  48432. // If one has value and the other one is `null/undefined`, we both set them
  48433. // to `settledOption`. This strategy enables the feature to clear the original
  48434. // value in `settledOption` to `null/undefined`.
  48435. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  48436. // and keep `settledOption` with the original value. This strategy enables users to
  48437. // only set <end or endValue> but not set <start or startValue> when calling
  48438. // `dispatchAction`.
  48439. // The pair <end, endValue> is treated in the same way.
  48440. if (opt[names[0]] != null || opt[names[1]] != null) {
  48441. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  48442. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  48443. }
  48444. }, this);
  48445. updateRangeUse(this, opt);
  48446. },
  48447. /**
  48448. * @public
  48449. * @param {Object} opt
  48450. * @param {number} [opt.start]
  48451. * @param {number} [opt.end]
  48452. * @param {number} [opt.startValue]
  48453. * @param {number} [opt.endValue]
  48454. */
  48455. setCalculatedRange: function (opt) {
  48456. var option = this.option;
  48457. each$12(['start', 'startValue', 'end', 'endValue'], function (name) {
  48458. option[name] = opt[name];
  48459. });
  48460. },
  48461. /**
  48462. * @public
  48463. * @return {Array.<number>} [startPercent, endPercent]
  48464. */
  48465. getPercentRange: function () {
  48466. var axisProxy = this.findRepresentativeAxisProxy();
  48467. if (axisProxy) {
  48468. return axisProxy.getDataPercentWindow();
  48469. }
  48470. },
  48471. /**
  48472. * @public
  48473. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  48474. *
  48475. * @param {string} [axisDimName]
  48476. * @param {number} [axisIndex]
  48477. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  48478. */
  48479. getValueRange: function (axisDimName, axisIndex) {
  48480. if (axisDimName == null && axisIndex == null) {
  48481. var axisProxy = this.findRepresentativeAxisProxy();
  48482. if (axisProxy) {
  48483. return axisProxy.getDataValueWindow();
  48484. }
  48485. }
  48486. else {
  48487. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  48488. }
  48489. },
  48490. /**
  48491. * @public
  48492. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  48493. * corresponding to the axisModel
  48494. * @return {module:echarts/component/dataZoom/AxisProxy}
  48495. */
  48496. findRepresentativeAxisProxy: function (axisModel) {
  48497. if (axisModel) {
  48498. return axisModel.__dzAxisProxy;
  48499. }
  48500. // Find the first hosted axisProxy
  48501. var axisProxies = this._axisProxies;
  48502. for (var key in axisProxies) {
  48503. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  48504. return axisProxies[key];
  48505. }
  48506. }
  48507. // If no hosted axis find not hosted axisProxy.
  48508. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  48509. // and the option.start or option.end settings are different. The percentRange
  48510. // should follow axisProxy.
  48511. // (We encounter this problem in toolbox data zoom.)
  48512. for (var key in axisProxies) {
  48513. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  48514. return axisProxies[key];
  48515. }
  48516. }
  48517. },
  48518. /**
  48519. * @return {Array.<string>}
  48520. */
  48521. getRangePropMode: function () {
  48522. return this._rangePropMode.slice();
  48523. }
  48524. });
  48525. /**
  48526. * Retrieve the those raw params from option, which will be cached separately.
  48527. * becasue they will be overwritten by normalized/calculated values in the main
  48528. * process.
  48529. */
  48530. function retrieveRawOption(option) {
  48531. var ret = {};
  48532. each$12(
  48533. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  48534. function (name) {
  48535. option.hasOwnProperty(name) && (ret[name] = option[name]);
  48536. }
  48537. );
  48538. return ret;
  48539. }
  48540. function updateRangeUse(dataZoomModel, inputRawOption) {
  48541. var rangePropMode = dataZoomModel._rangePropMode;
  48542. var rangeModeInOption = dataZoomModel.get('rangeMode');
  48543. each$12([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  48544. var percentSpecified = inputRawOption[names[0]] != null;
  48545. var valueSpecified = inputRawOption[names[1]] != null;
  48546. if (percentSpecified && !valueSpecified) {
  48547. rangePropMode[index] = 'percent';
  48548. }
  48549. else if (!percentSpecified && valueSpecified) {
  48550. rangePropMode[index] = 'value';
  48551. }
  48552. else if (rangeModeInOption) {
  48553. rangePropMode[index] = rangeModeInOption[index];
  48554. }
  48555. else if (percentSpecified) { // percentSpecified && valueSpecified
  48556. rangePropMode[index] = 'percent';
  48557. }
  48558. // else remain its original setting.
  48559. });
  48560. }
  48561. /*
  48562. * Licensed to the Apache Software Foundation (ASF) under one
  48563. * or more contributor license agreements. See the NOTICE file
  48564. * distributed with this work for additional information
  48565. * regarding copyright ownership. The ASF licenses this file
  48566. * to you under the Apache License, Version 2.0 (the
  48567. * "License"); you may not use this file except in compliance
  48568. * with the License. You may obtain a copy of the License at
  48569. *
  48570. * http://www.apache.org/licenses/LICENSE-2.0
  48571. *
  48572. * Unless required by applicable law or agreed to in writing,
  48573. * software distributed under the License is distributed on an
  48574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48575. * KIND, either express or implied. See the License for the
  48576. * specific language governing permissions and limitations
  48577. * under the License.
  48578. */
  48579. var DataZoomView = Component$1.extend({
  48580. type: 'dataZoom',
  48581. render: function (dataZoomModel, ecModel, api, payload) {
  48582. this.dataZoomModel = dataZoomModel;
  48583. this.ecModel = ecModel;
  48584. this.api = api;
  48585. },
  48586. /**
  48587. * Find the first target coordinate system.
  48588. *
  48589. * @protected
  48590. * @return {Object} {
  48591. * grid: [
  48592. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  48593. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  48594. * ...
  48595. * ], // cartesians must not be null/undefined.
  48596. * polar: [
  48597. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  48598. * ...
  48599. * ], // polars must not be null/undefined.
  48600. * singleAxis: [
  48601. * {model: coord0, axisModels: [], coordIndex: 0}
  48602. * ]
  48603. */
  48604. getTargetCoordInfo: function () {
  48605. var dataZoomModel = this.dataZoomModel;
  48606. var ecModel = this.ecModel;
  48607. var coordSysLists = {};
  48608. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  48609. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  48610. if (axisModel) {
  48611. var coordModel = axisModel.getCoordSysModel();
  48612. coordModel && save(
  48613. coordModel,
  48614. axisModel,
  48615. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  48616. coordModel.componentIndex
  48617. );
  48618. }
  48619. }, this);
  48620. function save(coordModel, axisModel, store, coordIndex) {
  48621. var item;
  48622. for (var i = 0; i < store.length; i++) {
  48623. if (store[i].model === coordModel) {
  48624. item = store[i];
  48625. break;
  48626. }
  48627. }
  48628. if (!item) {
  48629. store.push(item = {
  48630. model: coordModel, axisModels: [], coordIndex: coordIndex
  48631. });
  48632. }
  48633. item.axisModels.push(axisModel);
  48634. }
  48635. return coordSysLists;
  48636. }
  48637. });
  48638. /*
  48639. * Licensed to the Apache Software Foundation (ASF) under one
  48640. * or more contributor license agreements. See the NOTICE file
  48641. * distributed with this work for additional information
  48642. * regarding copyright ownership. The ASF licenses this file
  48643. * to you under the Apache License, Version 2.0 (the
  48644. * "License"); you may not use this file except in compliance
  48645. * with the License. You may obtain a copy of the License at
  48646. *
  48647. * http://www.apache.org/licenses/LICENSE-2.0
  48648. *
  48649. * Unless required by applicable law or agreed to in writing,
  48650. * software distributed under the License is distributed on an
  48651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48652. * KIND, either express or implied. See the License for the
  48653. * specific language governing permissions and limitations
  48654. * under the License.
  48655. */
  48656. var SliderZoomModel = DataZoomModel.extend({
  48657. type: 'dataZoom.slider',
  48658. layoutMode: 'box',
  48659. /**
  48660. * @protected
  48661. */
  48662. defaultOption: {
  48663. show: true,
  48664. // ph => placeholder. Using placehoder here because
  48665. // deault value can only be drived in view stage.
  48666. right: 'ph', // Default align to grid rect.
  48667. top: 'ph', // Default align to grid rect.
  48668. width: 'ph', // Default align to grid rect.
  48669. height: 'ph', // Default align to grid rect.
  48670. left: null, // Default align to grid rect.
  48671. bottom: null, // Default align to grid rect.
  48672. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  48673. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  48674. // highest priority, remain for compatibility of
  48675. // previous version, but not recommended any more.
  48676. dataBackground: {
  48677. lineStyle: {
  48678. color: '#2f4554',
  48679. width: 0.5,
  48680. opacity: 0.3
  48681. },
  48682. areaStyle: {
  48683. color: 'rgba(47,69,84,0.3)',
  48684. opacity: 0.3
  48685. }
  48686. },
  48687. borderColor: '#ddd', // border color of the box. For compatibility,
  48688. // if dataBackgroundColor is set, borderColor
  48689. // is ignored.
  48690. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  48691. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  48692. // 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',
  48693. /* eslint-disable */
  48694. 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',
  48695. /* eslint-enable */
  48696. // Percent of the slider height
  48697. handleSize: '100%',
  48698. handleStyle: {
  48699. color: '#a7b7cc'
  48700. },
  48701. labelPrecision: null,
  48702. labelFormatter: null,
  48703. showDetail: true,
  48704. showDataShadow: 'auto', // Default auto decision.
  48705. realtime: true,
  48706. zoomLock: false, // Whether disable zoom.
  48707. textStyle: {
  48708. color: '#333'
  48709. }
  48710. }
  48711. });
  48712. /*
  48713. * Licensed to the Apache Software Foundation (ASF) under one
  48714. * or more contributor license agreements. See the NOTICE file
  48715. * distributed with this work for additional information
  48716. * regarding copyright ownership. The ASF licenses this file
  48717. * to you under the Apache License, Version 2.0 (the
  48718. * "License"); you may not use this file except in compliance
  48719. * with the License. You may obtain a copy of the License at
  48720. *
  48721. * http://www.apache.org/licenses/LICENSE-2.0
  48722. *
  48723. * Unless required by applicable law or agreed to in writing,
  48724. * software distributed under the License is distributed on an
  48725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48726. * KIND, either express or implied. See the License for the
  48727. * specific language governing permissions and limitations
  48728. * under the License.
  48729. */
  48730. var Rect$1 = Rect;
  48731. var linearMap$1 = linearMap;
  48732. var asc$2 = asc;
  48733. var bind$3 = bind;
  48734. var each$14 = each$1;
  48735. // Constants
  48736. var DEFAULT_LOCATION_EDGE_GAP = 7;
  48737. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  48738. var DEFAULT_FILLER_SIZE = 30;
  48739. var HORIZONTAL = 'horizontal';
  48740. var VERTICAL = 'vertical';
  48741. var LABEL_GAP = 5;
  48742. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  48743. var SliderZoomView = DataZoomView.extend({
  48744. type: 'dataZoom.slider',
  48745. init: function (ecModel, api) {
  48746. /**
  48747. * @private
  48748. * @type {Object}
  48749. */
  48750. this._displayables = {};
  48751. /**
  48752. * @private
  48753. * @type {string}
  48754. */
  48755. this._orient;
  48756. /**
  48757. * [0, 100]
  48758. * @private
  48759. */
  48760. this._range;
  48761. /**
  48762. * [coord of the first handle, coord of the second handle]
  48763. * @private
  48764. */
  48765. this._handleEnds;
  48766. /**
  48767. * [length, thick]
  48768. * @private
  48769. * @type {Array.<number>}
  48770. */
  48771. this._size;
  48772. /**
  48773. * @private
  48774. * @type {number}
  48775. */
  48776. this._handleWidth;
  48777. /**
  48778. * @private
  48779. * @type {number}
  48780. */
  48781. this._handleHeight;
  48782. /**
  48783. * @private
  48784. */
  48785. this._location;
  48786. /**
  48787. * @private
  48788. */
  48789. this._dragging;
  48790. /**
  48791. * @private
  48792. */
  48793. this._dataShadowInfo;
  48794. this.api = api;
  48795. },
  48796. /**
  48797. * @override
  48798. */
  48799. render: function (dataZoomModel, ecModel, api, payload) {
  48800. SliderZoomView.superApply(this, 'render', arguments);
  48801. createOrUpdate(
  48802. this,
  48803. '_dispatchZoomAction',
  48804. this.dataZoomModel.get('throttle'),
  48805. 'fixRate'
  48806. );
  48807. this._orient = dataZoomModel.get('orient');
  48808. if (this.dataZoomModel.get('show') === false) {
  48809. this.group.removeAll();
  48810. return;
  48811. }
  48812. // Notice: this._resetInterval() should not be executed when payload.type
  48813. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  48814. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  48815. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  48816. this._buildView();
  48817. }
  48818. this._updateView();
  48819. },
  48820. /**
  48821. * @override
  48822. */
  48823. remove: function () {
  48824. SliderZoomView.superApply(this, 'remove', arguments);
  48825. clear(this, '_dispatchZoomAction');
  48826. },
  48827. /**
  48828. * @override
  48829. */
  48830. dispose: function () {
  48831. SliderZoomView.superApply(this, 'dispose', arguments);
  48832. clear(this, '_dispatchZoomAction');
  48833. },
  48834. _buildView: function () {
  48835. var thisGroup = this.group;
  48836. thisGroup.removeAll();
  48837. this._resetLocation();
  48838. this._resetInterval();
  48839. var barGroup = this._displayables.barGroup = new Group();
  48840. this._renderBackground();
  48841. this._renderHandle();
  48842. this._renderDataShadow();
  48843. thisGroup.add(barGroup);
  48844. this._positionGroup();
  48845. },
  48846. /**
  48847. * @private
  48848. */
  48849. _resetLocation: function () {
  48850. var dataZoomModel = this.dataZoomModel;
  48851. var api = this.api;
  48852. // If some of x/y/width/height are not specified,
  48853. // auto-adapt according to target grid.
  48854. var coordRect = this._findCoordRect();
  48855. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  48856. // Default align by coordinate system rect.
  48857. var positionInfo = this._orient === HORIZONTAL
  48858. ? {
  48859. // Why using 'right', because right should be used in vertical,
  48860. // and it is better to be consistent for dealing with position param merge.
  48861. right: ecSize.width - coordRect.x - coordRect.width,
  48862. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  48863. width: coordRect.width,
  48864. height: DEFAULT_FILLER_SIZE
  48865. }
  48866. : { // vertical
  48867. right: DEFAULT_LOCATION_EDGE_GAP,
  48868. top: coordRect.y,
  48869. width: DEFAULT_FILLER_SIZE,
  48870. height: coordRect.height
  48871. };
  48872. // Do not write back to option and replace value 'ph', because
  48873. // the 'ph' value should be recalculated when resize.
  48874. var layoutParams = getLayoutParams(dataZoomModel.option);
  48875. // Replace the placeholder value.
  48876. each$1(['right', 'top', 'width', 'height'], function (name) {
  48877. if (layoutParams[name] === 'ph') {
  48878. layoutParams[name] = positionInfo[name];
  48879. }
  48880. });
  48881. var layoutRect = getLayoutRect(
  48882. layoutParams,
  48883. ecSize,
  48884. dataZoomModel.padding
  48885. );
  48886. this._location = {x: layoutRect.x, y: layoutRect.y};
  48887. this._size = [layoutRect.width, layoutRect.height];
  48888. this._orient === VERTICAL && this._size.reverse();
  48889. },
  48890. /**
  48891. * @private
  48892. */
  48893. _positionGroup: function () {
  48894. var thisGroup = this.group;
  48895. var location = this._location;
  48896. var orient = this._orient;
  48897. // Just use the first axis to determine mapping.
  48898. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  48899. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  48900. var barGroup = this._displayables.barGroup;
  48901. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  48902. // Transform barGroup.
  48903. barGroup.attr(
  48904. (orient === HORIZONTAL && !inverse)
  48905. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  48906. : (orient === HORIZONTAL && inverse)
  48907. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  48908. : (orient === VERTICAL && !inverse)
  48909. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  48910. // Dont use Math.PI, considering shadow direction.
  48911. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  48912. );
  48913. // Position barGroup
  48914. var rect = thisGroup.getBoundingRect([barGroup]);
  48915. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  48916. },
  48917. /**
  48918. * @private
  48919. */
  48920. _getViewExtent: function () {
  48921. return [0, this._size[0]];
  48922. },
  48923. _renderBackground: function () {
  48924. var dataZoomModel = this.dataZoomModel;
  48925. var size = this._size;
  48926. var barGroup = this._displayables.barGroup;
  48927. barGroup.add(new Rect$1({
  48928. silent: true,
  48929. shape: {
  48930. x: 0, y: 0, width: size[0], height: size[1]
  48931. },
  48932. style: {
  48933. fill: dataZoomModel.get('backgroundColor')
  48934. },
  48935. z2: -40
  48936. }));
  48937. // Click panel, over shadow, below handles.
  48938. barGroup.add(new Rect$1({
  48939. shape: {
  48940. x: 0, y: 0, width: size[0], height: size[1]
  48941. },
  48942. style: {
  48943. fill: 'transparent'
  48944. },
  48945. z2: 0,
  48946. onclick: bind(this._onClickPanelClick, this)
  48947. }));
  48948. },
  48949. _renderDataShadow: function () {
  48950. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  48951. if (!info) {
  48952. return;
  48953. }
  48954. var size = this._size;
  48955. var seriesModel = info.series;
  48956. var data = seriesModel.getRawData();
  48957. var otherDim = seriesModel.getShadowDim
  48958. ? seriesModel.getShadowDim() // @see candlestick
  48959. : info.otherDim;
  48960. if (otherDim == null) {
  48961. return;
  48962. }
  48963. var otherDataExtent = data.getDataExtent(otherDim);
  48964. // Nice extent.
  48965. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  48966. otherDataExtent = [
  48967. otherDataExtent[0] - otherOffset,
  48968. otherDataExtent[1] + otherOffset
  48969. ];
  48970. var otherShadowExtent = [0, size[1]];
  48971. var thisShadowExtent = [0, size[0]];
  48972. var areaPoints = [[size[0], 0], [0, 0]];
  48973. var linePoints = [];
  48974. var step = thisShadowExtent[1] / (data.count() - 1);
  48975. var thisCoord = 0;
  48976. // Optimize for large data shadow
  48977. var stride = Math.round(data.count() / size[0]);
  48978. var lastIsEmpty;
  48979. data.each([otherDim], function (value, index) {
  48980. if (stride > 0 && (index % stride)) {
  48981. thisCoord += step;
  48982. return;
  48983. }
  48984. // FIXME
  48985. // Should consider axis.min/axis.max when drawing dataShadow.
  48986. // FIXME
  48987. // 应该使用统一的空判断?还是在list里进行空判断?
  48988. var isEmpty = value == null || isNaN(value) || value === '';
  48989. // See #4235.
  48990. var otherCoord = isEmpty
  48991. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  48992. // Attempt to draw data shadow precisely when there are empty value.
  48993. if (isEmpty && !lastIsEmpty && index) {
  48994. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  48995. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  48996. }
  48997. else if (!isEmpty && lastIsEmpty) {
  48998. areaPoints.push([thisCoord, 0]);
  48999. linePoints.push([thisCoord, 0]);
  49000. }
  49001. areaPoints.push([thisCoord, otherCoord]);
  49002. linePoints.push([thisCoord, otherCoord]);
  49003. thisCoord += step;
  49004. lastIsEmpty = isEmpty;
  49005. });
  49006. var dataZoomModel = this.dataZoomModel;
  49007. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  49008. this._displayables.barGroup.add(new Polygon({
  49009. shape: {points: areaPoints},
  49010. style: defaults(
  49011. {fill: dataZoomModel.get('dataBackgroundColor')},
  49012. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  49013. ),
  49014. silent: true,
  49015. z2: -20
  49016. }));
  49017. this._displayables.barGroup.add(new Polyline({
  49018. shape: {points: linePoints},
  49019. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  49020. silent: true,
  49021. z2: -19
  49022. }));
  49023. },
  49024. _prepareDataShadowInfo: function () {
  49025. var dataZoomModel = this.dataZoomModel;
  49026. var showDataShadow = dataZoomModel.get('showDataShadow');
  49027. if (showDataShadow === false) {
  49028. return;
  49029. }
  49030. // Find a representative series.
  49031. var result;
  49032. var ecModel = this.ecModel;
  49033. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  49034. var seriesModels = dataZoomModel
  49035. .getAxisProxy(dimNames.name, axisIndex)
  49036. .getTargetSeriesModels();
  49037. each$1(seriesModels, function (seriesModel) {
  49038. if (result) {
  49039. return;
  49040. }
  49041. if (showDataShadow !== true && indexOf(
  49042. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  49043. ) < 0
  49044. ) {
  49045. return;
  49046. }
  49047. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  49048. var otherDim = getOtherDim(dimNames.name);
  49049. var otherAxisInverse;
  49050. var coordSys = seriesModel.coordinateSystem;
  49051. if (otherDim != null && coordSys.getOtherAxis) {
  49052. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  49053. }
  49054. otherDim = seriesModel.getData().mapDimension(otherDim);
  49055. result = {
  49056. thisAxis: thisAxis,
  49057. series: seriesModel,
  49058. thisDim: dimNames.name,
  49059. otherDim: otherDim,
  49060. otherAxisInverse: otherAxisInverse
  49061. };
  49062. }, this);
  49063. }, this);
  49064. return result;
  49065. },
  49066. _renderHandle: function () {
  49067. var displaybles = this._displayables;
  49068. var handles = displaybles.handles = [];
  49069. var handleLabels = displaybles.handleLabels = [];
  49070. var barGroup = this._displayables.barGroup;
  49071. var size = this._size;
  49072. var dataZoomModel = this.dataZoomModel;
  49073. barGroup.add(displaybles.filler = new Rect$1({
  49074. draggable: true,
  49075. cursor: getCursor(this._orient),
  49076. drift: bind$3(this._onDragMove, this, 'all'),
  49077. ondragstart: bind$3(this._showDataInfo, this, true),
  49078. ondragend: bind$3(this._onDragEnd, this),
  49079. onmouseover: bind$3(this._showDataInfo, this, true),
  49080. onmouseout: bind$3(this._showDataInfo, this, false),
  49081. style: {
  49082. fill: dataZoomModel.get('fillerColor'),
  49083. textPosition: 'inside'
  49084. }
  49085. }));
  49086. // Frame border.
  49087. barGroup.add(new Rect$1({
  49088. silent: true,
  49089. subPixelOptimize: true,
  49090. shape: {
  49091. x: 0,
  49092. y: 0,
  49093. width: size[0],
  49094. height: size[1]
  49095. },
  49096. style: {
  49097. stroke: dataZoomModel.get('dataBackgroundColor')
  49098. || dataZoomModel.get('borderColor'),
  49099. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  49100. fill: 'rgba(0,0,0,0)'
  49101. }
  49102. }));
  49103. each$14([0, 1], function (handleIndex) {
  49104. var path = createIcon(
  49105. dataZoomModel.get('handleIcon'),
  49106. {
  49107. cursor: getCursor(this._orient),
  49108. draggable: true,
  49109. drift: bind$3(this._onDragMove, this, handleIndex),
  49110. ondragend: bind$3(this._onDragEnd, this),
  49111. onmouseover: bind$3(this._showDataInfo, this, true),
  49112. onmouseout: bind$3(this._showDataInfo, this, false)
  49113. },
  49114. {x: -1, y: 0, width: 2, height: 2}
  49115. );
  49116. var bRect = path.getBoundingRect();
  49117. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  49118. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  49119. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  49120. var handleColor = dataZoomModel.get('handleColor');
  49121. // Compatitable with previous version
  49122. if (handleColor != null) {
  49123. path.style.fill = handleColor;
  49124. }
  49125. barGroup.add(handles[handleIndex] = path);
  49126. var textStyleModel = dataZoomModel.textStyleModel;
  49127. this.group.add(
  49128. handleLabels[handleIndex] = new Text({
  49129. silent: true,
  49130. invisible: true,
  49131. style: {
  49132. x: 0, y: 0, text: '',
  49133. textVerticalAlign: 'middle',
  49134. textAlign: 'center',
  49135. textFill: textStyleModel.getTextColor(),
  49136. textFont: textStyleModel.getFont()
  49137. },
  49138. z2: 10
  49139. }));
  49140. }, this);
  49141. },
  49142. /**
  49143. * @private
  49144. */
  49145. _resetInterval: function () {
  49146. var range = this._range = this.dataZoomModel.getPercentRange();
  49147. var viewExtent = this._getViewExtent();
  49148. this._handleEnds = [
  49149. linearMap$1(range[0], [0, 100], viewExtent, true),
  49150. linearMap$1(range[1], [0, 100], viewExtent, true)
  49151. ];
  49152. },
  49153. /**
  49154. * @private
  49155. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  49156. * @param {number} delta
  49157. * @return {boolean} changed
  49158. */
  49159. _updateInterval: function (handleIndex, delta) {
  49160. var dataZoomModel = this.dataZoomModel;
  49161. var handleEnds = this._handleEnds;
  49162. var viewExtend = this._getViewExtent();
  49163. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  49164. var percentExtent = [0, 100];
  49165. sliderMove(
  49166. delta,
  49167. handleEnds,
  49168. viewExtend,
  49169. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  49170. minMaxSpan.minSpan != null
  49171. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  49172. minMaxSpan.maxSpan != null
  49173. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  49174. );
  49175. var lastRange = this._range;
  49176. var range = this._range = asc$2([
  49177. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  49178. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  49179. ]);
  49180. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  49181. },
  49182. /**
  49183. * @private
  49184. */
  49185. _updateView: function (nonRealtime) {
  49186. var displaybles = this._displayables;
  49187. var handleEnds = this._handleEnds;
  49188. var handleInterval = asc$2(handleEnds.slice());
  49189. var size = this._size;
  49190. each$14([0, 1], function (handleIndex) {
  49191. // Handles
  49192. var handle = displaybles.handles[handleIndex];
  49193. var handleHeight = this._handleHeight;
  49194. handle.attr({
  49195. scale: [handleHeight / 2, handleHeight / 2],
  49196. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  49197. });
  49198. }, this);
  49199. // Filler
  49200. displaybles.filler.setShape({
  49201. x: handleInterval[0],
  49202. y: 0,
  49203. width: handleInterval[1] - handleInterval[0],
  49204. height: size[1]
  49205. });
  49206. this._updateDataInfo(nonRealtime);
  49207. },
  49208. /**
  49209. * @private
  49210. */
  49211. _updateDataInfo: function (nonRealtime) {
  49212. var dataZoomModel = this.dataZoomModel;
  49213. var displaybles = this._displayables;
  49214. var handleLabels = displaybles.handleLabels;
  49215. var orient = this._orient;
  49216. var labelTexts = ['', ''];
  49217. // FIXME
  49218. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  49219. if (dataZoomModel.get('showDetail')) {
  49220. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  49221. if (axisProxy) {
  49222. var axis = axisProxy.getAxisModel().axis;
  49223. var range = this._range;
  49224. var dataInterval = nonRealtime
  49225. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  49226. ? axisProxy.calculateDataWindow({
  49227. start: range[0], end: range[1]
  49228. }).valueWindow
  49229. : axisProxy.getDataValueWindow();
  49230. labelTexts = [
  49231. this._formatLabel(dataInterval[0], axis),
  49232. this._formatLabel(dataInterval[1], axis)
  49233. ];
  49234. }
  49235. }
  49236. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  49237. setLabel.call(this, 0);
  49238. setLabel.call(this, 1);
  49239. function setLabel(handleIndex) {
  49240. // Label
  49241. // Text should not transform by barGroup.
  49242. // Ignore handlers transform
  49243. var barTransform = getTransform(
  49244. displaybles.handles[handleIndex].parent, this.group
  49245. );
  49246. var direction = transformDirection(
  49247. handleIndex === 0 ? 'right' : 'left', barTransform
  49248. );
  49249. var offset = this._handleWidth / 2 + LABEL_GAP;
  49250. var textPoint = applyTransform$1(
  49251. [
  49252. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  49253. this._size[1] / 2
  49254. ],
  49255. barTransform
  49256. );
  49257. handleLabels[handleIndex].setStyle({
  49258. x: textPoint[0],
  49259. y: textPoint[1],
  49260. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  49261. textAlign: orient === HORIZONTAL ? direction : 'center',
  49262. text: labelTexts[handleIndex]
  49263. });
  49264. }
  49265. },
  49266. /**
  49267. * @private
  49268. */
  49269. _formatLabel: function (value, axis) {
  49270. var dataZoomModel = this.dataZoomModel;
  49271. var labelFormatter = dataZoomModel.get('labelFormatter');
  49272. var labelPrecision = dataZoomModel.get('labelPrecision');
  49273. if (labelPrecision == null || labelPrecision === 'auto') {
  49274. labelPrecision = axis.getPixelPrecision();
  49275. }
  49276. var valueStr = (value == null || isNaN(value))
  49277. ? ''
  49278. // FIXME Glue code
  49279. : (axis.type === 'category' || axis.type === 'time')
  49280. ? axis.scale.getLabel(Math.round(value))
  49281. // param of toFixed should less then 20.
  49282. : value.toFixed(Math.min(labelPrecision, 20));
  49283. return isFunction$1(labelFormatter)
  49284. ? labelFormatter(value, valueStr)
  49285. : isString(labelFormatter)
  49286. ? labelFormatter.replace('{value}', valueStr)
  49287. : valueStr;
  49288. },
  49289. /**
  49290. * @private
  49291. * @param {boolean} showOrHide true: show, false: hide
  49292. */
  49293. _showDataInfo: function (showOrHide) {
  49294. // Always show when drgging.
  49295. showOrHide = this._dragging || showOrHide;
  49296. var handleLabels = this._displayables.handleLabels;
  49297. handleLabels[0].attr('invisible', !showOrHide);
  49298. handleLabels[1].attr('invisible', !showOrHide);
  49299. },
  49300. _onDragMove: function (handleIndex, dx, dy, event) {
  49301. this._dragging = true;
  49302. // For mobile device, prevent screen slider on the button.
  49303. stop(event.event);
  49304. // Transform dx, dy to bar coordination.
  49305. var barTransform = this._displayables.barGroup.getLocalTransform();
  49306. var vertex = applyTransform$1([dx, dy], barTransform, true);
  49307. var changed = this._updateInterval(handleIndex, vertex[0]);
  49308. var realtime = this.dataZoomModel.get('realtime');
  49309. this._updateView(!realtime);
  49310. // Avoid dispatch dataZoom repeatly but range not changed,
  49311. // which cause bad visual effect when progressive enabled.
  49312. changed && realtime && this._dispatchZoomAction();
  49313. },
  49314. _onDragEnd: function () {
  49315. this._dragging = false;
  49316. this._showDataInfo(false);
  49317. // While in realtime mode and stream mode, dispatch action when
  49318. // drag end will cause the whole view rerender, which is unnecessary.
  49319. var realtime = this.dataZoomModel.get('realtime');
  49320. !realtime && this._dispatchZoomAction();
  49321. },
  49322. _onClickPanelClick: function (e) {
  49323. var size = this._size;
  49324. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  49325. if (localPoint[0] < 0 || localPoint[0] > size[0]
  49326. || localPoint[1] < 0 || localPoint[1] > size[1]
  49327. ) {
  49328. return;
  49329. }
  49330. var handleEnds = this._handleEnds;
  49331. var center = (handleEnds[0] + handleEnds[1]) / 2;
  49332. var changed = this._updateInterval('all', localPoint[0] - center);
  49333. this._updateView();
  49334. changed && this._dispatchZoomAction();
  49335. },
  49336. /**
  49337. * This action will be throttled.
  49338. * @private
  49339. */
  49340. _dispatchZoomAction: function () {
  49341. var range = this._range;
  49342. this.api.dispatchAction({
  49343. type: 'dataZoom',
  49344. from: this.uid,
  49345. dataZoomId: this.dataZoomModel.id,
  49346. start: range[0],
  49347. end: range[1]
  49348. });
  49349. },
  49350. /**
  49351. * @private
  49352. */
  49353. _findCoordRect: function () {
  49354. // Find the grid coresponding to the first axis referred by dataZoom.
  49355. var rect;
  49356. each$14(this.getTargetCoordInfo(), function (coordInfoList) {
  49357. if (!rect && coordInfoList.length) {
  49358. var coordSys = coordInfoList[0].model.coordinateSystem;
  49359. rect = coordSys.getRect && coordSys.getRect();
  49360. }
  49361. });
  49362. if (!rect) {
  49363. var width = this.api.getWidth();
  49364. var height = this.api.getHeight();
  49365. rect = {
  49366. x: width * 0.2,
  49367. y: height * 0.2,
  49368. width: width * 0.6,
  49369. height: height * 0.6
  49370. };
  49371. }
  49372. return rect;
  49373. }
  49374. });
  49375. function getOtherDim(thisDim) {
  49376. // FIXME
  49377. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  49378. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  49379. return map$$1[thisDim];
  49380. }
  49381. function getCursor(orient) {
  49382. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  49383. }
  49384. /*
  49385. * Licensed to the Apache Software Foundation (ASF) under one
  49386. * or more contributor license agreements. See the NOTICE file
  49387. * distributed with this work for additional information
  49388. * regarding copyright ownership. The ASF licenses this file
  49389. * to you under the Apache License, Version 2.0 (the
  49390. * "License"); you may not use this file except in compliance
  49391. * with the License. You may obtain a copy of the License at
  49392. *
  49393. * http://www.apache.org/licenses/LICENSE-2.0
  49394. *
  49395. * Unless required by applicable law or agreed to in writing,
  49396. * software distributed under the License is distributed on an
  49397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49398. * KIND, either express or implied. See the License for the
  49399. * specific language governing permissions and limitations
  49400. * under the License.
  49401. */
  49402. registerProcessor({
  49403. // `dataZoomProcessor` will only be performed in needed series. Consider if
  49404. // there is a line series and a pie series, it is better not to update the
  49405. // line series if only pie series is needed to be updated.
  49406. getTargetSeries: function (ecModel) {
  49407. var seriesModelMap = createHashMap();
  49408. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49409. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49410. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  49411. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  49412. seriesModelMap.set(seriesModel.uid, seriesModel);
  49413. });
  49414. });
  49415. });
  49416. return seriesModelMap;
  49417. },
  49418. modifyOutputEnd: true,
  49419. // Consider appendData, where filter should be performed. Because data process is
  49420. // in block mode currently, it is not need to worry about that the overallProgress
  49421. // execute every frame.
  49422. overallReset: function (ecModel, api) {
  49423. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49424. // We calculate window and reset axis here but not in model
  49425. // init stage and not after action dispatch handler, because
  49426. // reset should be called after seriesData.restoreData.
  49427. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49428. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  49429. });
  49430. // Caution: data zoom filtering is order sensitive when using
  49431. // percent range and no min/max/scale set on axis.
  49432. // For example, we have dataZoom definition:
  49433. // [
  49434. // {xAxisIndex: 0, start: 30, end: 70},
  49435. // {yAxisIndex: 0, start: 20, end: 80}
  49436. // ]
  49437. // In this case, [20, 80] of y-dataZoom should be based on data
  49438. // that have filtered by x-dataZoom using range of [30, 70],
  49439. // but should not be based on full raw data. Thus sliding
  49440. // x-dataZoom will change both ranges of xAxis and yAxis,
  49441. // while sliding y-dataZoom will only change the range of yAxis.
  49442. // So we should filter x-axis after reset x-axis immediately,
  49443. // and then reset y-axis and filter y-axis.
  49444. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  49445. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  49446. });
  49447. });
  49448. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  49449. // Fullfill all of the range props so that user
  49450. // is able to get them from chart.getOption().
  49451. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  49452. var percentRange = axisProxy.getDataPercentWindow();
  49453. var valueRange = axisProxy.getDataValueWindow();
  49454. dataZoomModel.setCalculatedRange({
  49455. start: percentRange[0],
  49456. end: percentRange[1],
  49457. startValue: valueRange[0],
  49458. endValue: valueRange[1]
  49459. });
  49460. });
  49461. }
  49462. });
  49463. /*
  49464. * Licensed to the Apache Software Foundation (ASF) under one
  49465. * or more contributor license agreements. See the NOTICE file
  49466. * distributed with this work for additional information
  49467. * regarding copyright ownership. The ASF licenses this file
  49468. * to you under the Apache License, Version 2.0 (the
  49469. * "License"); you may not use this file except in compliance
  49470. * with the License. You may obtain a copy of the License at
  49471. *
  49472. * http://www.apache.org/licenses/LICENSE-2.0
  49473. *
  49474. * Unless required by applicable law or agreed to in writing,
  49475. * software distributed under the License is distributed on an
  49476. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49477. * KIND, either express or implied. See the License for the
  49478. * specific language governing permissions and limitations
  49479. * under the License.
  49480. */
  49481. registerAction('dataZoom', function (payload, ecModel) {
  49482. var linkedNodesFinder = createLinkedNodesFinder(
  49483. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  49484. eachAxisDim$1,
  49485. function (model, dimNames) {
  49486. return model.get(dimNames.axisIndex);
  49487. }
  49488. );
  49489. var effectedModels = [];
  49490. ecModel.eachComponent(
  49491. {mainType: 'dataZoom', query: payload},
  49492. function (model, index) {
  49493. effectedModels.push.apply(
  49494. effectedModels, linkedNodesFinder(model).nodes
  49495. );
  49496. }
  49497. );
  49498. each$1(effectedModels, function (dataZoomModel, index) {
  49499. dataZoomModel.setRawRange({
  49500. start: payload.start,
  49501. end: payload.end,
  49502. startValue: payload.startValue,
  49503. endValue: payload.endValue
  49504. });
  49505. });
  49506. });
  49507. /*
  49508. * Licensed to the Apache Software Foundation (ASF) under one
  49509. * or more contributor license agreements. See the NOTICE file
  49510. * distributed with this work for additional information
  49511. * regarding copyright ownership. The ASF licenses this file
  49512. * to you under the Apache License, Version 2.0 (the
  49513. * "License"); you may not use this file except in compliance
  49514. * with the License. You may obtain a copy of the License at
  49515. *
  49516. * http://www.apache.org/licenses/LICENSE-2.0
  49517. *
  49518. * Unless required by applicable law or agreed to in writing,
  49519. * software distributed under the License is distributed on an
  49520. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49521. * KIND, either express or implied. See the License for the
  49522. * specific language governing permissions and limitations
  49523. * under the License.
  49524. */
  49525. /*
  49526. * Licensed to the Apache Software Foundation (ASF) under one
  49527. * or more contributor license agreements. See the NOTICE file
  49528. * distributed with this work for additional information
  49529. * regarding copyright ownership. The ASF licenses this file
  49530. * to you under the Apache License, Version 2.0 (the
  49531. * "License"); you may not use this file except in compliance
  49532. * with the License. You may obtain a copy of the License at
  49533. *
  49534. * http://www.apache.org/licenses/LICENSE-2.0
  49535. *
  49536. * Unless required by applicable law or agreed to in writing,
  49537. * software distributed under the License is distributed on an
  49538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49539. * KIND, either express or implied. See the License for the
  49540. * specific language governing permissions and limitations
  49541. * under the License.
  49542. */
  49543. DataZoomModel.extend({
  49544. type: 'dataZoom.inside',
  49545. /**
  49546. * @protected
  49547. */
  49548. defaultOption: {
  49549. disabled: false, // Whether disable this inside zoom.
  49550. zoomLock: false, // Whether disable zoom but only pan.
  49551. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49552. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49553. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49554. preventDefaultMouseMove: true
  49555. }
  49556. });
  49557. /*
  49558. * Licensed to the Apache Software Foundation (ASF) under one
  49559. * or more contributor license agreements. See the NOTICE file
  49560. * distributed with this work for additional information
  49561. * regarding copyright ownership. The ASF licenses this file
  49562. * to you under the Apache License, Version 2.0 (the
  49563. * "License"); you may not use this file except in compliance
  49564. * with the License. You may obtain a copy of the License at
  49565. *
  49566. * http://www.apache.org/licenses/LICENSE-2.0
  49567. *
  49568. * Unless required by applicable law or agreed to in writing,
  49569. * software distributed under the License is distributed on an
  49570. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49571. * KIND, either express or implied. See the License for the
  49572. * specific language governing permissions and limitations
  49573. * under the License.
  49574. */
  49575. var ATTR$1 = '\0_ec_interaction_mutex';
  49576. function take(zr, resourceKey, userKey) {
  49577. var store = getStore(zr);
  49578. store[resourceKey] = userKey;
  49579. }
  49580. function release(zr, resourceKey, userKey) {
  49581. var store = getStore(zr);
  49582. var uKey = store[resourceKey];
  49583. if (uKey === userKey) {
  49584. store[resourceKey] = null;
  49585. }
  49586. }
  49587. function isTaken(zr, resourceKey) {
  49588. return !!getStore(zr)[resourceKey];
  49589. }
  49590. function getStore(zr) {
  49591. return zr[ATTR$1] || (zr[ATTR$1] = {});
  49592. }
  49593. /**
  49594. * payload: {
  49595. * type: 'takeGlobalCursor',
  49596. * key: 'dataZoomSelect', or 'brush', or ...,
  49597. * If no userKey, release global cursor.
  49598. * }
  49599. */
  49600. registerAction(
  49601. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  49602. function () {}
  49603. );
  49604. /*
  49605. * Licensed to the Apache Software Foundation (ASF) under one
  49606. * or more contributor license agreements. See the NOTICE file
  49607. * distributed with this work for additional information
  49608. * regarding copyright ownership. The ASF licenses this file
  49609. * to you under the Apache License, Version 2.0 (the
  49610. * "License"); you may not use this file except in compliance
  49611. * with the License. You may obtain a copy of the License at
  49612. *
  49613. * http://www.apache.org/licenses/LICENSE-2.0
  49614. *
  49615. * Unless required by applicable law or agreed to in writing,
  49616. * software distributed under the License is distributed on an
  49617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49618. * KIND, either express or implied. See the License for the
  49619. * specific language governing permissions and limitations
  49620. * under the License.
  49621. */
  49622. /**
  49623. * @alias module:echarts/component/helper/RoamController
  49624. * @constructor
  49625. * @mixin {module:zrender/mixin/Eventful}
  49626. *
  49627. * @param {module:zrender/zrender~ZRender} zr
  49628. */
  49629. function RoamController(zr) {
  49630. /**
  49631. * @type {Function}
  49632. */
  49633. this.pointerChecker;
  49634. /**
  49635. * @type {module:zrender}
  49636. */
  49637. this._zr = zr;
  49638. /**
  49639. * @type {Object}
  49640. */
  49641. this._opt = {};
  49642. // Avoid two roamController bind the same handler
  49643. var bind$$1 = bind;
  49644. var mousedownHandler = bind$$1(mousedown, this);
  49645. var mousemoveHandler = bind$$1(mousemove, this);
  49646. var mouseupHandler = bind$$1(mouseup, this);
  49647. var mousewheelHandler = bind$$1(mousewheel, this);
  49648. var pinchHandler = bind$$1(pinch, this);
  49649. Eventful.call(this);
  49650. /**
  49651. * @param {Function} pointerChecker
  49652. * input: x, y
  49653. * output: boolean
  49654. */
  49655. this.setPointerChecker = function (pointerChecker) {
  49656. this.pointerChecker = pointerChecker;
  49657. };
  49658. /**
  49659. * Notice: only enable needed types. For example, if 'zoom'
  49660. * is not needed, 'zoom' should not be enabled, otherwise
  49661. * default mousewheel behaviour (scroll page) will be disabled.
  49662. *
  49663. * @param {boolean|string} [controlType=true] Specify the control type,
  49664. * which can be null/undefined or true/false
  49665. * or 'pan/move' or 'zoom'/'scale'
  49666. * @param {Object} [opt]
  49667. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49668. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49669. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49670. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  49671. */
  49672. this.enable = function (controlType, opt) {
  49673. // Disable previous first
  49674. this.disable();
  49675. this._opt = defaults(clone(opt) || {}, {
  49676. zoomOnMouseWheel: true,
  49677. moveOnMouseMove: true,
  49678. // By default, wheel do not trigger move.
  49679. moveOnMouseWheel: false,
  49680. preventDefaultMouseMove: true
  49681. });
  49682. if (controlType == null) {
  49683. controlType = true;
  49684. }
  49685. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  49686. zr.on('mousedown', mousedownHandler);
  49687. zr.on('mousemove', mousemoveHandler);
  49688. zr.on('mouseup', mouseupHandler);
  49689. }
  49690. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  49691. zr.on('mousewheel', mousewheelHandler);
  49692. zr.on('pinch', pinchHandler);
  49693. }
  49694. };
  49695. this.disable = function () {
  49696. zr.off('mousedown', mousedownHandler);
  49697. zr.off('mousemove', mousemoveHandler);
  49698. zr.off('mouseup', mouseupHandler);
  49699. zr.off('mousewheel', mousewheelHandler);
  49700. zr.off('pinch', pinchHandler);
  49701. };
  49702. this.dispose = this.disable;
  49703. this.isDragging = function () {
  49704. return this._dragging;
  49705. };
  49706. this.isPinching = function () {
  49707. return this._pinching;
  49708. };
  49709. }
  49710. mixin(RoamController, Eventful);
  49711. function mousedown(e) {
  49712. if (isMiddleOrRightButtonOnMouseUpDown(e)
  49713. || (e.target && e.target.draggable)
  49714. ) {
  49715. return;
  49716. }
  49717. var x = e.offsetX;
  49718. var y = e.offsetY;
  49719. // Only check on mosedown, but not mousemove.
  49720. // Mouse can be out of target when mouse moving.
  49721. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  49722. this._x = x;
  49723. this._y = y;
  49724. this._dragging = true;
  49725. }
  49726. }
  49727. function mousemove(e) {
  49728. if (!this._dragging
  49729. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  49730. || e.gestureEvent === 'pinch'
  49731. || isTaken(this._zr, 'globalPan')
  49732. ) {
  49733. return;
  49734. }
  49735. var x = e.offsetX;
  49736. var y = e.offsetY;
  49737. var oldX = this._x;
  49738. var oldY = this._y;
  49739. var dx = x - oldX;
  49740. var dy = y - oldY;
  49741. this._x = x;
  49742. this._y = y;
  49743. this._opt.preventDefaultMouseMove && stop(e.event);
  49744. trigger(this, 'pan', 'moveOnMouseMove', e, {
  49745. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  49746. });
  49747. }
  49748. function mouseup(e) {
  49749. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  49750. this._dragging = false;
  49751. }
  49752. }
  49753. function mousewheel(e) {
  49754. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  49755. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  49756. var wheelDelta = e.wheelDelta;
  49757. var absWheelDeltaDelta = Math.abs(wheelDelta);
  49758. var originX = e.offsetX;
  49759. var originY = e.offsetY;
  49760. // wheelDelta maybe -0 in chrome mac.
  49761. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  49762. return;
  49763. }
  49764. // If both `shouldZoom` and `shouldMove` is true, trigger
  49765. // their event both, and the final behavior is determined
  49766. // by event listener themselves.
  49767. if (shouldZoom) {
  49768. // Convenience:
  49769. // Mac and VM Windows on Mac: scroll up: zoom out.
  49770. // Windows: scroll up: zoom in.
  49771. // FIXME: Should do more test in different environment.
  49772. // wheelDelta is too complicated in difference nvironment
  49773. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  49774. // although it has been normallized by zrender.
  49775. // wheelDelta of mouse wheel is bigger than touch pad.
  49776. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  49777. var scale = wheelDelta > 0 ? factor : 1 / factor;
  49778. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  49779. scale: scale, originX: originX, originY: originY
  49780. });
  49781. }
  49782. if (shouldMove) {
  49783. // FIXME: Should do more test in different environment.
  49784. var absDelta = Math.abs(wheelDelta);
  49785. // wheelDelta of mouse wheel is bigger than touch pad.
  49786. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  49787. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  49788. scrollDelta: scrollDelta, originX: originX, originY: originY
  49789. });
  49790. }
  49791. }
  49792. function pinch(e) {
  49793. if (isTaken(this._zr, 'globalPan')) {
  49794. return;
  49795. }
  49796. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  49797. checkPointerAndTrigger(this, 'zoom', null, e, {
  49798. scale: scale, originX: e.pinchX, originY: e.pinchY
  49799. });
  49800. }
  49801. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49802. if (controller.pointerChecker
  49803. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  49804. ) {
  49805. // When mouse is out of roamController rect,
  49806. // default befavoius should not be be disabled, otherwise
  49807. // page sliding is disabled, contrary to expectation.
  49808. stop(e.event);
  49809. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  49810. }
  49811. }
  49812. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  49813. // Also provide behavior checker for event listener, for some case that
  49814. // multiple components share one listener.
  49815. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  49816. controller.trigger(eventName, contollerEvent);
  49817. }
  49818. // settings: {
  49819. // zoomOnMouseWheel
  49820. // moveOnMouseMove
  49821. // moveOnMouseWheel
  49822. // }
  49823. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  49824. function isAvailableBehavior(behaviorToCheck, e, settings) {
  49825. var setting = settings[behaviorToCheck];
  49826. return !behaviorToCheck || (
  49827. setting && (!isString(setting) || e.event[setting + 'Key'])
  49828. );
  49829. }
  49830. /*
  49831. * Licensed to the Apache Software Foundation (ASF) under one
  49832. * or more contributor license agreements. See the NOTICE file
  49833. * distributed with this work for additional information
  49834. * regarding copyright ownership. The ASF licenses this file
  49835. * to you under the Apache License, Version 2.0 (the
  49836. * "License"); you may not use this file except in compliance
  49837. * with the License. You may obtain a copy of the License at
  49838. *
  49839. * http://www.apache.org/licenses/LICENSE-2.0
  49840. *
  49841. * Unless required by applicable law or agreed to in writing,
  49842. * software distributed under the License is distributed on an
  49843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49844. * KIND, either express or implied. See the License for the
  49845. * specific language governing permissions and limitations
  49846. * under the License.
  49847. */
  49848. // Only create one roam controller for each coordinate system.
  49849. // one roam controller might be refered by two inside data zoom
  49850. // components (for example, one for x and one for y). When user
  49851. // pan or zoom, only dispatch one action for those data zoom
  49852. // components.
  49853. var ATTR = '\0_ec_dataZoom_roams';
  49854. /**
  49855. * @public
  49856. * @param {module:echarts/ExtensionAPI} api
  49857. * @param {Object} dataZoomInfo
  49858. * @param {string} dataZoomInfo.coordId
  49859. * @param {Function} dataZoomInfo.containsPoint
  49860. * @param {Array.<string>} dataZoomInfo.allCoordIds
  49861. * @param {string} dataZoomInfo.dataZoomId
  49862. * @param {Object} dataZoomInfo.getRange
  49863. * @param {Function} dataZoomInfo.getRange.pan
  49864. * @param {Function} dataZoomInfo.getRange.zoom
  49865. * @param {Function} dataZoomInfo.getRange.scrollMove
  49866. * @param {boolean} dataZoomInfo.dataZoomModel
  49867. */
  49868. function register$1(api, dataZoomInfo) {
  49869. var store = giveStore(api);
  49870. var theDataZoomId = dataZoomInfo.dataZoomId;
  49871. var theCoordId = dataZoomInfo.coordId;
  49872. // Do clean when a dataZoom changes its target coordnate system.
  49873. // Avoid memory leak, dispose all not-used-registered.
  49874. each$1(store, function (record, coordId) {
  49875. var dataZoomInfos = record.dataZoomInfos;
  49876. if (dataZoomInfos[theDataZoomId]
  49877. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  49878. ) {
  49879. delete dataZoomInfos[theDataZoomId];
  49880. record.count--;
  49881. }
  49882. });
  49883. cleanStore(store);
  49884. var record = store[theCoordId];
  49885. // Create if needed.
  49886. if (!record) {
  49887. record = store[theCoordId] = {
  49888. coordId: theCoordId,
  49889. dataZoomInfos: {},
  49890. count: 0
  49891. };
  49892. record.controller = createController(api, record);
  49893. record.dispatchAction = curry(dispatchAction, api);
  49894. }
  49895. // Update reference of dataZoom.
  49896. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  49897. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  49898. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  49899. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  49900. // Consider resize, area should be always updated.
  49901. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  49902. // Update throttle.
  49903. createOrUpdate(
  49904. record,
  49905. 'dispatchAction',
  49906. dataZoomInfo.dataZoomModel.get('throttle', true),
  49907. 'fixRate'
  49908. );
  49909. }
  49910. /**
  49911. * @public
  49912. * @param {module:echarts/ExtensionAPI} api
  49913. * @param {string} dataZoomId
  49914. */
  49915. function unregister$1(api, dataZoomId) {
  49916. var store = giveStore(api);
  49917. each$1(store, function (record) {
  49918. record.controller.dispose();
  49919. var dataZoomInfos = record.dataZoomInfos;
  49920. if (dataZoomInfos[dataZoomId]) {
  49921. delete dataZoomInfos[dataZoomId];
  49922. record.count--;
  49923. }
  49924. });
  49925. cleanStore(store);
  49926. }
  49927. /**
  49928. * @public
  49929. */
  49930. function generateCoordId(coordModel) {
  49931. return coordModel.type + '\0_' + coordModel.id;
  49932. }
  49933. /**
  49934. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  49935. * @type {Array.<Object>}
  49936. */
  49937. function giveStore(api) {
  49938. // Mount store on zrender instance, so that we do not
  49939. // need to worry about dispose.
  49940. var zr = api.getZr();
  49941. return zr[ATTR] || (zr[ATTR] = {});
  49942. }
  49943. function createController(api, newRecord) {
  49944. var controller = new RoamController(api.getZr());
  49945. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  49946. controller.on(eventName, function (event) {
  49947. var batch = [];
  49948. each$1(newRecord.dataZoomInfos, function (info) {
  49949. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  49950. // moveOnMouseWheel, ...) enabled.
  49951. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  49952. return;
  49953. }
  49954. var method = (info.getRange || {})[eventName];
  49955. var range = method && method(newRecord.controller, event);
  49956. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  49957. dataZoomId: info.dataZoomId,
  49958. start: range[0],
  49959. end: range[1]
  49960. });
  49961. });
  49962. batch.length && newRecord.dispatchAction(batch);
  49963. });
  49964. });
  49965. return controller;
  49966. }
  49967. function cleanStore(store) {
  49968. each$1(store, function (record, coordId) {
  49969. if (!record.count) {
  49970. record.controller.dispose();
  49971. delete store[coordId];
  49972. }
  49973. });
  49974. }
  49975. /**
  49976. * This action will be throttled.
  49977. */
  49978. function dispatchAction(api, batch) {
  49979. api.dispatchAction({
  49980. type: 'dataZoom',
  49981. batch: batch
  49982. });
  49983. }
  49984. /**
  49985. * Merge roamController settings when multiple dataZooms share one roamController.
  49986. */
  49987. function mergeControllerParams(dataZoomInfos) {
  49988. var controlType;
  49989. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  49990. // as string, it is probably revert to reserved word by compress tool. See #7411.
  49991. var prefix = 'type_';
  49992. var typePriority = {
  49993. 'type_true': 2,
  49994. 'type_move': 1,
  49995. 'type_false': 0,
  49996. 'type_undefined': -1
  49997. };
  49998. var preventDefaultMouseMove = true;
  49999. each$1(dataZoomInfos, function (dataZoomInfo) {
  50000. var dataZoomModel = dataZoomInfo.dataZoomModel;
  50001. var oneType = dataZoomModel.get('disabled', true)
  50002. ? false
  50003. : dataZoomModel.get('zoomLock', true)
  50004. ? 'move'
  50005. : true;
  50006. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  50007. controlType = oneType;
  50008. }
  50009. // Prevent default move event by default. If one false, do not prevent. Otherwise
  50010. // users may be confused why it does not work when multiple insideZooms exist.
  50011. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  50012. });
  50013. return {
  50014. controlType: controlType,
  50015. opt: {
  50016. // RoamController will enable all of these functionalities,
  50017. // and the final behavior is determined by its event listener
  50018. // provided by each inside zoom.
  50019. zoomOnMouseWheel: true,
  50020. moveOnMouseMove: true,
  50021. moveOnMouseWheel: true,
  50022. preventDefaultMouseMove: !!preventDefaultMouseMove
  50023. }
  50024. };
  50025. }
  50026. /*
  50027. * Licensed to the Apache Software Foundation (ASF) under one
  50028. * or more contributor license agreements. See the NOTICE file
  50029. * distributed with this work for additional information
  50030. * regarding copyright ownership. The ASF licenses this file
  50031. * to you under the Apache License, Version 2.0 (the
  50032. * "License"); you may not use this file except in compliance
  50033. * with the License. You may obtain a copy of the License at
  50034. *
  50035. * http://www.apache.org/licenses/LICENSE-2.0
  50036. *
  50037. * Unless required by applicable law or agreed to in writing,
  50038. * software distributed under the License is distributed on an
  50039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50040. * KIND, either express or implied. See the License for the
  50041. * specific language governing permissions and limitations
  50042. * under the License.
  50043. */
  50044. var bind$4 = bind;
  50045. var InsideZoomView = DataZoomView.extend({
  50046. type: 'dataZoom.inside',
  50047. /**
  50048. * @override
  50049. */
  50050. init: function (ecModel, api) {
  50051. /**
  50052. * 'throttle' is used in this.dispatchAction, so we save range
  50053. * to avoid missing some 'pan' info.
  50054. * @private
  50055. * @type {Array.<number>}
  50056. */
  50057. this._range;
  50058. },
  50059. /**
  50060. * @override
  50061. */
  50062. render: function (dataZoomModel, ecModel, api, payload) {
  50063. InsideZoomView.superApply(this, 'render', arguments);
  50064. // Hence the `throttle` util ensures to preserve command order,
  50065. // here simply updating range all the time will not cause missing
  50066. // any of the the roam change.
  50067. this._range = dataZoomModel.getPercentRange();
  50068. // Reset controllers.
  50069. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  50070. var allCoordIds = map(coordInfoList, function (coordInfo) {
  50071. return generateCoordId(coordInfo.model);
  50072. });
  50073. each$1(coordInfoList, function (coordInfo) {
  50074. var coordModel = coordInfo.model;
  50075. var getRange = {};
  50076. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  50077. getRange[eventName] = bind$4(roamHandlers[eventName], this, coordInfo, coordSysName);
  50078. }, this);
  50079. register$1(
  50080. api,
  50081. {
  50082. coordId: generateCoordId(coordModel),
  50083. allCoordIds: allCoordIds,
  50084. containsPoint: function (e, x, y) {
  50085. return coordModel.coordinateSystem.containPoint([x, y]);
  50086. },
  50087. dataZoomId: dataZoomModel.id,
  50088. dataZoomModel: dataZoomModel,
  50089. getRange: getRange
  50090. }
  50091. );
  50092. }, this);
  50093. }, this);
  50094. },
  50095. /**
  50096. * @override
  50097. */
  50098. dispose: function () {
  50099. unregister$1(this.api, this.dataZoomModel.id);
  50100. InsideZoomView.superApply(this, 'dispose', arguments);
  50101. this._range = null;
  50102. }
  50103. });
  50104. var roamHandlers = {
  50105. /**
  50106. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50107. */
  50108. zoom: function (coordInfo, coordSysName, controller, e) {
  50109. var lastRange = this._range;
  50110. var range = lastRange.slice();
  50111. // Calculate transform by the first axis.
  50112. var axisModel = coordInfo.axisModels[0];
  50113. if (!axisModel) {
  50114. return;
  50115. }
  50116. var directionInfo = getDirectionInfo[coordSysName](
  50117. null, [e.originX, e.originY], axisModel, controller, coordInfo
  50118. );
  50119. var percentPoint = (
  50120. directionInfo.signal > 0
  50121. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  50122. : (directionInfo.pixel - directionInfo.pixelStart)
  50123. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  50124. var scale = Math.max(1 / e.scale, 0);
  50125. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  50126. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  50127. // Restrict range.
  50128. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  50129. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  50130. this._range = range;
  50131. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50132. return range;
  50133. }
  50134. },
  50135. /**
  50136. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50137. */
  50138. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  50139. var directionInfo = getDirectionInfo[coordSysName](
  50140. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  50141. );
  50142. return directionInfo.signal
  50143. * (range[1] - range[0])
  50144. * directionInfo.pixel / directionInfo.pixelLength;
  50145. }),
  50146. /**
  50147. * @this {module:echarts/component/dataZoom/InsideZoomView}
  50148. */
  50149. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  50150. var directionInfo = getDirectionInfo[coordSysName](
  50151. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  50152. );
  50153. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  50154. })
  50155. };
  50156. function makeMover(getPercentDelta) {
  50157. return function (coordInfo, coordSysName, controller, e) {
  50158. var lastRange = this._range;
  50159. var range = lastRange.slice();
  50160. // Calculate transform by the first axis.
  50161. var axisModel = coordInfo.axisModels[0];
  50162. if (!axisModel) {
  50163. return;
  50164. }
  50165. var percentDelta = getPercentDelta(
  50166. range, axisModel, coordInfo, coordSysName, controller, e
  50167. );
  50168. sliderMove(percentDelta, range, [0, 100], 'all');
  50169. this._range = range;
  50170. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  50171. return range;
  50172. }
  50173. };
  50174. }
  50175. var getDirectionInfo = {
  50176. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50177. var axis = axisModel.axis;
  50178. var ret = {};
  50179. var rect = coordInfo.model.coordinateSystem.getRect();
  50180. oldPoint = oldPoint || [0, 0];
  50181. if (axis.dim === 'x') {
  50182. ret.pixel = newPoint[0] - oldPoint[0];
  50183. ret.pixelLength = rect.width;
  50184. ret.pixelStart = rect.x;
  50185. ret.signal = axis.inverse ? 1 : -1;
  50186. }
  50187. else { // axis.dim === 'y'
  50188. ret.pixel = newPoint[1] - oldPoint[1];
  50189. ret.pixelLength = rect.height;
  50190. ret.pixelStart = rect.y;
  50191. ret.signal = axis.inverse ? -1 : 1;
  50192. }
  50193. return ret;
  50194. },
  50195. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50196. var axis = axisModel.axis;
  50197. var ret = {};
  50198. var polar = coordInfo.model.coordinateSystem;
  50199. var radiusExtent = polar.getRadiusAxis().getExtent();
  50200. var angleExtent = polar.getAngleAxis().getExtent();
  50201. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  50202. newPoint = polar.pointToCoord(newPoint);
  50203. if (axisModel.mainType === 'radiusAxis') {
  50204. ret.pixel = newPoint[0] - oldPoint[0];
  50205. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  50206. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  50207. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  50208. ret.pixelStart = radiusExtent[0];
  50209. ret.signal = axis.inverse ? 1 : -1;
  50210. }
  50211. else { // 'angleAxis'
  50212. ret.pixel = newPoint[1] - oldPoint[1];
  50213. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  50214. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  50215. ret.pixelLength = angleExtent[1] - angleExtent[0];
  50216. ret.pixelStart = angleExtent[0];
  50217. ret.signal = axis.inverse ? -1 : 1;
  50218. }
  50219. return ret;
  50220. },
  50221. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  50222. var axis = axisModel.axis;
  50223. var rect = coordInfo.model.coordinateSystem.getRect();
  50224. var ret = {};
  50225. oldPoint = oldPoint || [0, 0];
  50226. if (axis.orient === 'horizontal') {
  50227. ret.pixel = newPoint[0] - oldPoint[0];
  50228. ret.pixelLength = rect.width;
  50229. ret.pixelStart = rect.x;
  50230. ret.signal = axis.inverse ? 1 : -1;
  50231. }
  50232. else { // 'vertical'
  50233. ret.pixel = newPoint[1] - oldPoint[1];
  50234. ret.pixelLength = rect.height;
  50235. ret.pixelStart = rect.y;
  50236. ret.signal = axis.inverse ? -1 : 1;
  50237. }
  50238. return ret;
  50239. }
  50240. };
  50241. /*
  50242. * Licensed to the Apache Software Foundation (ASF) under one
  50243. * or more contributor license agreements. See the NOTICE file
  50244. * distributed with this work for additional information
  50245. * regarding copyright ownership. The ASF licenses this file
  50246. * to you under the Apache License, Version 2.0 (the
  50247. * "License"); you may not use this file except in compliance
  50248. * with the License. You may obtain a copy of the License at
  50249. *
  50250. * http://www.apache.org/licenses/LICENSE-2.0
  50251. *
  50252. * Unless required by applicable law or agreed to in writing,
  50253. * software distributed under the License is distributed on an
  50254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50255. * KIND, either express or implied. See the License for the
  50256. * specific language governing permissions and limitations
  50257. * under the License.
  50258. */
  50259. /*
  50260. * Licensed to the Apache Software Foundation (ASF) under one
  50261. * or more contributor license agreements. See the NOTICE file
  50262. * distributed with this work for additional information
  50263. * regarding copyright ownership. The ASF licenses this file
  50264. * to you under the Apache License, Version 2.0 (the
  50265. * "License"); you may not use this file except in compliance
  50266. * with the License. You may obtain a copy of the License at
  50267. *
  50268. * http://www.apache.org/licenses/LICENSE-2.0
  50269. *
  50270. * Unless required by applicable law or agreed to in writing,
  50271. * software distributed under the License is distributed on an
  50272. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50273. * KIND, either express or implied. See the License for the
  50274. * specific language governing permissions and limitations
  50275. * under the License.
  50276. */
  50277. // Do not include './dataZoomSelect',
  50278. // since it only work for toolbox dataZoom.
  50279. /*
  50280. * Licensed to the Apache Software Foundation (ASF) under one
  50281. * or more contributor license agreements. See the NOTICE file
  50282. * distributed with this work for additional information
  50283. * regarding copyright ownership. The ASF licenses this file
  50284. * to you under the Apache License, Version 2.0 (the
  50285. * "License"); you may not use this file except in compliance
  50286. * with the License. You may obtain a copy of the License at
  50287. *
  50288. * http://www.apache.org/licenses/LICENSE-2.0
  50289. *
  50290. * Unless required by applicable law or agreed to in writing,
  50291. * software distributed under the License is distributed on an
  50292. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50293. * KIND, either express or implied. See the License for the
  50294. * specific language governing permissions and limitations
  50295. * under the License.
  50296. */
  50297. var features = {};
  50298. function register$2(name, ctor) {
  50299. features[name] = ctor;
  50300. }
  50301. function get$1(name) {
  50302. return features[name];
  50303. }
  50304. /*
  50305. * Licensed to the Apache Software Foundation (ASF) under one
  50306. * or more contributor license agreements. See the NOTICE file
  50307. * distributed with this work for additional information
  50308. * regarding copyright ownership. The ASF licenses this file
  50309. * to you under the Apache License, Version 2.0 (the
  50310. * "License"); you may not use this file except in compliance
  50311. * with the License. You may obtain a copy of the License at
  50312. *
  50313. * http://www.apache.org/licenses/LICENSE-2.0
  50314. *
  50315. * Unless required by applicable law or agreed to in writing,
  50316. * software distributed under the License is distributed on an
  50317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50318. * KIND, either express or implied. See the License for the
  50319. * specific language governing permissions and limitations
  50320. * under the License.
  50321. */
  50322. var ToolboxModel = extendComponentModel({
  50323. type: 'toolbox',
  50324. layoutMode: {
  50325. type: 'box',
  50326. ignoreSize: true
  50327. },
  50328. optionUpdated: function () {
  50329. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  50330. each$1(this.option.feature, function (featureOpt, featureName) {
  50331. var Feature = get$1(featureName);
  50332. Feature && merge(featureOpt, Feature.defaultOption);
  50333. });
  50334. },
  50335. defaultOption: {
  50336. show: true,
  50337. z: 6,
  50338. zlevel: 0,
  50339. orient: 'horizontal',
  50340. left: 'right',
  50341. top: 'top',
  50342. // right
  50343. // bottom
  50344. backgroundColor: 'transparent',
  50345. borderColor: '#ccc',
  50346. borderRadius: 0,
  50347. borderWidth: 0,
  50348. padding: 5,
  50349. itemSize: 15,
  50350. itemGap: 8,
  50351. showTitle: true,
  50352. iconStyle: {
  50353. borderColor: '#666',
  50354. color: 'none'
  50355. },
  50356. emphasis: {
  50357. iconStyle: {
  50358. borderColor: '#3E98C5'
  50359. }
  50360. },
  50361. // textStyle: {},
  50362. // feature
  50363. tooltip: {
  50364. show: false
  50365. }
  50366. }
  50367. });
  50368. /*
  50369. * Licensed to the Apache Software Foundation (ASF) under one
  50370. * or more contributor license agreements. See the NOTICE file
  50371. * distributed with this work for additional information
  50372. * regarding copyright ownership. The ASF licenses this file
  50373. * to you under the Apache License, Version 2.0 (the
  50374. * "License"); you may not use this file except in compliance
  50375. * with the License. You may obtain a copy of the License at
  50376. *
  50377. * http://www.apache.org/licenses/LICENSE-2.0
  50378. *
  50379. * Unless required by applicable law or agreed to in writing,
  50380. * software distributed under the License is distributed on an
  50381. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50382. * KIND, either express or implied. See the License for the
  50383. * specific language governing permissions and limitations
  50384. * under the License.
  50385. */
  50386. extendComponentView({
  50387. type: 'toolbox',
  50388. render: function (toolboxModel, ecModel, api, payload) {
  50389. var group = this.group;
  50390. group.removeAll();
  50391. if (!toolboxModel.get('show')) {
  50392. return;
  50393. }
  50394. var itemSize = +toolboxModel.get('itemSize');
  50395. var featureOpts = toolboxModel.get('feature') || {};
  50396. var features = this._features || (this._features = {});
  50397. var featureNames = [];
  50398. each$1(featureOpts, function (opt, name) {
  50399. featureNames.push(name);
  50400. });
  50401. (new DataDiffer(this._featureNames || [], featureNames))
  50402. .add(processFeature)
  50403. .update(processFeature)
  50404. .remove(curry(processFeature, null))
  50405. .execute();
  50406. // Keep for diff.
  50407. this._featureNames = featureNames;
  50408. function processFeature(newIndex, oldIndex) {
  50409. var featureName = featureNames[newIndex];
  50410. var oldName = featureNames[oldIndex];
  50411. var featureOpt = featureOpts[featureName];
  50412. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  50413. var feature;
  50414. // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  50415. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  50416. featureOpt.title = payload.newTitle;
  50417. }
  50418. if (featureName && !oldName) { // Create
  50419. if (isUserFeatureName(featureName)) {
  50420. feature = {
  50421. model: featureModel,
  50422. onclick: featureModel.option.onclick,
  50423. featureName: featureName
  50424. };
  50425. }
  50426. else {
  50427. var Feature = get$1(featureName);
  50428. if (!Feature) {
  50429. return;
  50430. }
  50431. feature = new Feature(featureModel, ecModel, api);
  50432. }
  50433. features[featureName] = feature;
  50434. }
  50435. else {
  50436. feature = features[oldName];
  50437. // If feature does not exsit.
  50438. if (!feature) {
  50439. return;
  50440. }
  50441. feature.model = featureModel;
  50442. feature.ecModel = ecModel;
  50443. feature.api = api;
  50444. }
  50445. if (!featureName && oldName) {
  50446. feature.dispose && feature.dispose(ecModel, api);
  50447. return;
  50448. }
  50449. if (!featureModel.get('show') || feature.unusable) {
  50450. feature.remove && feature.remove(ecModel, api);
  50451. return;
  50452. }
  50453. createIconPaths(featureModel, feature, featureName);
  50454. featureModel.setIconStatus = function (iconName, status) {
  50455. var option = this.option;
  50456. var iconPaths = this.iconPaths;
  50457. option.iconStatus = option.iconStatus || {};
  50458. option.iconStatus[iconName] = status;
  50459. // FIXME
  50460. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  50461. };
  50462. if (feature.render) {
  50463. feature.render(featureModel, ecModel, api, payload);
  50464. }
  50465. }
  50466. function createIconPaths(featureModel, feature, featureName) {
  50467. var iconStyleModel = featureModel.getModel('iconStyle');
  50468. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  50469. // If one feature has mutiple icon. they are orginaized as
  50470. // {
  50471. // icon: {
  50472. // foo: '',
  50473. // bar: ''
  50474. // },
  50475. // title: {
  50476. // foo: '',
  50477. // bar: ''
  50478. // }
  50479. // }
  50480. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  50481. var titles = featureModel.get('title') || {};
  50482. if (typeof icons === 'string') {
  50483. var icon = icons;
  50484. var title = titles;
  50485. icons = {};
  50486. titles = {};
  50487. icons[featureName] = icon;
  50488. titles[featureName] = title;
  50489. }
  50490. var iconPaths = featureModel.iconPaths = {};
  50491. each$1(icons, function (iconStr, iconName) {
  50492. var path = createIcon(
  50493. iconStr,
  50494. {},
  50495. {
  50496. x: -itemSize / 2,
  50497. y: -itemSize / 2,
  50498. width: itemSize,
  50499. height: itemSize
  50500. }
  50501. );
  50502. path.setStyle(iconStyleModel.getItemStyle());
  50503. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50504. // Text position calculation
  50505. path.setStyle({
  50506. text: titles[iconName],
  50507. textAlign: iconStyleEmphasisModel.get('textAlign'),
  50508. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  50509. textPadding: iconStyleEmphasisModel.get('textPadding'),
  50510. textFill: null
  50511. });
  50512. var tooltipModel = toolboxModel.getModel('tooltip');
  50513. if (tooltipModel && tooltipModel.get('show')) {
  50514. path.attr('tooltip', extend({
  50515. content: titles[iconName],
  50516. formatter: tooltipModel.get('formatter', true)
  50517. || function () {
  50518. return titles[iconName];
  50519. },
  50520. formatterParams: {
  50521. componentType: 'toolbox',
  50522. name: iconName,
  50523. title: titles[iconName],
  50524. $vars: ['name', 'title']
  50525. },
  50526. position: tooltipModel.get('position', true) || 'bottom'
  50527. }, tooltipModel.option));
  50528. }
  50529. setHoverStyle(path);
  50530. if (toolboxModel.get('showTitle')) {
  50531. path.__title = titles[iconName];
  50532. path.on('mouseover', function () {
  50533. // Should not reuse above hoverStyle, which might be modified.
  50534. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  50535. var defaultTextPosition = toolboxModel.get('orient') === 'vertical'
  50536. ? (toolboxModel.get('right') == null ? 'right' : 'left')
  50537. : (toolboxModel.get('bottom') == null ? 'bottom' : 'top');
  50538. path.setStyle({
  50539. textFill: iconStyleEmphasisModel.get('textFill')
  50540. || hoverStyle.fill || hoverStyle.stroke || '#000',
  50541. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  50542. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  50543. });
  50544. })
  50545. .on('mouseout', function () {
  50546. path.setStyle({
  50547. textFill: null,
  50548. textBackgroundColor: null
  50549. });
  50550. });
  50551. }
  50552. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  50553. group.add(path);
  50554. path.on('click', bind(
  50555. feature.onclick, feature, ecModel, api, iconName
  50556. ));
  50557. iconPaths[iconName] = path;
  50558. });
  50559. }
  50560. layout$2(group, toolboxModel, api);
  50561. // Render background after group is layout
  50562. // FIXME
  50563. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  50564. // Adjust icon title positions to avoid them out of screen
  50565. group.eachChild(function (icon) {
  50566. var titleText = icon.__title;
  50567. var hoverStyle = icon.hoverStyle;
  50568. // May be background element
  50569. if (hoverStyle && titleText) {
  50570. var rect = getBoundingRect(
  50571. titleText, makeFont(hoverStyle)
  50572. );
  50573. var offsetX = icon.position[0] + group.position[0];
  50574. var offsetY = icon.position[1] + group.position[1] + itemSize;
  50575. var needPutOnTop = false;
  50576. if (offsetY + rect.height > api.getHeight()) {
  50577. hoverStyle.textPosition = 'top';
  50578. needPutOnTop = true;
  50579. }
  50580. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  50581. if (offsetX + rect.width / 2 > api.getWidth()) {
  50582. hoverStyle.textPosition = ['100%', topOffset];
  50583. hoverStyle.textAlign = 'right';
  50584. }
  50585. else if (offsetX - rect.width / 2 < 0) {
  50586. hoverStyle.textPosition = [0, topOffset];
  50587. hoverStyle.textAlign = 'left';
  50588. }
  50589. }
  50590. });
  50591. },
  50592. updateView: function (toolboxModel, ecModel, api, payload) {
  50593. each$1(this._features, function (feature) {
  50594. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  50595. });
  50596. },
  50597. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  50598. // zrUtil.each(this._features, function (feature) {
  50599. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  50600. // });
  50601. // },
  50602. remove: function (ecModel, api) {
  50603. each$1(this._features, function (feature) {
  50604. feature.remove && feature.remove(ecModel, api);
  50605. });
  50606. this.group.removeAll();
  50607. },
  50608. dispose: function (ecModel, api) {
  50609. each$1(this._features, function (feature) {
  50610. feature.dispose && feature.dispose(ecModel, api);
  50611. });
  50612. }
  50613. });
  50614. function isUserFeatureName(featureName) {
  50615. return featureName.indexOf('my') === 0;
  50616. }
  50617. /*
  50618. * Licensed to the Apache Software Foundation (ASF) under one
  50619. * or more contributor license agreements. See the NOTICE file
  50620. * distributed with this work for additional information
  50621. * regarding copyright ownership. The ASF licenses this file
  50622. * to you under the Apache License, Version 2.0 (the
  50623. * "License"); you may not use this file except in compliance
  50624. * with the License. You may obtain a copy of the License at
  50625. *
  50626. * http://www.apache.org/licenses/LICENSE-2.0
  50627. *
  50628. * Unless required by applicable law or agreed to in writing,
  50629. * software distributed under the License is distributed on an
  50630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50631. * KIND, either express or implied. See the License for the
  50632. * specific language governing permissions and limitations
  50633. * under the License.
  50634. */
  50635. /* global Uint8Array */
  50636. var saveAsImageLang = lang.toolbox.saveAsImage;
  50637. function SaveAsImage(model) {
  50638. this.model = model;
  50639. }
  50640. SaveAsImage.defaultOption = {
  50641. show: true,
  50642. 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',
  50643. title: saveAsImageLang.title,
  50644. type: 'png',
  50645. // Default use option.backgroundColor
  50646. // backgroundColor: '#fff',
  50647. connectedBackgroundColor: '#fff',
  50648. name: '',
  50649. excludeComponents: ['toolbox'],
  50650. pixelRatio: 1,
  50651. lang: saveAsImageLang.lang.slice()
  50652. };
  50653. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  50654. var proto$2 = SaveAsImage.prototype;
  50655. proto$2.onclick = function (ecModel, api) {
  50656. var model = this.model;
  50657. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  50658. var isSvg = api.getZr().painter.getType() === 'svg';
  50659. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  50660. var url = api.getConnectedDataURL({
  50661. type: type,
  50662. backgroundColor: model.get('backgroundColor', true)
  50663. || ecModel.get('backgroundColor') || '#fff',
  50664. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  50665. excludeComponents: model.get('excludeComponents'),
  50666. pixelRatio: model.get('pixelRatio')
  50667. });
  50668. // Chrome and Firefox
  50669. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  50670. var $a = document.createElement('a');
  50671. $a.download = title + '.' + type;
  50672. $a.target = '_blank';
  50673. $a.href = url;
  50674. var evt = new MouseEvent('click', {
  50675. view: window,
  50676. bubbles: true,
  50677. cancelable: false
  50678. });
  50679. $a.dispatchEvent(evt);
  50680. }
  50681. // IE
  50682. else {
  50683. if (window.navigator.msSaveOrOpenBlob) {
  50684. var bstr = atob(url.split(',')[1]);
  50685. var n = bstr.length;
  50686. var u8arr = new Uint8Array(n);
  50687. while (n--) {
  50688. u8arr[n] = bstr.charCodeAt(n);
  50689. }
  50690. var blob = new Blob([u8arr]);
  50691. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  50692. }
  50693. else {
  50694. var lang$$1 = model.get('lang');
  50695. var html = ''
  50696. + '<body style="margin:0;">'
  50697. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  50698. + '</body>';
  50699. var tab = window.open();
  50700. tab.document.write(html);
  50701. }
  50702. }
  50703. };
  50704. register$2(
  50705. 'saveAsImage', SaveAsImage
  50706. );
  50707. /*
  50708. * Licensed to the Apache Software Foundation (ASF) under one
  50709. * or more contributor license agreements. See the NOTICE file
  50710. * distributed with this work for additional information
  50711. * regarding copyright ownership. The ASF licenses this file
  50712. * to you under the Apache License, Version 2.0 (the
  50713. * "License"); you may not use this file except in compliance
  50714. * with the License. You may obtain a copy of the License at
  50715. *
  50716. * http://www.apache.org/licenses/LICENSE-2.0
  50717. *
  50718. * Unless required by applicable law or agreed to in writing,
  50719. * software distributed under the License is distributed on an
  50720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50721. * KIND, either express or implied. See the License for the
  50722. * specific language governing permissions and limitations
  50723. * under the License.
  50724. */
  50725. var magicTypeLang = lang.toolbox.magicType;
  50726. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  50727. function MagicType(model) {
  50728. this.model = model;
  50729. }
  50730. MagicType.defaultOption = {
  50731. show: true,
  50732. type: [],
  50733. // Icon group
  50734. icon: {
  50735. /* eslint-disable */
  50736. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  50737. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  50738. 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
  50739. /* eslint-enable */
  50740. },
  50741. // `line`, `bar`, `stack`, `tiled`
  50742. title: clone(magicTypeLang.title),
  50743. option: {},
  50744. seriesIndex: {}
  50745. };
  50746. var proto$3 = MagicType.prototype;
  50747. proto$3.getIcons = function () {
  50748. var model = this.model;
  50749. var availableIcons = model.get('icon');
  50750. var icons = {};
  50751. each$1(model.get('type'), function (type) {
  50752. if (availableIcons[type]) {
  50753. icons[type] = availableIcons[type];
  50754. }
  50755. });
  50756. return icons;
  50757. };
  50758. var seriesOptGenreator = {
  50759. 'line': function (seriesType, seriesId, seriesModel, model) {
  50760. if (seriesType === 'bar') {
  50761. return merge({
  50762. id: seriesId,
  50763. type: 'line',
  50764. // Preserve data related option
  50765. data: seriesModel.get('data'),
  50766. stack: seriesModel.get('stack'),
  50767. markPoint: seriesModel.get('markPoint'),
  50768. markLine: seriesModel.get('markLine')
  50769. }, model.get('option.line') || {}, true);
  50770. }
  50771. },
  50772. 'bar': function (seriesType, seriesId, seriesModel, model) {
  50773. if (seriesType === 'line') {
  50774. return merge({
  50775. id: seriesId,
  50776. type: 'bar',
  50777. // Preserve data related option
  50778. data: seriesModel.get('data'),
  50779. stack: seriesModel.get('stack'),
  50780. markPoint: seriesModel.get('markPoint'),
  50781. markLine: seriesModel.get('markLine')
  50782. }, model.get('option.bar') || {}, true);
  50783. }
  50784. },
  50785. 'stack': function (seriesType, seriesId, seriesModel, model) {
  50786. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  50787. if (seriesType === 'line' || seriesType === 'bar') {
  50788. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  50789. return merge({
  50790. id: seriesId,
  50791. stack: isStack ? '' : INNER_STACK_KEYWORD
  50792. }, model.get('option.stack') || {}, true);
  50793. }
  50794. }
  50795. };
  50796. var radioTypes = [
  50797. ['line', 'bar'],
  50798. ['stack']
  50799. ];
  50800. proto$3.onclick = function (ecModel, api, type) {
  50801. var model = this.model;
  50802. var seriesIndex = model.get('seriesIndex.' + type);
  50803. // Not supported magicType
  50804. if (!seriesOptGenreator[type]) {
  50805. return;
  50806. }
  50807. var newOption = {
  50808. series: []
  50809. };
  50810. var generateNewSeriesTypes = function (seriesModel) {
  50811. var seriesType = seriesModel.subType;
  50812. var seriesId = seriesModel.id;
  50813. var newSeriesOpt = seriesOptGenreator[type](
  50814. seriesType, seriesId, seriesModel, model
  50815. );
  50816. if (newSeriesOpt) {
  50817. // PENDING If merge original option?
  50818. defaults(newSeriesOpt, seriesModel.option);
  50819. newOption.series.push(newSeriesOpt);
  50820. }
  50821. // Modify boundaryGap
  50822. var coordSys = seriesModel.coordinateSystem;
  50823. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  50824. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  50825. if (categoryAxis) {
  50826. var axisDim = categoryAxis.dim;
  50827. var axisType = axisDim + 'Axis';
  50828. var axisModel = ecModel.queryComponents({
  50829. mainType: axisType,
  50830. index: seriesModel.get(name + 'Index'),
  50831. id: seriesModel.get(name + 'Id')
  50832. })[0];
  50833. var axisIndex = axisModel.componentIndex;
  50834. newOption[axisType] = newOption[axisType] || [];
  50835. for (var i = 0; i <= axisIndex; i++) {
  50836. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  50837. }
  50838. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  50839. }
  50840. }
  50841. };
  50842. each$1(radioTypes, function (radio) {
  50843. if (indexOf(radio, type) >= 0) {
  50844. each$1(radio, function (item) {
  50845. model.setIconStatus(item, 'normal');
  50846. });
  50847. }
  50848. });
  50849. model.setIconStatus(type, 'emphasis');
  50850. ecModel.eachComponent(
  50851. {
  50852. mainType: 'series',
  50853. query: seriesIndex == null ? null : {
  50854. seriesIndex: seriesIndex
  50855. }
  50856. }, generateNewSeriesTypes
  50857. );
  50858. var newTitle;
  50859. // Change title of stack
  50860. if (type === 'stack') {
  50861. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  50862. newTitle = isStack
  50863. ? merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
  50864. : clone(magicTypeLang.title);
  50865. }
  50866. api.dispatchAction({
  50867. type: 'changeMagicType',
  50868. currentType: type,
  50869. newOption: newOption,
  50870. newTitle: newTitle,
  50871. featureName: 'magicType'
  50872. });
  50873. };
  50874. registerAction({
  50875. type: 'changeMagicType',
  50876. event: 'magicTypeChanged',
  50877. update: 'prepareAndUpdate'
  50878. }, function (payload, ecModel) {
  50879. ecModel.mergeOption(payload.newOption);
  50880. });
  50881. register$2('magicType', MagicType);
  50882. /*
  50883. * Licensed to the Apache Software Foundation (ASF) under one
  50884. * or more contributor license agreements. See the NOTICE file
  50885. * distributed with this work for additional information
  50886. * regarding copyright ownership. The ASF licenses this file
  50887. * to you under the Apache License, Version 2.0 (the
  50888. * "License"); you may not use this file except in compliance
  50889. * with the License. You may obtain a copy of the License at
  50890. *
  50891. * http://www.apache.org/licenses/LICENSE-2.0
  50892. *
  50893. * Unless required by applicable law or agreed to in writing,
  50894. * software distributed under the License is distributed on an
  50895. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50896. * KIND, either express or implied. See the License for the
  50897. * specific language governing permissions and limitations
  50898. * under the License.
  50899. */
  50900. var dataViewLang = lang.toolbox.dataView;
  50901. var BLOCK_SPLITER = new Array(60).join('-');
  50902. var ITEM_SPLITER = '\t';
  50903. /**
  50904. * Group series into two types
  50905. * 1. on category axis, like line, bar
  50906. * 2. others, like scatter, pie
  50907. * @param {module:echarts/model/Global} ecModel
  50908. * @return {Object}
  50909. * @inner
  50910. */
  50911. function groupSeries(ecModel) {
  50912. var seriesGroupByCategoryAxis = {};
  50913. var otherSeries = [];
  50914. var meta = [];
  50915. ecModel.eachRawSeries(function (seriesModel) {
  50916. var coordSys = seriesModel.coordinateSystem;
  50917. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  50918. var baseAxis = coordSys.getBaseAxis();
  50919. if (baseAxis.type === 'category') {
  50920. var key = baseAxis.dim + '_' + baseAxis.index;
  50921. if (!seriesGroupByCategoryAxis[key]) {
  50922. seriesGroupByCategoryAxis[key] = {
  50923. categoryAxis: baseAxis,
  50924. valueAxis: coordSys.getOtherAxis(baseAxis),
  50925. series: []
  50926. };
  50927. meta.push({
  50928. axisDim: baseAxis.dim,
  50929. axisIndex: baseAxis.index
  50930. });
  50931. }
  50932. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  50933. }
  50934. else {
  50935. otherSeries.push(seriesModel);
  50936. }
  50937. }
  50938. else {
  50939. otherSeries.push(seriesModel);
  50940. }
  50941. });
  50942. return {
  50943. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  50944. other: otherSeries,
  50945. meta: meta
  50946. };
  50947. }
  50948. /**
  50949. * Assemble content of series on cateogory axis
  50950. * @param {Array.<module:echarts/model/Series>} series
  50951. * @return {string}
  50952. * @inner
  50953. */
  50954. function assembleSeriesWithCategoryAxis(series) {
  50955. var tables = [];
  50956. each$1(series, function (group, key) {
  50957. var categoryAxis = group.categoryAxis;
  50958. var valueAxis = group.valueAxis;
  50959. var valueAxisDim = valueAxis.dim;
  50960. var headers = [' '].concat(map(group.series, function (series) {
  50961. return series.name;
  50962. }));
  50963. var columns = [categoryAxis.model.getCategories()];
  50964. each$1(group.series, function (series) {
  50965. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  50966. return val;
  50967. }));
  50968. });
  50969. // Assemble table content
  50970. var lines = [headers.join(ITEM_SPLITER)];
  50971. for (var i = 0; i < columns[0].length; i++) {
  50972. var items = [];
  50973. for (var j = 0; j < columns.length; j++) {
  50974. items.push(columns[j][i]);
  50975. }
  50976. lines.push(items.join(ITEM_SPLITER));
  50977. }
  50978. tables.push(lines.join('\n'));
  50979. });
  50980. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  50981. }
  50982. /**
  50983. * Assemble content of other series
  50984. * @param {Array.<module:echarts/model/Series>} series
  50985. * @return {string}
  50986. * @inner
  50987. */
  50988. function assembleOtherSeries(series) {
  50989. return map(series, function (series) {
  50990. var data = series.getRawData();
  50991. var lines = [series.name];
  50992. var vals = [];
  50993. data.each(data.dimensions, function () {
  50994. var argLen = arguments.length;
  50995. var dataIndex = arguments[argLen - 1];
  50996. var name = data.getName(dataIndex);
  50997. for (var i = 0; i < argLen - 1; i++) {
  50998. vals[i] = arguments[i];
  50999. }
  51000. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  51001. });
  51002. return lines.join('\n');
  51003. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  51004. }
  51005. /**
  51006. * @param {module:echarts/model/Global}
  51007. * @return {Object}
  51008. * @inner
  51009. */
  51010. function getContentFromModel(ecModel) {
  51011. var result = groupSeries(ecModel);
  51012. return {
  51013. value: filter([
  51014. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  51015. assembleOtherSeries(result.other)
  51016. ], function (str) {
  51017. return str.replace(/[\n\t\s]/g, '');
  51018. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  51019. meta: result.meta
  51020. };
  51021. }
  51022. function trim$1(str) {
  51023. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  51024. }
  51025. /**
  51026. * If a block is tsv format
  51027. */
  51028. function isTSVFormat(block) {
  51029. // Simple method to find out if a block is tsv format
  51030. var firstLine = block.slice(0, block.indexOf('\n'));
  51031. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  51032. return true;
  51033. }
  51034. }
  51035. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  51036. /**
  51037. * @param {string} tsv
  51038. * @return {Object}
  51039. */
  51040. function parseTSVContents(tsv) {
  51041. var tsvLines = tsv.split(/\n+/g);
  51042. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  51043. var categories = [];
  51044. var series = map(headers, function (header) {
  51045. return {
  51046. name: header,
  51047. data: []
  51048. };
  51049. });
  51050. for (var i = 0; i < tsvLines.length; i++) {
  51051. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  51052. categories.push(items.shift());
  51053. for (var j = 0; j < items.length; j++) {
  51054. series[j] && (series[j].data[i] = items[j]);
  51055. }
  51056. }
  51057. return {
  51058. series: series,
  51059. categories: categories
  51060. };
  51061. }
  51062. /**
  51063. * @param {string} str
  51064. * @return {Array.<Object>}
  51065. * @inner
  51066. */
  51067. function parseListContents(str) {
  51068. var lines = str.split(/\n+/g);
  51069. var seriesName = trim$1(lines.shift());
  51070. var data = [];
  51071. for (var i = 0; i < lines.length; i++) {
  51072. var items = trim$1(lines[i]).split(itemSplitRegex);
  51073. var name = '';
  51074. var value;
  51075. var hasName = false;
  51076. if (isNaN(items[0])) { // First item is name
  51077. hasName = true;
  51078. name = items[0];
  51079. items = items.slice(1);
  51080. data[i] = {
  51081. name: name,
  51082. value: []
  51083. };
  51084. value = data[i].value;
  51085. }
  51086. else {
  51087. value = data[i] = [];
  51088. }
  51089. for (var j = 0; j < items.length; j++) {
  51090. value.push(+items[j]);
  51091. }
  51092. if (value.length === 1) {
  51093. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  51094. }
  51095. }
  51096. return {
  51097. name: seriesName,
  51098. data: data
  51099. };
  51100. }
  51101. /**
  51102. * @param {string} str
  51103. * @param {Array.<Object>} blockMetaList
  51104. * @return {Object}
  51105. * @inner
  51106. */
  51107. function parseContents(str, blockMetaList) {
  51108. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  51109. var newOption = {
  51110. series: []
  51111. };
  51112. each$1(blocks, function (block, idx) {
  51113. if (isTSVFormat(block)) {
  51114. var result = parseTSVContents(block);
  51115. var blockMeta = blockMetaList[idx];
  51116. var axisKey = blockMeta.axisDim + 'Axis';
  51117. if (blockMeta) {
  51118. newOption[axisKey] = newOption[axisKey] || [];
  51119. newOption[axisKey][blockMeta.axisIndex] = {
  51120. data: result.categories
  51121. };
  51122. newOption.series = newOption.series.concat(result.series);
  51123. }
  51124. }
  51125. else {
  51126. var result = parseListContents(block);
  51127. newOption.series.push(result);
  51128. }
  51129. });
  51130. return newOption;
  51131. }
  51132. /**
  51133. * @alias {module:echarts/component/toolbox/feature/DataView}
  51134. * @constructor
  51135. * @param {module:echarts/model/Model} model
  51136. */
  51137. function DataView(model) {
  51138. this._dom = null;
  51139. this.model = model;
  51140. }
  51141. DataView.defaultOption = {
  51142. show: true,
  51143. readOnly: false,
  51144. optionToContent: null,
  51145. contentToOption: null,
  51146. 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',
  51147. title: clone(dataViewLang.title),
  51148. lang: clone(dataViewLang.lang),
  51149. backgroundColor: '#fff',
  51150. textColor: '#000',
  51151. textareaColor: '#fff',
  51152. textareaBorderColor: '#333',
  51153. buttonColor: '#c23531',
  51154. buttonTextColor: '#fff'
  51155. };
  51156. DataView.prototype.onclick = function (ecModel, api) {
  51157. var container = api.getDom();
  51158. var model = this.model;
  51159. if (this._dom) {
  51160. container.removeChild(this._dom);
  51161. }
  51162. var root = document.createElement('div');
  51163. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  51164. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  51165. // Create elements
  51166. var header = document.createElement('h4');
  51167. var lang$$1 = model.get('lang') || [];
  51168. header.innerHTML = lang$$1[0] || model.get('title');
  51169. header.style.cssText = 'margin: 10px 20px;';
  51170. header.style.color = model.get('textColor');
  51171. var viewMain = document.createElement('div');
  51172. var textarea = document.createElement('textarea');
  51173. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  51174. var optionToContent = model.get('optionToContent');
  51175. var contentToOption = model.get('contentToOption');
  51176. var result = getContentFromModel(ecModel);
  51177. if (typeof optionToContent === 'function') {
  51178. var htmlOrDom = optionToContent(api.getOption());
  51179. if (typeof htmlOrDom === 'string') {
  51180. viewMain.innerHTML = htmlOrDom;
  51181. }
  51182. else if (isDom(htmlOrDom)) {
  51183. viewMain.appendChild(htmlOrDom);
  51184. }
  51185. }
  51186. else {
  51187. // Use default textarea
  51188. viewMain.appendChild(textarea);
  51189. textarea.readOnly = model.get('readOnly');
  51190. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  51191. textarea.style.color = model.get('textColor');
  51192. textarea.style.borderColor = model.get('textareaBorderColor');
  51193. textarea.style.backgroundColor = model.get('textareaColor');
  51194. textarea.value = result.value;
  51195. }
  51196. var blockMetaList = result.meta;
  51197. var buttonContainer = document.createElement('div');
  51198. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  51199. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  51200. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  51201. var closeButton = document.createElement('div');
  51202. var refreshButton = document.createElement('div');
  51203. buttonStyle += ';background-color:' + model.get('buttonColor');
  51204. buttonStyle += ';color:' + model.get('buttonTextColor');
  51205. var self = this;
  51206. function close() {
  51207. container.removeChild(root);
  51208. self._dom = null;
  51209. }
  51210. addEventListener(closeButton, 'click', close);
  51211. addEventListener(refreshButton, 'click', function () {
  51212. var newOption;
  51213. try {
  51214. if (typeof contentToOption === 'function') {
  51215. newOption = contentToOption(viewMain, api.getOption());
  51216. }
  51217. else {
  51218. newOption = parseContents(textarea.value, blockMetaList);
  51219. }
  51220. }
  51221. catch (e) {
  51222. close();
  51223. throw new Error('Data view format error ' + e);
  51224. }
  51225. if (newOption) {
  51226. api.dispatchAction({
  51227. type: 'changeDataView',
  51228. newOption: newOption
  51229. });
  51230. }
  51231. close();
  51232. });
  51233. closeButton.innerHTML = lang$$1[1];
  51234. refreshButton.innerHTML = lang$$1[2];
  51235. refreshButton.style.cssText = buttonStyle;
  51236. closeButton.style.cssText = buttonStyle;
  51237. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  51238. buttonContainer.appendChild(closeButton);
  51239. root.appendChild(header);
  51240. root.appendChild(viewMain);
  51241. root.appendChild(buttonContainer);
  51242. viewMain.style.height = (container.clientHeight - 80) + 'px';
  51243. container.appendChild(root);
  51244. this._dom = root;
  51245. };
  51246. DataView.prototype.remove = function (ecModel, api) {
  51247. this._dom && api.getDom().removeChild(this._dom);
  51248. };
  51249. DataView.prototype.dispose = function (ecModel, api) {
  51250. this.remove(ecModel, api);
  51251. };
  51252. /**
  51253. * @inner
  51254. */
  51255. function tryMergeDataOption(newData, originalData) {
  51256. return map(newData, function (newVal, idx) {
  51257. var original = originalData && originalData[idx];
  51258. if (isObject$1(original) && !isArray(original)) {
  51259. if (isObject$1(newVal) && !isArray(newVal)) {
  51260. newVal = newVal.value;
  51261. }
  51262. // Original data has option
  51263. return defaults({
  51264. value: newVal
  51265. }, original);
  51266. }
  51267. else {
  51268. return newVal;
  51269. }
  51270. });
  51271. }
  51272. register$2('dataView', DataView);
  51273. registerAction({
  51274. type: 'changeDataView',
  51275. event: 'dataViewChanged',
  51276. update: 'prepareAndUpdate'
  51277. }, function (payload, ecModel) {
  51278. var newSeriesOptList = [];
  51279. each$1(payload.newOption.series, function (seriesOpt) {
  51280. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  51281. if (!seriesModel) {
  51282. // New created series
  51283. // Geuss the series type
  51284. newSeriesOptList.push(extend({
  51285. // Default is scatter
  51286. type: 'scatter'
  51287. }, seriesOpt));
  51288. }
  51289. else {
  51290. var originalData = seriesModel.get('data');
  51291. newSeriesOptList.push({
  51292. name: seriesOpt.name,
  51293. data: tryMergeDataOption(seriesOpt.data, originalData)
  51294. });
  51295. }
  51296. });
  51297. ecModel.mergeOption(defaults({
  51298. series: newSeriesOptList
  51299. }, payload.newOption));
  51300. });
  51301. /*
  51302. * Licensed to the Apache Software Foundation (ASF) under one
  51303. * or more contributor license agreements. See the NOTICE file
  51304. * distributed with this work for additional information
  51305. * regarding copyright ownership. The ASF licenses this file
  51306. * to you under the Apache License, Version 2.0 (the
  51307. * "License"); you may not use this file except in compliance
  51308. * with the License. You may obtain a copy of the License at
  51309. *
  51310. * http://www.apache.org/licenses/LICENSE-2.0
  51311. *
  51312. * Unless required by applicable law or agreed to in writing,
  51313. * software distributed under the License is distributed on an
  51314. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51315. * KIND, either express or implied. See the License for the
  51316. * specific language governing permissions and limitations
  51317. * under the License.
  51318. */
  51319. var curry$5 = curry;
  51320. var each$16 = each$1;
  51321. var map$2 = map;
  51322. var mathMin$5 = Math.min;
  51323. var mathMax$5 = Math.max;
  51324. var mathPow$2 = Math.pow;
  51325. var COVER_Z = 10000;
  51326. var UNSELECT_THRESHOLD = 6;
  51327. var MIN_RESIZE_LINE_WIDTH = 6;
  51328. var MUTEX_RESOURCE_KEY = 'globalPan';
  51329. var DIRECTION_MAP = {
  51330. w: [0, 0],
  51331. e: [0, 1],
  51332. n: [1, 0],
  51333. s: [1, 1]
  51334. };
  51335. var CURSOR_MAP = {
  51336. w: 'ew',
  51337. e: 'ew',
  51338. n: 'ns',
  51339. s: 'ns',
  51340. ne: 'nesw',
  51341. sw: 'nesw',
  51342. nw: 'nwse',
  51343. se: 'nwse'
  51344. };
  51345. var DEFAULT_BRUSH_OPT = {
  51346. brushStyle: {
  51347. lineWidth: 2,
  51348. stroke: 'rgba(0,0,0,0.3)',
  51349. fill: 'rgba(0,0,0,0.1)'
  51350. },
  51351. transformable: true,
  51352. brushMode: 'single',
  51353. removeOnClick: false
  51354. };
  51355. var baseUID = 0;
  51356. /**
  51357. * @alias module:echarts/component/helper/BrushController
  51358. * @constructor
  51359. * @mixin {module:zrender/mixin/Eventful}
  51360. * @event module:echarts/component/helper/BrushController#brush
  51361. * params:
  51362. * areas: Array.<Array>, coord relates to container group,
  51363. * If no container specified, to global.
  51364. * opt {
  51365. * isEnd: boolean,
  51366. * removeOnClick: boolean
  51367. * }
  51368. *
  51369. * @param {module:zrender/zrender~ZRender} zr
  51370. */
  51371. function BrushController(zr) {
  51372. if (__DEV__) {
  51373. assert$1(zr);
  51374. }
  51375. Eventful.call(this);
  51376. /**
  51377. * @type {module:zrender/zrender~ZRender}
  51378. * @private
  51379. */
  51380. this._zr = zr;
  51381. /**
  51382. * @type {module:zrender/container/Group}
  51383. * @readOnly
  51384. */
  51385. this.group = new Group();
  51386. /**
  51387. * Only for drawing (after enabledBrush).
  51388. * 'line', 'rect', 'polygon' or false
  51389. * If passing false/null/undefined, disable brush.
  51390. * If passing 'auto', determined by panel.defaultBrushType
  51391. * @private
  51392. * @type {string}
  51393. */
  51394. this._brushType;
  51395. /**
  51396. * Only for drawing (after enabledBrush).
  51397. *
  51398. * @private
  51399. * @type {Object}
  51400. */
  51401. this._brushOption;
  51402. /**
  51403. * @private
  51404. * @type {Object}
  51405. */
  51406. this._panels;
  51407. /**
  51408. * @private
  51409. * @type {Array.<nubmer>}
  51410. */
  51411. this._track = [];
  51412. /**
  51413. * @private
  51414. * @type {boolean}
  51415. */
  51416. this._dragging;
  51417. /**
  51418. * @private
  51419. * @type {Array}
  51420. */
  51421. this._covers = [];
  51422. /**
  51423. * @private
  51424. * @type {moudule:zrender/container/Group}
  51425. */
  51426. this._creatingCover;
  51427. /**
  51428. * `true` means global panel
  51429. * @private
  51430. * @type {module:zrender/container/Group|boolean}
  51431. */
  51432. this._creatingPanel;
  51433. /**
  51434. * @private
  51435. * @type {boolean}
  51436. */
  51437. this._enableGlobalPan;
  51438. /**
  51439. * @private
  51440. * @type {boolean}
  51441. */
  51442. if (__DEV__) {
  51443. this._mounted;
  51444. }
  51445. /**
  51446. * @private
  51447. * @type {string}
  51448. */
  51449. this._uid = 'brushController_' + baseUID++;
  51450. /**
  51451. * @private
  51452. * @type {Object}
  51453. */
  51454. this._handlers = {};
  51455. each$16(pointerHandlers, function (handler, eventName) {
  51456. this._handlers[eventName] = bind(handler, this);
  51457. }, this);
  51458. }
  51459. BrushController.prototype = {
  51460. constructor: BrushController,
  51461. /**
  51462. * If set to null/undefined/false, select disabled.
  51463. * @param {Object} brushOption
  51464. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  51465. * If passing false/null/undefined, disable brush.
  51466. * If passing 'auto', determined by panel.defaultBrushType.
  51467. * ('auto' can not be used in global panel)
  51468. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  51469. * @param {boolean} [brushOption.transformable=true]
  51470. * @param {boolean} [brushOption.removeOnClick=false]
  51471. * @param {Object} [brushOption.brushStyle]
  51472. * @param {number} [brushOption.brushStyle.width]
  51473. * @param {number} [brushOption.brushStyle.lineWidth]
  51474. * @param {string} [brushOption.brushStyle.stroke]
  51475. * @param {string} [brushOption.brushStyle.fill]
  51476. * @param {number} [brushOption.z]
  51477. */
  51478. enableBrush: function (brushOption) {
  51479. if (__DEV__) {
  51480. assert$1(this._mounted);
  51481. }
  51482. this._brushType && doDisableBrush(this);
  51483. brushOption.brushType && doEnableBrush(this, brushOption);
  51484. return this;
  51485. },
  51486. /**
  51487. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  51488. * Each items: {
  51489. * panelId, // mandatory.
  51490. * clipPath, // mandatory. function.
  51491. * isTargetByCursor, // mandatory. function.
  51492. * defaultBrushType, // optional, only used when brushType is 'auto'.
  51493. * getLinearBrushOtherExtent, // optional. function.
  51494. * }
  51495. */
  51496. setPanels: function (panelOpts) {
  51497. if (panelOpts && panelOpts.length) {
  51498. var panels = this._panels = {};
  51499. each$1(panelOpts, function (panelOpts) {
  51500. panels[panelOpts.panelId] = clone(panelOpts);
  51501. });
  51502. }
  51503. else {
  51504. this._panels = null;
  51505. }
  51506. return this;
  51507. },
  51508. /**
  51509. * @param {Object} [opt]
  51510. * @return {boolean} [opt.enableGlobalPan=false]
  51511. */
  51512. mount: function (opt) {
  51513. opt = opt || {};
  51514. if (__DEV__) {
  51515. this._mounted = true; // should be at first.
  51516. }
  51517. this._enableGlobalPan = opt.enableGlobalPan;
  51518. var thisGroup = this.group;
  51519. this._zr.add(thisGroup);
  51520. thisGroup.attr({
  51521. position: opt.position || [0, 0],
  51522. rotation: opt.rotation || 0,
  51523. scale: opt.scale || [1, 1]
  51524. });
  51525. this._transform = thisGroup.getLocalTransform();
  51526. return this;
  51527. },
  51528. eachCover: function (cb, context) {
  51529. each$16(this._covers, cb, context);
  51530. },
  51531. /**
  51532. * Update covers.
  51533. * @param {Array.<Object>} brushOptionList Like:
  51534. * [
  51535. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  51536. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  51537. * ...
  51538. * ]
  51539. * `brushType` is required in each cover info. (can not be 'auto')
  51540. * `id` is not mandatory.
  51541. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  51542. * If brushOptionList is null/undefined, all covers removed.
  51543. */
  51544. updateCovers: function (brushOptionList) {
  51545. if (__DEV__) {
  51546. assert$1(this._mounted);
  51547. }
  51548. brushOptionList = map(brushOptionList, function (brushOption) {
  51549. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51550. });
  51551. var tmpIdPrefix = '\0-brush-index-';
  51552. var oldCovers = this._covers;
  51553. var newCovers = this._covers = [];
  51554. var controller = this;
  51555. var creatingCover = this._creatingCover;
  51556. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  51557. .add(addOrUpdate)
  51558. .update(addOrUpdate)
  51559. .remove(remove)
  51560. .execute();
  51561. return this;
  51562. function getKey(brushOption, index) {
  51563. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  51564. + '-' + brushOption.brushType;
  51565. }
  51566. function oldGetKey(cover, index) {
  51567. return getKey(cover.__brushOption, index);
  51568. }
  51569. function addOrUpdate(newIndex, oldIndex) {
  51570. var newBrushOption = brushOptionList[newIndex];
  51571. // Consider setOption in event listener of brushSelect,
  51572. // where updating cover when creating should be forbiden.
  51573. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  51574. newCovers[newIndex] = oldCovers[oldIndex];
  51575. }
  51576. else {
  51577. var cover = newCovers[newIndex] = oldIndex != null
  51578. ? (
  51579. oldCovers[oldIndex].__brushOption = newBrushOption,
  51580. oldCovers[oldIndex]
  51581. )
  51582. : endCreating(controller, createCover(controller, newBrushOption));
  51583. updateCoverAfterCreation(controller, cover);
  51584. }
  51585. }
  51586. function remove(oldIndex) {
  51587. if (oldCovers[oldIndex] !== creatingCover) {
  51588. controller.group.remove(oldCovers[oldIndex]);
  51589. }
  51590. }
  51591. },
  51592. unmount: function () {
  51593. if (__DEV__) {
  51594. if (!this._mounted) {
  51595. return;
  51596. }
  51597. }
  51598. this.enableBrush(false);
  51599. // container may 'removeAll' outside.
  51600. clearCovers(this);
  51601. this._zr.remove(this.group);
  51602. if (__DEV__) {
  51603. this._mounted = false; // should be at last.
  51604. }
  51605. return this;
  51606. },
  51607. dispose: function () {
  51608. this.unmount();
  51609. this.off();
  51610. }
  51611. };
  51612. mixin(BrushController, Eventful);
  51613. function doEnableBrush(controller, brushOption) {
  51614. var zr = controller._zr;
  51615. // Consider roam, which takes globalPan too.
  51616. if (!controller._enableGlobalPan) {
  51617. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51618. }
  51619. mountHandlers(zr, controller._handlers);
  51620. controller._brushType = brushOption.brushType;
  51621. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  51622. }
  51623. function doDisableBrush(controller) {
  51624. var zr = controller._zr;
  51625. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  51626. unmountHandlers(zr, controller._handlers);
  51627. controller._brushType = controller._brushOption = null;
  51628. }
  51629. function mountHandlers(zr, handlers) {
  51630. each$16(handlers, function (handler, eventName) {
  51631. zr.on(eventName, handler);
  51632. });
  51633. }
  51634. function unmountHandlers(zr, handlers) {
  51635. each$16(handlers, function (handler, eventName) {
  51636. zr.off(eventName, handler);
  51637. });
  51638. }
  51639. function createCover(controller, brushOption) {
  51640. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  51641. cover.__brushOption = brushOption;
  51642. updateZ$1(cover, brushOption);
  51643. controller.group.add(cover);
  51644. return cover;
  51645. }
  51646. function endCreating(controller, creatingCover) {
  51647. var coverRenderer = getCoverRenderer(creatingCover);
  51648. if (coverRenderer.endCreating) {
  51649. coverRenderer.endCreating(controller, creatingCover);
  51650. updateZ$1(creatingCover, creatingCover.__brushOption);
  51651. }
  51652. return creatingCover;
  51653. }
  51654. function updateCoverShape(controller, cover) {
  51655. var brushOption = cover.__brushOption;
  51656. getCoverRenderer(cover).updateCoverShape(
  51657. controller, cover, brushOption.range, brushOption
  51658. );
  51659. }
  51660. function updateZ$1(cover, brushOption) {
  51661. var z = brushOption.z;
  51662. z == null && (z = COVER_Z);
  51663. cover.traverse(function (el) {
  51664. el.z = z;
  51665. el.z2 = z; // Consider in given container.
  51666. });
  51667. }
  51668. function updateCoverAfterCreation(controller, cover) {
  51669. getCoverRenderer(cover).updateCommon(controller, cover);
  51670. updateCoverShape(controller, cover);
  51671. }
  51672. function getCoverRenderer(cover) {
  51673. return coverRenderers[cover.__brushOption.brushType];
  51674. }
  51675. // return target panel or `true` (means global panel)
  51676. function getPanelByPoint(controller, e, localCursorPoint) {
  51677. var panels = controller._panels;
  51678. if (!panels) {
  51679. return true; // Global panel
  51680. }
  51681. var panel;
  51682. var transform = controller._transform;
  51683. each$16(panels, function (pn) {
  51684. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  51685. });
  51686. return panel;
  51687. }
  51688. // Return a panel or true
  51689. function getPanelByCover(controller, cover) {
  51690. var panels = controller._panels;
  51691. if (!panels) {
  51692. return true; // Global panel
  51693. }
  51694. var panelId = cover.__brushOption.panelId;
  51695. // User may give cover without coord sys info,
  51696. // which is then treated as global panel.
  51697. return panelId != null ? panels[panelId] : true;
  51698. }
  51699. function clearCovers(controller) {
  51700. var covers = controller._covers;
  51701. var originalLength = covers.length;
  51702. each$16(covers, function (cover) {
  51703. controller.group.remove(cover);
  51704. }, controller);
  51705. covers.length = 0;
  51706. return !!originalLength;
  51707. }
  51708. function trigger$1(controller, opt) {
  51709. var areas = map$2(controller._covers, function (cover) {
  51710. var brushOption = cover.__brushOption;
  51711. var range = clone(brushOption.range);
  51712. return {
  51713. brushType: brushOption.brushType,
  51714. panelId: brushOption.panelId,
  51715. range: range
  51716. };
  51717. });
  51718. controller.trigger('brush', areas, {
  51719. isEnd: !!opt.isEnd,
  51720. removeOnClick: !!opt.removeOnClick
  51721. });
  51722. }
  51723. function shouldShowCover(controller) {
  51724. var track = controller._track;
  51725. if (!track.length) {
  51726. return false;
  51727. }
  51728. var p2 = track[track.length - 1];
  51729. var p1 = track[0];
  51730. var dx = p2[0] - p1[0];
  51731. var dy = p2[1] - p1[1];
  51732. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  51733. return dist > UNSELECT_THRESHOLD;
  51734. }
  51735. function getTrackEnds(track) {
  51736. var tail = track.length - 1;
  51737. tail < 0 && (tail = 0);
  51738. return [track[0], track[tail]];
  51739. }
  51740. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  51741. var cover = new Group();
  51742. cover.add(new Rect({
  51743. name: 'main',
  51744. style: makeStyle(brushOption),
  51745. silent: true,
  51746. draggable: true,
  51747. cursor: 'move',
  51748. drift: curry$5(doDrift, controller, cover, 'nswe'),
  51749. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51750. }));
  51751. each$16(
  51752. edgeNames,
  51753. function (name) {
  51754. cover.add(new Rect({
  51755. name: name,
  51756. style: {opacity: 0},
  51757. draggable: true,
  51758. silent: true,
  51759. invisible: true,
  51760. drift: curry$5(doDrift, controller, cover, name),
  51761. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  51762. }));
  51763. }
  51764. );
  51765. return cover;
  51766. }
  51767. function updateBaseRect(controller, cover, localRange, brushOption) {
  51768. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  51769. var handleSize = mathMax$5(lineWidth, MIN_RESIZE_LINE_WIDTH);
  51770. var x = localRange[0][0];
  51771. var y = localRange[1][0];
  51772. var xa = x - lineWidth / 2;
  51773. var ya = y - lineWidth / 2;
  51774. var x2 = localRange[0][1];
  51775. var y2 = localRange[1][1];
  51776. var x2a = x2 - handleSize + lineWidth / 2;
  51777. var y2a = y2 - handleSize + lineWidth / 2;
  51778. var width = x2 - x;
  51779. var height = y2 - y;
  51780. var widtha = width + lineWidth;
  51781. var heighta = height + lineWidth;
  51782. updateRectShape(controller, cover, 'main', x, y, width, height);
  51783. if (brushOption.transformable) {
  51784. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51785. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51786. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51787. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51788. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51789. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51790. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51791. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51792. }
  51793. }
  51794. function updateCommon(controller, cover) {
  51795. var brushOption = cover.__brushOption;
  51796. var transformable = brushOption.transformable;
  51797. var mainEl = cover.childAt(0);
  51798. mainEl.useStyle(makeStyle(brushOption));
  51799. mainEl.attr({
  51800. silent: !transformable,
  51801. cursor: transformable ? 'move' : 'default'
  51802. });
  51803. each$16(
  51804. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  51805. function (name) {
  51806. var el = cover.childOfName(name);
  51807. var globalDir = getGlobalDirection(controller, name);
  51808. el && el.attr({
  51809. silent: !transformable,
  51810. invisible: !transformable,
  51811. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51812. });
  51813. }
  51814. );
  51815. }
  51816. function updateRectShape(controller, cover, name, x, y, w, h) {
  51817. var el = cover.childOfName(name);
  51818. el && el.setShape(pointsToRect(
  51819. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51820. ));
  51821. }
  51822. function makeStyle(brushOption) {
  51823. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51824. }
  51825. function formatRectRange(x, y, x2, y2) {
  51826. var min = [mathMin$5(x, x2), mathMin$5(y, y2)];
  51827. var max = [mathMax$5(x, x2), mathMax$5(y, y2)];
  51828. return [
  51829. [min[0], max[0]], // x range
  51830. [min[1], max[1]] // y range
  51831. ];
  51832. }
  51833. function getTransform$1(controller) {
  51834. return getTransform(controller.group);
  51835. }
  51836. function getGlobalDirection(controller, localDirection) {
  51837. if (localDirection.length > 1) {
  51838. localDirection = localDirection.split('');
  51839. var globalDir = [
  51840. getGlobalDirection(controller, localDirection[0]),
  51841. getGlobalDirection(controller, localDirection[1])
  51842. ];
  51843. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51844. return globalDir.join('');
  51845. }
  51846. else {
  51847. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  51848. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  51849. var globalDir = transformDirection(
  51850. map$$1[localDirection], getTransform$1(controller)
  51851. );
  51852. return inverseMap[globalDir];
  51853. }
  51854. }
  51855. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  51856. var brushOption = cover.__brushOption;
  51857. var rectRange = toRectRange(brushOption.range);
  51858. var localDelta = toLocalDelta(controller, dx, dy);
  51859. each$16(name.split(''), function (namePart) {
  51860. var ind = DIRECTION_MAP[namePart];
  51861. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51862. });
  51863. brushOption.range = fromRectRange(formatRectRange(
  51864. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  51865. ));
  51866. updateCoverAfterCreation(controller, cover);
  51867. trigger$1(controller, {isEnd: false});
  51868. }
  51869. function driftPolygon(controller, cover, dx, dy, e) {
  51870. var range = cover.__brushOption.range;
  51871. var localDelta = toLocalDelta(controller, dx, dy);
  51872. each$16(range, function (point) {
  51873. point[0] += localDelta[0];
  51874. point[1] += localDelta[1];
  51875. });
  51876. updateCoverAfterCreation(controller, cover);
  51877. trigger$1(controller, {isEnd: false});
  51878. }
  51879. function toLocalDelta(controller, dx, dy) {
  51880. var thisGroup = controller.group;
  51881. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51882. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51883. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51884. }
  51885. function clipByPanel(controller, cover, data) {
  51886. var panel = getPanelByCover(controller, cover);
  51887. return (panel && panel !== true)
  51888. ? panel.clipPath(data, controller._transform)
  51889. : clone(data);
  51890. }
  51891. function pointsToRect(points) {
  51892. var xmin = mathMin$5(points[0][0], points[1][0]);
  51893. var ymin = mathMin$5(points[0][1], points[1][1]);
  51894. var xmax = mathMax$5(points[0][0], points[1][0]);
  51895. var ymax = mathMax$5(points[0][1], points[1][1]);
  51896. return {
  51897. x: xmin,
  51898. y: ymin,
  51899. width: xmax - xmin,
  51900. height: ymax - ymin
  51901. };
  51902. }
  51903. function resetCursor(controller, e, localCursorPoint) {
  51904. if (
  51905. // Check active
  51906. !controller._brushType
  51907. // resetCursor should be always called when mouse is in zr area,
  51908. // but not called when mouse is out of zr area to avoid bad influence
  51909. // if `mousemove`, `mouseup` are triggered from `document` event.
  51910. || isOutsideZrArea(controller, e)
  51911. ) {
  51912. return;
  51913. }
  51914. var zr = controller._zr;
  51915. var covers = controller._covers;
  51916. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51917. // Check whether in covers.
  51918. if (!controller._dragging) {
  51919. for (var i = 0; i < covers.length; i++) {
  51920. var brushOption = covers[i].__brushOption;
  51921. if (currPanel
  51922. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  51923. && coverRenderers[brushOption.brushType].contain(
  51924. covers[i], localCursorPoint[0], localCursorPoint[1]
  51925. )
  51926. ) {
  51927. // Use cursor style set on cover.
  51928. return;
  51929. }
  51930. }
  51931. }
  51932. currPanel && zr.setCursorStyle('crosshair');
  51933. }
  51934. function preventDefault(e) {
  51935. var rawE = e.event;
  51936. rawE.preventDefault && rawE.preventDefault();
  51937. }
  51938. function mainShapeContain(cover, x, y) {
  51939. return cover.childOfName('main').contain(x, y);
  51940. }
  51941. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51942. var creatingCover = controller._creatingCover;
  51943. var panel = controller._creatingPanel;
  51944. var thisBrushOption = controller._brushOption;
  51945. var eventParams;
  51946. controller._track.push(localCursorPoint.slice());
  51947. if (shouldShowCover(controller) || creatingCover) {
  51948. if (panel && !creatingCover) {
  51949. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51950. var brushOption = clone(thisBrushOption);
  51951. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51952. brushOption.panelId = panel === true ? null : panel.panelId;
  51953. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51954. controller._covers.push(creatingCover);
  51955. }
  51956. if (creatingCover) {
  51957. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51958. var coverBrushOption = creatingCover.__brushOption;
  51959. coverBrushOption.range = coverRenderer.getCreatingRange(
  51960. clipByPanel(controller, creatingCover, controller._track)
  51961. );
  51962. if (isEnd) {
  51963. endCreating(controller, creatingCover);
  51964. coverRenderer.updateCommon(controller, creatingCover);
  51965. }
  51966. updateCoverShape(controller, creatingCover);
  51967. eventParams = {isEnd: isEnd};
  51968. }
  51969. }
  51970. else if (
  51971. isEnd
  51972. && thisBrushOption.brushMode === 'single'
  51973. && thisBrushOption.removeOnClick
  51974. ) {
  51975. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51976. // But a single click do not clear covers, because user may have casual
  51977. // clicks (for example, click on other component and do not expect covers
  51978. // disappear).
  51979. // Only some cover removed, trigger action, but not every click trigger action.
  51980. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51981. eventParams = {isEnd: isEnd, removeOnClick: true};
  51982. }
  51983. }
  51984. return eventParams;
  51985. }
  51986. function determineBrushType(brushType, panel) {
  51987. if (brushType === 'auto') {
  51988. if (__DEV__) {
  51989. assert$1(
  51990. panel && panel.defaultBrushType,
  51991. 'MUST have defaultBrushType when brushType is "atuo"'
  51992. );
  51993. }
  51994. return panel.defaultBrushType;
  51995. }
  51996. return brushType;
  51997. }
  51998. var pointerHandlers = {
  51999. mousedown: function (e) {
  52000. if (this._dragging) {
  52001. // In case some browser do not support globalOut,
  52002. // and release mose out side the browser.
  52003. handleDragEnd(this, e);
  52004. }
  52005. else if (!e.target || !e.target.draggable) {
  52006. preventDefault(e);
  52007. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  52008. this._creatingCover = null;
  52009. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  52010. if (panel) {
  52011. this._dragging = true;
  52012. this._track = [localCursorPoint.slice()];
  52013. }
  52014. }
  52015. },
  52016. mousemove: function (e) {
  52017. var x = e.offsetX;
  52018. var y = e.offsetY;
  52019. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  52020. resetCursor(this, e, localCursorPoint);
  52021. if (this._dragging) {
  52022. preventDefault(e);
  52023. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  52024. eventParams && trigger$1(this, eventParams);
  52025. }
  52026. },
  52027. mouseup: function (e) {
  52028. handleDragEnd(this, e);
  52029. }
  52030. };
  52031. function handleDragEnd(controller, e) {
  52032. if (controller._dragging) {
  52033. preventDefault(e);
  52034. var x = e.offsetX;
  52035. var y = e.offsetY;
  52036. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  52037. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  52038. controller._dragging = false;
  52039. controller._track = [];
  52040. controller._creatingCover = null;
  52041. // trigger event shoule be at final, after procedure will be nested.
  52042. eventParams && trigger$1(controller, eventParams);
  52043. }
  52044. }
  52045. function isOutsideZrArea(controller, x, y) {
  52046. var zr = controller._zr;
  52047. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  52048. }
  52049. /**
  52050. * key: brushType
  52051. * @type {Object}
  52052. */
  52053. var coverRenderers = {
  52054. lineX: getLineRenderer(0),
  52055. lineY: getLineRenderer(1),
  52056. rect: {
  52057. createCover: function (controller, brushOption) {
  52058. return createBaseRectCover(
  52059. curry$5(
  52060. driftRect,
  52061. function (range) {
  52062. return range;
  52063. },
  52064. function (range) {
  52065. return range;
  52066. }
  52067. ),
  52068. controller,
  52069. brushOption,
  52070. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  52071. );
  52072. },
  52073. getCreatingRange: function (localTrack) {
  52074. var ends = getTrackEnds(localTrack);
  52075. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  52076. },
  52077. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52078. updateBaseRect(controller, cover, localRange, brushOption);
  52079. },
  52080. updateCommon: updateCommon,
  52081. contain: mainShapeContain
  52082. },
  52083. polygon: {
  52084. createCover: function (controller, brushOption) {
  52085. var cover = new Group();
  52086. // Do not use graphic.Polygon because graphic.Polyline do not close the
  52087. // border of the shape when drawing, which is a better experience for user.
  52088. cover.add(new Polyline({
  52089. name: 'main',
  52090. style: makeStyle(brushOption),
  52091. silent: true
  52092. }));
  52093. return cover;
  52094. },
  52095. getCreatingRange: function (localTrack) {
  52096. return localTrack;
  52097. },
  52098. endCreating: function (controller, cover) {
  52099. cover.remove(cover.childAt(0));
  52100. // Use graphic.Polygon close the shape.
  52101. cover.add(new Polygon({
  52102. name: 'main',
  52103. draggable: true,
  52104. drift: curry$5(driftPolygon, controller, cover),
  52105. ondragend: curry$5(trigger$1, controller, {isEnd: true})
  52106. }));
  52107. },
  52108. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52109. cover.childAt(0).setShape({
  52110. points: clipByPanel(controller, cover, localRange)
  52111. });
  52112. },
  52113. updateCommon: updateCommon,
  52114. contain: mainShapeContain
  52115. }
  52116. };
  52117. function getLineRenderer(xyIndex) {
  52118. return {
  52119. createCover: function (controller, brushOption) {
  52120. return createBaseRectCover(
  52121. curry$5(
  52122. driftRect,
  52123. function (range) {
  52124. var rectRange = [range, [0, 100]];
  52125. xyIndex && rectRange.reverse();
  52126. return rectRange;
  52127. },
  52128. function (rectRange) {
  52129. return rectRange[xyIndex];
  52130. }
  52131. ),
  52132. controller,
  52133. brushOption,
  52134. [['w', 'e'], ['n', 's']][xyIndex]
  52135. );
  52136. },
  52137. getCreatingRange: function (localTrack) {
  52138. var ends = getTrackEnds(localTrack);
  52139. var min = mathMin$5(ends[0][xyIndex], ends[1][xyIndex]);
  52140. var max = mathMax$5(ends[0][xyIndex], ends[1][xyIndex]);
  52141. return [min, max];
  52142. },
  52143. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52144. var otherExtent;
  52145. // If brushWidth not specified, fit the panel.
  52146. var panel = getPanelByCover(controller, cover);
  52147. if (panel !== true && panel.getLinearBrushOtherExtent) {
  52148. otherExtent = panel.getLinearBrushOtherExtent(
  52149. xyIndex, controller._transform
  52150. );
  52151. }
  52152. else {
  52153. var zr = controller._zr;
  52154. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  52155. }
  52156. var rectRange = [localRange, otherExtent];
  52157. xyIndex && rectRange.reverse();
  52158. updateBaseRect(controller, cover, rectRange, brushOption);
  52159. },
  52160. updateCommon: updateCommon,
  52161. contain: mainShapeContain
  52162. };
  52163. }
  52164. /*
  52165. * Licensed to the Apache Software Foundation (ASF) under one
  52166. * or more contributor license agreements. See the NOTICE file
  52167. * distributed with this work for additional information
  52168. * regarding copyright ownership. The ASF licenses this file
  52169. * to you under the Apache License, Version 2.0 (the
  52170. * "License"); you may not use this file except in compliance
  52171. * with the License. You may obtain a copy of the License at
  52172. *
  52173. * http://www.apache.org/licenses/LICENSE-2.0
  52174. *
  52175. * Unless required by applicable law or agreed to in writing,
  52176. * software distributed under the License is distributed on an
  52177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52178. * KIND, either express or implied. See the License for the
  52179. * specific language governing permissions and limitations
  52180. * under the License.
  52181. */
  52182. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  52183. /**
  52184. * Avoid that: mouse click on a elements that is over geo or graph,
  52185. * but roam is triggered.
  52186. */
  52187. function onIrrelevantElement(e, api, targetCoordSysModel) {
  52188. var model = api.getComponentByElement(e.topTarget);
  52189. // If model is axisModel, it works only if it is injected with coordinateSystem.
  52190. var coordSys = model && model.coordinateSystem;
  52191. return model
  52192. && model !== targetCoordSysModel
  52193. && !IRRELEVANT_EXCLUDES[model.mainType]
  52194. && (coordSys && coordSys.model !== targetCoordSysModel);
  52195. }
  52196. /*
  52197. * Licensed to the Apache Software Foundation (ASF) under one
  52198. * or more contributor license agreements. See the NOTICE file
  52199. * distributed with this work for additional information
  52200. * regarding copyright ownership. The ASF licenses this file
  52201. * to you under the Apache License, Version 2.0 (the
  52202. * "License"); you may not use this file except in compliance
  52203. * with the License. You may obtain a copy of the License at
  52204. *
  52205. * http://www.apache.org/licenses/LICENSE-2.0
  52206. *
  52207. * Unless required by applicable law or agreed to in writing,
  52208. * software distributed under the License is distributed on an
  52209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52210. * KIND, either express or implied. See the License for the
  52211. * specific language governing permissions and limitations
  52212. * under the License.
  52213. */
  52214. function makeRectPanelClipPath(rect) {
  52215. rect = normalizeRect(rect);
  52216. return function (localPoints, transform) {
  52217. return clipPointsByRect(localPoints, rect);
  52218. };
  52219. }
  52220. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  52221. rect = normalizeRect(rect);
  52222. return function (xyIndex) {
  52223. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  52224. var brushWidth = idx ? rect.width : rect.height;
  52225. var base = idx ? rect.x : rect.y;
  52226. return [base, base + (brushWidth || 0)];
  52227. };
  52228. }
  52229. function makeRectIsTargetByCursor(rect, api, targetModel) {
  52230. rect = normalizeRect(rect);
  52231. return function (e, localCursorPoint, transform) {
  52232. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  52233. && !onIrrelevantElement(e, api, targetModel);
  52234. };
  52235. }
  52236. // Consider width/height is negative.
  52237. function normalizeRect(rect) {
  52238. return BoundingRect.create(rect);
  52239. }
  52240. /*
  52241. * Licensed to the Apache Software Foundation (ASF) under one
  52242. * or more contributor license agreements. See the NOTICE file
  52243. * distributed with this work for additional information
  52244. * regarding copyright ownership. The ASF licenses this file
  52245. * to you under the Apache License, Version 2.0 (the
  52246. * "License"); you may not use this file except in compliance
  52247. * with the License. You may obtain a copy of the License at
  52248. *
  52249. * http://www.apache.org/licenses/LICENSE-2.0
  52250. *
  52251. * Unless required by applicable law or agreed to in writing,
  52252. * software distributed under the License is distributed on an
  52253. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52254. * KIND, either express or implied. See the License for the
  52255. * specific language governing permissions and limitations
  52256. * under the License.
  52257. */
  52258. var each$17 = each$1;
  52259. var indexOf$2 = indexOf;
  52260. var curry$6 = curry;
  52261. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  52262. // FIXME
  52263. // how to genarialize to more coordinate systems.
  52264. var INCLUDE_FINDER_MAIN_TYPES = [
  52265. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  52266. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  52267. ];
  52268. /**
  52269. * [option in constructor]:
  52270. * {
  52271. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  52272. * }
  52273. *
  52274. *
  52275. * [targetInfo]:
  52276. *
  52277. * There can be multiple axes in a single targetInfo. Consider the case
  52278. * of `grid` component, a targetInfo represents a grid which contains one or more
  52279. * cartesian and one or more axes. And consider the case of parallel system,
  52280. * which has multiple axes in a coordinate system.
  52281. * Can be {
  52282. * panelId: ...,
  52283. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  52284. * coordSyses: all cartesians.
  52285. * gridModel: <grid component>
  52286. * xAxes: correspond to coordSyses on index
  52287. * yAxes: correspond to coordSyses on index
  52288. * }
  52289. * or {
  52290. * panelId: ...,
  52291. * coordSys: <geo coord sys>
  52292. * coordSyses: [<geo coord sys>]
  52293. * geoModel: <geo component>
  52294. * }
  52295. *
  52296. *
  52297. * [panelOpt]:
  52298. *
  52299. * Make from targetInfo. Input to BrushController.
  52300. * {
  52301. * panelId: ...,
  52302. * rect: ...
  52303. * }
  52304. *
  52305. *
  52306. * [area]:
  52307. *
  52308. * Generated by BrushController or user input.
  52309. * {
  52310. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  52311. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  52312. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  52313. * range: pixel range.
  52314. * coordRange: representitive coord range (the first one of coordRanges).
  52315. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  52316. * }
  52317. */
  52318. /**
  52319. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  52320. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  52321. * @param {module:echarts/model/Global} ecModel
  52322. * @param {Object} [opt]
  52323. * @param {Array.<string>} [opt.include] include coordinate system types.
  52324. */
  52325. function BrushTargetManager(option, ecModel, opt) {
  52326. /**
  52327. * @private
  52328. * @type {Array.<Object>}
  52329. */
  52330. var targetInfoList = this._targetInfoList = [];
  52331. var info = {};
  52332. var foundCpts = parseFinder$1(ecModel, option);
  52333. each$17(targetInfoBuilders, function (builder, type) {
  52334. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  52335. builder(foundCpts, targetInfoList, info);
  52336. }
  52337. });
  52338. }
  52339. var proto$5 = BrushTargetManager.prototype;
  52340. proto$5.setOutputRanges = function (areas, ecModel) {
  52341. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52342. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  52343. // area.coordRange is the first of area.coordRanges
  52344. if (!area.coordRange) {
  52345. area.coordRange = coordRange;
  52346. // In 'category' axis, coord to pixel is not reversible, so we can not
  52347. // rebuild range by coordRange accrately, which may bring trouble when
  52348. // brushing only one item. So we use __rangeOffset to rebuilding range
  52349. // by coordRange. And this it only used in brush component so it is no
  52350. // need to be adapted to coordRanges.
  52351. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  52352. area.__rangeOffset = {
  52353. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  52354. xyMinMax: result.xyMinMax
  52355. };
  52356. }
  52357. });
  52358. };
  52359. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  52360. each$17(areas, function (area) {
  52361. var targetInfo = this.findTargetInfo(area, ecModel);
  52362. if (targetInfo && targetInfo !== true) {
  52363. each$1(
  52364. targetInfo.coordSyses,
  52365. function (coordSys) {
  52366. var result = coordConvert[area.brushType](1, coordSys, area.range);
  52367. cb(area, result.values, coordSys, ecModel);
  52368. }
  52369. );
  52370. }
  52371. }, this);
  52372. };
  52373. proto$5.setInputRanges = function (areas, ecModel) {
  52374. each$17(areas, function (area) {
  52375. var targetInfo = this.findTargetInfo(area, ecModel);
  52376. if (__DEV__) {
  52377. assert$1(
  52378. !targetInfo || targetInfo === true || area.coordRange,
  52379. 'coordRange must be specified when coord index specified.'
  52380. );
  52381. assert$1(
  52382. !targetInfo || targetInfo !== true || area.range,
  52383. 'range must be specified in global brush.'
  52384. );
  52385. }
  52386. area.range = area.range || [];
  52387. // convert coordRange to global range and set panelId.
  52388. if (targetInfo && targetInfo !== true) {
  52389. area.panelId = targetInfo.panelId;
  52390. // (1) area.range shoule always be calculate from coordRange but does
  52391. // not keep its original value, for the sake of the dataZoom scenario,
  52392. // where area.coordRange remains unchanged but area.range may be changed.
  52393. // (2) Only support converting one coordRange to pixel range in brush
  52394. // component. So do not consider `coordRanges`.
  52395. // (3) About __rangeOffset, see comment above.
  52396. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  52397. var rangeOffset = area.__rangeOffset;
  52398. area.range = rangeOffset
  52399. ? diffProcessor[area.brushType](
  52400. result.values,
  52401. rangeOffset.offset,
  52402. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  52403. )
  52404. : result.values;
  52405. }
  52406. }, this);
  52407. };
  52408. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  52409. return map(this._targetInfoList, function (targetInfo) {
  52410. var rect = targetInfo.getPanelRect();
  52411. return {
  52412. panelId: targetInfo.panelId,
  52413. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  52414. clipPath: makeRectPanelClipPath(rect),
  52415. isTargetByCursor: makeRectIsTargetByCursor(
  52416. rect, api, targetInfo.coordSysModel
  52417. ),
  52418. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  52419. };
  52420. });
  52421. };
  52422. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  52423. // Check whether area is bound in coord, and series do not belong to that coord.
  52424. // If do not do this check, some brush (like lineX) will controll all axes.
  52425. var targetInfo = this.findTargetInfo(area, ecModel);
  52426. return targetInfo === true || (
  52427. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  52428. );
  52429. };
  52430. /**
  52431. * If return Object, a coord found.
  52432. * If reutrn true, global found.
  52433. * Otherwise nothing found.
  52434. *
  52435. * @param {Object} area
  52436. * @param {Array} targetInfoList
  52437. * @return {Object|boolean}
  52438. */
  52439. proto$5.findTargetInfo = function (area, ecModel) {
  52440. var targetInfoList = this._targetInfoList;
  52441. var foundCpts = parseFinder$1(ecModel, area);
  52442. for (var i = 0; i < targetInfoList.length; i++) {
  52443. var targetInfo = targetInfoList[i];
  52444. var areaPanelId = area.panelId;
  52445. if (areaPanelId) {
  52446. if (targetInfo.panelId === areaPanelId) {
  52447. return targetInfo;
  52448. }
  52449. }
  52450. else {
  52451. for (var i = 0; i < targetInfoMatchers.length; i++) {
  52452. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  52453. return targetInfo;
  52454. }
  52455. }
  52456. }
  52457. }
  52458. return true;
  52459. };
  52460. function formatMinMax(minMax) {
  52461. minMax[0] > minMax[1] && minMax.reverse();
  52462. return minMax;
  52463. }
  52464. function parseFinder$1(ecModel, option) {
  52465. return parseFinder(
  52466. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  52467. );
  52468. }
  52469. var targetInfoBuilders = {
  52470. grid: function (foundCpts, targetInfoList) {
  52471. var xAxisModels = foundCpts.xAxisModels;
  52472. var yAxisModels = foundCpts.yAxisModels;
  52473. var gridModels = foundCpts.gridModels;
  52474. // Remove duplicated.
  52475. var gridModelMap = createHashMap();
  52476. var xAxesHas = {};
  52477. var yAxesHas = {};
  52478. if (!xAxisModels && !yAxisModels && !gridModels) {
  52479. return;
  52480. }
  52481. each$17(xAxisModels, function (axisModel) {
  52482. var gridModel = axisModel.axis.grid.model;
  52483. gridModelMap.set(gridModel.id, gridModel);
  52484. xAxesHas[gridModel.id] = true;
  52485. });
  52486. each$17(yAxisModels, function (axisModel) {
  52487. var gridModel = axisModel.axis.grid.model;
  52488. gridModelMap.set(gridModel.id, gridModel);
  52489. yAxesHas[gridModel.id] = true;
  52490. });
  52491. each$17(gridModels, function (gridModel) {
  52492. gridModelMap.set(gridModel.id, gridModel);
  52493. xAxesHas[gridModel.id] = true;
  52494. yAxesHas[gridModel.id] = true;
  52495. });
  52496. gridModelMap.each(function (gridModel) {
  52497. var grid = gridModel.coordinateSystem;
  52498. var cartesians = [];
  52499. each$17(grid.getCartesians(), function (cartesian, index) {
  52500. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  52501. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  52502. ) {
  52503. cartesians.push(cartesian);
  52504. }
  52505. });
  52506. targetInfoList.push({
  52507. panelId: 'grid--' + gridModel.id,
  52508. gridModel: gridModel,
  52509. coordSysModel: gridModel,
  52510. // Use the first one as the representitive coordSys.
  52511. coordSys: cartesians[0],
  52512. coordSyses: cartesians,
  52513. getPanelRect: panelRectBuilder.grid,
  52514. xAxisDeclared: xAxesHas[gridModel.id],
  52515. yAxisDeclared: yAxesHas[gridModel.id]
  52516. });
  52517. });
  52518. },
  52519. geo: function (foundCpts, targetInfoList) {
  52520. each$17(foundCpts.geoModels, function (geoModel) {
  52521. var coordSys = geoModel.coordinateSystem;
  52522. targetInfoList.push({
  52523. panelId: 'geo--' + geoModel.id,
  52524. geoModel: geoModel,
  52525. coordSysModel: geoModel,
  52526. coordSys: coordSys,
  52527. coordSyses: [coordSys],
  52528. getPanelRect: panelRectBuilder.geo
  52529. });
  52530. });
  52531. }
  52532. };
  52533. var targetInfoMatchers = [
  52534. // grid
  52535. function (foundCpts, targetInfo) {
  52536. var xAxisModel = foundCpts.xAxisModel;
  52537. var yAxisModel = foundCpts.yAxisModel;
  52538. var gridModel = foundCpts.gridModel;
  52539. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  52540. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  52541. return gridModel && gridModel === targetInfo.gridModel;
  52542. },
  52543. // geo
  52544. function (foundCpts, targetInfo) {
  52545. var geoModel = foundCpts.geoModel;
  52546. return geoModel && geoModel === targetInfo.geoModel;
  52547. }
  52548. ];
  52549. var panelRectBuilder = {
  52550. grid: function () {
  52551. // grid is not Transformable.
  52552. return this.coordSys.grid.getRect().clone();
  52553. },
  52554. geo: function () {
  52555. var coordSys = this.coordSys;
  52556. var rect = coordSys.getBoundingRect().clone();
  52557. // geo roam and zoom transform
  52558. rect.applyTransform(getTransform(coordSys));
  52559. return rect;
  52560. }
  52561. };
  52562. var coordConvert = {
  52563. lineX: curry$6(axisConvert, 0),
  52564. lineY: curry$6(axisConvert, 1),
  52565. rect: function (to, coordSys, rangeOrCoordRange) {
  52566. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  52567. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  52568. var values = [
  52569. formatMinMax([xminymin[0], xmaxymax[0]]),
  52570. formatMinMax([xminymin[1], xmaxymax[1]])
  52571. ];
  52572. return {values: values, xyMinMax: values};
  52573. },
  52574. polygon: function (to, coordSys, rangeOrCoordRange) {
  52575. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  52576. var values = map(rangeOrCoordRange, function (item) {
  52577. var p = coordSys[COORD_CONVERTS[to]](item);
  52578. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  52579. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  52580. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  52581. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  52582. return p;
  52583. });
  52584. return {values: values, xyMinMax: xyMinMax};
  52585. }
  52586. };
  52587. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  52588. if (__DEV__) {
  52589. assert$1(
  52590. coordSys.type === 'cartesian2d',
  52591. 'lineX/lineY brush is available only in cartesian2d.'
  52592. );
  52593. }
  52594. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  52595. var values = formatMinMax(map([0, 1], function (i) {
  52596. return to
  52597. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  52598. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  52599. }));
  52600. var xyMinMax = [];
  52601. xyMinMax[axisNameIndex] = values;
  52602. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  52603. return {values: values, xyMinMax: xyMinMax};
  52604. }
  52605. var diffProcessor = {
  52606. lineX: curry$6(axisDiffProcessor, 0),
  52607. lineY: curry$6(axisDiffProcessor, 1),
  52608. rect: function (values, refer, scales) {
  52609. return [
  52610. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  52611. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  52612. ];
  52613. },
  52614. polygon: function (values, refer, scales) {
  52615. return map(values, function (item, idx) {
  52616. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  52617. });
  52618. }
  52619. };
  52620. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  52621. return [
  52622. values[0] - scales[axisNameIndex] * refer[0],
  52623. values[1] - scales[axisNameIndex] * refer[1]
  52624. ];
  52625. }
  52626. // We have to process scale caused by dataZoom manually,
  52627. // although it might be not accurate.
  52628. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  52629. var sizeCurr = getSize(xyMinMaxCurr);
  52630. var sizeOrigin = getSize(xyMinMaxOrigin);
  52631. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  52632. isNaN(scales[0]) && (scales[0] = 1);
  52633. isNaN(scales[1]) && (scales[1] = 1);
  52634. return scales;
  52635. }
  52636. function getSize(xyMinMax) {
  52637. return xyMinMax
  52638. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  52639. : [NaN, NaN];
  52640. }
  52641. /*
  52642. * Licensed to the Apache Software Foundation (ASF) under one
  52643. * or more contributor license agreements. See the NOTICE file
  52644. * distributed with this work for additional information
  52645. * regarding copyright ownership. The ASF licenses this file
  52646. * to you under the Apache License, Version 2.0 (the
  52647. * "License"); you may not use this file except in compliance
  52648. * with the License. You may obtain a copy of the License at
  52649. *
  52650. * http://www.apache.org/licenses/LICENSE-2.0
  52651. *
  52652. * Unless required by applicable law or agreed to in writing,
  52653. * software distributed under the License is distributed on an
  52654. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52655. * KIND, either express or implied. See the License for the
  52656. * specific language governing permissions and limitations
  52657. * under the License.
  52658. */
  52659. var each$18 = each$1;
  52660. var ATTR$2 = '\0_ec_hist_store';
  52661. /**
  52662. * @param {module:echarts/model/Global} ecModel
  52663. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  52664. */
  52665. function push(ecModel, newSnapshot) {
  52666. var store = giveStore$1(ecModel);
  52667. // If previous dataZoom can not be found,
  52668. // complete an range with current range.
  52669. each$18(newSnapshot, function (batchItem, dataZoomId) {
  52670. var i = store.length - 1;
  52671. for (; i >= 0; i--) {
  52672. var snapshot = store[i];
  52673. if (snapshot[dataZoomId]) {
  52674. break;
  52675. }
  52676. }
  52677. if (i < 0) {
  52678. // No origin range set, create one by current range.
  52679. var dataZoomModel = ecModel.queryComponents(
  52680. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  52681. )[0];
  52682. if (dataZoomModel) {
  52683. var percentRange = dataZoomModel.getPercentRange();
  52684. store[0][dataZoomId] = {
  52685. dataZoomId: dataZoomId,
  52686. start: percentRange[0],
  52687. end: percentRange[1]
  52688. };
  52689. }
  52690. }
  52691. });
  52692. store.push(newSnapshot);
  52693. }
  52694. /**
  52695. * @param {module:echarts/model/Global} ecModel
  52696. * @return {Object} snapshot
  52697. */
  52698. function pop(ecModel) {
  52699. var store = giveStore$1(ecModel);
  52700. var head = store[store.length - 1];
  52701. store.length > 1 && store.pop();
  52702. // Find top for all dataZoom.
  52703. var snapshot = {};
  52704. each$18(head, function (batchItem, dataZoomId) {
  52705. for (var i = store.length - 1; i >= 0; i--) {
  52706. var batchItem = store[i][dataZoomId];
  52707. if (batchItem) {
  52708. snapshot[dataZoomId] = batchItem;
  52709. break;
  52710. }
  52711. }
  52712. });
  52713. return snapshot;
  52714. }
  52715. /**
  52716. * @param {module:echarts/model/Global} ecModel
  52717. */
  52718. function clear$1(ecModel) {
  52719. ecModel[ATTR$2] = null;
  52720. }
  52721. /**
  52722. * @param {module:echarts/model/Global} ecModel
  52723. * @return {number} records. always >= 1.
  52724. */
  52725. function count(ecModel) {
  52726. return giveStore$1(ecModel).length;
  52727. }
  52728. /**
  52729. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  52730. * History length of each dataZoom may be different.
  52731. * this._history[0] is used to store origin range.
  52732. * @type {Array.<Object>}
  52733. */
  52734. function giveStore$1(ecModel) {
  52735. var store = ecModel[ATTR$2];
  52736. if (!store) {
  52737. store = ecModel[ATTR$2] = [{}];
  52738. }
  52739. return store;
  52740. }
  52741. /*
  52742. * Licensed to the Apache Software Foundation (ASF) under one
  52743. * or more contributor license agreements. See the NOTICE file
  52744. * distributed with this work for additional information
  52745. * regarding copyright ownership. The ASF licenses this file
  52746. * to you under the Apache License, Version 2.0 (the
  52747. * "License"); you may not use this file except in compliance
  52748. * with the License. You may obtain a copy of the License at
  52749. *
  52750. * http://www.apache.org/licenses/LICENSE-2.0
  52751. *
  52752. * Unless required by applicable law or agreed to in writing,
  52753. * software distributed under the License is distributed on an
  52754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52755. * KIND, either express or implied. See the License for the
  52756. * specific language governing permissions and limitations
  52757. * under the License.
  52758. */
  52759. DataZoomModel.extend({
  52760. type: 'dataZoom.select'
  52761. });
  52762. /*
  52763. * Licensed to the Apache Software Foundation (ASF) under one
  52764. * or more contributor license agreements. See the NOTICE file
  52765. * distributed with this work for additional information
  52766. * regarding copyright ownership. The ASF licenses this file
  52767. * to you under the Apache License, Version 2.0 (the
  52768. * "License"); you may not use this file except in compliance
  52769. * with the License. You may obtain a copy of the License at
  52770. *
  52771. * http://www.apache.org/licenses/LICENSE-2.0
  52772. *
  52773. * Unless required by applicable law or agreed to in writing,
  52774. * software distributed under the License is distributed on an
  52775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52776. * KIND, either express or implied. See the License for the
  52777. * specific language governing permissions and limitations
  52778. * under the License.
  52779. */
  52780. DataZoomView.extend({
  52781. type: 'dataZoom.select'
  52782. });
  52783. /*
  52784. * Licensed to the Apache Software Foundation (ASF) under one
  52785. * or more contributor license agreements. See the NOTICE file
  52786. * distributed with this work for additional information
  52787. * regarding copyright ownership. The ASF licenses this file
  52788. * to you under the Apache License, Version 2.0 (the
  52789. * "License"); you may not use this file except in compliance
  52790. * with the License. You may obtain a copy of the License at
  52791. *
  52792. * http://www.apache.org/licenses/LICENSE-2.0
  52793. *
  52794. * Unless required by applicable law or agreed to in writing,
  52795. * software distributed under the License is distributed on an
  52796. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52797. * KIND, either express or implied. See the License for the
  52798. * specific language governing permissions and limitations
  52799. * under the License.
  52800. */
  52801. /**
  52802. * Only work for toolbox dataZoom. User
  52803. * MUST NOT import this module directly.
  52804. */
  52805. /*
  52806. * Licensed to the Apache Software Foundation (ASF) under one
  52807. * or more contributor license agreements. See the NOTICE file
  52808. * distributed with this work for additional information
  52809. * regarding copyright ownership. The ASF licenses this file
  52810. * to you under the Apache License, Version 2.0 (the
  52811. * "License"); you may not use this file except in compliance
  52812. * with the License. You may obtain a copy of the License at
  52813. *
  52814. * http://www.apache.org/licenses/LICENSE-2.0
  52815. *
  52816. * Unless required by applicable law or agreed to in writing,
  52817. * software distributed under the License is distributed on an
  52818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52819. * KIND, either express or implied. See the License for the
  52820. * specific language governing permissions and limitations
  52821. * under the License.
  52822. */
  52823. // Use dataZoomSelect
  52824. var dataZoomLang = lang.toolbox.dataZoom;
  52825. var each$15 = each$1;
  52826. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  52827. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  52828. function DataZoom(model, ecModel, api) {
  52829. /**
  52830. * @private
  52831. * @type {module:echarts/component/helper/BrushController}
  52832. */
  52833. (this._brushController = new BrushController(api.getZr()))
  52834. .on('brush', bind(this._onBrush, this))
  52835. .mount();
  52836. /**
  52837. * @private
  52838. * @type {boolean}
  52839. */
  52840. this._isZoomActive;
  52841. }
  52842. DataZoom.defaultOption = {
  52843. show: true,
  52844. filterMode: 'filter',
  52845. // Icon group
  52846. icon: {
  52847. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  52848. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  52849. },
  52850. // `zoom`, `back`
  52851. title: clone(dataZoomLang.title)
  52852. };
  52853. var proto$4 = DataZoom.prototype;
  52854. proto$4.render = function (featureModel, ecModel, api, payload) {
  52855. this.model = featureModel;
  52856. this.ecModel = ecModel;
  52857. this.api = api;
  52858. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  52859. updateBackBtnStatus(featureModel, ecModel);
  52860. };
  52861. proto$4.onclick = function (ecModel, api, type) {
  52862. handlers[type].call(this);
  52863. };
  52864. proto$4.remove = function (ecModel, api) {
  52865. this._brushController.unmount();
  52866. };
  52867. proto$4.dispose = function (ecModel, api) {
  52868. this._brushController.dispose();
  52869. };
  52870. /**
  52871. * @private
  52872. */
  52873. var handlers = {
  52874. zoom: function () {
  52875. var nextActive = !this._isZoomActive;
  52876. this.api.dispatchAction({
  52877. type: 'takeGlobalCursor',
  52878. key: 'dataZoomSelect',
  52879. dataZoomSelectActive: nextActive
  52880. });
  52881. },
  52882. back: function () {
  52883. this._dispatchZoomAction(pop(this.ecModel));
  52884. }
  52885. };
  52886. /**
  52887. * @private
  52888. */
  52889. proto$4._onBrush = function (areas, opt) {
  52890. if (!opt.isEnd || !areas.length) {
  52891. return;
  52892. }
  52893. var snapshot = {};
  52894. var ecModel = this.ecModel;
  52895. this._brushController.updateCovers([]); // remove cover
  52896. var brushTargetManager = new BrushTargetManager(
  52897. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  52898. );
  52899. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  52900. if (coordSys.type !== 'cartesian2d') {
  52901. return;
  52902. }
  52903. var brushType = area.brushType;
  52904. if (brushType === 'rect') {
  52905. setBatch('x', coordSys, coordRange[0]);
  52906. setBatch('y', coordSys, coordRange[1]);
  52907. }
  52908. else {
  52909. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  52910. }
  52911. });
  52912. push(ecModel, snapshot);
  52913. this._dispatchZoomAction(snapshot);
  52914. function setBatch(dimName, coordSys, minMax) {
  52915. var axis = coordSys.getAxis(dimName);
  52916. var axisModel = axis.model;
  52917. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  52918. // Restrict range.
  52919. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  52920. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  52921. minMax = sliderMove(
  52922. 0, minMax.slice(), axis.scale.getExtent(), 0,
  52923. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  52924. );
  52925. }
  52926. dataZoomModel && (snapshot[dataZoomModel.id] = {
  52927. dataZoomId: dataZoomModel.id,
  52928. startValue: minMax[0],
  52929. endValue: minMax[1]
  52930. });
  52931. }
  52932. function findDataZoom(dimName, axisModel, ecModel) {
  52933. var found;
  52934. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  52935. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  52936. has && (found = dzModel);
  52937. });
  52938. return found;
  52939. }
  52940. };
  52941. /**
  52942. * @private
  52943. */
  52944. proto$4._dispatchZoomAction = function (snapshot) {
  52945. var batch = [];
  52946. // Convert from hash map to array.
  52947. each$15(snapshot, function (batchItem, dataZoomId) {
  52948. batch.push(clone(batchItem));
  52949. });
  52950. batch.length && this.api.dispatchAction({
  52951. type: 'dataZoom',
  52952. from: this.uid,
  52953. batch: batch
  52954. });
  52955. };
  52956. function retrieveAxisSetting(option) {
  52957. var setting = {};
  52958. // Compatible with previous setting: null => all axis, false => no axis.
  52959. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  52960. setting[name] = option[name];
  52961. setting[name] == null && (setting[name] = 'all');
  52962. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  52963. });
  52964. return setting;
  52965. }
  52966. function updateBackBtnStatus(featureModel, ecModel) {
  52967. featureModel.setIconStatus(
  52968. 'back',
  52969. count(ecModel) > 1 ? 'emphasis' : 'normal'
  52970. );
  52971. }
  52972. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  52973. var zoomActive = view._isZoomActive;
  52974. if (payload && payload.type === 'takeGlobalCursor') {
  52975. zoomActive = payload.key === 'dataZoomSelect'
  52976. ? payload.dataZoomSelectActive : false;
  52977. }
  52978. view._isZoomActive = zoomActive;
  52979. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  52980. var brushTargetManager = new BrushTargetManager(
  52981. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  52982. );
  52983. view._brushController
  52984. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  52985. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  52986. ? 'lineX'
  52987. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  52988. ? 'lineY'
  52989. : 'rect';
  52990. }))
  52991. .enableBrush(
  52992. zoomActive
  52993. ? {
  52994. brushType: 'auto',
  52995. brushStyle: {
  52996. // FIXME user customized?
  52997. lineWidth: 0,
  52998. fill: 'rgba(0,0,0,0.2)'
  52999. }
  53000. }
  53001. : false
  53002. );
  53003. }
  53004. register$2('dataZoom', DataZoom);
  53005. // Create special dataZoom option for select
  53006. // FIXME consider the case of merge option, where axes options are not exists.
  53007. registerPreprocessor(function (option) {
  53008. if (!option) {
  53009. return;
  53010. }
  53011. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  53012. if (!isArray(dataZoomOpts)) {
  53013. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  53014. }
  53015. var toolboxOpt = option.toolbox;
  53016. if (toolboxOpt) {
  53017. // Assume there is only one toolbox
  53018. if (isArray(toolboxOpt)) {
  53019. toolboxOpt = toolboxOpt[0];
  53020. }
  53021. if (toolboxOpt && toolboxOpt.feature) {
  53022. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  53023. // FIXME: If add dataZoom when setOption in merge mode,
  53024. // no axis info to be added. See `test/dataZoom-extreme.html`
  53025. addForAxis('xAxis', dataZoomOpt);
  53026. addForAxis('yAxis', dataZoomOpt);
  53027. }
  53028. }
  53029. function addForAxis(axisName, dataZoomOpt) {
  53030. if (!dataZoomOpt) {
  53031. return;
  53032. }
  53033. // Try not to modify model, because it is not merged yet.
  53034. var axisIndicesName = axisName + 'Index';
  53035. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  53036. if (givenAxisIndices != null
  53037. && givenAxisIndices !== 'all'
  53038. && !isArray(givenAxisIndices)
  53039. ) {
  53040. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  53041. }
  53042. forEachComponent(axisName, function (axisOpt, axisIndex) {
  53043. if (givenAxisIndices != null
  53044. && givenAxisIndices !== 'all'
  53045. && indexOf(givenAxisIndices, axisIndex) === -1
  53046. ) {
  53047. return;
  53048. }
  53049. var newOpt = {
  53050. type: 'select',
  53051. $fromToolbox: true,
  53052. // Default to be filter
  53053. filterMode: dataZoomOpt.filterMode || 'filter',
  53054. // Id for merge mapping.
  53055. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  53056. };
  53057. // FIXME
  53058. // Only support one axis now.
  53059. newOpt[axisIndicesName] = axisIndex;
  53060. dataZoomOpts.push(newOpt);
  53061. });
  53062. }
  53063. function forEachComponent(mainType, cb) {
  53064. var opts = option[mainType];
  53065. if (!isArray(opts)) {
  53066. opts = opts ? [opts] : [];
  53067. }
  53068. each$15(opts, cb);
  53069. }
  53070. });
  53071. /*
  53072. * Licensed to the Apache Software Foundation (ASF) under one
  53073. * or more contributor license agreements. See the NOTICE file
  53074. * distributed with this work for additional information
  53075. * regarding copyright ownership. The ASF licenses this file
  53076. * to you under the Apache License, Version 2.0 (the
  53077. * "License"); you may not use this file except in compliance
  53078. * with the License. You may obtain a copy of the License at
  53079. *
  53080. * http://www.apache.org/licenses/LICENSE-2.0
  53081. *
  53082. * Unless required by applicable law or agreed to in writing,
  53083. * software distributed under the License is distributed on an
  53084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53085. * KIND, either express or implied. See the License for the
  53086. * specific language governing permissions and limitations
  53087. * under the License.
  53088. */
  53089. var restoreLang = lang.toolbox.restore;
  53090. function Restore(model) {
  53091. this.model = model;
  53092. }
  53093. Restore.defaultOption = {
  53094. show: true,
  53095. /* eslint-disable */
  53096. 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',
  53097. /* eslint-enable */
  53098. title: restoreLang.title
  53099. };
  53100. var proto$6 = Restore.prototype;
  53101. proto$6.onclick = function (ecModel, api, type) {
  53102. clear$1(ecModel);
  53103. api.dispatchAction({
  53104. type: 'restore',
  53105. from: this.uid
  53106. });
  53107. };
  53108. register$2('restore', Restore);
  53109. registerAction(
  53110. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  53111. function (payload, ecModel) {
  53112. ecModel.resetOption('recreate');
  53113. }
  53114. );
  53115. /*
  53116. * Licensed to the Apache Software Foundation (ASF) under one
  53117. * or more contributor license agreements. See the NOTICE file
  53118. * distributed with this work for additional information
  53119. * regarding copyright ownership. The ASF licenses this file
  53120. * to you under the Apache License, Version 2.0 (the
  53121. * "License"); you may not use this file except in compliance
  53122. * with the License. You may obtain a copy of the License at
  53123. *
  53124. * http://www.apache.org/licenses/LICENSE-2.0
  53125. *
  53126. * Unless required by applicable law or agreed to in writing,
  53127. * software distributed under the License is distributed on an
  53128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53129. * KIND, either express or implied. See the License for the
  53130. * specific language governing permissions and limitations
  53131. * under the License.
  53132. */
  53133. var urn = 'urn:schemas-microsoft-com:vml';
  53134. var win = typeof window === 'undefined' ? null : window;
  53135. var vmlInited = false;
  53136. var doc = win && win.document;
  53137. function createNode(tagName) {
  53138. return doCreateNode(tagName);
  53139. }
  53140. // Avoid assign to an exported variable, for transforming to cjs.
  53141. var doCreateNode;
  53142. if (doc && !env$1.canvasSupported) {
  53143. try {
  53144. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  53145. doCreateNode = function (tagName) {
  53146. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  53147. };
  53148. }
  53149. catch (e) {
  53150. doCreateNode = function (tagName) {
  53151. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  53152. };
  53153. }
  53154. }
  53155. // From raphael
  53156. function initVML() {
  53157. if (vmlInited || !doc) {
  53158. return;
  53159. }
  53160. vmlInited = true;
  53161. var styleSheets = doc.styleSheets;
  53162. if (styleSheets.length < 31) {
  53163. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  53164. }
  53165. else {
  53166. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  53167. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  53168. }
  53169. }
  53170. // http://www.w3.org/TR/NOTE-VML
  53171. // TODO Use proxy like svg instead of overwrite brush methods
  53172. var CMD$3 = PathProxy.CMD;
  53173. var round$2 = Math.round;
  53174. var sqrt = Math.sqrt;
  53175. var abs$1 = Math.abs;
  53176. var cos = Math.cos;
  53177. var sin = Math.sin;
  53178. var mathMax$6 = Math.max;
  53179. if (!env$1.canvasSupported) {
  53180. var comma = ',';
  53181. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  53182. var Z = 21600;
  53183. var Z2 = Z / 2;
  53184. var ZLEVEL_BASE = 100000;
  53185. var Z_BASE = 1000;
  53186. var initRootElStyle = function (el) {
  53187. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  53188. el.coordsize = Z + ',' + Z;
  53189. el.coordorigin = '0,0';
  53190. };
  53191. var encodeHtmlAttribute = function (s) {
  53192. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  53193. };
  53194. var rgb2Str = function (r, g, b) {
  53195. return 'rgb(' + [r, g, b].join(',') + ')';
  53196. };
  53197. var append = function (parent, child) {
  53198. if (child && parent && child.parentNode !== parent) {
  53199. parent.appendChild(child);
  53200. }
  53201. };
  53202. var remove = function (parent, child) {
  53203. if (child && parent && child.parentNode === parent) {
  53204. parent.removeChild(child);
  53205. }
  53206. };
  53207. var getZIndex = function (zlevel, z, z2) {
  53208. // z 的取值范围为 [0, 1000]
  53209. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  53210. };
  53211. var parsePercent$3 = parsePercent;
  53212. /***************************************************
  53213. * PATH
  53214. **************************************************/
  53215. var setColorAndOpacity = function (el, color, opacity) {
  53216. var colorArr = parse(color);
  53217. opacity = +opacity;
  53218. if (isNaN(opacity)) {
  53219. opacity = 1;
  53220. }
  53221. if (colorArr) {
  53222. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  53223. el.opacity = opacity * colorArr[3];
  53224. }
  53225. };
  53226. var getColorAndAlpha = function (color) {
  53227. var colorArr = parse(color);
  53228. return [
  53229. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  53230. colorArr[3]
  53231. ];
  53232. };
  53233. var updateFillNode = function (el, style, zrEl) {
  53234. // TODO pattern
  53235. var fill = style.fill;
  53236. if (fill != null) {
  53237. // Modified from excanvas
  53238. if (fill instanceof Gradient) {
  53239. var gradientType;
  53240. var angle = 0;
  53241. var focus = [0, 0];
  53242. // additional offset
  53243. var shift = 0;
  53244. // scale factor for offset
  53245. var expansion = 1;
  53246. var rect = zrEl.getBoundingRect();
  53247. var rectWidth = rect.width;
  53248. var rectHeight = rect.height;
  53249. if (fill.type === 'linear') {
  53250. gradientType = 'gradient';
  53251. var transform = zrEl.transform;
  53252. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  53253. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  53254. if (transform) {
  53255. applyTransform(p0, p0, transform);
  53256. applyTransform(p1, p1, transform);
  53257. }
  53258. var dx = p1[0] - p0[0];
  53259. var dy = p1[1] - p0[1];
  53260. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  53261. // The angle should be a non-negative number.
  53262. if (angle < 0) {
  53263. angle += 360;
  53264. }
  53265. // Very small angles produce an unexpected result because they are
  53266. // converted to a scientific notation string.
  53267. if (angle < 1e-6) {
  53268. angle = 0;
  53269. }
  53270. }
  53271. else {
  53272. gradientType = 'gradientradial';
  53273. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  53274. var transform = zrEl.transform;
  53275. var scale$$1 = zrEl.scale;
  53276. var width = rectWidth;
  53277. var height = rectHeight;
  53278. focus = [
  53279. // Percent in bounding rect
  53280. (p0[0] - rect.x) / width,
  53281. (p0[1] - rect.y) / height
  53282. ];
  53283. if (transform) {
  53284. applyTransform(p0, p0, transform);
  53285. }
  53286. width /= scale$$1[0] * Z;
  53287. height /= scale$$1[1] * Z;
  53288. var dimension = mathMax$6(width, height);
  53289. shift = 2 * 0 / dimension;
  53290. expansion = 2 * fill.r / dimension - shift;
  53291. }
  53292. // We need to sort the color stops in ascending order by offset,
  53293. // otherwise IE won't interpret it correctly.
  53294. var stops = fill.colorStops.slice();
  53295. stops.sort(function (cs1, cs2) {
  53296. return cs1.offset - cs2.offset;
  53297. });
  53298. var length$$1 = stops.length;
  53299. // Color and alpha list of first and last stop
  53300. var colorAndAlphaList = [];
  53301. var colors = [];
  53302. for (var i = 0; i < length$$1; i++) {
  53303. var stop = stops[i];
  53304. var colorAndAlpha = getColorAndAlpha(stop.color);
  53305. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  53306. if (i === 0 || i === length$$1 - 1) {
  53307. colorAndAlphaList.push(colorAndAlpha);
  53308. }
  53309. }
  53310. if (length$$1 >= 2) {
  53311. var color1 = colorAndAlphaList[0][0];
  53312. var color2 = colorAndAlphaList[1][0];
  53313. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  53314. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  53315. el.type = gradientType;
  53316. el.method = 'none';
  53317. el.focus = '100%';
  53318. el.angle = angle;
  53319. el.color = color1;
  53320. el.color2 = color2;
  53321. el.colors = colors.join(',');
  53322. // When colors attribute is used, the meanings of opacity and o:opacity2
  53323. // are reversed.
  53324. el.opacity = opacity2;
  53325. // FIXME g_o_:opacity ?
  53326. el.opacity2 = opacity1;
  53327. }
  53328. if (gradientType === 'radial') {
  53329. el.focusposition = focus.join(',');
  53330. }
  53331. }
  53332. else {
  53333. // FIXME Change from Gradient fill to color fill
  53334. setColorAndOpacity(el, fill, style.opacity);
  53335. }
  53336. }
  53337. };
  53338. var updateStrokeNode = function (el, style) {
  53339. // if (style.lineJoin != null) {
  53340. // el.joinstyle = style.lineJoin;
  53341. // }
  53342. // if (style.miterLimit != null) {
  53343. // el.miterlimit = style.miterLimit * Z;
  53344. // }
  53345. // if (style.lineCap != null) {
  53346. // el.endcap = style.lineCap;
  53347. // }
  53348. if (style.lineDash) {
  53349. el.dashstyle = style.lineDash.join(' ');
  53350. }
  53351. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  53352. setColorAndOpacity(el, style.stroke, style.opacity);
  53353. }
  53354. };
  53355. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  53356. var isFill = type === 'fill';
  53357. var el = vmlEl.getElementsByTagName(type)[0];
  53358. // Stroke must have lineWidth
  53359. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  53360. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  53361. // FIXME Remove before updating, or set `colors` will throw error
  53362. if (style[type] instanceof Gradient) {
  53363. remove(vmlEl, el);
  53364. }
  53365. if (!el) {
  53366. el = createNode(type);
  53367. }
  53368. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  53369. append(vmlEl, el);
  53370. }
  53371. else {
  53372. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  53373. remove(vmlEl, el);
  53374. }
  53375. };
  53376. var points$1 = [[], [], []];
  53377. var pathDataToString = function (path, m) {
  53378. var M = CMD$3.M;
  53379. var C = CMD$3.C;
  53380. var L = CMD$3.L;
  53381. var A = CMD$3.A;
  53382. var Q = CMD$3.Q;
  53383. var str = [];
  53384. var nPoint;
  53385. var cmdStr;
  53386. var cmd;
  53387. var i;
  53388. var xi;
  53389. var yi;
  53390. var data = path.data;
  53391. var dataLength = path.len();
  53392. for (i = 0; i < dataLength;) {
  53393. cmd = data[i++];
  53394. cmdStr = '';
  53395. nPoint = 0;
  53396. switch (cmd) {
  53397. case M:
  53398. cmdStr = ' m ';
  53399. nPoint = 1;
  53400. xi = data[i++];
  53401. yi = data[i++];
  53402. points$1[0][0] = xi;
  53403. points$1[0][1] = yi;
  53404. break;
  53405. case L:
  53406. cmdStr = ' l ';
  53407. nPoint = 1;
  53408. xi = data[i++];
  53409. yi = data[i++];
  53410. points$1[0][0] = xi;
  53411. points$1[0][1] = yi;
  53412. break;
  53413. case Q:
  53414. case C:
  53415. cmdStr = ' c ';
  53416. nPoint = 3;
  53417. var x1 = data[i++];
  53418. var y1 = data[i++];
  53419. var x2 = data[i++];
  53420. var y2 = data[i++];
  53421. var x3;
  53422. var y3;
  53423. if (cmd === Q) {
  53424. // Convert quadratic to cubic using degree elevation
  53425. x3 = x2;
  53426. y3 = y2;
  53427. x2 = (x2 + 2 * x1) / 3;
  53428. y2 = (y2 + 2 * y1) / 3;
  53429. x1 = (xi + 2 * x1) / 3;
  53430. y1 = (yi + 2 * y1) / 3;
  53431. }
  53432. else {
  53433. x3 = data[i++];
  53434. y3 = data[i++];
  53435. }
  53436. points$1[0][0] = x1;
  53437. points$1[0][1] = y1;
  53438. points$1[1][0] = x2;
  53439. points$1[1][1] = y2;
  53440. points$1[2][0] = x3;
  53441. points$1[2][1] = y3;
  53442. xi = x3;
  53443. yi = y3;
  53444. break;
  53445. case A:
  53446. var x = 0;
  53447. var y = 0;
  53448. var sx = 1;
  53449. var sy = 1;
  53450. var angle = 0;
  53451. if (m) {
  53452. // Extract SRT from matrix
  53453. x = m[4];
  53454. y = m[5];
  53455. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  53456. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  53457. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  53458. }
  53459. var cx = data[i++];
  53460. var cy = data[i++];
  53461. var rx = data[i++];
  53462. var ry = data[i++];
  53463. var startAngle = data[i++] + angle;
  53464. var endAngle = data[i++] + startAngle + angle;
  53465. // FIXME
  53466. // var psi = data[i++];
  53467. i++;
  53468. var clockwise = data[i++];
  53469. var x0 = cx + cos(startAngle) * rx;
  53470. var y0 = cy + sin(startAngle) * ry;
  53471. var x1 = cx + cos(endAngle) * rx;
  53472. var y1 = cy + sin(endAngle) * ry;
  53473. var type = clockwise ? ' wa ' : ' at ';
  53474. if (Math.abs(x0 - x1) < 1e-4) {
  53475. // IE won't render arches drawn counter clockwise if x0 == x1.
  53476. if (Math.abs(endAngle - startAngle) > 1e-2) {
  53477. // Offset x0 by 1/80 of a pixel. Use something
  53478. // that can be represented in binary
  53479. if (clockwise) {
  53480. x0 += 270 / Z;
  53481. }
  53482. }
  53483. else {
  53484. // Avoid case draw full circle
  53485. if (Math.abs(y0 - cy) < 1e-4) {
  53486. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  53487. y1 -= 270 / Z;
  53488. }
  53489. else {
  53490. y1 += 270 / Z;
  53491. }
  53492. }
  53493. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  53494. x1 += 270 / Z;
  53495. }
  53496. else {
  53497. x1 -= 270 / Z;
  53498. }
  53499. }
  53500. }
  53501. str.push(
  53502. type,
  53503. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  53504. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  53505. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  53506. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  53507. round$2((x0 * sx + x) * Z - Z2), comma,
  53508. round$2((y0 * sy + y) * Z - Z2), comma,
  53509. round$2((x1 * sx + x) * Z - Z2), comma,
  53510. round$2((y1 * sy + y) * Z - Z2)
  53511. );
  53512. xi = x1;
  53513. yi = y1;
  53514. break;
  53515. case CMD$3.R:
  53516. var p0 = points$1[0];
  53517. var p1 = points$1[1];
  53518. // x0, y0
  53519. p0[0] = data[i++];
  53520. p0[1] = data[i++];
  53521. // x1, y1
  53522. p1[0] = p0[0] + data[i++];
  53523. p1[1] = p0[1] + data[i++];
  53524. if (m) {
  53525. applyTransform(p0, p0, m);
  53526. applyTransform(p1, p1, m);
  53527. }
  53528. p0[0] = round$2(p0[0] * Z - Z2);
  53529. p1[0] = round$2(p1[0] * Z - Z2);
  53530. p0[1] = round$2(p0[1] * Z - Z2);
  53531. p1[1] = round$2(p1[1] * Z - Z2);
  53532. str.push(
  53533. // x0, y0
  53534. ' m ', p0[0], comma, p0[1],
  53535. // x1, y0
  53536. ' l ', p1[0], comma, p0[1],
  53537. // x1, y1
  53538. ' l ', p1[0], comma, p1[1],
  53539. // x0, y1
  53540. ' l ', p0[0], comma, p1[1]
  53541. );
  53542. break;
  53543. case CMD$3.Z:
  53544. // FIXME Update xi, yi
  53545. str.push(' x ');
  53546. }
  53547. if (nPoint > 0) {
  53548. str.push(cmdStr);
  53549. for (var k = 0; k < nPoint; k++) {
  53550. var p = points$1[k];
  53551. m && applyTransform(p, p, m);
  53552. // 不 round 会非常慢
  53553. str.push(
  53554. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  53555. k < nPoint - 1 ? comma : ''
  53556. );
  53557. }
  53558. }
  53559. }
  53560. return str.join('');
  53561. };
  53562. // Rewrite the original path method
  53563. Path.prototype.brushVML = function (vmlRoot) {
  53564. var style = this.style;
  53565. var vmlEl = this._vmlEl;
  53566. if (!vmlEl) {
  53567. vmlEl = createNode('shape');
  53568. initRootElStyle(vmlEl);
  53569. this._vmlEl = vmlEl;
  53570. }
  53571. updateFillAndStroke(vmlEl, 'fill', style, this);
  53572. updateFillAndStroke(vmlEl, 'stroke', style, this);
  53573. var m = this.transform;
  53574. var needTransform = m != null;
  53575. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  53576. if (strokeEl) {
  53577. var lineWidth = style.lineWidth;
  53578. // Get the line scale.
  53579. // Determinant of this.m_ means how much the area is enlarged by the
  53580. // transformation. So its square root can be used as a scale factor
  53581. // for width.
  53582. if (needTransform && !style.strokeNoScale) {
  53583. var det = m[0] * m[3] - m[1] * m[2];
  53584. lineWidth *= sqrt(abs$1(det));
  53585. }
  53586. strokeEl.weight = lineWidth + 'px';
  53587. }
  53588. var path = this.path || (this.path = new PathProxy());
  53589. if (this.__dirtyPath) {
  53590. path.beginPath();
  53591. path.subPixelOptimize = false;
  53592. this.buildPath(path, this.shape);
  53593. path.toStatic();
  53594. this.__dirtyPath = false;
  53595. }
  53596. vmlEl.path = pathDataToString(path, this.transform);
  53597. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53598. // Append to root
  53599. append(vmlRoot, vmlEl);
  53600. // Text
  53601. if (style.text != null) {
  53602. this.drawRectText(vmlRoot, this.getBoundingRect());
  53603. }
  53604. else {
  53605. this.removeRectText(vmlRoot);
  53606. }
  53607. };
  53608. Path.prototype.onRemove = function (vmlRoot) {
  53609. remove(vmlRoot, this._vmlEl);
  53610. this.removeRectText(vmlRoot);
  53611. };
  53612. Path.prototype.onAdd = function (vmlRoot) {
  53613. append(vmlRoot, this._vmlEl);
  53614. this.appendRectText(vmlRoot);
  53615. };
  53616. /***************************************************
  53617. * IMAGE
  53618. **************************************************/
  53619. var isImage = function (img) {
  53620. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  53621. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  53622. // return img instanceof Image;
  53623. };
  53624. // Rewrite the original path method
  53625. ZImage.prototype.brushVML = function (vmlRoot) {
  53626. var style = this.style;
  53627. var image = style.image;
  53628. // Image original width, height
  53629. var ow;
  53630. var oh;
  53631. if (isImage(image)) {
  53632. var src = image.src;
  53633. if (src === this._imageSrc) {
  53634. ow = this._imageWidth;
  53635. oh = this._imageHeight;
  53636. }
  53637. else {
  53638. var imageRuntimeStyle = image.runtimeStyle;
  53639. var oldRuntimeWidth = imageRuntimeStyle.width;
  53640. var oldRuntimeHeight = imageRuntimeStyle.height;
  53641. imageRuntimeStyle.width = 'auto';
  53642. imageRuntimeStyle.height = 'auto';
  53643. // get the original size
  53644. ow = image.width;
  53645. oh = image.height;
  53646. // and remove overides
  53647. imageRuntimeStyle.width = oldRuntimeWidth;
  53648. imageRuntimeStyle.height = oldRuntimeHeight;
  53649. // Caching image original width, height and src
  53650. this._imageSrc = src;
  53651. this._imageWidth = ow;
  53652. this._imageHeight = oh;
  53653. }
  53654. image = src;
  53655. }
  53656. else {
  53657. if (image === this._imageSrc) {
  53658. ow = this._imageWidth;
  53659. oh = this._imageHeight;
  53660. }
  53661. }
  53662. if (!image) {
  53663. return;
  53664. }
  53665. var x = style.x || 0;
  53666. var y = style.y || 0;
  53667. var dw = style.width;
  53668. var dh = style.height;
  53669. var sw = style.sWidth;
  53670. var sh = style.sHeight;
  53671. var sx = style.sx || 0;
  53672. var sy = style.sy || 0;
  53673. var hasCrop = sw && sh;
  53674. var vmlEl = this._vmlEl;
  53675. if (!vmlEl) {
  53676. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  53677. // vmlEl = vmlCore.createNode('group');
  53678. vmlEl = doc.createElement('div');
  53679. initRootElStyle(vmlEl);
  53680. this._vmlEl = vmlEl;
  53681. }
  53682. var vmlElStyle = vmlEl.style;
  53683. var hasRotation = false;
  53684. var m;
  53685. var scaleX = 1;
  53686. var scaleY = 1;
  53687. if (this.transform) {
  53688. m = this.transform;
  53689. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  53690. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  53691. hasRotation = m[1] || m[2];
  53692. }
  53693. if (hasRotation) {
  53694. // If filters are necessary (rotation exists), create them
  53695. // filters are bog-slow, so only create them if abbsolutely necessary
  53696. // The following check doesn't account for skews (which don't exist
  53697. // in the canvas spec (yet) anyway.
  53698. // From excanvas
  53699. var p0 = [x, y];
  53700. var p1 = [x + dw, y];
  53701. var p2 = [x, y + dh];
  53702. var p3 = [x + dw, y + dh];
  53703. applyTransform(p0, p0, m);
  53704. applyTransform(p1, p1, m);
  53705. applyTransform(p2, p2, m);
  53706. applyTransform(p3, p3, m);
  53707. var maxX = mathMax$6(p0[0], p1[0], p2[0], p3[0]);
  53708. var maxY = mathMax$6(p0[1], p1[1], p2[1], p3[1]);
  53709. var transformFilter = [];
  53710. transformFilter.push('M11=', m[0] / scaleX, comma,
  53711. 'M12=', m[2] / scaleY, comma,
  53712. 'M21=', m[1] / scaleX, comma,
  53713. 'M22=', m[3] / scaleY, comma,
  53714. 'Dx=', round$2(x * scaleX + m[4]), comma,
  53715. 'Dy=', round$2(y * scaleY + m[5]));
  53716. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  53717. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  53718. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  53719. + transformFilter.join('') + ', SizingMethod=clip)';
  53720. }
  53721. else {
  53722. if (m) {
  53723. x = x * scaleX + m[4];
  53724. y = y * scaleY + m[5];
  53725. }
  53726. vmlElStyle.filter = '';
  53727. vmlElStyle.left = round$2(x) + 'px';
  53728. vmlElStyle.top = round$2(y) + 'px';
  53729. }
  53730. var imageEl = this._imageEl;
  53731. var cropEl = this._cropEl;
  53732. if (!imageEl) {
  53733. imageEl = doc.createElement('div');
  53734. this._imageEl = imageEl;
  53735. }
  53736. var imageELStyle = imageEl.style;
  53737. if (hasCrop) {
  53738. // Needs know image original width and height
  53739. if (!(ow && oh)) {
  53740. var tmpImage = new Image();
  53741. var self = this;
  53742. tmpImage.onload = function () {
  53743. tmpImage.onload = null;
  53744. ow = tmpImage.width;
  53745. oh = tmpImage.height;
  53746. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  53747. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53748. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53749. // Caching image original width, height and src
  53750. self._imageWidth = ow;
  53751. self._imageHeight = oh;
  53752. self._imageSrc = image;
  53753. };
  53754. tmpImage.src = image;
  53755. }
  53756. else {
  53757. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  53758. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  53759. }
  53760. if (!cropEl) {
  53761. cropEl = doc.createElement('div');
  53762. cropEl.style.overflow = 'hidden';
  53763. this._cropEl = cropEl;
  53764. }
  53765. var cropElStyle = cropEl.style;
  53766. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  53767. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  53768. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  53769. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  53770. if (!cropEl.parentNode) {
  53771. vmlEl.appendChild(cropEl);
  53772. }
  53773. if (imageEl.parentNode !== cropEl) {
  53774. cropEl.appendChild(imageEl);
  53775. }
  53776. }
  53777. else {
  53778. imageELStyle.width = round$2(scaleX * dw) + 'px';
  53779. imageELStyle.height = round$2(scaleY * dh) + 'px';
  53780. vmlEl.appendChild(imageEl);
  53781. if (cropEl && cropEl.parentNode) {
  53782. vmlEl.removeChild(cropEl);
  53783. this._cropEl = null;
  53784. }
  53785. }
  53786. var filterStr = '';
  53787. var alpha = style.opacity;
  53788. if (alpha < 1) {
  53789. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  53790. }
  53791. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  53792. imageELStyle.filter = filterStr;
  53793. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  53794. // Append to root
  53795. append(vmlRoot, vmlEl);
  53796. // Text
  53797. if (style.text != null) {
  53798. this.drawRectText(vmlRoot, this.getBoundingRect());
  53799. }
  53800. };
  53801. ZImage.prototype.onRemove = function (vmlRoot) {
  53802. remove(vmlRoot, this._vmlEl);
  53803. this._vmlEl = null;
  53804. this._cropEl = null;
  53805. this._imageEl = null;
  53806. this.removeRectText(vmlRoot);
  53807. };
  53808. ZImage.prototype.onAdd = function (vmlRoot) {
  53809. append(vmlRoot, this._vmlEl);
  53810. this.appendRectText(vmlRoot);
  53811. };
  53812. /***************************************************
  53813. * TEXT
  53814. **************************************************/
  53815. var DEFAULT_STYLE_NORMAL = 'normal';
  53816. var fontStyleCache = {};
  53817. var fontStyleCacheCount = 0;
  53818. var MAX_FONT_CACHE_SIZE = 100;
  53819. var fontEl = document.createElement('div');
  53820. var getFontStyle = function (fontString) {
  53821. var fontStyle = fontStyleCache[fontString];
  53822. if (!fontStyle) {
  53823. // Clear cache
  53824. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  53825. fontStyleCacheCount = 0;
  53826. fontStyleCache = {};
  53827. }
  53828. var style = fontEl.style;
  53829. var fontFamily;
  53830. try {
  53831. style.font = fontString;
  53832. fontFamily = style.fontFamily.split(',')[0];
  53833. }
  53834. catch (e) {
  53835. }
  53836. fontStyle = {
  53837. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  53838. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  53839. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  53840. size: parseFloat(style.fontSize || 12) | 0,
  53841. family: fontFamily || 'Microsoft YaHei'
  53842. };
  53843. fontStyleCache[fontString] = fontStyle;
  53844. fontStyleCacheCount++;
  53845. }
  53846. return fontStyle;
  53847. };
  53848. var textMeasureEl;
  53849. // Overwrite measure text method
  53850. $override$1('measureText', function (text, textFont) {
  53851. var doc$$1 = doc;
  53852. if (!textMeasureEl) {
  53853. textMeasureEl = doc$$1.createElement('div');
  53854. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  53855. + 'padding:0;margin:0;border:none;white-space:pre;';
  53856. doc.body.appendChild(textMeasureEl);
  53857. }
  53858. try {
  53859. textMeasureEl.style.font = textFont;
  53860. }
  53861. catch (ex) {
  53862. // Ignore failures to set to invalid font.
  53863. }
  53864. textMeasureEl.innerHTML = '';
  53865. // Don't use innerHTML or innerText because they allow markup/whitespace.
  53866. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  53867. return {
  53868. width: textMeasureEl.offsetWidth
  53869. };
  53870. });
  53871. var tmpRect$2 = new BoundingRect();
  53872. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  53873. var style = this.style;
  53874. // Optimize, avoid normalize every time.
  53875. this.__dirty && normalizeTextStyle(style, true);
  53876. var text = style.text;
  53877. // Convert to string
  53878. text != null && (text += '');
  53879. if (!text) {
  53880. return;
  53881. }
  53882. // Convert rich text to plain text. Rich text is not supported in
  53883. // IE8-, but tags in rich text template will be removed.
  53884. if (style.rich) {
  53885. var contentBlock = parseRichText(text, style);
  53886. text = [];
  53887. for (var i = 0; i < contentBlock.lines.length; i++) {
  53888. var tokens = contentBlock.lines[i].tokens;
  53889. var textLine = [];
  53890. for (var j = 0; j < tokens.length; j++) {
  53891. textLine.push(tokens[j].text);
  53892. }
  53893. text.push(textLine.join(''));
  53894. }
  53895. text = text.join('\n');
  53896. }
  53897. var x;
  53898. var y;
  53899. var align = style.textAlign;
  53900. var verticalAlign = style.textVerticalAlign;
  53901. var fontStyle = getFontStyle(style.font);
  53902. // FIXME encodeHtmlAttribute ?
  53903. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  53904. + fontStyle.size + 'px "' + fontStyle.family + '"';
  53905. textRect = textRect || getBoundingRect(
  53906. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  53907. );
  53908. // Transform rect to view space
  53909. var m = this.transform;
  53910. // Ignore transform for text in other element
  53911. if (m && !fromTextEl) {
  53912. tmpRect$2.copy(rect);
  53913. tmpRect$2.applyTransform(m);
  53914. rect = tmpRect$2;
  53915. }
  53916. if (!fromTextEl) {
  53917. var textPosition = style.textPosition;
  53918. // Text position represented by coord
  53919. if (textPosition instanceof Array) {
  53920. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  53921. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  53922. align = align || 'left';
  53923. }
  53924. else {
  53925. var res = this.calculateTextPosition
  53926. ? this.calculateTextPosition({}, style, rect)
  53927. : calculateTextPosition({}, style, rect);
  53928. x = res.x;
  53929. y = res.y;
  53930. // Default align and baseline when has textPosition
  53931. align = align || res.textAlign;
  53932. verticalAlign = verticalAlign || res.textVerticalAlign;
  53933. }
  53934. }
  53935. else {
  53936. x = rect.x;
  53937. y = rect.y;
  53938. }
  53939. x = adjustTextX(x, textRect.width, align);
  53940. y = adjustTextY(y, textRect.height, verticalAlign);
  53941. // Force baseline 'middle'
  53942. y += textRect.height / 2;
  53943. // var fontSize = fontStyle.size;
  53944. // 1.75 is an arbitrary number, as there is no info about the text baseline
  53945. // switch (baseline) {
  53946. // case 'hanging':
  53947. // case 'top':
  53948. // y += fontSize / 1.75;
  53949. // break;
  53950. // case 'middle':
  53951. // break;
  53952. // default:
  53953. // // case null:
  53954. // // case 'alphabetic':
  53955. // // case 'ideographic':
  53956. // // case 'bottom':
  53957. // y -= fontSize / 2.25;
  53958. // break;
  53959. // }
  53960. // switch (align) {
  53961. // case 'left':
  53962. // break;
  53963. // case 'center':
  53964. // x -= textRect.width / 2;
  53965. // break;
  53966. // case 'right':
  53967. // x -= textRect.width;
  53968. // break;
  53969. // case 'end':
  53970. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  53971. // break;
  53972. // case 'start':
  53973. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  53974. // break;
  53975. // default:
  53976. // align = 'left';
  53977. // }
  53978. var createNode$$1 = createNode;
  53979. var textVmlEl = this._textVmlEl;
  53980. var pathEl;
  53981. var textPathEl;
  53982. var skewEl;
  53983. if (!textVmlEl) {
  53984. textVmlEl = createNode$$1('line');
  53985. pathEl = createNode$$1('path');
  53986. textPathEl = createNode$$1('textpath');
  53987. skewEl = createNode$$1('skew');
  53988. // FIXME Why here is not cammel case
  53989. // Align 'center' seems wrong
  53990. textPathEl.style['v-text-align'] = 'left';
  53991. initRootElStyle(textVmlEl);
  53992. pathEl.textpathok = true;
  53993. textPathEl.on = true;
  53994. textVmlEl.from = '0 0';
  53995. textVmlEl.to = '1000 0.05';
  53996. append(textVmlEl, skewEl);
  53997. append(textVmlEl, pathEl);
  53998. append(textVmlEl, textPathEl);
  53999. this._textVmlEl = textVmlEl;
  54000. }
  54001. else {
  54002. // 这里是在前面 appendChild 保证顺序的前提下
  54003. skewEl = textVmlEl.firstChild;
  54004. pathEl = skewEl.nextSibling;
  54005. textPathEl = pathEl.nextSibling;
  54006. }
  54007. var coords = [x, y];
  54008. var textVmlElStyle = textVmlEl.style;
  54009. // Ignore transform for text in other element
  54010. if (m && fromTextEl) {
  54011. applyTransform(coords, coords, m);
  54012. skewEl.on = true;
  54013. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  54014. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  54015. // Text position
  54016. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  54017. // Left top point as origin
  54018. skewEl.origin = '0 0';
  54019. textVmlElStyle.left = '0px';
  54020. textVmlElStyle.top = '0px';
  54021. }
  54022. else {
  54023. skewEl.on = false;
  54024. textVmlElStyle.left = round$2(x) + 'px';
  54025. textVmlElStyle.top = round$2(y) + 'px';
  54026. }
  54027. textPathEl.string = encodeHtmlAttribute(text);
  54028. // TODO
  54029. try {
  54030. textPathEl.style.font = font;
  54031. }
  54032. // Error font format
  54033. catch (e) {}
  54034. updateFillAndStroke(textVmlEl, 'fill', {
  54035. fill: style.textFill,
  54036. opacity: style.opacity
  54037. }, this);
  54038. updateFillAndStroke(textVmlEl, 'stroke', {
  54039. stroke: style.textStroke,
  54040. opacity: style.opacity,
  54041. lineDash: style.lineDash || null // style.lineDash can be `false`.
  54042. }, this);
  54043. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  54044. // Attached to root
  54045. append(vmlRoot, textVmlEl);
  54046. };
  54047. var removeRectText = function (vmlRoot) {
  54048. remove(vmlRoot, this._textVmlEl);
  54049. this._textVmlEl = null;
  54050. };
  54051. var appendRectText = function (vmlRoot) {
  54052. append(vmlRoot, this._textVmlEl);
  54053. };
  54054. var list = [RectText, Displayable, ZImage, Path, Text];
  54055. // In case Displayable has been mixed in RectText
  54056. for (var i$1 = 0; i$1 < list.length; i$1++) {
  54057. var proto$7 = list[i$1].prototype;
  54058. proto$7.drawRectText = drawRectText;
  54059. proto$7.removeRectText = removeRectText;
  54060. proto$7.appendRectText = appendRectText;
  54061. }
  54062. Text.prototype.brushVML = function (vmlRoot) {
  54063. var style = this.style;
  54064. if (style.text != null) {
  54065. this.drawRectText(vmlRoot, {
  54066. x: style.x || 0, y: style.y || 0,
  54067. width: 0, height: 0
  54068. }, this.getBoundingRect(), true);
  54069. }
  54070. else {
  54071. this.removeRectText(vmlRoot);
  54072. }
  54073. };
  54074. Text.prototype.onRemove = function (vmlRoot) {
  54075. this.removeRectText(vmlRoot);
  54076. };
  54077. Text.prototype.onAdd = function (vmlRoot) {
  54078. this.appendRectText(vmlRoot);
  54079. };
  54080. }
  54081. /**
  54082. * VML Painter.
  54083. *
  54084. * @module zrender/vml/Painter
  54085. */
  54086. function parseInt10$1(val) {
  54087. return parseInt(val, 10);
  54088. }
  54089. /**
  54090. * @alias module:zrender/vml/Painter
  54091. */
  54092. function VMLPainter(root, storage) {
  54093. initVML();
  54094. this.root = root;
  54095. this.storage = storage;
  54096. var vmlViewport = document.createElement('div');
  54097. var vmlRoot = document.createElement('div');
  54098. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  54099. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  54100. root.appendChild(vmlViewport);
  54101. this._vmlRoot = vmlRoot;
  54102. this._vmlViewport = vmlViewport;
  54103. this.resize();
  54104. // Modify storage
  54105. var oldDelFromStorage = storage.delFromStorage;
  54106. var oldAddToStorage = storage.addToStorage;
  54107. storage.delFromStorage = function (el) {
  54108. oldDelFromStorage.call(storage, el);
  54109. if (el) {
  54110. el.onRemove && el.onRemove(vmlRoot);
  54111. }
  54112. };
  54113. storage.addToStorage = function (el) {
  54114. // Displayable already has a vml node
  54115. el.onAdd && el.onAdd(vmlRoot);
  54116. oldAddToStorage.call(storage, el);
  54117. };
  54118. this._firstPaint = true;
  54119. }
  54120. VMLPainter.prototype = {
  54121. constructor: VMLPainter,
  54122. getType: function () {
  54123. return 'vml';
  54124. },
  54125. /**
  54126. * @return {HTMLDivElement}
  54127. */
  54128. getViewportRoot: function () {
  54129. return this._vmlViewport;
  54130. },
  54131. getViewportRootOffset: function () {
  54132. var viewportRoot = this.getViewportRoot();
  54133. if (viewportRoot) {
  54134. return {
  54135. offsetLeft: viewportRoot.offsetLeft || 0,
  54136. offsetTop: viewportRoot.offsetTop || 0
  54137. };
  54138. }
  54139. },
  54140. /**
  54141. * 刷新
  54142. */
  54143. refresh: function () {
  54144. var list = this.storage.getDisplayList(true, true);
  54145. this._paintList(list);
  54146. },
  54147. _paintList: function (list) {
  54148. var vmlRoot = this._vmlRoot;
  54149. for (var i = 0; i < list.length; i++) {
  54150. var el = list[i];
  54151. if (el.invisible || el.ignore) {
  54152. if (!el.__alreadyNotVisible) {
  54153. el.onRemove(vmlRoot);
  54154. }
  54155. // Set as already invisible
  54156. el.__alreadyNotVisible = true;
  54157. }
  54158. else {
  54159. if (el.__alreadyNotVisible) {
  54160. el.onAdd(vmlRoot);
  54161. }
  54162. el.__alreadyNotVisible = false;
  54163. if (el.__dirty) {
  54164. el.beforeBrush && el.beforeBrush();
  54165. (el.brushVML || el.brush).call(el, vmlRoot);
  54166. el.afterBrush && el.afterBrush();
  54167. }
  54168. }
  54169. el.__dirty = false;
  54170. }
  54171. if (this._firstPaint) {
  54172. // Detached from document at first time
  54173. // to avoid page refreshing too many times
  54174. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  54175. this._vmlViewport.appendChild(vmlRoot);
  54176. this._firstPaint = false;
  54177. }
  54178. },
  54179. resize: function (width, height) {
  54180. var width = width == null ? this._getWidth() : width;
  54181. var height = height == null ? this._getHeight() : height;
  54182. if (this._width !== width || this._height !== height) {
  54183. this._width = width;
  54184. this._height = height;
  54185. var vmlViewportStyle = this._vmlViewport.style;
  54186. vmlViewportStyle.width = width + 'px';
  54187. vmlViewportStyle.height = height + 'px';
  54188. }
  54189. },
  54190. dispose: function () {
  54191. this.root.innerHTML = '';
  54192. this._vmlRoot =
  54193. this._vmlViewport =
  54194. this.storage = null;
  54195. },
  54196. getWidth: function () {
  54197. return this._width;
  54198. },
  54199. getHeight: function () {
  54200. return this._height;
  54201. },
  54202. clear: function () {
  54203. if (this._vmlViewport) {
  54204. this.root.removeChild(this._vmlViewport);
  54205. }
  54206. },
  54207. _getWidth: function () {
  54208. var root = this.root;
  54209. var stl = root.currentStyle;
  54210. return ((root.clientWidth || parseInt10$1(stl.width))
  54211. - parseInt10$1(stl.paddingLeft)
  54212. - parseInt10$1(stl.paddingRight)) | 0;
  54213. },
  54214. _getHeight: function () {
  54215. var root = this.root;
  54216. var stl = root.currentStyle;
  54217. return ((root.clientHeight || parseInt10$1(stl.height))
  54218. - parseInt10$1(stl.paddingTop)
  54219. - parseInt10$1(stl.paddingBottom)) | 0;
  54220. }
  54221. };
  54222. // Not supported methods
  54223. function createMethodNotSupport(method) {
  54224. return function () {
  54225. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  54226. };
  54227. }
  54228. // Unsupported methods
  54229. each$1([
  54230. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  54231. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  54232. ], function (name) {
  54233. VMLPainter.prototype[name] = createMethodNotSupport(name);
  54234. });
  54235. registerPainter('vml', VMLPainter);
  54236. var svgURI = 'http://www.w3.org/2000/svg';
  54237. function createElement(name) {
  54238. return document.createElementNS(svgURI, name);
  54239. }
  54240. // TODO
  54241. // 1. shadow
  54242. // 2. Image: sx, sy, sw, sh
  54243. var CMD$4 = PathProxy.CMD;
  54244. var arrayJoin = Array.prototype.join;
  54245. var NONE = 'none';
  54246. var mathRound = Math.round;
  54247. var mathSin$3 = Math.sin;
  54248. var mathCos$3 = Math.cos;
  54249. var PI$3 = Math.PI;
  54250. var PI2$5 = Math.PI * 2;
  54251. var degree = 180 / PI$3;
  54252. var EPSILON$4 = 1e-4;
  54253. function round4(val) {
  54254. return mathRound(val * 1e4) / 1e4;
  54255. }
  54256. function isAroundZero$1(val) {
  54257. return val < EPSILON$4 && val > -EPSILON$4;
  54258. }
  54259. function pathHasFill(style, isText) {
  54260. var fill = isText ? style.textFill : style.fill;
  54261. return fill != null && fill !== NONE;
  54262. }
  54263. function pathHasStroke(style, isText) {
  54264. var stroke = isText ? style.textStroke : style.stroke;
  54265. return stroke != null && stroke !== NONE;
  54266. }
  54267. function setTransform(svgEl, m) {
  54268. if (m) {
  54269. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  54270. }
  54271. }
  54272. function attr(el, key, val) {
  54273. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  54274. // Don't set attribute for gradient, since it need new dom nodes
  54275. el.setAttribute(key, val);
  54276. }
  54277. }
  54278. function attrXLink(el, key, val) {
  54279. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  54280. }
  54281. function bindStyle(svgEl, style, isText, el) {
  54282. if (pathHasFill(style, isText)) {
  54283. var fill = isText ? style.textFill : style.fill;
  54284. fill = fill === 'transparent' ? NONE : fill;
  54285. attr(svgEl, 'fill', fill);
  54286. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  54287. }
  54288. else {
  54289. attr(svgEl, 'fill', NONE);
  54290. }
  54291. if (pathHasStroke(style, isText)) {
  54292. var stroke = isText ? style.textStroke : style.stroke;
  54293. stroke = stroke === 'transparent' ? NONE : stroke;
  54294. attr(svgEl, 'stroke', stroke);
  54295. var strokeWidth = isText
  54296. ? style.textStrokeWidth
  54297. : style.lineWidth;
  54298. var strokeScale = !isText && style.strokeNoScale
  54299. ? el.getLineScale()
  54300. : 1;
  54301. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  54302. // stroke then fill for text; fill then stroke for others
  54303. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  54304. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  54305. var lineDash = style.lineDash;
  54306. if (lineDash) {
  54307. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  54308. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  54309. }
  54310. else {
  54311. attr(svgEl, 'stroke-dasharray', '');
  54312. }
  54313. // PENDING
  54314. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  54315. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  54316. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  54317. }
  54318. else {
  54319. attr(svgEl, 'stroke', NONE);
  54320. }
  54321. }
  54322. /***************************************************
  54323. * PATH
  54324. **************************************************/
  54325. function pathDataToString$1(path) {
  54326. var str = [];
  54327. var data = path.data;
  54328. var dataLength = path.len();
  54329. for (var i = 0; i < dataLength;) {
  54330. var cmd = data[i++];
  54331. var cmdStr = '';
  54332. var nData = 0;
  54333. switch (cmd) {
  54334. case CMD$4.M:
  54335. cmdStr = 'M';
  54336. nData = 2;
  54337. break;
  54338. case CMD$4.L:
  54339. cmdStr = 'L';
  54340. nData = 2;
  54341. break;
  54342. case CMD$4.Q:
  54343. cmdStr = 'Q';
  54344. nData = 4;
  54345. break;
  54346. case CMD$4.C:
  54347. cmdStr = 'C';
  54348. nData = 6;
  54349. break;
  54350. case CMD$4.A:
  54351. var cx = data[i++];
  54352. var cy = data[i++];
  54353. var rx = data[i++];
  54354. var ry = data[i++];
  54355. var theta = data[i++];
  54356. var dTheta = data[i++];
  54357. var psi = data[i++];
  54358. var clockwise = data[i++];
  54359. var dThetaPositive = Math.abs(dTheta);
  54360. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  54361. || (clockwise ? dTheta >= PI2$5 : -dTheta >= PI2$5);
  54362. // Mapping to 0~2PI
  54363. var unifiedTheta = dTheta > 0 ? dTheta % PI2$5 : (dTheta % PI2$5 + PI2$5);
  54364. var large = false;
  54365. if (isCircle) {
  54366. large = true;
  54367. }
  54368. else if (isAroundZero$1(dThetaPositive)) {
  54369. large = false;
  54370. }
  54371. else {
  54372. large = (unifiedTheta >= PI$3) === !!clockwise;
  54373. }
  54374. var x0 = round4(cx + rx * mathCos$3(theta));
  54375. var y0 = round4(cy + ry * mathSin$3(theta));
  54376. // It will not draw if start point and end point are exactly the same
  54377. // We need to shift the end point with a small value
  54378. // FIXME A better way to draw circle ?
  54379. if (isCircle) {
  54380. if (clockwise) {
  54381. dTheta = PI2$5 - 1e-4;
  54382. }
  54383. else {
  54384. dTheta = -PI2$5 + 1e-4;
  54385. }
  54386. large = true;
  54387. if (i === 9) {
  54388. // Move to (x0, y0) only when CMD.A comes at the
  54389. // first position of a shape.
  54390. // For instance, when drawing a ring, CMD.A comes
  54391. // after CMD.M, so it's unnecessary to move to
  54392. // (x0, y0).
  54393. str.push('M', x0, y0);
  54394. }
  54395. }
  54396. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  54397. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  54398. // FIXME Ellipse
  54399. str.push('A', round4(rx), round4(ry),
  54400. mathRound(psi * degree), +large, +clockwise, x, y);
  54401. break;
  54402. case CMD$4.Z:
  54403. cmdStr = 'Z';
  54404. break;
  54405. case CMD$4.R:
  54406. var x = round4(data[i++]);
  54407. var y = round4(data[i++]);
  54408. var w = round4(data[i++]);
  54409. var h = round4(data[i++]);
  54410. str.push(
  54411. 'M', x, y,
  54412. 'L', x + w, y,
  54413. 'L', x + w, y + h,
  54414. 'L', x, y + h,
  54415. 'L', x, y
  54416. );
  54417. break;
  54418. }
  54419. cmdStr && str.push(cmdStr);
  54420. for (var j = 0; j < nData; j++) {
  54421. // PENDING With scale
  54422. str.push(round4(data[i++]));
  54423. }
  54424. }
  54425. return str.join(' ');
  54426. }
  54427. var svgPath = {};
  54428. svgPath.brush = function (el) {
  54429. var style = el.style;
  54430. var svgEl = el.__svgEl;
  54431. if (!svgEl) {
  54432. svgEl = createElement('path');
  54433. el.__svgEl = svgEl;
  54434. }
  54435. if (!el.path) {
  54436. el.createPathProxy();
  54437. }
  54438. var path = el.path;
  54439. if (el.__dirtyPath) {
  54440. path.beginPath();
  54441. path.subPixelOptimize = false;
  54442. el.buildPath(path, el.shape);
  54443. el.__dirtyPath = false;
  54444. var pathStr = pathDataToString$1(path);
  54445. if (pathStr.indexOf('NaN') < 0) {
  54446. // Ignore illegal path, which may happen such in out-of-range
  54447. // data in Calendar series.
  54448. attr(svgEl, 'd', pathStr);
  54449. }
  54450. }
  54451. bindStyle(svgEl, style, false, el);
  54452. setTransform(svgEl, el.transform);
  54453. if (style.text != null) {
  54454. svgTextDrawRectText(el, el.getBoundingRect());
  54455. }
  54456. else {
  54457. removeOldTextNode(el);
  54458. }
  54459. };
  54460. /***************************************************
  54461. * IMAGE
  54462. **************************************************/
  54463. var svgImage = {};
  54464. svgImage.brush = function (el) {
  54465. var style = el.style;
  54466. var image = style.image;
  54467. if (image instanceof HTMLImageElement) {
  54468. var src = image.src;
  54469. image = src;
  54470. }
  54471. if (!image) {
  54472. return;
  54473. }
  54474. var x = style.x || 0;
  54475. var y = style.y || 0;
  54476. var dw = style.width;
  54477. var dh = style.height;
  54478. var svgEl = el.__svgEl;
  54479. if (!svgEl) {
  54480. svgEl = createElement('image');
  54481. el.__svgEl = svgEl;
  54482. }
  54483. if (image !== el.__imageSrc) {
  54484. attrXLink(svgEl, 'href', image);
  54485. // Caching image src
  54486. el.__imageSrc = image;
  54487. }
  54488. attr(svgEl, 'width', dw);
  54489. attr(svgEl, 'height', dh);
  54490. attr(svgEl, 'x', x);
  54491. attr(svgEl, 'y', y);
  54492. setTransform(svgEl, el.transform);
  54493. if (style.text != null) {
  54494. svgTextDrawRectText(el, el.getBoundingRect());
  54495. }
  54496. else {
  54497. removeOldTextNode(el);
  54498. }
  54499. };
  54500. /***************************************************
  54501. * TEXT
  54502. **************************************************/
  54503. var svgText = {};
  54504. var _tmpTextHostRect = new BoundingRect();
  54505. var _tmpTextBoxPos = {};
  54506. var _tmpTextTransform = [];
  54507. var TEXT_ALIGN_TO_ANCHRO = {
  54508. left: 'start',
  54509. right: 'end',
  54510. center: 'middle',
  54511. middle: 'middle'
  54512. };
  54513. /**
  54514. * @param {module:zrender/Element} el
  54515. * @param {Object|boolean} [hostRect] {x, y, width, height}
  54516. * If set false, rect text is not used.
  54517. */
  54518. var svgTextDrawRectText = function (el, hostRect) {
  54519. var style = el.style;
  54520. var elTransform = el.transform;
  54521. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  54522. el.__dirty && normalizeTextStyle(style, true);
  54523. var text = style.text;
  54524. // Convert to string
  54525. text != null && (text += '');
  54526. if (!needDrawText(text, style)) {
  54527. return;
  54528. }
  54529. // render empty text for svg if no text but need draw text.
  54530. text == null && (text = '');
  54531. // Follow the setting in the canvas renderer, if not transform the
  54532. // text, transform the hostRect, by which the text is located.
  54533. if (!needTransformTextByHostEl && elTransform) {
  54534. _tmpTextHostRect.copy(hostRect);
  54535. _tmpTextHostRect.applyTransform(elTransform);
  54536. hostRect = _tmpTextHostRect;
  54537. }
  54538. var textSvgEl = el.__textSvgEl;
  54539. if (!textSvgEl) {
  54540. textSvgEl = createElement('text');
  54541. el.__textSvgEl = textSvgEl;
  54542. }
  54543. // style.font has been normalized by `normalizeTextStyle`.
  54544. var textSvgElStyle = textSvgEl.style;
  54545. var font = style.font || DEFAULT_FONT$1;
  54546. var computedFont = textSvgEl.__computedFont;
  54547. if (font !== textSvgEl.__styleFont) {
  54548. textSvgElStyle.font = textSvgEl.__styleFont = font;
  54549. // The computedFont might not be the orginal font if it is illegal font.
  54550. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  54551. }
  54552. var textPadding = style.textPadding;
  54553. var textLineHeight = style.textLineHeight;
  54554. var contentBlock = el.__textCotentBlock;
  54555. if (!contentBlock || el.__dirtyText) {
  54556. contentBlock = el.__textCotentBlock = parsePlainText(
  54557. text, computedFont, textPadding, textLineHeight, style.truncate
  54558. );
  54559. }
  54560. var outerHeight = contentBlock.outerHeight;
  54561. var lineHeight = contentBlock.lineHeight;
  54562. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  54563. var baseX = _tmpTextBoxPos.baseX;
  54564. var baseY = _tmpTextBoxPos.baseY;
  54565. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  54566. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  54567. setTextTransform(
  54568. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  54569. );
  54570. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  54571. var textX = baseX;
  54572. var textY = boxY;
  54573. // TODO needDrawBg
  54574. if (textPadding) {
  54575. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  54576. textY += textPadding[0];
  54577. }
  54578. // `textBaseline` is set as 'middle'.
  54579. textY += lineHeight / 2;
  54580. bindStyle(textSvgEl, style, true, el);
  54581. // FIXME
  54582. // Add a <style> to reset all of the text font as inherit?
  54583. // otherwise the outer <style> may set the unexpected style.
  54584. // Font may affect position of each tspan elements
  54585. var canCacheByTextString = contentBlock.canCacheByTextString;
  54586. var tspanList = el.__tspanList || (el.__tspanList = []);
  54587. var tspanOriginLen = tspanList.length;
  54588. // Optimize for most cases, just compare text string to determine change.
  54589. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  54590. if (el.__dirtyText && tspanOriginLen) {
  54591. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  54592. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  54593. }
  54594. }
  54595. }
  54596. else {
  54597. el.__text = text;
  54598. el.__canCacheByTextString = canCacheByTextString;
  54599. var textLines = contentBlock.lines;
  54600. var nTextLines = textLines.length;
  54601. var idx = 0;
  54602. for (; idx < nTextLines; idx++) {
  54603. // Using cached tspan elements
  54604. var tspan = tspanList[idx];
  54605. var singleLineText = textLines[idx];
  54606. if (!tspan) {
  54607. tspan = tspanList[idx] = createElement('tspan');
  54608. textSvgEl.appendChild(tspan);
  54609. tspan.appendChild(document.createTextNode(singleLineText));
  54610. }
  54611. else if (tspan.__zrText !== singleLineText) {
  54612. tspan.innerHTML = '';
  54613. tspan.appendChild(document.createTextNode(singleLineText));
  54614. }
  54615. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  54616. }
  54617. // Remove unused tspan elements
  54618. if (tspanOriginLen > nTextLines) {
  54619. for (; idx < tspanOriginLen; idx++) {
  54620. textSvgEl.removeChild(tspanList[idx]);
  54621. }
  54622. tspanList.length = nTextLines;
  54623. }
  54624. }
  54625. };
  54626. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  54627. identity(_tmpTextTransform);
  54628. if (needTransformTextByHostEl && elTransform) {
  54629. copy$1(_tmpTextTransform, elTransform);
  54630. }
  54631. // textRotation only apply in RectText.
  54632. var textRotation = style.textRotation;
  54633. if (hostRect && textRotation) {
  54634. var origin = style.textOrigin;
  54635. if (origin === 'center') {
  54636. baseX = hostRect.width / 2 + hostRect.x;
  54637. baseY = hostRect.height / 2 + hostRect.y;
  54638. }
  54639. else if (origin) {
  54640. baseX = origin[0] + hostRect.x;
  54641. baseY = origin[1] + hostRect.y;
  54642. }
  54643. _tmpTextTransform[4] -= baseX;
  54644. _tmpTextTransform[5] -= baseY;
  54645. // Positive: anticlockwise
  54646. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  54647. _tmpTextTransform[4] += baseX;
  54648. _tmpTextTransform[5] += baseY;
  54649. }
  54650. // See the definition in `Style.js#textOrigin`, the default
  54651. // origin is from the result of `getBoxPosition`.
  54652. setTransform(textSvgEl, _tmpTextTransform);
  54653. }
  54654. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  54655. function getTextXForPadding$1(x, textAlign, textPadding) {
  54656. return textAlign === 'right'
  54657. ? (x - textPadding[1])
  54658. : textAlign === 'center'
  54659. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  54660. : (x + textPadding[3]);
  54661. }
  54662. function updateTextLocation(tspan, textAlign, x, y) {
  54663. // Consider different font display differently in vertial align, we always
  54664. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  54665. attr(tspan, 'dominant-baseline', 'middle');
  54666. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  54667. attr(tspan, 'x', x);
  54668. attr(tspan, 'y', y);
  54669. }
  54670. function removeOldTextNode(el) {
  54671. if (el && el.__textSvgEl) {
  54672. // textSvgEl may has no parentNode if el has been removed temporary.
  54673. if (el.__textSvgEl.parentNode) {
  54674. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  54675. }
  54676. el.__textSvgEl = null;
  54677. el.__tspanList = [];
  54678. el.__text = null;
  54679. }
  54680. }
  54681. svgText.drawRectText = svgTextDrawRectText;
  54682. svgText.brush = function (el) {
  54683. var style = el.style;
  54684. if (style.text != null) {
  54685. svgTextDrawRectText(el, false);
  54686. }
  54687. else {
  54688. removeOldTextNode(el);
  54689. }
  54690. };
  54691. // Myers' Diff Algorithm
  54692. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  54693. function Diff() {}
  54694. Diff.prototype = {
  54695. diff: function (oldArr, newArr, equals) {
  54696. if (!equals) {
  54697. equals = function (a, b) {
  54698. return a === b;
  54699. };
  54700. }
  54701. this.equals = equals;
  54702. var self = this;
  54703. oldArr = oldArr.slice();
  54704. newArr = newArr.slice();
  54705. // Allow subclasses to massage the input prior to running
  54706. var newLen = newArr.length;
  54707. var oldLen = oldArr.length;
  54708. var editLength = 1;
  54709. var maxEditLength = newLen + oldLen;
  54710. var bestPath = [{ newPos: -1, components: [] }];
  54711. // Seed editLength = 0, i.e. the content starts with the same values
  54712. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  54713. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54714. var indices = [];
  54715. for (var i = 0; i < newArr.length; i++) {
  54716. indices.push(i);
  54717. }
  54718. // Identity per the equality and tokenizer
  54719. return [{
  54720. indices: indices, count: newArr.length
  54721. }];
  54722. }
  54723. // Main worker method. checks all permutations of a given edit length for acceptance.
  54724. function execEditLength() {
  54725. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  54726. var basePath;
  54727. var addPath = bestPath[diagonalPath - 1];
  54728. var removePath = bestPath[diagonalPath + 1];
  54729. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  54730. if (addPath) {
  54731. // No one else is going to attempt to use this value, clear it
  54732. bestPath[diagonalPath - 1] = undefined;
  54733. }
  54734. var canAdd = addPath && addPath.newPos + 1 < newLen;
  54735. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  54736. if (!canAdd && !canRemove) {
  54737. // If this path is a terminal then prune
  54738. bestPath[diagonalPath] = undefined;
  54739. continue;
  54740. }
  54741. // Select the diagonal that we want to branch from. We select the prior
  54742. // path whose position in the new string is the farthest from the origin
  54743. // and does not pass the bounds of the diff graph
  54744. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  54745. basePath = clonePath(removePath);
  54746. self.pushComponent(basePath.components, undefined, true);
  54747. }
  54748. else {
  54749. basePath = addPath; // No need to clone, we've pulled it from the list
  54750. basePath.newPos++;
  54751. self.pushComponent(basePath.components, true, undefined);
  54752. }
  54753. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  54754. // If we have hit the end of both strings, then we are done
  54755. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  54756. return buildValues(self, basePath.components, newArr, oldArr);
  54757. }
  54758. else {
  54759. // Otherwise track this path as a potential candidate and continue.
  54760. bestPath[diagonalPath] = basePath;
  54761. }
  54762. }
  54763. editLength++;
  54764. }
  54765. while (editLength <= maxEditLength) {
  54766. var ret = execEditLength();
  54767. if (ret) {
  54768. return ret;
  54769. }
  54770. }
  54771. },
  54772. pushComponent: function (components, added, removed) {
  54773. var last = components[components.length - 1];
  54774. if (last && last.added === added && last.removed === removed) {
  54775. // We need to clone here as the component clone operation is just
  54776. // as shallow array clone
  54777. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  54778. }
  54779. else {
  54780. components.push({count: 1, added: added, removed: removed });
  54781. }
  54782. },
  54783. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  54784. var newLen = newArr.length;
  54785. var oldLen = oldArr.length;
  54786. var newPos = basePath.newPos;
  54787. var oldPos = newPos - diagonalPath;
  54788. var commonCount = 0;
  54789. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  54790. newPos++;
  54791. oldPos++;
  54792. commonCount++;
  54793. }
  54794. if (commonCount) {
  54795. basePath.components.push({count: commonCount});
  54796. }
  54797. basePath.newPos = newPos;
  54798. return oldPos;
  54799. },
  54800. tokenize: function (value) {
  54801. return value.slice();
  54802. },
  54803. join: function (value) {
  54804. return value.slice();
  54805. }
  54806. };
  54807. function buildValues(diff, components, newArr, oldArr) {
  54808. var componentPos = 0;
  54809. var componentLen = components.length;
  54810. var newPos = 0;
  54811. var oldPos = 0;
  54812. for (; componentPos < componentLen; componentPos++) {
  54813. var component = components[componentPos];
  54814. if (!component.removed) {
  54815. var indices = [];
  54816. for (var i = newPos; i < newPos + component.count; i++) {
  54817. indices.push(i);
  54818. }
  54819. component.indices = indices;
  54820. newPos += component.count;
  54821. // Common case
  54822. if (!component.added) {
  54823. oldPos += component.count;
  54824. }
  54825. }
  54826. else {
  54827. var indices = [];
  54828. for (var i = oldPos; i < oldPos + component.count; i++) {
  54829. indices.push(i);
  54830. }
  54831. component.indices = indices;
  54832. oldPos += component.count;
  54833. }
  54834. }
  54835. return components;
  54836. }
  54837. function clonePath(path) {
  54838. return { newPos: path.newPos, components: path.components.slice(0) };
  54839. }
  54840. var arrayDiff = new Diff();
  54841. var arrayDiff$1 = function (oldArr, newArr, callback) {
  54842. return arrayDiff.diff(oldArr, newArr, callback);
  54843. };
  54844. /**
  54845. * @file Manages elements that can be defined in <defs> in SVG,
  54846. * e.g., gradients, clip path, etc.
  54847. * @author Zhang Wenli
  54848. */
  54849. var MARK_UNUSED = '0';
  54850. var MARK_USED = '1';
  54851. /**
  54852. * Manages elements that can be defined in <defs> in SVG,
  54853. * e.g., gradients, clip path, etc.
  54854. *
  54855. * @class
  54856. * @param {number} zrId zrender instance id
  54857. * @param {SVGElement} svgRoot root of SVG document
  54858. * @param {string|string[]} tagNames possible tag names
  54859. * @param {string} markLabel label name to make if the element
  54860. * is used
  54861. */
  54862. function Definable(
  54863. zrId,
  54864. svgRoot,
  54865. tagNames,
  54866. markLabel,
  54867. domName
  54868. ) {
  54869. this._zrId = zrId;
  54870. this._svgRoot = svgRoot;
  54871. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  54872. this._markLabel = markLabel;
  54873. this._domName = domName || '_dom';
  54874. this.nextId = 0;
  54875. }
  54876. Definable.prototype.createElement = createElement;
  54877. /**
  54878. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  54879. *
  54880. * @param {boolean} isForceCreating if need to create when not exists
  54881. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  54882. * exist and isForceCreating is false
  54883. */
  54884. Definable.prototype.getDefs = function (isForceCreating) {
  54885. var svgRoot = this._svgRoot;
  54886. var defs = this._svgRoot.getElementsByTagName('defs');
  54887. if (defs.length === 0) {
  54888. // Not exist
  54889. if (isForceCreating) {
  54890. defs = svgRoot.insertBefore(
  54891. this.createElement('defs'), // Create new tag
  54892. svgRoot.firstChild // Insert in the front of svg
  54893. );
  54894. if (!defs.contains) {
  54895. // IE doesn't support contains method
  54896. defs.contains = function (el) {
  54897. var children = defs.children;
  54898. if (!children) {
  54899. return false;
  54900. }
  54901. for (var i = children.length - 1; i >= 0; --i) {
  54902. if (children[i] === el) {
  54903. return true;
  54904. }
  54905. }
  54906. return false;
  54907. };
  54908. }
  54909. return defs;
  54910. }
  54911. else {
  54912. return null;
  54913. }
  54914. }
  54915. else {
  54916. return defs[0];
  54917. }
  54918. };
  54919. /**
  54920. * Update DOM element if necessary.
  54921. *
  54922. * @param {Object|string} element style element. e.g., for gradient,
  54923. * it may be '#ccc' or {type: 'linear', ...}
  54924. * @param {Function|undefined} onUpdate update callback
  54925. */
  54926. Definable.prototype.update = function (element, onUpdate) {
  54927. if (!element) {
  54928. return;
  54929. }
  54930. var defs = this.getDefs(false);
  54931. if (element[this._domName] && defs.contains(element[this._domName])) {
  54932. // Update DOM
  54933. if (typeof onUpdate === 'function') {
  54934. onUpdate(element);
  54935. }
  54936. }
  54937. else {
  54938. // No previous dom, create new
  54939. var dom = this.add(element);
  54940. if (dom) {
  54941. element[this._domName] = dom;
  54942. }
  54943. }
  54944. };
  54945. /**
  54946. * Add gradient dom to defs
  54947. *
  54948. * @param {SVGElement} dom DOM to be added to <defs>
  54949. */
  54950. Definable.prototype.addDom = function (dom) {
  54951. var defs = this.getDefs(true);
  54952. defs.appendChild(dom);
  54953. };
  54954. /**
  54955. * Remove DOM of a given element.
  54956. *
  54957. * @param {SVGElement} element element to remove dom
  54958. */
  54959. Definable.prototype.removeDom = function (element) {
  54960. var defs = this.getDefs(false);
  54961. if (defs && element[this._domName]) {
  54962. defs.removeChild(element[this._domName]);
  54963. element[this._domName] = null;
  54964. }
  54965. };
  54966. /**
  54967. * Get DOMs of this element.
  54968. *
  54969. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  54970. */
  54971. Definable.prototype.getDoms = function () {
  54972. var defs = this.getDefs(false);
  54973. if (!defs) {
  54974. // No dom when defs is not defined
  54975. return [];
  54976. }
  54977. var doms = [];
  54978. each$1(this._tagNames, function (tagName) {
  54979. var tags = defs.getElementsByTagName(tagName);
  54980. // Note that tags is HTMLCollection, which is array-like
  54981. // rather than real array.
  54982. // So `doms.concat(tags)` add tags as one object.
  54983. doms = doms.concat([].slice.call(tags));
  54984. });
  54985. return doms;
  54986. };
  54987. /**
  54988. * Mark DOMs to be unused before painting, and clear unused ones at the end
  54989. * of the painting.
  54990. */
  54991. Definable.prototype.markAllUnused = function () {
  54992. var doms = this.getDoms();
  54993. var that = this;
  54994. each$1(doms, function (dom) {
  54995. dom[that._markLabel] = MARK_UNUSED;
  54996. });
  54997. };
  54998. /**
  54999. * Mark a single DOM to be used.
  55000. *
  55001. * @param {SVGElement} dom DOM to mark
  55002. */
  55003. Definable.prototype.markUsed = function (dom) {
  55004. if (dom) {
  55005. dom[this._markLabel] = MARK_USED;
  55006. }
  55007. };
  55008. /**
  55009. * Remove unused DOMs defined in <defs>
  55010. */
  55011. Definable.prototype.removeUnused = function () {
  55012. var defs = this.getDefs(false);
  55013. if (!defs) {
  55014. // Nothing to remove
  55015. return;
  55016. }
  55017. var doms = this.getDoms();
  55018. var that = this;
  55019. each$1(doms, function (dom) {
  55020. if (dom[that._markLabel] !== MARK_USED) {
  55021. // Remove gradient
  55022. defs.removeChild(dom);
  55023. }
  55024. });
  55025. };
  55026. /**
  55027. * Get SVG proxy.
  55028. *
  55029. * @param {Displayable} displayable displayable element
  55030. * @return {Path|Image|Text} svg proxy of given element
  55031. */
  55032. Definable.prototype.getSvgProxy = function (displayable) {
  55033. if (displayable instanceof Path) {
  55034. return svgPath;
  55035. }
  55036. else if (displayable instanceof ZImage) {
  55037. return svgImage;
  55038. }
  55039. else if (displayable instanceof Text) {
  55040. return svgText;
  55041. }
  55042. else {
  55043. return svgPath;
  55044. }
  55045. };
  55046. /**
  55047. * Get text SVG element.
  55048. *
  55049. * @param {Displayable} displayable displayable element
  55050. * @return {SVGElement} SVG element of text
  55051. */
  55052. Definable.prototype.getTextSvgElement = function (displayable) {
  55053. return displayable.__textSvgEl;
  55054. };
  55055. /**
  55056. * Get SVG element.
  55057. *
  55058. * @param {Displayable} displayable displayable element
  55059. * @return {SVGElement} SVG element
  55060. */
  55061. Definable.prototype.getSvgElement = function (displayable) {
  55062. return displayable.__svgEl;
  55063. };
  55064. /**
  55065. * @file Manages SVG gradient elements.
  55066. * @author Zhang Wenli
  55067. */
  55068. /**
  55069. * Manages SVG gradient elements.
  55070. *
  55071. * @class
  55072. * @extends Definable
  55073. * @param {number} zrId zrender instance id
  55074. * @param {SVGElement} svgRoot root of SVG document
  55075. */
  55076. function GradientManager(zrId, svgRoot) {
  55077. Definable.call(
  55078. this,
  55079. zrId,
  55080. svgRoot,
  55081. ['linearGradient', 'radialGradient'],
  55082. '__gradient_in_use__'
  55083. );
  55084. }
  55085. inherits(GradientManager, Definable);
  55086. /**
  55087. * Create new gradient DOM for fill or stroke if not exist,
  55088. * but will not update gradient if exists.
  55089. *
  55090. * @param {SvgElement} svgElement SVG element to paint
  55091. * @param {Displayable} displayable zrender displayable element
  55092. */
  55093. GradientManager.prototype.addWithoutUpdate = function (
  55094. svgElement,
  55095. displayable
  55096. ) {
  55097. if (displayable && displayable.style) {
  55098. var that = this;
  55099. each$1(['fill', 'stroke'], function (fillOrStroke) {
  55100. if (displayable.style[fillOrStroke]
  55101. && (displayable.style[fillOrStroke].type === 'linear'
  55102. || displayable.style[fillOrStroke].type === 'radial')
  55103. ) {
  55104. var gradient = displayable.style[fillOrStroke];
  55105. var defs = that.getDefs(true);
  55106. // Create dom in <defs> if not exists
  55107. var dom;
  55108. if (gradient._dom) {
  55109. // Gradient exists
  55110. dom = gradient._dom;
  55111. if (!defs.contains(gradient._dom)) {
  55112. // _dom is no longer in defs, recreate
  55113. that.addDom(dom);
  55114. }
  55115. }
  55116. else {
  55117. // New dom
  55118. dom = that.add(gradient);
  55119. }
  55120. that.markUsed(displayable);
  55121. var id = dom.getAttribute('id');
  55122. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  55123. }
  55124. });
  55125. }
  55126. };
  55127. /**
  55128. * Add a new gradient tag in <defs>
  55129. *
  55130. * @param {Gradient} gradient zr gradient instance
  55131. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  55132. * created DOM
  55133. */
  55134. GradientManager.prototype.add = function (gradient) {
  55135. var dom;
  55136. if (gradient.type === 'linear') {
  55137. dom = this.createElement('linearGradient');
  55138. }
  55139. else if (gradient.type === 'radial') {
  55140. dom = this.createElement('radialGradient');
  55141. }
  55142. else {
  55143. logError$1('Illegal gradient type.');
  55144. return null;
  55145. }
  55146. // Set dom id with gradient id, since each gradient instance
  55147. // will have no more than one dom element.
  55148. // id may exists before for those dirty elements, in which case
  55149. // id should remain the same, and other attributes should be
  55150. // updated.
  55151. gradient.id = gradient.id || this.nextId++;
  55152. dom.setAttribute('id', 'zr' + this._zrId
  55153. + '-gradient-' + gradient.id);
  55154. this.updateDom(gradient, dom);
  55155. this.addDom(dom);
  55156. return dom;
  55157. };
  55158. /**
  55159. * Update gradient.
  55160. *
  55161. * @param {Gradient} gradient zr gradient instance
  55162. */
  55163. GradientManager.prototype.update = function (gradient) {
  55164. var that = this;
  55165. Definable.prototype.update.call(this, gradient, function () {
  55166. var type = gradient.type;
  55167. var tagName = gradient._dom.tagName;
  55168. if (type === 'linear' && tagName === 'linearGradient'
  55169. || type === 'radial' && tagName === 'radialGradient'
  55170. ) {
  55171. // Gradient type is not changed, update gradient
  55172. that.updateDom(gradient, gradient._dom);
  55173. }
  55174. else {
  55175. // Remove and re-create if type is changed
  55176. that.removeDom(gradient);
  55177. that.add(gradient);
  55178. }
  55179. });
  55180. };
  55181. /**
  55182. * Update gradient dom
  55183. *
  55184. * @param {Gradient} gradient zr gradient instance
  55185. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  55186. * DOM to update
  55187. */
  55188. GradientManager.prototype.updateDom = function (gradient, dom) {
  55189. if (gradient.type === 'linear') {
  55190. dom.setAttribute('x1', gradient.x);
  55191. dom.setAttribute('y1', gradient.y);
  55192. dom.setAttribute('x2', gradient.x2);
  55193. dom.setAttribute('y2', gradient.y2);
  55194. }
  55195. else if (gradient.type === 'radial') {
  55196. dom.setAttribute('cx', gradient.x);
  55197. dom.setAttribute('cy', gradient.y);
  55198. dom.setAttribute('r', gradient.r);
  55199. }
  55200. else {
  55201. logError$1('Illegal gradient type.');
  55202. return;
  55203. }
  55204. if (gradient.global) {
  55205. // x1, x2, y1, y2 in range of 0 to canvas width or height
  55206. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  55207. }
  55208. else {
  55209. // x1, x2, y1, y2 in range of 0 to 1
  55210. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  55211. }
  55212. // Remove color stops if exists
  55213. dom.innerHTML = '';
  55214. // Add color stops
  55215. var colors = gradient.colorStops;
  55216. for (var i = 0, len = colors.length; i < len; ++i) {
  55217. var stop = this.createElement('stop');
  55218. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  55219. var color = colors[i].color;
  55220. if (color.indexOf('rgba' > -1)) {
  55221. // Fix Safari bug that stop-color not recognizing alpha #9014
  55222. var opacity = parse(color)[3];
  55223. var hex = toHex(color);
  55224. // stop-color cannot be color, since:
  55225. // The opacity value used for the gradient calculation is the
  55226. // *product* of the value of stop-opacity and the opacity of the
  55227. // value of stop-color.
  55228. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  55229. stop.setAttribute('stop-color', '#' + hex);
  55230. stop.setAttribute('stop-opacity', opacity);
  55231. }
  55232. else {
  55233. stop.setAttribute('stop-color', colors[i].color);
  55234. }
  55235. dom.appendChild(stop);
  55236. }
  55237. // Store dom element in gradient, to avoid creating multiple
  55238. // dom instances for the same gradient element
  55239. gradient._dom = dom;
  55240. };
  55241. /**
  55242. * Mark a single gradient to be used
  55243. *
  55244. * @param {Displayable} displayable displayable element
  55245. */
  55246. GradientManager.prototype.markUsed = function (displayable) {
  55247. if (displayable.style) {
  55248. var gradient = displayable.style.fill;
  55249. if (gradient && gradient._dom) {
  55250. Definable.prototype.markUsed.call(this, gradient._dom);
  55251. }
  55252. gradient = displayable.style.stroke;
  55253. if (gradient && gradient._dom) {
  55254. Definable.prototype.markUsed.call(this, gradient._dom);
  55255. }
  55256. }
  55257. };
  55258. /**
  55259. * @file Manages SVG clipPath elements.
  55260. * @author Zhang Wenli
  55261. */
  55262. /**
  55263. * Manages SVG clipPath elements.
  55264. *
  55265. * @class
  55266. * @extends Definable
  55267. * @param {number} zrId zrender instance id
  55268. * @param {SVGElement} svgRoot root of SVG document
  55269. */
  55270. function ClippathManager(zrId, svgRoot) {
  55271. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  55272. }
  55273. inherits(ClippathManager, Definable);
  55274. /**
  55275. * Update clipPath.
  55276. *
  55277. * @param {Displayable} displayable displayable element
  55278. */
  55279. ClippathManager.prototype.update = function (displayable) {
  55280. var svgEl = this.getSvgElement(displayable);
  55281. if (svgEl) {
  55282. this.updateDom(svgEl, displayable.__clipPaths, false);
  55283. }
  55284. var textEl = this.getTextSvgElement(displayable);
  55285. if (textEl) {
  55286. // Make another clipPath for text, since it's transform
  55287. // matrix is not the same with svgElement
  55288. this.updateDom(textEl, displayable.__clipPaths, true);
  55289. }
  55290. this.markUsed(displayable);
  55291. };
  55292. /**
  55293. * Create an SVGElement of displayable and create a <clipPath> of its
  55294. * clipPath
  55295. *
  55296. * @param {Displayable} parentEl parent element
  55297. * @param {ClipPath[]} clipPaths clipPaths of parent element
  55298. * @param {boolean} isText if parent element is Text
  55299. */
  55300. ClippathManager.prototype.updateDom = function (
  55301. parentEl,
  55302. clipPaths,
  55303. isText
  55304. ) {
  55305. if (clipPaths && clipPaths.length > 0) {
  55306. // Has clipPath, create <clipPath> with the first clipPath
  55307. var defs = this.getDefs(true);
  55308. var clipPath = clipPaths[0];
  55309. var clipPathEl;
  55310. var id;
  55311. var dom = isText ? '_textDom' : '_dom';
  55312. if (clipPath[dom]) {
  55313. // Use a dom that is already in <defs>
  55314. id = clipPath[dom].getAttribute('id');
  55315. clipPathEl = clipPath[dom];
  55316. // Use a dom that is already in <defs>
  55317. if (!defs.contains(clipPathEl)) {
  55318. // This happens when set old clipPath that has
  55319. // been previously removed
  55320. defs.appendChild(clipPathEl);
  55321. }
  55322. }
  55323. else {
  55324. // New <clipPath>
  55325. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  55326. ++this.nextId;
  55327. clipPathEl = this.createElement('clipPath');
  55328. clipPathEl.setAttribute('id', id);
  55329. defs.appendChild(clipPathEl);
  55330. clipPath[dom] = clipPathEl;
  55331. }
  55332. // Build path and add to <clipPath>
  55333. var svgProxy = this.getSvgProxy(clipPath);
  55334. if (clipPath.transform
  55335. && clipPath.parent.invTransform
  55336. && !isText
  55337. ) {
  55338. /**
  55339. * If a clipPath has a parent with transform, the transform
  55340. * of parent should not be considered when setting transform
  55341. * of clipPath. So we need to transform back from parent's
  55342. * transform, which is done by multiplying parent's inverse
  55343. * transform.
  55344. */
  55345. // Store old transform
  55346. var transform = Array.prototype.slice.call(
  55347. clipPath.transform
  55348. );
  55349. // Transform back from parent, and brush path
  55350. mul$1(
  55351. clipPath.transform,
  55352. clipPath.parent.invTransform,
  55353. clipPath.transform
  55354. );
  55355. svgProxy.brush(clipPath);
  55356. // Set back transform of clipPath
  55357. clipPath.transform = transform;
  55358. }
  55359. else {
  55360. svgProxy.brush(clipPath);
  55361. }
  55362. var pathEl = this.getSvgElement(clipPath);
  55363. clipPathEl.innerHTML = '';
  55364. /**
  55365. * Use `cloneNode()` here to appendChild to multiple parents,
  55366. * which may happend when Text and other shapes are using the same
  55367. * clipPath. Since Text will create an extra clipPath DOM due to
  55368. * different transform rules.
  55369. */
  55370. clipPathEl.appendChild(pathEl.cloneNode());
  55371. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  55372. if (clipPaths.length > 1) {
  55373. // Make the other clipPaths recursively
  55374. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  55375. }
  55376. }
  55377. else {
  55378. // No clipPath
  55379. if (parentEl) {
  55380. parentEl.setAttribute('clip-path', 'none');
  55381. }
  55382. }
  55383. };
  55384. /**
  55385. * Mark a single clipPath to be used
  55386. *
  55387. * @param {Displayable} displayable displayable element
  55388. */
  55389. ClippathManager.prototype.markUsed = function (displayable) {
  55390. var that = this;
  55391. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  55392. if (displayable.__clipPaths) {
  55393. each$1(displayable.__clipPaths, function (clipPath) {
  55394. if (clipPath._dom) {
  55395. Definable.prototype.markUsed.call(that, clipPath._dom);
  55396. }
  55397. if (clipPath._textDom) {
  55398. Definable.prototype.markUsed.call(that, clipPath._textDom);
  55399. }
  55400. });
  55401. }
  55402. };
  55403. /**
  55404. * @file Manages SVG shadow elements.
  55405. * @author Zhang Wenli
  55406. */
  55407. /**
  55408. * Manages SVG shadow elements.
  55409. *
  55410. * @class
  55411. * @extends Definable
  55412. * @param {number} zrId zrender instance id
  55413. * @param {SVGElement} svgRoot root of SVG document
  55414. */
  55415. function ShadowManager(zrId, svgRoot) {
  55416. Definable.call(
  55417. this,
  55418. zrId,
  55419. svgRoot,
  55420. ['filter'],
  55421. '__filter_in_use__',
  55422. '_shadowDom'
  55423. );
  55424. }
  55425. inherits(ShadowManager, Definable);
  55426. /**
  55427. * Create new shadow DOM for fill or stroke if not exist,
  55428. * but will not update shadow if exists.
  55429. *
  55430. * @param {SvgElement} svgElement SVG element to paint
  55431. * @param {Displayable} displayable zrender displayable element
  55432. */
  55433. ShadowManager.prototype.addWithoutUpdate = function (
  55434. svgElement,
  55435. displayable
  55436. ) {
  55437. if (displayable && hasShadow(displayable.style)) {
  55438. // Create dom in <defs> if not exists
  55439. var dom;
  55440. if (displayable._shadowDom) {
  55441. // Gradient exists
  55442. dom = displayable._shadowDom;
  55443. var defs = this.getDefs(true);
  55444. if (!defs.contains(displayable._shadowDom)) {
  55445. // _shadowDom is no longer in defs, recreate
  55446. this.addDom(dom);
  55447. }
  55448. }
  55449. else {
  55450. // New dom
  55451. dom = this.add(displayable);
  55452. }
  55453. this.markUsed(displayable);
  55454. var id = dom.getAttribute('id');
  55455. svgElement.style.filter = 'url(#' + id + ')';
  55456. }
  55457. };
  55458. /**
  55459. * Add a new shadow tag in <defs>
  55460. *
  55461. * @param {Displayable} displayable zrender displayable element
  55462. * @return {SVGFilterElement} created DOM
  55463. */
  55464. ShadowManager.prototype.add = function (displayable) {
  55465. var dom = this.createElement('filter');
  55466. // Set dom id with shadow id, since each shadow instance
  55467. // will have no more than one dom element.
  55468. // id may exists before for those dirty elements, in which case
  55469. // id should remain the same, and other attributes should be
  55470. // updated.
  55471. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  55472. dom.setAttribute('id', 'zr' + this._zrId
  55473. + '-shadow-' + displayable._shadowDomId);
  55474. this.updateDom(displayable, dom);
  55475. this.addDom(dom);
  55476. return dom;
  55477. };
  55478. /**
  55479. * Update shadow.
  55480. *
  55481. * @param {Displayable} displayable zrender displayable element
  55482. */
  55483. ShadowManager.prototype.update = function (svgElement, displayable) {
  55484. var style = displayable.style;
  55485. if (hasShadow(style)) {
  55486. var that = this;
  55487. Definable.prototype.update.call(this, displayable, function () {
  55488. that.updateDom(displayable, displayable._shadowDom);
  55489. });
  55490. }
  55491. else {
  55492. // Remove shadow
  55493. this.remove(svgElement, displayable);
  55494. }
  55495. };
  55496. /**
  55497. * Remove DOM and clear parent filter
  55498. */
  55499. ShadowManager.prototype.remove = function (svgElement, displayable) {
  55500. if (displayable._shadowDomId != null) {
  55501. this.removeDom(svgElement);
  55502. svgElement.style.filter = '';
  55503. }
  55504. };
  55505. /**
  55506. * Update shadow dom
  55507. *
  55508. * @param {Displayable} displayable zrender displayable element
  55509. * @param {SVGFilterElement} dom DOM to update
  55510. */
  55511. ShadowManager.prototype.updateDom = function (displayable, dom) {
  55512. var domChild = dom.getElementsByTagName('feDropShadow');
  55513. if (domChild.length === 0) {
  55514. domChild = this.createElement('feDropShadow');
  55515. }
  55516. else {
  55517. domChild = domChild[0];
  55518. }
  55519. var style = displayable.style;
  55520. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  55521. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  55522. // TODO: textBoxShadowBlur is not supported yet
  55523. var offsetX;
  55524. var offsetY;
  55525. var blur;
  55526. var color;
  55527. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  55528. offsetX = style.shadowOffsetX || 0;
  55529. offsetY = style.shadowOffsetY || 0;
  55530. blur = style.shadowBlur;
  55531. color = style.shadowColor;
  55532. }
  55533. else if (style.textShadowBlur) {
  55534. offsetX = style.textShadowOffsetX || 0;
  55535. offsetY = style.textShadowOffsetY || 0;
  55536. blur = style.textShadowBlur;
  55537. color = style.textShadowColor;
  55538. }
  55539. else {
  55540. // Remove shadow
  55541. this.removeDom(dom, style);
  55542. return;
  55543. }
  55544. domChild.setAttribute('dx', offsetX / scaleX);
  55545. domChild.setAttribute('dy', offsetY / scaleY);
  55546. domChild.setAttribute('flood-color', color);
  55547. // Divide by two here so that it looks the same as in canvas
  55548. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  55549. var stdDx = blur / 2 / scaleX;
  55550. var stdDy = blur / 2 / scaleY;
  55551. var stdDeviation = stdDx + ' ' + stdDy;
  55552. domChild.setAttribute('stdDeviation', stdDeviation);
  55553. // Fix filter clipping problem
  55554. dom.setAttribute('x', '-100%');
  55555. dom.setAttribute('y', '-100%');
  55556. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  55557. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  55558. dom.appendChild(domChild);
  55559. // Store dom element in shadow, to avoid creating multiple
  55560. // dom instances for the same shadow element
  55561. displayable._shadowDom = dom;
  55562. };
  55563. /**
  55564. * Mark a single shadow to be used
  55565. *
  55566. * @param {Displayable} displayable displayable element
  55567. */
  55568. ShadowManager.prototype.markUsed = function (displayable) {
  55569. if (displayable._shadowDom) {
  55570. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  55571. }
  55572. };
  55573. function hasShadow(style) {
  55574. // TODO: textBoxShadowBlur is not supported yet
  55575. return style
  55576. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  55577. || style.textShadowBlur || style.textShadowOffsetX
  55578. || style.textShadowOffsetY);
  55579. }
  55580. /**
  55581. * SVG Painter
  55582. * @module zrender/svg/Painter
  55583. */
  55584. function parseInt10$2(val) {
  55585. return parseInt(val, 10);
  55586. }
  55587. function getSvgProxy(el) {
  55588. if (el instanceof Path) {
  55589. return svgPath;
  55590. }
  55591. else if (el instanceof ZImage) {
  55592. return svgImage;
  55593. }
  55594. else if (el instanceof Text) {
  55595. return svgText;
  55596. }
  55597. else {
  55598. return svgPath;
  55599. }
  55600. }
  55601. function checkParentAvailable(parent, child) {
  55602. return child && parent && child.parentNode !== parent;
  55603. }
  55604. function insertAfter(parent, child, prevSibling) {
  55605. if (checkParentAvailable(parent, child) && prevSibling) {
  55606. var nextSibling = prevSibling.nextSibling;
  55607. nextSibling ? parent.insertBefore(child, nextSibling)
  55608. : parent.appendChild(child);
  55609. }
  55610. }
  55611. function prepend(parent, child) {
  55612. if (checkParentAvailable(parent, child)) {
  55613. var firstChild = parent.firstChild;
  55614. firstChild ? parent.insertBefore(child, firstChild)
  55615. : parent.appendChild(child);
  55616. }
  55617. }
  55618. // function append(parent, child) {
  55619. // if (checkParentAvailable(parent, child)) {
  55620. // parent.appendChild(child);
  55621. // }
  55622. // }
  55623. function remove$1(parent, child) {
  55624. if (child && parent && child.parentNode === parent) {
  55625. parent.removeChild(child);
  55626. }
  55627. }
  55628. function getTextSvgElement(displayable) {
  55629. return displayable.__textSvgEl;
  55630. }
  55631. function getSvgElement(displayable) {
  55632. return displayable.__svgEl;
  55633. }
  55634. /**
  55635. * @alias module:zrender/svg/Painter
  55636. * @constructor
  55637. * @param {HTMLElement} root 绘图容器
  55638. * @param {module:zrender/Storage} storage
  55639. * @param {Object} opts
  55640. */
  55641. var SVGPainter = function (root, storage, opts, zrId) {
  55642. this.root = root;
  55643. this.storage = storage;
  55644. this._opts = opts = extend({}, opts || {});
  55645. var svgDom = createElement('svg');
  55646. svgDom.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  55647. svgDom.setAttribute('version', '1.1');
  55648. svgDom.setAttribute('baseProfile', 'full');
  55649. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  55650. var bgRoot = createElement('g');
  55651. svgDom.appendChild(bgRoot);
  55652. var svgRoot = createElement('g');
  55653. svgDom.appendChild(svgRoot);
  55654. this.gradientManager = new GradientManager(zrId, svgRoot);
  55655. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  55656. this.shadowManager = new ShadowManager(zrId, svgRoot);
  55657. var viewport = document.createElement('div');
  55658. viewport.style.cssText = 'overflow:hidden;position:relative';
  55659. this._svgDom = svgDom;
  55660. this._svgRoot = svgRoot;
  55661. this._backgroundRoot = bgRoot;
  55662. this._viewport = viewport;
  55663. root.appendChild(viewport);
  55664. viewport.appendChild(svgDom);
  55665. this.resize(opts.width, opts.height);
  55666. this._visibleList = [];
  55667. };
  55668. SVGPainter.prototype = {
  55669. constructor: SVGPainter,
  55670. getType: function () {
  55671. return 'svg';
  55672. },
  55673. getViewportRoot: function () {
  55674. return this._viewport;
  55675. },
  55676. getSvgDom: function () {
  55677. return this._svgDom;
  55678. },
  55679. getSvgRoot: function () {
  55680. return this._svgRoot;
  55681. },
  55682. getViewportRootOffset: function () {
  55683. var viewportRoot = this.getViewportRoot();
  55684. if (viewportRoot) {
  55685. return {
  55686. offsetLeft: viewportRoot.offsetLeft || 0,
  55687. offsetTop: viewportRoot.offsetTop || 0
  55688. };
  55689. }
  55690. },
  55691. refresh: function () {
  55692. var list = this.storage.getDisplayList(true);
  55693. this._paintList(list);
  55694. },
  55695. setBackgroundColor: function (backgroundColor) {
  55696. // TODO gradient
  55697. // Insert a bg rect instead of setting background to viewport.
  55698. // Otherwise, the exported SVG don't have background.
  55699. if (this._backgroundRoot && this._backgroundNode) {
  55700. this._backgroundRoot.removeChild(this._backgroundNode);
  55701. }
  55702. var bgNode = createElement('rect');
  55703. bgNode.setAttribute('width', this.getWidth());
  55704. bgNode.setAttribute('height', this.getHeight());
  55705. bgNode.setAttribute('x', 0);
  55706. bgNode.setAttribute('y', 0);
  55707. bgNode.setAttribute('id', 0);
  55708. bgNode.style.fill = backgroundColor;
  55709. this._backgroundRoot.appendChild(bgNode);
  55710. this._backgroundNode = bgNode;
  55711. },
  55712. _paintList: function (list) {
  55713. this.gradientManager.markAllUnused();
  55714. this.clipPathManager.markAllUnused();
  55715. this.shadowManager.markAllUnused();
  55716. var svgRoot = this._svgRoot;
  55717. var visibleList = this._visibleList;
  55718. var listLen = list.length;
  55719. var newVisibleList = [];
  55720. var i;
  55721. for (i = 0; i < listLen; i++) {
  55722. var displayable = list[i];
  55723. var svgProxy = getSvgProxy(displayable);
  55724. var svgElement = getSvgElement(displayable)
  55725. || getTextSvgElement(displayable);
  55726. if (!displayable.invisible) {
  55727. if (displayable.__dirty) {
  55728. svgProxy && svgProxy.brush(displayable);
  55729. // Update clipPath
  55730. this.clipPathManager.update(displayable);
  55731. // Update gradient and shadow
  55732. if (displayable.style) {
  55733. this.gradientManager
  55734. .update(displayable.style.fill);
  55735. this.gradientManager
  55736. .update(displayable.style.stroke);
  55737. this.shadowManager
  55738. .update(svgElement, displayable);
  55739. }
  55740. displayable.__dirty = false;
  55741. }
  55742. newVisibleList.push(displayable);
  55743. }
  55744. }
  55745. var diff = arrayDiff$1(visibleList, newVisibleList);
  55746. var prevSvgElement;
  55747. // First do remove, in case element moved to the head and do remove
  55748. // after add
  55749. for (i = 0; i < diff.length; i++) {
  55750. var item = diff[i];
  55751. if (item.removed) {
  55752. for (var k = 0; k < item.count; k++) {
  55753. var displayable = visibleList[item.indices[k]];
  55754. var svgElement = getSvgElement(displayable);
  55755. var textSvgElement = getTextSvgElement(displayable);
  55756. remove$1(svgRoot, svgElement);
  55757. remove$1(svgRoot, textSvgElement);
  55758. }
  55759. }
  55760. }
  55761. for (i = 0; i < diff.length; i++) {
  55762. var item = diff[i];
  55763. if (item.added) {
  55764. for (var k = 0; k < item.count; k++) {
  55765. var displayable = newVisibleList[item.indices[k]];
  55766. var svgElement = getSvgElement(displayable);
  55767. var textSvgElement = getTextSvgElement(displayable);
  55768. prevSvgElement
  55769. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  55770. : prepend(svgRoot, svgElement);
  55771. if (svgElement) {
  55772. insertAfter(svgRoot, textSvgElement, svgElement);
  55773. }
  55774. else if (prevSvgElement) {
  55775. insertAfter(
  55776. svgRoot, textSvgElement, prevSvgElement
  55777. );
  55778. }
  55779. else {
  55780. prepend(svgRoot, textSvgElement);
  55781. }
  55782. // Insert text
  55783. insertAfter(svgRoot, textSvgElement, svgElement);
  55784. prevSvgElement = textSvgElement || svgElement
  55785. || prevSvgElement;
  55786. // zrender.Text only create textSvgElement.
  55787. this.gradientManager
  55788. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55789. this.shadowManager
  55790. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55791. this.clipPathManager.markUsed(displayable);
  55792. }
  55793. }
  55794. else if (!item.removed) {
  55795. for (var k = 0; k < item.count; k++) {
  55796. var displayable = newVisibleList[item.indices[k]];
  55797. var svgElement = getSvgElement(displayable);
  55798. var textSvgElement = getTextSvgElement(displayable);
  55799. var svgElement = getSvgElement(displayable);
  55800. var textSvgElement = getTextSvgElement(displayable);
  55801. this.gradientManager.markUsed(displayable);
  55802. this.gradientManager
  55803. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55804. this.shadowManager.markUsed(displayable);
  55805. this.shadowManager
  55806. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  55807. this.clipPathManager.markUsed(displayable);
  55808. if (textSvgElement) { // Insert text.
  55809. insertAfter(svgRoot, textSvgElement, svgElement);
  55810. }
  55811. prevSvgElement = svgElement
  55812. || textSvgElement || prevSvgElement;
  55813. }
  55814. }
  55815. }
  55816. this.gradientManager.removeUnused();
  55817. this.clipPathManager.removeUnused();
  55818. this.shadowManager.removeUnused();
  55819. this._visibleList = newVisibleList;
  55820. },
  55821. _getDefs: function (isForceCreating) {
  55822. var svgRoot = this._svgDom;
  55823. var defs = svgRoot.getElementsByTagName('defs');
  55824. if (defs.length === 0) {
  55825. // Not exist
  55826. if (isForceCreating) {
  55827. var defs = svgRoot.insertBefore(
  55828. createElement('defs'), // Create new tag
  55829. svgRoot.firstChild // Insert in the front of svg
  55830. );
  55831. if (!defs.contains) {
  55832. // IE doesn't support contains method
  55833. defs.contains = function (el) {
  55834. var children = defs.children;
  55835. if (!children) {
  55836. return false;
  55837. }
  55838. for (var i = children.length - 1; i >= 0; --i) {
  55839. if (children[i] === el) {
  55840. return true;
  55841. }
  55842. }
  55843. return false;
  55844. };
  55845. }
  55846. return defs;
  55847. }
  55848. else {
  55849. return null;
  55850. }
  55851. }
  55852. else {
  55853. return defs[0];
  55854. }
  55855. },
  55856. resize: function (width, height) {
  55857. var viewport = this._viewport;
  55858. // FIXME Why ?
  55859. viewport.style.display = 'none';
  55860. // Save input w/h
  55861. var opts = this._opts;
  55862. width != null && (opts.width = width);
  55863. height != null && (opts.height = height);
  55864. width = this._getSize(0);
  55865. height = this._getSize(1);
  55866. viewport.style.display = '';
  55867. if (this._width !== width || this._height !== height) {
  55868. this._width = width;
  55869. this._height = height;
  55870. var viewportStyle = viewport.style;
  55871. viewportStyle.width = width + 'px';
  55872. viewportStyle.height = height + 'px';
  55873. var svgRoot = this._svgDom;
  55874. // Set width by 'svgRoot.width = width' is invalid
  55875. svgRoot.setAttribute('width', width);
  55876. svgRoot.setAttribute('height', height);
  55877. }
  55878. if (this._backgroundNode) {
  55879. this._backgroundNode.setAttribute('width', width);
  55880. this._backgroundNode.setAttribute('height', height);
  55881. }
  55882. },
  55883. /**
  55884. * 获取绘图区域宽度
  55885. */
  55886. getWidth: function () {
  55887. return this._width;
  55888. },
  55889. /**
  55890. * 获取绘图区域高度
  55891. */
  55892. getHeight: function () {
  55893. return this._height;
  55894. },
  55895. _getSize: function (whIdx) {
  55896. var opts = this._opts;
  55897. var wh = ['width', 'height'][whIdx];
  55898. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  55899. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  55900. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  55901. if (opts[wh] != null && opts[wh] !== 'auto') {
  55902. return parseFloat(opts[wh]);
  55903. }
  55904. var root = this.root;
  55905. // IE8 does not support getComputedStyle, but it use VML.
  55906. var stl = document.defaultView.getComputedStyle(root);
  55907. return (
  55908. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  55909. - (parseInt10$2(stl[plt]) || 0)
  55910. - (parseInt10$2(stl[prb]) || 0)
  55911. ) | 0;
  55912. },
  55913. dispose: function () {
  55914. this.root.innerHTML = '';
  55915. this._svgRoot
  55916. = this._backgroundRoot
  55917. = this._svgDom
  55918. = this._backgroundNode
  55919. = this._viewport
  55920. = this.storage
  55921. = null;
  55922. },
  55923. clear: function () {
  55924. if (this._viewport) {
  55925. this.root.removeChild(this._viewport);
  55926. }
  55927. },
  55928. toDataURL: function () {
  55929. this.refresh();
  55930. var html = encodeURIComponent(this._svgDom.outerHTML.replace(/></g, '>\n\r<'));
  55931. return 'data:image/svg+xml;charset=UTF-8,' + html;
  55932. }
  55933. };
  55934. // Not supported methods
  55935. function createMethodNotSupport$1(method) {
  55936. return function () {
  55937. logError$1('In SVG mode painter not support method "' + method + '"');
  55938. };
  55939. }
  55940. // Unsuppoted methods
  55941. each$1([
  55942. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  55943. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  55944. 'pathToImage'
  55945. ], function (name) {
  55946. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  55947. });
  55948. registerPainter('svg', SVGPainter);
  55949. /*
  55950. * Licensed to the Apache Software Foundation (ASF) under one
  55951. * or more contributor license agreements. See the NOTICE file
  55952. * distributed with this work for additional information
  55953. * regarding copyright ownership. The ASF licenses this file
  55954. * to you under the Apache License, Version 2.0 (the
  55955. * "License"); you may not use this file except in compliance
  55956. * with the License. You may obtain a copy of the License at
  55957. *
  55958. * http://www.apache.org/licenses/LICENSE-2.0
  55959. *
  55960. * Unless required by applicable law or agreed to in writing,
  55961. * software distributed under the License is distributed on an
  55962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55963. * KIND, either express or implied. See the License for the
  55964. * specific language governing permissions and limitations
  55965. * under the License.
  55966. */
  55967. exports.version = version;
  55968. exports.dependencies = dependencies;
  55969. exports.PRIORITY = PRIORITY;
  55970. exports.init = init;
  55971. exports.connect = connect;
  55972. exports.disConnect = disConnect;
  55973. exports.disconnect = disconnect;
  55974. exports.dispose = dispose;
  55975. exports.getInstanceByDom = getInstanceByDom;
  55976. exports.getInstanceById = getInstanceById;
  55977. exports.registerTheme = registerTheme;
  55978. exports.registerPreprocessor = registerPreprocessor;
  55979. exports.registerProcessor = registerProcessor;
  55980. exports.registerPostUpdate = registerPostUpdate;
  55981. exports.registerAction = registerAction;
  55982. exports.registerCoordinateSystem = registerCoordinateSystem;
  55983. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  55984. exports.registerLayout = registerLayout;
  55985. exports.registerVisual = registerVisual;
  55986. exports.registerLoading = registerLoading;
  55987. exports.extendComponentModel = extendComponentModel;
  55988. exports.extendComponentView = extendComponentView;
  55989. exports.extendSeriesModel = extendSeriesModel;
  55990. exports.extendChartView = extendChartView;
  55991. exports.setCanvasCreator = setCanvasCreator;
  55992. exports.registerMap = registerMap;
  55993. exports.getMap = getMap;
  55994. exports.dataTool = dataTool;
  55995. exports.zrender = zrender;
  55996. exports.number = number;
  55997. exports.format = format;
  55998. exports.throttle = throttle;
  55999. exports.helper = helper;
  56000. exports.matrix = matrix;
  56001. exports.vector = vector;
  56002. exports.color = color;
  56003. exports.parseGeoJSON = parseGeoJSON;
  56004. exports.parseGeoJson = parseGeoJson;
  56005. exports.util = ecUtil;
  56006. exports.graphic = graphic$1;
  56007. exports.List = List;
  56008. exports.Model = Model;
  56009. exports.Axis = Axis;
  56010. exports.env = env$1;
  56011. })));