echarts.common.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138
  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. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  7. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  8. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  9. // declaration is behind of the using position (for example in `Model.extent`,
  10. // And tools like rollup can not analysis the dependency if not import).
  11. var dev;
  12. // In browser
  13. if (typeof window !== 'undefined') {
  14. dev = window.__DEV__;
  15. }
  16. // In node
  17. else if (typeof global !== 'undefined') {
  18. dev = global.__DEV__;
  19. }
  20. if (typeof dev === 'undefined') {
  21. dev = true;
  22. }
  23. var __DEV__ = dev;
  24. /**
  25. * zrender: 生成唯一id
  26. *
  27. * @author errorrik (errorrik@gmail.com)
  28. */
  29. var idStart = 0x0907;
  30. var guid = function () {
  31. return idStart++;
  32. };
  33. /**
  34. * echarts设备环境识别
  35. *
  36. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  37. * @author firede[firede@firede.us]
  38. * @desc thanks zepto.
  39. */
  40. var env = {};
  41. if (typeof wx !== 'undefined') {
  42. // In Weixin Application
  43. env = {
  44. browser: {},
  45. os: {},
  46. node: false,
  47. wxa: true, // Weixin Application
  48. canvasSupported: true,
  49. svgSupported: false,
  50. touchEventsSupported: true
  51. };
  52. }
  53. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  54. // In worker
  55. env = {
  56. browser: {},
  57. os: {},
  58. node: false,
  59. worker: true,
  60. canvasSupported: true
  61. };
  62. }
  63. else if (typeof navigator === 'undefined') {
  64. // In node
  65. env = {
  66. browser: {},
  67. os: {},
  68. node: true,
  69. worker: false,
  70. // Assume canvas is supported
  71. canvasSupported: true,
  72. svgSupported: true
  73. };
  74. }
  75. else {
  76. env = detect(navigator.userAgent);
  77. }
  78. var env$1 = env;
  79. // Zepto.js
  80. // (c) 2010-2013 Thomas Fuchs
  81. // Zepto.js may be freely distributed under the MIT license.
  82. function detect(ua) {
  83. var os = {};
  84. var browser = {};
  85. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  86. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  87. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  88. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  89. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  90. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  91. // var touchpad = webos && ua.match(/TouchPad/);
  92. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  93. // var silk = ua.match(/Silk\/([\d._]+)/);
  94. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  95. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  96. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  97. // var playbook = ua.match(/PlayBook/);
  98. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  99. var firefox = ua.match(/Firefox\/([\d.]+)/);
  100. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  101. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  102. var ie = ua.match(/MSIE\s([\d.]+)/)
  103. // IE 11 Trident/7.0; rv:11.0
  104. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  105. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  106. var weChat = (/micromessenger/i).test(ua);
  107. // Todo: clean this up with a better OS/browser seperation:
  108. // - discern (more) between multiple browsers on android
  109. // - decide if kindle fire in silk mode is android or not
  110. // - Firefox on Android doesn't specify the Android version
  111. // - possibly devide in os, device and browser hashes
  112. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  113. // if (android) os.android = true, os.version = android[2];
  114. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  115. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  116. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  117. // if (webos) os.webos = true, os.version = webos[2];
  118. // if (touchpad) os.touchpad = true;
  119. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  120. // if (bb10) os.bb10 = true, os.version = bb10[2];
  121. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  122. // if (playbook) browser.playbook = true;
  123. // if (kindle) os.kindle = true, os.version = kindle[1];
  124. // if (silk) browser.silk = true, browser.version = silk[1];
  125. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  126. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  127. if (firefox) {
  128. browser.firefox = true;
  129. browser.version = firefox[1];
  130. }
  131. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  132. // if (webview) browser.webview = true;
  133. if (ie) {
  134. browser.ie = true;
  135. browser.version = ie[1];
  136. }
  137. if (edge) {
  138. browser.edge = true;
  139. browser.version = edge[1];
  140. }
  141. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  142. // not be set on win phone. So we do not consider Win Phone.
  143. if (weChat) {
  144. browser.weChat = true;
  145. }
  146. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  147. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  148. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  149. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  150. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  151. return {
  152. browser: browser,
  153. os: os,
  154. node: false,
  155. // 原生canvas支持,改极端点了
  156. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  157. canvasSupported: !!document.createElement('canvas').getContext,
  158. svgSupported: typeof SVGRect !== 'undefined',
  159. // works on most browsers
  160. // IE10/11 does not support touch event, and MS Edge supports them but not by
  161. // default, so we dont check navigator.maxTouchPoints for them here.
  162. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  163. // <http://caniuse.com/#search=pointer%20event>.
  164. pointerEventsSupported: 'onpointerdown' in window
  165. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  166. // events currently. So we dont use that on other browsers unless tested sufficiently.
  167. // Although IE 10 supports pointer event, it use old style and is different from the
  168. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  169. && (browser.edge || (browser.ie && browser.version >= 11))
  170. };
  171. }
  172. /**
  173. * @module zrender/core/util
  174. */
  175. // 用于处理merge时无法遍历Date等对象的问题
  176. var BUILTIN_OBJECT = {
  177. '[object Function]': 1,
  178. '[object RegExp]': 1,
  179. '[object Date]': 1,
  180. '[object Error]': 1,
  181. '[object CanvasGradient]': 1,
  182. '[object CanvasPattern]': 1,
  183. // For node-canvas
  184. '[object Image]': 1,
  185. '[object Canvas]': 1
  186. };
  187. var TYPED_ARRAY = {
  188. '[object Int8Array]': 1,
  189. '[object Uint8Array]': 1,
  190. '[object Uint8ClampedArray]': 1,
  191. '[object Int16Array]': 1,
  192. '[object Uint16Array]': 1,
  193. '[object Int32Array]': 1,
  194. '[object Uint32Array]': 1,
  195. '[object Float32Array]': 1,
  196. '[object Float64Array]': 1
  197. };
  198. var objToString = Object.prototype.toString;
  199. var arrayProto = Array.prototype;
  200. var nativeForEach = arrayProto.forEach;
  201. var nativeFilter = arrayProto.filter;
  202. var nativeSlice = arrayProto.slice;
  203. var nativeMap = arrayProto.map;
  204. var nativeReduce = arrayProto.reduce;
  205. // Avoid assign to an exported variable, for transforming to cjs.
  206. var methods = {};
  207. function $override(name, fn) {
  208. // Clear ctx instance for different environment
  209. if (name === 'createCanvas') {
  210. _ctx = null;
  211. }
  212. methods[name] = fn;
  213. }
  214. /**
  215. * Those data types can be cloned:
  216. * Plain object, Array, TypedArray, number, string, null, undefined.
  217. * Those data types will be assgined using the orginal data:
  218. * BUILTIN_OBJECT
  219. * Instance of user defined class will be cloned to a plain object, without
  220. * properties in prototype.
  221. * Other data types is not supported (not sure what will happen).
  222. *
  223. * Caution: do not support clone Date, for performance consideration.
  224. * (There might be a large number of date in `series.data`).
  225. * So date should not be modified in and out of echarts.
  226. *
  227. * @param {*} source
  228. * @return {*} new
  229. */
  230. function clone(source) {
  231. if (source == null || typeof source != 'object') {
  232. return source;
  233. }
  234. var result = source;
  235. var typeStr = objToString.call(source);
  236. if (typeStr === '[object Array]') {
  237. if (!isPrimitive(source)) {
  238. result = [];
  239. for (var i = 0, len = source.length; i < len; i++) {
  240. result[i] = clone(source[i]);
  241. }
  242. }
  243. }
  244. else if (TYPED_ARRAY[typeStr]) {
  245. if (!isPrimitive(source)) {
  246. var Ctor = source.constructor;
  247. if (source.constructor.from) {
  248. result = Ctor.from(source);
  249. }
  250. else {
  251. result = new Ctor(source.length);
  252. for (var i = 0, len = source.length; i < len; i++) {
  253. result[i] = clone(source[i]);
  254. }
  255. }
  256. }
  257. }
  258. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  259. result = {};
  260. for (var key in source) {
  261. if (source.hasOwnProperty(key)) {
  262. result[key] = clone(source[key]);
  263. }
  264. }
  265. }
  266. return result;
  267. }
  268. /**
  269. * @memberOf module:zrender/core/util
  270. * @param {*} target
  271. * @param {*} source
  272. * @param {boolean} [overwrite=false]
  273. */
  274. function merge(target, source, overwrite) {
  275. // We should escapse that source is string
  276. // and enter for ... in ...
  277. if (!isObject$1(source) || !isObject$1(target)) {
  278. return overwrite ? clone(source) : target;
  279. }
  280. for (var key in source) {
  281. if (source.hasOwnProperty(key)) {
  282. var targetProp = target[key];
  283. var sourceProp = source[key];
  284. if (isObject$1(sourceProp)
  285. && isObject$1(targetProp)
  286. && !isArray(sourceProp)
  287. && !isArray(targetProp)
  288. && !isDom(sourceProp)
  289. && !isDom(targetProp)
  290. && !isBuiltInObject(sourceProp)
  291. && !isBuiltInObject(targetProp)
  292. && !isPrimitive(sourceProp)
  293. && !isPrimitive(targetProp)
  294. ) {
  295. // 如果需要递归覆盖,就递归调用merge
  296. merge(targetProp, sourceProp, overwrite);
  297. }
  298. else if (overwrite || !(key in target)) {
  299. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  300. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  301. target[key] = clone(source[key], true);
  302. }
  303. }
  304. }
  305. return target;
  306. }
  307. /**
  308. * @param {Array} targetAndSources The first item is target, and the rests are source.
  309. * @param {boolean} [overwrite=false]
  310. * @return {*} target
  311. */
  312. function mergeAll(targetAndSources, overwrite) {
  313. var result = targetAndSources[0];
  314. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  315. result = merge(result, targetAndSources[i], overwrite);
  316. }
  317. return result;
  318. }
  319. /**
  320. * @param {*} target
  321. * @param {*} source
  322. * @memberOf module:zrender/core/util
  323. */
  324. function extend(target, source) {
  325. for (var key in source) {
  326. if (source.hasOwnProperty(key)) {
  327. target[key] = source[key];
  328. }
  329. }
  330. return target;
  331. }
  332. /**
  333. * @param {*} target
  334. * @param {*} source
  335. * @param {boolean} [overlay=false]
  336. * @memberOf module:zrender/core/util
  337. */
  338. function defaults(target, source, overlay) {
  339. for (var key in source) {
  340. if (source.hasOwnProperty(key)
  341. && (overlay ? source[key] != null : target[key] == null)
  342. ) {
  343. target[key] = source[key];
  344. }
  345. }
  346. return target;
  347. }
  348. var createCanvas = function () {
  349. return methods.createCanvas();
  350. };
  351. methods.createCanvas = function () {
  352. return document.createElement('canvas');
  353. };
  354. // FIXME
  355. var _ctx;
  356. function getContext() {
  357. if (!_ctx) {
  358. // Use util.createCanvas instead of createCanvas
  359. // because createCanvas may be overwritten in different environment
  360. _ctx = createCanvas().getContext('2d');
  361. }
  362. return _ctx;
  363. }
  364. /**
  365. * 查询数组中元素的index
  366. * @memberOf module:zrender/core/util
  367. */
  368. function indexOf(array, value) {
  369. if (array) {
  370. if (array.indexOf) {
  371. return array.indexOf(value);
  372. }
  373. for (var i = 0, len = array.length; i < len; i++) {
  374. if (array[i] === value) {
  375. return i;
  376. }
  377. }
  378. }
  379. return -1;
  380. }
  381. /**
  382. * 构造类继承关系
  383. *
  384. * @memberOf module:zrender/core/util
  385. * @param {Function} clazz 源类
  386. * @param {Function} baseClazz 基类
  387. */
  388. function inherits(clazz, baseClazz) {
  389. var clazzPrototype = clazz.prototype;
  390. function F() {}
  391. F.prototype = baseClazz.prototype;
  392. clazz.prototype = new F();
  393. for (var prop in clazzPrototype) {
  394. clazz.prototype[prop] = clazzPrototype[prop];
  395. }
  396. clazz.prototype.constructor = clazz;
  397. clazz.superClass = baseClazz;
  398. }
  399. /**
  400. * @memberOf module:zrender/core/util
  401. * @param {Object|Function} target
  402. * @param {Object|Function} sorce
  403. * @param {boolean} overlay
  404. */
  405. function mixin(target, source, overlay) {
  406. target = 'prototype' in target ? target.prototype : target;
  407. source = 'prototype' in source ? source.prototype : source;
  408. defaults(target, source, overlay);
  409. }
  410. /**
  411. * Consider typed array.
  412. * @param {Array|TypedArray} data
  413. */
  414. function isArrayLike(data) {
  415. if (! data) {
  416. return;
  417. }
  418. if (typeof data == 'string') {
  419. return false;
  420. }
  421. return typeof data.length == 'number';
  422. }
  423. /**
  424. * 数组或对象遍历
  425. * @memberOf module:zrender/core/util
  426. * @param {Object|Array} obj
  427. * @param {Function} cb
  428. * @param {*} [context]
  429. */
  430. function each$1(obj, cb, context) {
  431. if (!(obj && cb)) {
  432. return;
  433. }
  434. if (obj.forEach && obj.forEach === nativeForEach) {
  435. obj.forEach(cb, context);
  436. }
  437. else if (obj.length === +obj.length) {
  438. for (var i = 0, len = obj.length; i < len; i++) {
  439. cb.call(context, obj[i], i, obj);
  440. }
  441. }
  442. else {
  443. for (var key in obj) {
  444. if (obj.hasOwnProperty(key)) {
  445. cb.call(context, obj[key], key, obj);
  446. }
  447. }
  448. }
  449. }
  450. /**
  451. * 数组映射
  452. * @memberOf module:zrender/core/util
  453. * @param {Array} obj
  454. * @param {Function} cb
  455. * @param {*} [context]
  456. * @return {Array}
  457. */
  458. function map(obj, cb, context) {
  459. if (!(obj && cb)) {
  460. return;
  461. }
  462. if (obj.map && obj.map === nativeMap) {
  463. return obj.map(cb, context);
  464. }
  465. else {
  466. var result = [];
  467. for (var i = 0, len = obj.length; i < len; i++) {
  468. result.push(cb.call(context, obj[i], i, obj));
  469. }
  470. return result;
  471. }
  472. }
  473. /**
  474. * @memberOf module:zrender/core/util
  475. * @param {Array} obj
  476. * @param {Function} cb
  477. * @param {Object} [memo]
  478. * @param {*} [context]
  479. * @return {Array}
  480. */
  481. function reduce(obj, cb, memo, context) {
  482. if (!(obj && cb)) {
  483. return;
  484. }
  485. if (obj.reduce && obj.reduce === nativeReduce) {
  486. return obj.reduce(cb, memo, context);
  487. }
  488. else {
  489. for (var i = 0, len = obj.length; i < len; i++) {
  490. memo = cb.call(context, memo, obj[i], i, obj);
  491. }
  492. return memo;
  493. }
  494. }
  495. /**
  496. * 数组过滤
  497. * @memberOf module:zrender/core/util
  498. * @param {Array} obj
  499. * @param {Function} cb
  500. * @param {*} [context]
  501. * @return {Array}
  502. */
  503. function filter(obj, cb, context) {
  504. if (!(obj && cb)) {
  505. return;
  506. }
  507. if (obj.filter && obj.filter === nativeFilter) {
  508. return obj.filter(cb, context);
  509. }
  510. else {
  511. var result = [];
  512. for (var i = 0, len = obj.length; i < len; i++) {
  513. if (cb.call(context, obj[i], i, obj)) {
  514. result.push(obj[i]);
  515. }
  516. }
  517. return result;
  518. }
  519. }
  520. /**
  521. * 数组项查找
  522. * @memberOf module:zrender/core/util
  523. * @param {Array} obj
  524. * @param {Function} cb
  525. * @param {*} [context]
  526. * @return {*}
  527. */
  528. function find(obj, cb, context) {
  529. if (!(obj && cb)) {
  530. return;
  531. }
  532. for (var i = 0, len = obj.length; i < len; i++) {
  533. if (cb.call(context, obj[i], i, obj)) {
  534. return obj[i];
  535. }
  536. }
  537. }
  538. /**
  539. * @memberOf module:zrender/core/util
  540. * @param {Function} func
  541. * @param {*} context
  542. * @return {Function}
  543. */
  544. function bind(func, context) {
  545. var args = nativeSlice.call(arguments, 2);
  546. return function () {
  547. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  548. };
  549. }
  550. /**
  551. * @memberOf module:zrender/core/util
  552. * @param {Function} func
  553. * @return {Function}
  554. */
  555. function curry(func) {
  556. var args = nativeSlice.call(arguments, 1);
  557. return function () {
  558. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  559. };
  560. }
  561. /**
  562. * @memberOf module:zrender/core/util
  563. * @param {*} value
  564. * @return {boolean}
  565. */
  566. function isArray(value) {
  567. return objToString.call(value) === '[object Array]';
  568. }
  569. /**
  570. * @memberOf module:zrender/core/util
  571. * @param {*} value
  572. * @return {boolean}
  573. */
  574. function isFunction$1(value) {
  575. return typeof value === 'function';
  576. }
  577. /**
  578. * @memberOf module:zrender/core/util
  579. * @param {*} value
  580. * @return {boolean}
  581. */
  582. function isString(value) {
  583. return objToString.call(value) === '[object String]';
  584. }
  585. /**
  586. * @memberOf module:zrender/core/util
  587. * @param {*} value
  588. * @return {boolean}
  589. */
  590. function isObject$1(value) {
  591. // Avoid a V8 JIT bug in Chrome 19-20.
  592. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  593. var type = typeof value;
  594. return type === 'function' || (!!value && type == 'object');
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {*} value
  599. * @return {boolean}
  600. */
  601. function isBuiltInObject(value) {
  602. return !!BUILTIN_OBJECT[objToString.call(value)];
  603. }
  604. /**
  605. * @memberOf module:zrender/core/util
  606. * @param {*} value
  607. * @return {boolean}
  608. */
  609. function isTypedArray(value) {
  610. return !!TYPED_ARRAY[objToString.call(value)];
  611. }
  612. /**
  613. * @memberOf module:zrender/core/util
  614. * @param {*} value
  615. * @return {boolean}
  616. */
  617. function isDom(value) {
  618. return typeof value === 'object'
  619. && typeof value.nodeType === 'number'
  620. && typeof value.ownerDocument === 'object';
  621. }
  622. /**
  623. * Whether is exactly NaN. Notice isNaN('a') returns true.
  624. * @param {*} value
  625. * @return {boolean}
  626. */
  627. function eqNaN(value) {
  628. return value !== value;
  629. }
  630. /**
  631. * If value1 is not null, then return value1, otherwise judget rest of values.
  632. * Low performance.
  633. * @memberOf module:zrender/core/util
  634. * @return {*} Final value
  635. */
  636. function retrieve(values) {
  637. for (var i = 0, len = arguments.length; i < len; i++) {
  638. if (arguments[i] != null) {
  639. return arguments[i];
  640. }
  641. }
  642. }
  643. function retrieve2(value0, value1) {
  644. return value0 != null
  645. ? value0
  646. : value1;
  647. }
  648. function retrieve3(value0, value1, value2) {
  649. return value0 != null
  650. ? value0
  651. : value1 != null
  652. ? value1
  653. : value2;
  654. }
  655. /**
  656. * @memberOf module:zrender/core/util
  657. * @param {Array} arr
  658. * @param {number} startIndex
  659. * @param {number} endIndex
  660. * @return {Array}
  661. */
  662. function slice() {
  663. return Function.call.apply(nativeSlice, arguments);
  664. }
  665. /**
  666. * Normalize css liked array configuration
  667. * e.g.
  668. * 3 => [3, 3, 3, 3]
  669. * [4, 2] => [4, 2, 4, 2]
  670. * [4, 3, 2] => [4, 3, 2, 3]
  671. * @param {number|Array.<number>} val
  672. * @return {Array.<number>}
  673. */
  674. function normalizeCssArray(val) {
  675. if (typeof (val) === 'number') {
  676. return [val, val, val, val];
  677. }
  678. var len = val.length;
  679. if (len === 2) {
  680. // vertical | horizontal
  681. return [val[0], val[1], val[0], val[1]];
  682. }
  683. else if (len === 3) {
  684. // top | horizontal | bottom
  685. return [val[0], val[1], val[2], val[1]];
  686. }
  687. return val;
  688. }
  689. /**
  690. * @memberOf module:zrender/core/util
  691. * @param {boolean} condition
  692. * @param {string} message
  693. */
  694. function assert$1(condition, message) {
  695. if (!condition) {
  696. throw new Error(message);
  697. }
  698. }
  699. /**
  700. * @memberOf module:zrender/core/util
  701. * @param {string} str string to be trimed
  702. * @return {string} trimed string
  703. */
  704. function trim(str) {
  705. if (str == null) {
  706. return null;
  707. }
  708. else if (typeof str.trim === 'function') {
  709. return str.trim();
  710. }
  711. else {
  712. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  713. }
  714. }
  715. var primitiveKey = '__ec_primitive__';
  716. /**
  717. * Set an object as primitive to be ignored traversing children in clone or merge
  718. */
  719. function setAsPrimitive(obj) {
  720. obj[primitiveKey] = true;
  721. }
  722. function isPrimitive(obj) {
  723. return obj[primitiveKey];
  724. }
  725. /**
  726. * @constructor
  727. * @param {Object} obj Only apply `ownProperty`.
  728. */
  729. function HashMap(obj) {
  730. var isArr = isArray(obj);
  731. var thisMap = this;
  732. (obj instanceof HashMap)
  733. ? obj.each(visit)
  734. : (obj && each$1(obj, visit));
  735. function visit(value, key) {
  736. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  737. }
  738. }
  739. // Add prefix to avoid conflict with Object.prototype.
  740. HashMap.prototype = {
  741. constructor: HashMap,
  742. // Do not provide `has` method to avoid defining what is `has`.
  743. // (We usually treat `null` and `undefined` as the same, different
  744. // from ES6 Map).
  745. get: function (key) {
  746. return this.hasOwnProperty(key) ? this[key] : null;
  747. },
  748. set: function (key, value) {
  749. // Comparing with invocation chaining, `return value` is more commonly
  750. // used in this case: `var someVal = map.set('a', genVal());`
  751. return (this[key] = value);
  752. },
  753. // Although util.each can be performed on this hashMap directly, user
  754. // should not use the exposed keys, who are prefixed.
  755. each: function (cb, context) {
  756. context !== void 0 && (cb = bind(cb, context));
  757. for (var key in this) {
  758. this.hasOwnProperty(key) && cb(this[key], key);
  759. }
  760. },
  761. // Do not use this method if performance sensitive.
  762. removeKey: function (key) {
  763. delete this[key];
  764. }
  765. };
  766. function createHashMap(obj) {
  767. return new HashMap(obj);
  768. }
  769. function concatArray(a, b) {
  770. var newArray = new a.constructor(a.length + b.length);
  771. for (var i = 0; i < a.length; i++) {
  772. newArray[i] = a[i];
  773. }
  774. var offset = a.length;
  775. for (i = 0; i < b.length; i++) {
  776. newArray[i + offset] = b[i];
  777. }
  778. return newArray;
  779. }
  780. function noop() {}
  781. var zrUtil = (Object.freeze || Object)({
  782. $override: $override,
  783. clone: clone,
  784. merge: merge,
  785. mergeAll: mergeAll,
  786. extend: extend,
  787. defaults: defaults,
  788. createCanvas: createCanvas,
  789. getContext: getContext,
  790. indexOf: indexOf,
  791. inherits: inherits,
  792. mixin: mixin,
  793. isArrayLike: isArrayLike,
  794. each: each$1,
  795. map: map,
  796. reduce: reduce,
  797. filter: filter,
  798. find: find,
  799. bind: bind,
  800. curry: curry,
  801. isArray: isArray,
  802. isFunction: isFunction$1,
  803. isString: isString,
  804. isObject: isObject$1,
  805. isBuiltInObject: isBuiltInObject,
  806. isTypedArray: isTypedArray,
  807. isDom: isDom,
  808. eqNaN: eqNaN,
  809. retrieve: retrieve,
  810. retrieve2: retrieve2,
  811. retrieve3: retrieve3,
  812. slice: slice,
  813. normalizeCssArray: normalizeCssArray,
  814. assert: assert$1,
  815. trim: trim,
  816. setAsPrimitive: setAsPrimitive,
  817. isPrimitive: isPrimitive,
  818. createHashMap: createHashMap,
  819. concatArray: concatArray,
  820. noop: noop
  821. });
  822. var ArrayCtor = typeof Float32Array === 'undefined'
  823. ? Array
  824. : Float32Array;
  825. /**
  826. * 创建一个向量
  827. * @param {number} [x=0]
  828. * @param {number} [y=0]
  829. * @return {Vector2}
  830. */
  831. function create(x, y) {
  832. var out = new ArrayCtor(2);
  833. if (x == null) {
  834. x = 0;
  835. }
  836. if (y == null) {
  837. y = 0;
  838. }
  839. out[0] = x;
  840. out[1] = y;
  841. return out;
  842. }
  843. /**
  844. * 复制向量数据
  845. * @param {Vector2} out
  846. * @param {Vector2} v
  847. * @return {Vector2}
  848. */
  849. function copy(out, v) {
  850. out[0] = v[0];
  851. out[1] = v[1];
  852. return out;
  853. }
  854. /**
  855. * 克隆一个向量
  856. * @param {Vector2} v
  857. * @return {Vector2}
  858. */
  859. function clone$1(v) {
  860. var out = new ArrayCtor(2);
  861. out[0] = v[0];
  862. out[1] = v[1];
  863. return out;
  864. }
  865. /**
  866. * 设置向量的两个项
  867. * @param {Vector2} out
  868. * @param {number} a
  869. * @param {number} b
  870. * @return {Vector2} 结果
  871. */
  872. function set(out, a, b) {
  873. out[0] = a;
  874. out[1] = b;
  875. return out;
  876. }
  877. /**
  878. * 向量相加
  879. * @param {Vector2} out
  880. * @param {Vector2} v1
  881. * @param {Vector2} v2
  882. */
  883. function add(out, v1, v2) {
  884. out[0] = v1[0] + v2[0];
  885. out[1] = v1[1] + v2[1];
  886. return out;
  887. }
  888. /**
  889. * 向量缩放后相加
  890. * @param {Vector2} out
  891. * @param {Vector2} v1
  892. * @param {Vector2} v2
  893. * @param {number} a
  894. */
  895. function scaleAndAdd(out, v1, v2, a) {
  896. out[0] = v1[0] + v2[0] * a;
  897. out[1] = v1[1] + v2[1] * a;
  898. return out;
  899. }
  900. /**
  901. * 向量相减
  902. * @param {Vector2} out
  903. * @param {Vector2} v1
  904. * @param {Vector2} v2
  905. */
  906. function sub(out, v1, v2) {
  907. out[0] = v1[0] - v2[0];
  908. out[1] = v1[1] - v2[1];
  909. return out;
  910. }
  911. /**
  912. * 向量长度
  913. * @param {Vector2} v
  914. * @return {number}
  915. */
  916. function len(v) {
  917. return Math.sqrt(lenSquare(v));
  918. }
  919. var length = len; // jshint ignore:line
  920. /**
  921. * 向量长度平方
  922. * @param {Vector2} v
  923. * @return {number}
  924. */
  925. function lenSquare(v) {
  926. return v[0] * v[0] + v[1] * v[1];
  927. }
  928. var lengthSquare = lenSquare;
  929. /**
  930. * 向量乘法
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function mul(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. */
  946. function div(out, v1, v2) {
  947. out[0] = v1[0] / v2[0];
  948. out[1] = v1[1] / v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量点乘
  953. * @param {Vector2} v1
  954. * @param {Vector2} v2
  955. * @return {number}
  956. */
  957. function dot(v1, v2) {
  958. return v1[0] * v2[0] + v1[1] * v2[1];
  959. }
  960. /**
  961. * 向量缩放
  962. * @param {Vector2} out
  963. * @param {Vector2} v
  964. * @param {number} s
  965. */
  966. function scale(out, v, s) {
  967. out[0] = v[0] * s;
  968. out[1] = v[1] * s;
  969. return out;
  970. }
  971. /**
  972. * 向量归一化
  973. * @param {Vector2} out
  974. * @param {Vector2} v
  975. */
  976. function normalize(out, v) {
  977. var d = len(v);
  978. if (d === 0) {
  979. out[0] = 0;
  980. out[1] = 0;
  981. }
  982. else {
  983. out[0] = v[0] / d;
  984. out[1] = v[1] / d;
  985. }
  986. return out;
  987. }
  988. /**
  989. * 计算向量间距离
  990. * @param {Vector2} v1
  991. * @param {Vector2} v2
  992. * @return {number}
  993. */
  994. function distance(v1, v2) {
  995. return Math.sqrt(
  996. (v1[0] - v2[0]) * (v1[0] - v2[0])
  997. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  998. );
  999. }
  1000. var dist = distance;
  1001. /**
  1002. * 向量距离平方
  1003. * @param {Vector2} v1
  1004. * @param {Vector2} v2
  1005. * @return {number}
  1006. */
  1007. function distanceSquare(v1, v2) {
  1008. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1009. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1010. }
  1011. var distSquare = distanceSquare;
  1012. /**
  1013. * 求负向量
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. */
  1017. function negate(out, v) {
  1018. out[0] = -v[0];
  1019. out[1] = -v[1];
  1020. return out;
  1021. }
  1022. /**
  1023. * 插值两个点
  1024. * @param {Vector2} out
  1025. * @param {Vector2} v1
  1026. * @param {Vector2} v2
  1027. * @param {number} t
  1028. */
  1029. function lerp(out, v1, v2, t) {
  1030. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1031. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1032. return out;
  1033. }
  1034. /**
  1035. * 矩阵左乘向量
  1036. * @param {Vector2} out
  1037. * @param {Vector2} v
  1038. * @param {Vector2} m
  1039. */
  1040. function applyTransform(out, v, m) {
  1041. var x = v[0];
  1042. var y = v[1];
  1043. out[0] = m[0] * x + m[2] * y + m[4];
  1044. out[1] = m[1] * x + m[3] * y + m[5];
  1045. return out;
  1046. }
  1047. /**
  1048. * 求两个向量最小值
  1049. * @param {Vector2} out
  1050. * @param {Vector2} v1
  1051. * @param {Vector2} v2
  1052. */
  1053. function min(out, v1, v2) {
  1054. out[0] = Math.min(v1[0], v2[0]);
  1055. out[1] = Math.min(v1[1], v2[1]);
  1056. return out;
  1057. }
  1058. /**
  1059. * 求两个向量最大值
  1060. * @param {Vector2} out
  1061. * @param {Vector2} v1
  1062. * @param {Vector2} v2
  1063. */
  1064. function max(out, v1, v2) {
  1065. out[0] = Math.max(v1[0], v2[0]);
  1066. out[1] = Math.max(v1[1], v2[1]);
  1067. return out;
  1068. }
  1069. var vector = (Object.freeze || Object)({
  1070. create: create,
  1071. copy: copy,
  1072. clone: clone$1,
  1073. set: set,
  1074. add: add,
  1075. scaleAndAdd: scaleAndAdd,
  1076. sub: sub,
  1077. len: len,
  1078. length: length,
  1079. lenSquare: lenSquare,
  1080. lengthSquare: lengthSquare,
  1081. mul: mul,
  1082. div: div,
  1083. dot: dot,
  1084. scale: scale,
  1085. normalize: normalize,
  1086. distance: distance,
  1087. dist: dist,
  1088. distanceSquare: distanceSquare,
  1089. distSquare: distSquare,
  1090. negate: negate,
  1091. lerp: lerp,
  1092. applyTransform: applyTransform,
  1093. min: min,
  1094. max: max
  1095. });
  1096. // TODO Draggable for group
  1097. // FIXME Draggable on element which has parent rotation or scale
  1098. function Draggable() {
  1099. this.on('mousedown', this._dragStart, this);
  1100. this.on('mousemove', this._drag, this);
  1101. this.on('mouseup', this._dragEnd, this);
  1102. this.on('globalout', this._dragEnd, this);
  1103. // this._dropTarget = null;
  1104. // this._draggingTarget = null;
  1105. // this._x = 0;
  1106. // this._y = 0;
  1107. }
  1108. Draggable.prototype = {
  1109. constructor: Draggable,
  1110. _dragStart: function (e) {
  1111. var draggingTarget = e.target;
  1112. if (draggingTarget && draggingTarget.draggable) {
  1113. this._draggingTarget = draggingTarget;
  1114. draggingTarget.dragging = true;
  1115. this._x = e.offsetX;
  1116. this._y = e.offsetY;
  1117. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1118. }
  1119. },
  1120. _drag: function (e) {
  1121. var draggingTarget = this._draggingTarget;
  1122. if (draggingTarget) {
  1123. var x = e.offsetX;
  1124. var y = e.offsetY;
  1125. var dx = x - this._x;
  1126. var dy = y - this._y;
  1127. this._x = x;
  1128. this._y = y;
  1129. draggingTarget.drift(dx, dy, e);
  1130. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1131. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1132. var lastDropTarget = this._dropTarget;
  1133. this._dropTarget = dropTarget;
  1134. if (draggingTarget !== dropTarget) {
  1135. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1136. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1137. }
  1138. if (dropTarget && dropTarget !== lastDropTarget) {
  1139. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1140. }
  1141. }
  1142. }
  1143. },
  1144. _dragEnd: function (e) {
  1145. var draggingTarget = this._draggingTarget;
  1146. if (draggingTarget) {
  1147. draggingTarget.dragging = false;
  1148. }
  1149. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1150. if (this._dropTarget) {
  1151. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1152. }
  1153. this._draggingTarget = null;
  1154. this._dropTarget = null;
  1155. }
  1156. };
  1157. function param(target, e) {
  1158. return {target: target, topTarget: e && e.topTarget};
  1159. }
  1160. /**
  1161. * 事件扩展
  1162. * @module zrender/mixin/Eventful
  1163. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1164. * pissang (https://www.github.com/pissang)
  1165. */
  1166. var arrySlice = Array.prototype.slice;
  1167. /**
  1168. * 事件分发器
  1169. * @alias module:zrender/mixin/Eventful
  1170. * @constructor
  1171. */
  1172. var Eventful = function () {
  1173. this._$handlers = {};
  1174. };
  1175. Eventful.prototype = {
  1176. constructor: Eventful,
  1177. /**
  1178. * 单次触发绑定,trigger后销毁
  1179. *
  1180. * @param {string} event 事件名
  1181. * @param {Function} handler 响应函数
  1182. * @param {Object} context
  1183. */
  1184. one: function (event, handler, context) {
  1185. var _h = this._$handlers;
  1186. if (!handler || !event) {
  1187. return this;
  1188. }
  1189. if (!_h[event]) {
  1190. _h[event] = [];
  1191. }
  1192. for (var i = 0; i < _h[event].length; i++) {
  1193. if (_h[event][i].h === handler) {
  1194. return this;
  1195. }
  1196. }
  1197. _h[event].push({
  1198. h: handler,
  1199. one: true,
  1200. ctx: context || this
  1201. });
  1202. return this;
  1203. },
  1204. /**
  1205. * 绑定事件
  1206. * @param {string} event 事件名
  1207. * @param {Function} handler 事件处理函数
  1208. * @param {Object} [context]
  1209. */
  1210. on: function (event, handler, context) {
  1211. var _h = this._$handlers;
  1212. if (!handler || !event) {
  1213. return this;
  1214. }
  1215. if (!_h[event]) {
  1216. _h[event] = [];
  1217. }
  1218. for (var i = 0; i < _h[event].length; i++) {
  1219. if (_h[event][i].h === handler) {
  1220. return this;
  1221. }
  1222. }
  1223. _h[event].push({
  1224. h: handler,
  1225. one: false,
  1226. ctx: context || this
  1227. });
  1228. return this;
  1229. },
  1230. /**
  1231. * 是否绑定了事件
  1232. * @param {string} event
  1233. * @return {boolean}
  1234. */
  1235. isSilent: function (event) {
  1236. var _h = this._$handlers;
  1237. return _h[event] && _h[event].length;
  1238. },
  1239. /**
  1240. * 解绑事件
  1241. * @param {string} event 事件名
  1242. * @param {Function} [handler] 事件处理函数
  1243. */
  1244. off: function (event, handler) {
  1245. var _h = this._$handlers;
  1246. if (!event) {
  1247. this._$handlers = {};
  1248. return this;
  1249. }
  1250. if (handler) {
  1251. if (_h[event]) {
  1252. var newList = [];
  1253. for (var i = 0, l = _h[event].length; i < l; i++) {
  1254. if (_h[event][i]['h'] != handler) {
  1255. newList.push(_h[event][i]);
  1256. }
  1257. }
  1258. _h[event] = newList;
  1259. }
  1260. if (_h[event] && _h[event].length === 0) {
  1261. delete _h[event];
  1262. }
  1263. }
  1264. else {
  1265. delete _h[event];
  1266. }
  1267. return this;
  1268. },
  1269. /**
  1270. * 事件分发
  1271. *
  1272. * @param {string} type 事件类型
  1273. */
  1274. trigger: function (type) {
  1275. if (this._$handlers[type]) {
  1276. var args = arguments;
  1277. var argLen = args.length;
  1278. if (argLen > 3) {
  1279. args = arrySlice.call(args, 1);
  1280. }
  1281. var _h = this._$handlers[type];
  1282. var len = _h.length;
  1283. for (var i = 0; i < len;) {
  1284. // Optimize advise from backbone
  1285. switch (argLen) {
  1286. case 1:
  1287. _h[i]['h'].call(_h[i]['ctx']);
  1288. break;
  1289. case 2:
  1290. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1291. break;
  1292. case 3:
  1293. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1294. break;
  1295. default:
  1296. // have more than 2 given arguments
  1297. _h[i]['h'].apply(_h[i]['ctx'], args);
  1298. break;
  1299. }
  1300. if (_h[i]['one']) {
  1301. _h.splice(i, 1);
  1302. len--;
  1303. }
  1304. else {
  1305. i++;
  1306. }
  1307. }
  1308. }
  1309. return this;
  1310. },
  1311. /**
  1312. * 带有context的事件分发, 最后一个参数是事件回调的context
  1313. * @param {string} type 事件类型
  1314. */
  1315. triggerWithContext: function (type) {
  1316. if (this._$handlers[type]) {
  1317. var args = arguments;
  1318. var argLen = args.length;
  1319. if (argLen > 4) {
  1320. args = arrySlice.call(args, 1, args.length - 1);
  1321. }
  1322. var ctx = args[args.length - 1];
  1323. var _h = this._$handlers[type];
  1324. var len = _h.length;
  1325. for (var i = 0; i < len;) {
  1326. // Optimize advise from backbone
  1327. switch (argLen) {
  1328. case 1:
  1329. _h[i]['h'].call(ctx);
  1330. break;
  1331. case 2:
  1332. _h[i]['h'].call(ctx, args[1]);
  1333. break;
  1334. case 3:
  1335. _h[i]['h'].call(ctx, args[1], args[2]);
  1336. break;
  1337. default:
  1338. // have more than 2 given arguments
  1339. _h[i]['h'].apply(ctx, args);
  1340. break;
  1341. }
  1342. if (_h[i]['one']) {
  1343. _h.splice(i, 1);
  1344. len--;
  1345. }
  1346. else {
  1347. i++;
  1348. }
  1349. }
  1350. }
  1351. return this;
  1352. }
  1353. };
  1354. var SILENT = 'silent';
  1355. function makeEventPacket(eveType, targetInfo, event) {
  1356. return {
  1357. type: eveType,
  1358. event: event,
  1359. // target can only be an element that is not silent.
  1360. target: targetInfo.target,
  1361. // topTarget can be a silent element.
  1362. topTarget: targetInfo.topTarget,
  1363. cancelBubble: false,
  1364. offsetX: event.zrX,
  1365. offsetY: event.zrY,
  1366. gestureEvent: event.gestureEvent,
  1367. pinchX: event.pinchX,
  1368. pinchY: event.pinchY,
  1369. pinchScale: event.pinchScale,
  1370. wheelDelta: event.zrDelta,
  1371. zrByTouch: event.zrByTouch,
  1372. which: event.which
  1373. };
  1374. }
  1375. function EmptyProxy () {}
  1376. EmptyProxy.prototype.dispose = function () {};
  1377. var handlerNames = [
  1378. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1379. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1380. ];
  1381. /**
  1382. * @alias module:zrender/Handler
  1383. * @constructor
  1384. * @extends module:zrender/mixin/Eventful
  1385. * @param {module:zrender/Storage} storage Storage instance.
  1386. * @param {module:zrender/Painter} painter Painter instance.
  1387. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1388. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1389. */
  1390. var Handler = function(storage, painter, proxy, painterRoot) {
  1391. Eventful.call(this);
  1392. this.storage = storage;
  1393. this.painter = painter;
  1394. this.painterRoot = painterRoot;
  1395. proxy = proxy || new EmptyProxy();
  1396. /**
  1397. * Proxy of event. can be Dom, WebGLSurface, etc.
  1398. */
  1399. this.proxy = null;
  1400. /**
  1401. * {target, topTarget, x, y}
  1402. * @private
  1403. * @type {Object}
  1404. */
  1405. this._hovered = {};
  1406. /**
  1407. * @private
  1408. * @type {Date}
  1409. */
  1410. this._lastTouchMoment;
  1411. /**
  1412. * @private
  1413. * @type {number}
  1414. */
  1415. this._lastX;
  1416. /**
  1417. * @private
  1418. * @type {number}
  1419. */
  1420. this._lastY;
  1421. Draggable.call(this);
  1422. this.setHandlerProxy(proxy);
  1423. };
  1424. Handler.prototype = {
  1425. constructor: Handler,
  1426. setHandlerProxy: function (proxy) {
  1427. if (this.proxy) {
  1428. this.proxy.dispose();
  1429. }
  1430. if (proxy) {
  1431. each$1(handlerNames, function (name) {
  1432. proxy.on && proxy.on(name, this[name], this);
  1433. }, this);
  1434. // Attach handler
  1435. proxy.handler = this;
  1436. }
  1437. this.proxy = proxy;
  1438. },
  1439. mousemove: function (event) {
  1440. var x = event.zrX;
  1441. var y = event.zrY;
  1442. var lastHovered = this._hovered;
  1443. var lastHoveredTarget = lastHovered.target;
  1444. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1445. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1446. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1447. // See #6198.
  1448. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1449. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1450. lastHoveredTarget = lastHovered.target;
  1451. }
  1452. var hovered = this._hovered = this.findHover(x, y);
  1453. var hoveredTarget = hovered.target;
  1454. var proxy = this.proxy;
  1455. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1456. // Mouse out on previous hovered element
  1457. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1458. this.dispatchToElement(lastHovered, 'mouseout', event);
  1459. }
  1460. // Mouse moving on one element
  1461. this.dispatchToElement(hovered, 'mousemove', event);
  1462. // Mouse over on a new element
  1463. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1464. this.dispatchToElement(hovered, 'mouseover', event);
  1465. }
  1466. },
  1467. mouseout: function (event) {
  1468. this.dispatchToElement(this._hovered, 'mouseout', event);
  1469. // There might be some doms created by upper layer application
  1470. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1471. // dom created by echarts), where 'globalout' event should not
  1472. // be triggered when mouse enters these doms. (But 'mouseout'
  1473. // should be triggered at the original hovered element as usual).
  1474. var element = event.toElement || event.relatedTarget;
  1475. var innerDom;
  1476. do {
  1477. element = element && element.parentNode;
  1478. }
  1479. while (element && element.nodeType != 9 && !(
  1480. innerDom = element === this.painterRoot
  1481. ));
  1482. !innerDom && this.trigger('globalout', {event: event});
  1483. },
  1484. /**
  1485. * Resize
  1486. */
  1487. resize: function (event) {
  1488. this._hovered = {};
  1489. },
  1490. /**
  1491. * Dispatch event
  1492. * @param {string} eventName
  1493. * @param {event=} eventArgs
  1494. */
  1495. dispatch: function (eventName, eventArgs) {
  1496. var handler = this[eventName];
  1497. handler && handler.call(this, eventArgs);
  1498. },
  1499. /**
  1500. * Dispose
  1501. */
  1502. dispose: function () {
  1503. this.proxy.dispose();
  1504. this.storage =
  1505. this.proxy =
  1506. this.painter = null;
  1507. },
  1508. /**
  1509. * 设置默认的cursor style
  1510. * @param {string} [cursorStyle='default'] 例如 crosshair
  1511. */
  1512. setCursorStyle: function (cursorStyle) {
  1513. var proxy = this.proxy;
  1514. proxy.setCursor && proxy.setCursor(cursorStyle);
  1515. },
  1516. /**
  1517. * 事件分发代理
  1518. *
  1519. * @private
  1520. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1521. * @param {string} eventName 事件名称
  1522. * @param {Object} event 事件对象
  1523. */
  1524. dispatchToElement: function (targetInfo, eventName, event) {
  1525. targetInfo = targetInfo || {};
  1526. var el = targetInfo.target;
  1527. if (el && el.silent) {
  1528. return;
  1529. }
  1530. var eventHandler = 'on' + eventName;
  1531. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1532. while (el) {
  1533. el[eventHandler]
  1534. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1535. el.trigger(eventName, eventPacket);
  1536. el = el.parent;
  1537. if (eventPacket.cancelBubble) {
  1538. break;
  1539. }
  1540. }
  1541. if (!eventPacket.cancelBubble) {
  1542. // 冒泡到顶级 zrender 对象
  1543. this.trigger(eventName, eventPacket);
  1544. // 分发事件到用户自定义层
  1545. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1546. this.painter && this.painter.eachOtherLayer(function (layer) {
  1547. if (typeof(layer[eventHandler]) == 'function') {
  1548. layer[eventHandler].call(layer, eventPacket);
  1549. }
  1550. if (layer.trigger) {
  1551. layer.trigger(eventName, eventPacket);
  1552. }
  1553. });
  1554. }
  1555. },
  1556. /**
  1557. * @private
  1558. * @param {number} x
  1559. * @param {number} y
  1560. * @param {module:zrender/graphic/Displayable} exclude
  1561. * @return {model:zrender/Element}
  1562. * @method
  1563. */
  1564. findHover: function(x, y, exclude) {
  1565. var list = this.storage.getDisplayList();
  1566. var out = {x: x, y: y};
  1567. for (var i = list.length - 1; i >= 0 ; i--) {
  1568. var hoverCheckResult;
  1569. if (list[i] !== exclude
  1570. // getDisplayList may include ignored item in VML mode
  1571. && !list[i].ignore
  1572. && (hoverCheckResult = isHover(list[i], x, y))
  1573. ) {
  1574. !out.topTarget && (out.topTarget = list[i]);
  1575. if (hoverCheckResult !== SILENT) {
  1576. out.target = list[i];
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. return out;
  1582. }
  1583. };
  1584. // Common handlers
  1585. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1586. Handler.prototype[name] = function (event) {
  1587. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1588. var hovered = this.findHover(event.zrX, event.zrY);
  1589. var hoveredTarget = hovered.target;
  1590. if (name === 'mousedown') {
  1591. this._downEl = hoveredTarget;
  1592. this._downPoint = [event.zrX, event.zrY];
  1593. // In case click triggered before mouseup
  1594. this._upEl = hoveredTarget;
  1595. }
  1596. else if (name === 'mouseup') {
  1597. this._upEl = hoveredTarget;
  1598. }
  1599. else if (name === 'click') {
  1600. if (this._downEl !== this._upEl
  1601. // Original click event is triggered on the whole canvas element,
  1602. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1603. // which should be filtered, otherwise it will bring trouble to
  1604. // pan and zoom.
  1605. || !this._downPoint
  1606. // Arbitrary value
  1607. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1608. ) {
  1609. return;
  1610. }
  1611. this._downPoint = null;
  1612. }
  1613. this.dispatchToElement(hovered, name, event);
  1614. };
  1615. });
  1616. function isHover(displayable, x, y) {
  1617. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1618. var el = displayable;
  1619. var isSilent;
  1620. while (el) {
  1621. // If clipped by ancestor.
  1622. // FIXME: If clipPath has neither stroke nor fill,
  1623. // el.clipPath.contain(x, y) will always return false.
  1624. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1625. return false;
  1626. }
  1627. if (el.silent) {
  1628. isSilent = true;
  1629. }
  1630. el = el.parent;
  1631. }
  1632. return isSilent ? SILENT : true;
  1633. }
  1634. return false;
  1635. }
  1636. mixin(Handler, Eventful);
  1637. mixin(Handler, Draggable);
  1638. /**
  1639. * 3x2矩阵操作类
  1640. * @exports zrender/tool/matrix
  1641. */
  1642. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1643. ? Array
  1644. : Float32Array;
  1645. /**
  1646. * Create a identity matrix.
  1647. * @return {Float32Array|Array.<number>}
  1648. */
  1649. function create$1() {
  1650. var out = new ArrayCtor$1(6);
  1651. identity(out);
  1652. return out;
  1653. }
  1654. /**
  1655. * 设置矩阵为单位矩阵
  1656. * @param {Float32Array|Array.<number>} out
  1657. */
  1658. function identity(out) {
  1659. out[0] = 1;
  1660. out[1] = 0;
  1661. out[2] = 0;
  1662. out[3] = 1;
  1663. out[4] = 0;
  1664. out[5] = 0;
  1665. return out;
  1666. }
  1667. /**
  1668. * 复制矩阵
  1669. * @param {Float32Array|Array.<number>} out
  1670. * @param {Float32Array|Array.<number>} m
  1671. */
  1672. function copy$1(out, m) {
  1673. out[0] = m[0];
  1674. out[1] = m[1];
  1675. out[2] = m[2];
  1676. out[3] = m[3];
  1677. out[4] = m[4];
  1678. out[5] = m[5];
  1679. return out;
  1680. }
  1681. /**
  1682. * 矩阵相乘
  1683. * @param {Float32Array|Array.<number>} out
  1684. * @param {Float32Array|Array.<number>} m1
  1685. * @param {Float32Array|Array.<number>} m2
  1686. */
  1687. function mul$1(out, m1, m2) {
  1688. // Consider matrix.mul(m, m2, m);
  1689. // where out is the same as m2.
  1690. // So use temp variable to escape error.
  1691. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1692. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1693. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1694. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1695. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1696. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1697. out[0] = out0;
  1698. out[1] = out1;
  1699. out[2] = out2;
  1700. out[3] = out3;
  1701. out[4] = out4;
  1702. out[5] = out5;
  1703. return out;
  1704. }
  1705. /**
  1706. * 平移变换
  1707. * @param {Float32Array|Array.<number>} out
  1708. * @param {Float32Array|Array.<number>} a
  1709. * @param {Float32Array|Array.<number>} v
  1710. */
  1711. function translate(out, a, v) {
  1712. out[0] = a[0];
  1713. out[1] = a[1];
  1714. out[2] = a[2];
  1715. out[3] = a[3];
  1716. out[4] = a[4] + v[0];
  1717. out[5] = a[5] + v[1];
  1718. return out;
  1719. }
  1720. /**
  1721. * 旋转变换
  1722. * @param {Float32Array|Array.<number>} out
  1723. * @param {Float32Array|Array.<number>} a
  1724. * @param {number} rad
  1725. */
  1726. function rotate(out, a, rad) {
  1727. var aa = a[0];
  1728. var ac = a[2];
  1729. var atx = a[4];
  1730. var ab = a[1];
  1731. var ad = a[3];
  1732. var aty = a[5];
  1733. var st = Math.sin(rad);
  1734. var ct = Math.cos(rad);
  1735. out[0] = aa * ct + ab * st;
  1736. out[1] = -aa * st + ab * ct;
  1737. out[2] = ac * ct + ad * st;
  1738. out[3] = -ac * st + ct * ad;
  1739. out[4] = ct * atx + st * aty;
  1740. out[5] = ct * aty - st * atx;
  1741. return out;
  1742. }
  1743. /**
  1744. * 缩放变换
  1745. * @param {Float32Array|Array.<number>} out
  1746. * @param {Float32Array|Array.<number>} a
  1747. * @param {Float32Array|Array.<number>} v
  1748. */
  1749. function scale$1(out, a, v) {
  1750. var vx = v[0];
  1751. var vy = v[1];
  1752. out[0] = a[0] * vx;
  1753. out[1] = a[1] * vy;
  1754. out[2] = a[2] * vx;
  1755. out[3] = a[3] * vy;
  1756. out[4] = a[4] * vx;
  1757. out[5] = a[5] * vy;
  1758. return out;
  1759. }
  1760. /**
  1761. * 求逆矩阵
  1762. * @param {Float32Array|Array.<number>} out
  1763. * @param {Float32Array|Array.<number>} a
  1764. */
  1765. function invert(out, a) {
  1766. var aa = a[0];
  1767. var ac = a[2];
  1768. var atx = a[4];
  1769. var ab = a[1];
  1770. var ad = a[3];
  1771. var aty = a[5];
  1772. var det = aa * ad - ab * ac;
  1773. if (!det) {
  1774. return null;
  1775. }
  1776. det = 1.0 / det;
  1777. out[0] = ad * det;
  1778. out[1] = -ab * det;
  1779. out[2] = -ac * det;
  1780. out[3] = aa * det;
  1781. out[4] = (ac * aty - ad * atx) * det;
  1782. out[5] = (ab * atx - aa * aty) * det;
  1783. return out;
  1784. }
  1785. /**
  1786. * Clone a new matrix.
  1787. * @param {Float32Array|Array.<number>} a
  1788. */
  1789. function clone$2(a) {
  1790. var b = create$1();
  1791. copy$1(b, a);
  1792. return b;
  1793. }
  1794. var matrix = (Object.freeze || Object)({
  1795. create: create$1,
  1796. identity: identity,
  1797. copy: copy$1,
  1798. mul: mul$1,
  1799. translate: translate,
  1800. rotate: rotate,
  1801. scale: scale$1,
  1802. invert: invert,
  1803. clone: clone$2
  1804. });
  1805. /**
  1806. * 提供变换扩展
  1807. * @module zrender/mixin/Transformable
  1808. * @author pissang (https://www.github.com/pissang)
  1809. */
  1810. var mIdentity = identity;
  1811. var EPSILON = 5e-5;
  1812. function isNotAroundZero(val) {
  1813. return val > EPSILON || val < -EPSILON;
  1814. }
  1815. /**
  1816. * @alias module:zrender/mixin/Transformable
  1817. * @constructor
  1818. */
  1819. var Transformable = function (opts) {
  1820. opts = opts || {};
  1821. // If there are no given position, rotation, scale
  1822. if (!opts.position) {
  1823. /**
  1824. * 平移
  1825. * @type {Array.<number>}
  1826. * @default [0, 0]
  1827. */
  1828. this.position = [0, 0];
  1829. }
  1830. if (opts.rotation == null) {
  1831. /**
  1832. * 旋转
  1833. * @type {Array.<number>}
  1834. * @default 0
  1835. */
  1836. this.rotation = 0;
  1837. }
  1838. if (!opts.scale) {
  1839. /**
  1840. * 缩放
  1841. * @type {Array.<number>}
  1842. * @default [1, 1]
  1843. */
  1844. this.scale = [1, 1];
  1845. }
  1846. /**
  1847. * 旋转和缩放的原点
  1848. * @type {Array.<number>}
  1849. * @default null
  1850. */
  1851. this.origin = this.origin || null;
  1852. };
  1853. var transformableProto = Transformable.prototype;
  1854. transformableProto.transform = null;
  1855. /**
  1856. * 判断是否需要有坐标变换
  1857. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1858. */
  1859. transformableProto.needLocalTransform = function () {
  1860. return isNotAroundZero(this.rotation)
  1861. || isNotAroundZero(this.position[0])
  1862. || isNotAroundZero(this.position[1])
  1863. || isNotAroundZero(this.scale[0] - 1)
  1864. || isNotAroundZero(this.scale[1] - 1);
  1865. };
  1866. transformableProto.updateTransform = function () {
  1867. var parent = this.parent;
  1868. var parentHasTransform = parent && parent.transform;
  1869. var needLocalTransform = this.needLocalTransform();
  1870. var m = this.transform;
  1871. if (!(needLocalTransform || parentHasTransform)) {
  1872. m && mIdentity(m);
  1873. return;
  1874. }
  1875. m = m || create$1();
  1876. if (needLocalTransform) {
  1877. this.getLocalTransform(m);
  1878. }
  1879. else {
  1880. mIdentity(m);
  1881. }
  1882. // 应用父节点变换
  1883. if (parentHasTransform) {
  1884. if (needLocalTransform) {
  1885. mul$1(m, parent.transform, m);
  1886. }
  1887. else {
  1888. copy$1(m, parent.transform);
  1889. }
  1890. }
  1891. // 保存这个变换矩阵
  1892. this.transform = m;
  1893. this.invTransform = this.invTransform || create$1();
  1894. invert(this.invTransform, m);
  1895. };
  1896. transformableProto.getLocalTransform = function (m) {
  1897. return Transformable.getLocalTransform(this, m);
  1898. };
  1899. /**
  1900. * 将自己的transform应用到context上
  1901. * @param {CanvasRenderingContext2D} ctx
  1902. */
  1903. transformableProto.setTransform = function (ctx) {
  1904. var m = this.transform;
  1905. var dpr = ctx.dpr || 1;
  1906. if (m) {
  1907. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1908. }
  1909. else {
  1910. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1911. }
  1912. };
  1913. transformableProto.restoreTransform = function (ctx) {
  1914. var dpr = ctx.dpr || 1;
  1915. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1916. };
  1917. var tmpTransform = [];
  1918. /**
  1919. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1920. */
  1921. transformableProto.decomposeTransform = function () {
  1922. if (!this.transform) {
  1923. return;
  1924. }
  1925. var parent = this.parent;
  1926. var m = this.transform;
  1927. if (parent && parent.transform) {
  1928. // Get local transform and decompose them to position, scale, rotation
  1929. mul$1(tmpTransform, parent.invTransform, m);
  1930. m = tmpTransform;
  1931. }
  1932. var sx = m[0] * m[0] + m[1] * m[1];
  1933. var sy = m[2] * m[2] + m[3] * m[3];
  1934. var position = this.position;
  1935. var scale$$1 = this.scale;
  1936. if (isNotAroundZero(sx - 1)) {
  1937. sx = Math.sqrt(sx);
  1938. }
  1939. if (isNotAroundZero(sy - 1)) {
  1940. sy = Math.sqrt(sy);
  1941. }
  1942. if (m[0] < 0) {
  1943. sx = -sx;
  1944. }
  1945. if (m[3] < 0) {
  1946. sy = -sy;
  1947. }
  1948. position[0] = m[4];
  1949. position[1] = m[5];
  1950. scale$$1[0] = sx;
  1951. scale$$1[1] = sy;
  1952. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1953. };
  1954. /**
  1955. * Get global scale
  1956. * @return {Array.<number>}
  1957. */
  1958. transformableProto.getGlobalScale = function () {
  1959. var m = this.transform;
  1960. if (!m) {
  1961. return [1, 1];
  1962. }
  1963. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1964. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1965. if (m[0] < 0) {
  1966. sx = -sx;
  1967. }
  1968. if (m[3] < 0) {
  1969. sy = -sy;
  1970. }
  1971. return [sx, sy];
  1972. };
  1973. /**
  1974. * 变换坐标位置到 shape 的局部坐标空间
  1975. * @method
  1976. * @param {number} x
  1977. * @param {number} y
  1978. * @return {Array.<number>}
  1979. */
  1980. transformableProto.transformCoordToLocal = function (x, y) {
  1981. var v2 = [x, y];
  1982. var invTransform = this.invTransform;
  1983. if (invTransform) {
  1984. applyTransform(v2, v2, invTransform);
  1985. }
  1986. return v2;
  1987. };
  1988. /**
  1989. * 变换局部坐标位置到全局坐标空间
  1990. * @method
  1991. * @param {number} x
  1992. * @param {number} y
  1993. * @return {Array.<number>}
  1994. */
  1995. transformableProto.transformCoordToGlobal = function (x, y) {
  1996. var v2 = [x, y];
  1997. var transform = this.transform;
  1998. if (transform) {
  1999. applyTransform(v2, v2, transform);
  2000. }
  2001. return v2;
  2002. };
  2003. /**
  2004. * @static
  2005. * @param {Object} target
  2006. * @param {Array.<number>} target.origin
  2007. * @param {number} target.rotation
  2008. * @param {Array.<number>} target.position
  2009. * @param {Array.<number>} [m]
  2010. */
  2011. Transformable.getLocalTransform = function (target, m) {
  2012. m = m || [];
  2013. mIdentity(m);
  2014. var origin = target.origin;
  2015. var scale$$1 = target.scale || [1, 1];
  2016. var rotation = target.rotation || 0;
  2017. var position = target.position || [0, 0];
  2018. if (origin) {
  2019. // Translate to origin
  2020. m[4] -= origin[0];
  2021. m[5] -= origin[1];
  2022. }
  2023. scale$1(m, m, scale$$1);
  2024. if (rotation) {
  2025. rotate(m, m, rotation);
  2026. }
  2027. if (origin) {
  2028. // Translate back from origin
  2029. m[4] += origin[0];
  2030. m[5] += origin[1];
  2031. }
  2032. m[4] += position[0];
  2033. m[5] += position[1];
  2034. return m;
  2035. };
  2036. /**
  2037. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2038. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2039. * @exports zrender/animation/easing
  2040. */
  2041. var easing = {
  2042. /**
  2043. * @param {number} k
  2044. * @return {number}
  2045. */
  2046. linear: function (k) {
  2047. return k;
  2048. },
  2049. /**
  2050. * @param {number} k
  2051. * @return {number}
  2052. */
  2053. quadraticIn: function (k) {
  2054. return k * k;
  2055. },
  2056. /**
  2057. * @param {number} k
  2058. * @return {number}
  2059. */
  2060. quadraticOut: function (k) {
  2061. return k * (2 - k);
  2062. },
  2063. /**
  2064. * @param {number} k
  2065. * @return {number}
  2066. */
  2067. quadraticInOut: function (k) {
  2068. if ((k *= 2) < 1) {
  2069. return 0.5 * k * k;
  2070. }
  2071. return -0.5 * (--k * (k - 2) - 1);
  2072. },
  2073. // 三次方的缓动(t^3)
  2074. /**
  2075. * @param {number} k
  2076. * @return {number}
  2077. */
  2078. cubicIn: function (k) {
  2079. return k * k * k;
  2080. },
  2081. /**
  2082. * @param {number} k
  2083. * @return {number}
  2084. */
  2085. cubicOut: function (k) {
  2086. return --k * k * k + 1;
  2087. },
  2088. /**
  2089. * @param {number} k
  2090. * @return {number}
  2091. */
  2092. cubicInOut: function (k) {
  2093. if ((k *= 2) < 1) {
  2094. return 0.5 * k * k * k;
  2095. }
  2096. return 0.5 * ((k -= 2) * k * k + 2);
  2097. },
  2098. // 四次方的缓动(t^4)
  2099. /**
  2100. * @param {number} k
  2101. * @return {number}
  2102. */
  2103. quarticIn: function (k) {
  2104. return k * k * k * k;
  2105. },
  2106. /**
  2107. * @param {number} k
  2108. * @return {number}
  2109. */
  2110. quarticOut: function (k) {
  2111. return 1 - (--k * k * k * k);
  2112. },
  2113. /**
  2114. * @param {number} k
  2115. * @return {number}
  2116. */
  2117. quarticInOut: function (k) {
  2118. if ((k *= 2) < 1) {
  2119. return 0.5 * k * k * k * k;
  2120. }
  2121. return -0.5 * ((k -= 2) * k * k * k - 2);
  2122. },
  2123. // 五次方的缓动(t^5)
  2124. /**
  2125. * @param {number} k
  2126. * @return {number}
  2127. */
  2128. quinticIn: function (k) {
  2129. return k * k * k * k * k;
  2130. },
  2131. /**
  2132. * @param {number} k
  2133. * @return {number}
  2134. */
  2135. quinticOut: function (k) {
  2136. return --k * k * k * k * k + 1;
  2137. },
  2138. /**
  2139. * @param {number} k
  2140. * @return {number}
  2141. */
  2142. quinticInOut: function (k) {
  2143. if ((k *= 2) < 1) {
  2144. return 0.5 * k * k * k * k * k;
  2145. }
  2146. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2147. },
  2148. // 正弦曲线的缓动(sin(t))
  2149. /**
  2150. * @param {number} k
  2151. * @return {number}
  2152. */
  2153. sinusoidalIn: function (k) {
  2154. return 1 - Math.cos(k * Math.PI / 2);
  2155. },
  2156. /**
  2157. * @param {number} k
  2158. * @return {number}
  2159. */
  2160. sinusoidalOut: function (k) {
  2161. return Math.sin(k * Math.PI / 2);
  2162. },
  2163. /**
  2164. * @param {number} k
  2165. * @return {number}
  2166. */
  2167. sinusoidalInOut: function (k) {
  2168. return 0.5 * (1 - Math.cos(Math.PI * k));
  2169. },
  2170. // 指数曲线的缓动(2^t)
  2171. /**
  2172. * @param {number} k
  2173. * @return {number}
  2174. */
  2175. exponentialIn: function (k) {
  2176. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2177. },
  2178. /**
  2179. * @param {number} k
  2180. * @return {number}
  2181. */
  2182. exponentialOut: function (k) {
  2183. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2184. },
  2185. /**
  2186. * @param {number} k
  2187. * @return {number}
  2188. */
  2189. exponentialInOut: function (k) {
  2190. if (k === 0) {
  2191. return 0;
  2192. }
  2193. if (k === 1) {
  2194. return 1;
  2195. }
  2196. if ((k *= 2) < 1) {
  2197. return 0.5 * Math.pow(1024, k - 1);
  2198. }
  2199. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2200. },
  2201. // 圆形曲线的缓动(sqrt(1-t^2))
  2202. /**
  2203. * @param {number} k
  2204. * @return {number}
  2205. */
  2206. circularIn: function (k) {
  2207. return 1 - Math.sqrt(1 - k * k);
  2208. },
  2209. /**
  2210. * @param {number} k
  2211. * @return {number}
  2212. */
  2213. circularOut: function (k) {
  2214. return Math.sqrt(1 - (--k * k));
  2215. },
  2216. /**
  2217. * @param {number} k
  2218. * @return {number}
  2219. */
  2220. circularInOut: function (k) {
  2221. if ((k *= 2) < 1) {
  2222. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2223. }
  2224. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2225. },
  2226. // 创建类似于弹簧在停止前来回振荡的动画
  2227. /**
  2228. * @param {number} k
  2229. * @return {number}
  2230. */
  2231. elasticIn: function (k) {
  2232. var s;
  2233. var a = 0.1;
  2234. var p = 0.4;
  2235. if (k === 0) {
  2236. return 0;
  2237. }
  2238. if (k === 1) {
  2239. return 1;
  2240. }
  2241. if (!a || a < 1) {
  2242. a = 1; s = p / 4;
  2243. }
  2244. else {
  2245. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2246. }
  2247. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2248. Math.sin((k - s) * (2 * Math.PI) / p));
  2249. },
  2250. /**
  2251. * @param {number} k
  2252. * @return {number}
  2253. */
  2254. elasticOut: function (k) {
  2255. var s;
  2256. var a = 0.1;
  2257. var p = 0.4;
  2258. if (k === 0) {
  2259. return 0;
  2260. }
  2261. if (k === 1) {
  2262. return 1;
  2263. }
  2264. if (!a || a < 1) {
  2265. a = 1; s = p / 4;
  2266. }
  2267. else {
  2268. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2269. }
  2270. return (a * Math.pow(2, -10 * k) *
  2271. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2272. },
  2273. /**
  2274. * @param {number} k
  2275. * @return {number}
  2276. */
  2277. elasticInOut: function (k) {
  2278. var s;
  2279. var a = 0.1;
  2280. var p = 0.4;
  2281. if (k === 0) {
  2282. return 0;
  2283. }
  2284. if (k === 1) {
  2285. return 1;
  2286. }
  2287. if (!a || a < 1) {
  2288. a = 1; s = p / 4;
  2289. }
  2290. else {
  2291. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2292. }
  2293. if ((k *= 2) < 1) {
  2294. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2295. * Math.sin((k - s) * (2 * Math.PI) / p));
  2296. }
  2297. return a * Math.pow(2, -10 * (k -= 1))
  2298. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2299. },
  2300. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2301. /**
  2302. * @param {number} k
  2303. * @return {number}
  2304. */
  2305. backIn: function (k) {
  2306. var s = 1.70158;
  2307. return k * k * ((s + 1) * k - s);
  2308. },
  2309. /**
  2310. * @param {number} k
  2311. * @return {number}
  2312. */
  2313. backOut: function (k) {
  2314. var s = 1.70158;
  2315. return --k * k * ((s + 1) * k + s) + 1;
  2316. },
  2317. /**
  2318. * @param {number} k
  2319. * @return {number}
  2320. */
  2321. backInOut: function (k) {
  2322. var s = 1.70158 * 1.525;
  2323. if ((k *= 2) < 1) {
  2324. return 0.5 * (k * k * ((s + 1) * k - s));
  2325. }
  2326. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2327. },
  2328. // 创建弹跳效果
  2329. /**
  2330. * @param {number} k
  2331. * @return {number}
  2332. */
  2333. bounceIn: function (k) {
  2334. return 1 - easing.bounceOut(1 - k);
  2335. },
  2336. /**
  2337. * @param {number} k
  2338. * @return {number}
  2339. */
  2340. bounceOut: function (k) {
  2341. if (k < (1 / 2.75)) {
  2342. return 7.5625 * k * k;
  2343. }
  2344. else if (k < (2 / 2.75)) {
  2345. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2346. }
  2347. else if (k < (2.5 / 2.75)) {
  2348. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2349. }
  2350. else {
  2351. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2352. }
  2353. },
  2354. /**
  2355. * @param {number} k
  2356. * @return {number}
  2357. */
  2358. bounceInOut: function (k) {
  2359. if (k < 0.5) {
  2360. return easing.bounceIn(k * 2) * 0.5;
  2361. }
  2362. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2363. }
  2364. };
  2365. /**
  2366. * 动画主控制器
  2367. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2368. * @config life(1000) 动画时长
  2369. * @config delay(0) 动画延迟时间
  2370. * @config loop(true)
  2371. * @config gap(0) 循环的间隔时间
  2372. * @config onframe
  2373. * @config easing(optional)
  2374. * @config ondestroy(optional)
  2375. * @config onrestart(optional)
  2376. *
  2377. * TODO pause
  2378. */
  2379. function Clip(options) {
  2380. this._target = options.target;
  2381. // 生命周期
  2382. this._life = options.life || 1000;
  2383. // 延时
  2384. this._delay = options.delay || 0;
  2385. // 开始时间
  2386. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2387. this._initialized = false;
  2388. // 是否循环
  2389. this.loop = options.loop == null ? false : options.loop;
  2390. this.gap = options.gap || 0;
  2391. this.easing = options.easing || 'Linear';
  2392. this.onframe = options.onframe;
  2393. this.ondestroy = options.ondestroy;
  2394. this.onrestart = options.onrestart;
  2395. this._pausedTime = 0;
  2396. this._paused = false;
  2397. }
  2398. Clip.prototype = {
  2399. constructor: Clip,
  2400. step: function (globalTime, deltaTime) {
  2401. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2402. // PENDING
  2403. if (!this._initialized) {
  2404. this._startTime = globalTime + this._delay;
  2405. this._initialized = true;
  2406. }
  2407. if (this._paused) {
  2408. this._pausedTime += deltaTime;
  2409. return;
  2410. }
  2411. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2412. // 还没开始
  2413. if (percent < 0) {
  2414. return;
  2415. }
  2416. percent = Math.min(percent, 1);
  2417. var easing$$1 = this.easing;
  2418. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2419. var schedule = typeof easingFunc === 'function'
  2420. ? easingFunc(percent)
  2421. : percent;
  2422. this.fire('frame', schedule);
  2423. // 结束
  2424. if (percent == 1) {
  2425. if (this.loop) {
  2426. this.restart (globalTime);
  2427. // 重新开始周期
  2428. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2429. return 'restart';
  2430. }
  2431. // 动画完成将这个控制器标识为待删除
  2432. // 在Animation.update中进行批量删除
  2433. this._needsRemove = true;
  2434. return 'destroy';
  2435. }
  2436. return null;
  2437. },
  2438. restart: function (globalTime) {
  2439. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2440. this._startTime = globalTime - remainder + this.gap;
  2441. this._pausedTime = 0;
  2442. this._needsRemove = false;
  2443. },
  2444. fire: function (eventType, arg) {
  2445. eventType = 'on' + eventType;
  2446. if (this[eventType]) {
  2447. this[eventType](this._target, arg);
  2448. }
  2449. },
  2450. pause: function () {
  2451. this._paused = true;
  2452. },
  2453. resume: function () {
  2454. this._paused = false;
  2455. }
  2456. };
  2457. // Simple LRU cache use doubly linked list
  2458. // @module zrender/core/LRU
  2459. /**
  2460. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2461. * @constructor
  2462. */
  2463. var LinkedList = function () {
  2464. /**
  2465. * @type {module:zrender/core/LRU~Entry}
  2466. */
  2467. this.head = null;
  2468. /**
  2469. * @type {module:zrender/core/LRU~Entry}
  2470. */
  2471. this.tail = null;
  2472. this._len = 0;
  2473. };
  2474. var linkedListProto = LinkedList.prototype;
  2475. /**
  2476. * Insert a new value at the tail
  2477. * @param {} val
  2478. * @return {module:zrender/core/LRU~Entry}
  2479. */
  2480. linkedListProto.insert = function (val) {
  2481. var entry = new Entry(val);
  2482. this.insertEntry(entry);
  2483. return entry;
  2484. };
  2485. /**
  2486. * Insert an entry at the tail
  2487. * @param {module:zrender/core/LRU~Entry} entry
  2488. */
  2489. linkedListProto.insertEntry = function (entry) {
  2490. if (!this.head) {
  2491. this.head = this.tail = entry;
  2492. }
  2493. else {
  2494. this.tail.next = entry;
  2495. entry.prev = this.tail;
  2496. entry.next = null;
  2497. this.tail = entry;
  2498. }
  2499. this._len++;
  2500. };
  2501. /**
  2502. * Remove entry.
  2503. * @param {module:zrender/core/LRU~Entry} entry
  2504. */
  2505. linkedListProto.remove = function (entry) {
  2506. var prev = entry.prev;
  2507. var next = entry.next;
  2508. if (prev) {
  2509. prev.next = next;
  2510. }
  2511. else {
  2512. // Is head
  2513. this.head = next;
  2514. }
  2515. if (next) {
  2516. next.prev = prev;
  2517. }
  2518. else {
  2519. // Is tail
  2520. this.tail = prev;
  2521. }
  2522. entry.next = entry.prev = null;
  2523. this._len--;
  2524. };
  2525. /**
  2526. * @return {number}
  2527. */
  2528. linkedListProto.len = function () {
  2529. return this._len;
  2530. };
  2531. /**
  2532. * Clear list
  2533. */
  2534. linkedListProto.clear = function () {
  2535. this.head = this.tail = null;
  2536. this._len = 0;
  2537. };
  2538. /**
  2539. * @constructor
  2540. * @param {} val
  2541. */
  2542. var Entry = function (val) {
  2543. /**
  2544. * @type {}
  2545. */
  2546. this.value = val;
  2547. /**
  2548. * @type {module:zrender/core/LRU~Entry}
  2549. */
  2550. this.next;
  2551. /**
  2552. * @type {module:zrender/core/LRU~Entry}
  2553. */
  2554. this.prev;
  2555. };
  2556. /**
  2557. * LRU Cache
  2558. * @constructor
  2559. * @alias module:zrender/core/LRU
  2560. */
  2561. var LRU = function (maxSize) {
  2562. this._list = new LinkedList();
  2563. this._map = {};
  2564. this._maxSize = maxSize || 10;
  2565. this._lastRemovedEntry = null;
  2566. };
  2567. var LRUProto = LRU.prototype;
  2568. /**
  2569. * @param {string} key
  2570. * @param {} value
  2571. * @return {} Removed value
  2572. */
  2573. LRUProto.put = function (key, value) {
  2574. var list = this._list;
  2575. var map = this._map;
  2576. var removed = null;
  2577. if (map[key] == null) {
  2578. var len = list.len();
  2579. // Reuse last removed entry
  2580. var entry = this._lastRemovedEntry;
  2581. if (len >= this._maxSize && len > 0) {
  2582. // Remove the least recently used
  2583. var leastUsedEntry = list.head;
  2584. list.remove(leastUsedEntry);
  2585. delete map[leastUsedEntry.key];
  2586. removed = leastUsedEntry.value;
  2587. this._lastRemovedEntry = leastUsedEntry;
  2588. }
  2589. if (entry) {
  2590. entry.value = value;
  2591. }
  2592. else {
  2593. entry = new Entry(value);
  2594. }
  2595. entry.key = key;
  2596. list.insertEntry(entry);
  2597. map[key] = entry;
  2598. }
  2599. return removed;
  2600. };
  2601. /**
  2602. * @param {string} key
  2603. * @return {}
  2604. */
  2605. LRUProto.get = function (key) {
  2606. var entry = this._map[key];
  2607. var list = this._list;
  2608. if (entry != null) {
  2609. // Put the latest used entry in the tail
  2610. if (entry !== list.tail) {
  2611. list.remove(entry);
  2612. list.insertEntry(entry);
  2613. }
  2614. return entry.value;
  2615. }
  2616. };
  2617. /**
  2618. * Clear the cache
  2619. */
  2620. LRUProto.clear = function () {
  2621. this._list.clear();
  2622. this._map = {};
  2623. };
  2624. var kCSSColorTable = {
  2625. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2626. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2627. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2628. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2629. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2630. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2631. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2632. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2633. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2634. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2635. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2636. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2637. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2638. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2639. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2640. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2641. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2642. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2643. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2644. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2645. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2646. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2647. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2648. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2649. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2650. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2651. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2652. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2653. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2654. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2655. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2656. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2657. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2658. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2659. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2660. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2661. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2662. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2663. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2664. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2665. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2666. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2667. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2668. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2669. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2670. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2671. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2672. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2673. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2674. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2675. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2676. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2677. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2678. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2679. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2680. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2681. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2682. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2683. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2684. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2685. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2686. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2687. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2688. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2689. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2690. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2691. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2692. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2693. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2694. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2695. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2696. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2697. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2698. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2699. };
  2700. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2701. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2702. return i < 0 ? 0 : i > 255 ? 255 : i;
  2703. }
  2704. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2705. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2706. return i < 0 ? 0 : i > 360 ? 360 : i;
  2707. }
  2708. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2709. return f < 0 ? 0 : f > 1 ? 1 : f;
  2710. }
  2711. function parseCssInt(str) { // int or percentage.
  2712. if (str.length && str.charAt(str.length - 1) === '%') {
  2713. return clampCssByte(parseFloat(str) / 100 * 255);
  2714. }
  2715. return clampCssByte(parseInt(str, 10));
  2716. }
  2717. function parseCssFloat(str) { // float or percentage.
  2718. if (str.length && str.charAt(str.length - 1) === '%') {
  2719. return clampCssFloat(parseFloat(str) / 100);
  2720. }
  2721. return clampCssFloat(parseFloat(str));
  2722. }
  2723. function cssHueToRgb(m1, m2, h) {
  2724. if (h < 0) {
  2725. h += 1;
  2726. }
  2727. else if (h > 1) {
  2728. h -= 1;
  2729. }
  2730. if (h * 6 < 1) {
  2731. return m1 + (m2 - m1) * h * 6;
  2732. }
  2733. if (h * 2 < 1) {
  2734. return m2;
  2735. }
  2736. if (h * 3 < 2) {
  2737. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2738. }
  2739. return m1;
  2740. }
  2741. function lerpNumber(a, b, p) {
  2742. return a + (b - a) * p;
  2743. }
  2744. function setRgba(out, r, g, b, a) {
  2745. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2746. return out;
  2747. }
  2748. function copyRgba(out, a) {
  2749. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2750. return out;
  2751. }
  2752. var colorCache = new LRU(20);
  2753. var lastRemovedArr = null;
  2754. function putToCache(colorStr, rgbaArr) {
  2755. // Reuse removed array
  2756. if (lastRemovedArr) {
  2757. copyRgba(lastRemovedArr, rgbaArr);
  2758. }
  2759. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2760. }
  2761. /**
  2762. * @param {string} colorStr
  2763. * @param {Array.<number>} out
  2764. * @return {Array.<number>}
  2765. * @memberOf module:zrender/util/color
  2766. */
  2767. function parse(colorStr, rgbaArr) {
  2768. if (!colorStr) {
  2769. return;
  2770. }
  2771. rgbaArr = rgbaArr || [];
  2772. var cached = colorCache.get(colorStr);
  2773. if (cached) {
  2774. return copyRgba(rgbaArr, cached);
  2775. }
  2776. // colorStr may be not string
  2777. colorStr = colorStr + '';
  2778. // Remove all whitespace, not compliant, but should just be more accepting.
  2779. var str = colorStr.replace(/ /g, '').toLowerCase();
  2780. // Color keywords (and transparent) lookup.
  2781. if (str in kCSSColorTable) {
  2782. copyRgba(rgbaArr, kCSSColorTable[str]);
  2783. putToCache(colorStr, rgbaArr);
  2784. return rgbaArr;
  2785. }
  2786. // #abc and #abc123 syntax.
  2787. if (str.charAt(0) === '#') {
  2788. if (str.length === 4) {
  2789. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2790. if (!(iv >= 0 && iv <= 0xfff)) {
  2791. setRgba(rgbaArr, 0, 0, 0, 1);
  2792. return; // Covers NaN.
  2793. }
  2794. setRgba(rgbaArr,
  2795. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2796. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2797. (iv & 0xf) | ((iv & 0xf) << 4),
  2798. 1
  2799. );
  2800. putToCache(colorStr, rgbaArr);
  2801. return rgbaArr;
  2802. }
  2803. else if (str.length === 7) {
  2804. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2805. if (!(iv >= 0 && iv <= 0xffffff)) {
  2806. setRgba(rgbaArr, 0, 0, 0, 1);
  2807. return; // Covers NaN.
  2808. }
  2809. setRgba(rgbaArr,
  2810. (iv & 0xff0000) >> 16,
  2811. (iv & 0xff00) >> 8,
  2812. iv & 0xff,
  2813. 1
  2814. );
  2815. putToCache(colorStr, rgbaArr);
  2816. return rgbaArr;
  2817. }
  2818. return;
  2819. }
  2820. var op = str.indexOf('('), ep = str.indexOf(')');
  2821. if (op !== -1 && ep + 1 === str.length) {
  2822. var fname = str.substr(0, op);
  2823. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2824. var alpha = 1; // To allow case fallthrough.
  2825. switch (fname) {
  2826. case 'rgba':
  2827. if (params.length !== 4) {
  2828. setRgba(rgbaArr, 0, 0, 0, 1);
  2829. return;
  2830. }
  2831. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2832. // Fall through.
  2833. case 'rgb':
  2834. if (params.length !== 3) {
  2835. setRgba(rgbaArr, 0, 0, 0, 1);
  2836. return;
  2837. }
  2838. setRgba(rgbaArr,
  2839. parseCssInt(params[0]),
  2840. parseCssInt(params[1]),
  2841. parseCssInt(params[2]),
  2842. alpha
  2843. );
  2844. putToCache(colorStr, rgbaArr);
  2845. return rgbaArr;
  2846. case 'hsla':
  2847. if (params.length !== 4) {
  2848. setRgba(rgbaArr, 0, 0, 0, 1);
  2849. return;
  2850. }
  2851. params[3] = parseCssFloat(params[3]);
  2852. hsla2rgba(params, rgbaArr);
  2853. putToCache(colorStr, rgbaArr);
  2854. return rgbaArr;
  2855. case 'hsl':
  2856. if (params.length !== 3) {
  2857. setRgba(rgbaArr, 0, 0, 0, 1);
  2858. return;
  2859. }
  2860. hsla2rgba(params, rgbaArr);
  2861. putToCache(colorStr, rgbaArr);
  2862. return rgbaArr;
  2863. default:
  2864. return;
  2865. }
  2866. }
  2867. setRgba(rgbaArr, 0, 0, 0, 1);
  2868. return;
  2869. }
  2870. /**
  2871. * @param {Array.<number>} hsla
  2872. * @param {Array.<number>} rgba
  2873. * @return {Array.<number>} rgba
  2874. */
  2875. function hsla2rgba(hsla, rgba) {
  2876. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2877. // NOTE(deanm): According to the CSS spec s/l should only be
  2878. // percentages, but we don't bother and let float or percentage.
  2879. var s = parseCssFloat(hsla[1]);
  2880. var l = parseCssFloat(hsla[2]);
  2881. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2882. var m1 = l * 2 - m2;
  2883. rgba = rgba || [];
  2884. setRgba(rgba,
  2885. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2886. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2887. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2888. 1
  2889. );
  2890. if (hsla.length === 4) {
  2891. rgba[3] = hsla[3];
  2892. }
  2893. return rgba;
  2894. }
  2895. /**
  2896. * @param {Array.<number>} rgba
  2897. * @return {Array.<number>} hsla
  2898. */
  2899. function rgba2hsla(rgba) {
  2900. if (!rgba) {
  2901. return;
  2902. }
  2903. // RGB from 0 to 255
  2904. var R = rgba[0] / 255;
  2905. var G = rgba[1] / 255;
  2906. var B = rgba[2] / 255;
  2907. var vMin = Math.min(R, G, B); // Min. value of RGB
  2908. var vMax = Math.max(R, G, B); // Max. value of RGB
  2909. var delta = vMax - vMin; // Delta RGB value
  2910. var L = (vMax + vMin) / 2;
  2911. var H;
  2912. var S;
  2913. // HSL results from 0 to 1
  2914. if (delta === 0) {
  2915. H = 0;
  2916. S = 0;
  2917. }
  2918. else {
  2919. if (L < 0.5) {
  2920. S = delta / (vMax + vMin);
  2921. }
  2922. else {
  2923. S = delta / (2 - vMax - vMin);
  2924. }
  2925. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2926. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2927. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2928. if (R === vMax) {
  2929. H = deltaB - deltaG;
  2930. }
  2931. else if (G === vMax) {
  2932. H = (1 / 3) + deltaR - deltaB;
  2933. }
  2934. else if (B === vMax) {
  2935. H = (2 / 3) + deltaG - deltaR;
  2936. }
  2937. if (H < 0) {
  2938. H += 1;
  2939. }
  2940. if (H > 1) {
  2941. H -= 1;
  2942. }
  2943. }
  2944. var hsla = [H * 360, S, L];
  2945. if (rgba[3] != null) {
  2946. hsla.push(rgba[3]);
  2947. }
  2948. return hsla;
  2949. }
  2950. /**
  2951. * @param {string} color
  2952. * @param {number} level
  2953. * @return {string}
  2954. * @memberOf module:zrender/util/color
  2955. */
  2956. function lift(color, level) {
  2957. var colorArr = parse(color);
  2958. if (colorArr) {
  2959. for (var i = 0; i < 3; i++) {
  2960. if (level < 0) {
  2961. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2962. }
  2963. else {
  2964. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2965. }
  2966. }
  2967. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2968. }
  2969. }
  2970. /**
  2971. * @param {string} color
  2972. * @return {string}
  2973. * @memberOf module:zrender/util/color
  2974. */
  2975. function toHex(color) {
  2976. var colorArr = parse(color);
  2977. if (colorArr) {
  2978. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2979. }
  2980. }
  2981. /**
  2982. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  2983. * @param {number} normalizedValue A float between 0 and 1.
  2984. * @param {Array.<Array.<number>>} colors List of rgba color array
  2985. * @param {Array.<number>} [out] Mapped gba color array
  2986. * @return {Array.<number>} will be null/undefined if input illegal.
  2987. */
  2988. function fastLerp(normalizedValue, colors, out) {
  2989. if (!(colors && colors.length)
  2990. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2991. ) {
  2992. return;
  2993. }
  2994. out = out || [];
  2995. var value = normalizedValue * (colors.length - 1);
  2996. var leftIndex = Math.floor(value);
  2997. var rightIndex = Math.ceil(value);
  2998. var leftColor = colors[leftIndex];
  2999. var rightColor = colors[rightIndex];
  3000. var dv = value - leftIndex;
  3001. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3002. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3003. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3004. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3005. return out;
  3006. }
  3007. /**
  3008. * @deprecated
  3009. */
  3010. var fastMapToColor = fastLerp;
  3011. /**
  3012. * @param {number} normalizedValue A float between 0 and 1.
  3013. * @param {Array.<string>} colors Color list.
  3014. * @param {boolean=} fullOutput Default false.
  3015. * @return {(string|Object)} Result color. If fullOutput,
  3016. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3017. * @memberOf module:zrender/util/color
  3018. */
  3019. function lerp$1(normalizedValue, colors, fullOutput) {
  3020. if (!(colors && colors.length)
  3021. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3022. ) {
  3023. return;
  3024. }
  3025. var value = normalizedValue * (colors.length - 1);
  3026. var leftIndex = Math.floor(value);
  3027. var rightIndex = Math.ceil(value);
  3028. var leftColor = parse(colors[leftIndex]);
  3029. var rightColor = parse(colors[rightIndex]);
  3030. var dv = value - leftIndex;
  3031. var color = stringify(
  3032. [
  3033. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3034. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3035. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3036. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3037. ],
  3038. 'rgba'
  3039. );
  3040. return fullOutput
  3041. ? {
  3042. color: color,
  3043. leftIndex: leftIndex,
  3044. rightIndex: rightIndex,
  3045. value: value
  3046. }
  3047. : color;
  3048. }
  3049. /**
  3050. * @deprecated
  3051. */
  3052. var mapToColor = lerp$1;
  3053. /**
  3054. * @param {string} color
  3055. * @param {number=} h 0 ~ 360, ignore when null.
  3056. * @param {number=} s 0 ~ 1, ignore when null.
  3057. * @param {number=} l 0 ~ 1, ignore when null.
  3058. * @return {string} Color string in rgba format.
  3059. * @memberOf module:zrender/util/color
  3060. */
  3061. function modifyHSL(color, h, s, l) {
  3062. color = parse(color);
  3063. if (color) {
  3064. color = rgba2hsla(color);
  3065. h != null && (color[0] = clampCssAngle(h));
  3066. s != null && (color[1] = parseCssFloat(s));
  3067. l != null && (color[2] = parseCssFloat(l));
  3068. return stringify(hsla2rgba(color), 'rgba');
  3069. }
  3070. }
  3071. /**
  3072. * @param {string} color
  3073. * @param {number=} alpha 0 ~ 1
  3074. * @return {string} Color string in rgba format.
  3075. * @memberOf module:zrender/util/color
  3076. */
  3077. function modifyAlpha(color, alpha) {
  3078. color = parse(color);
  3079. if (color && alpha != null) {
  3080. color[3] = clampCssFloat(alpha);
  3081. return stringify(color, 'rgba');
  3082. }
  3083. }
  3084. /**
  3085. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3086. * @param {string} type 'rgba', 'hsva', ...
  3087. * @return {string} Result color. (If input illegal, return undefined).
  3088. */
  3089. function stringify(arrColor, type) {
  3090. if (!arrColor || !arrColor.length) {
  3091. return;
  3092. }
  3093. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3094. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3095. colorStr += ',' + arrColor[3];
  3096. }
  3097. return type + '(' + colorStr + ')';
  3098. }
  3099. var color = (Object.freeze || Object)({
  3100. parse: parse,
  3101. lift: lift,
  3102. toHex: toHex,
  3103. fastLerp: fastLerp,
  3104. fastMapToColor: fastMapToColor,
  3105. lerp: lerp$1,
  3106. mapToColor: mapToColor,
  3107. modifyHSL: modifyHSL,
  3108. modifyAlpha: modifyAlpha,
  3109. stringify: stringify
  3110. });
  3111. /**
  3112. * @module echarts/animation/Animator
  3113. */
  3114. var arraySlice = Array.prototype.slice;
  3115. function defaultGetter(target, key) {
  3116. return target[key];
  3117. }
  3118. function defaultSetter(target, key, value) {
  3119. target[key] = value;
  3120. }
  3121. /**
  3122. * @param {number} p0
  3123. * @param {number} p1
  3124. * @param {number} percent
  3125. * @return {number}
  3126. */
  3127. function interpolateNumber(p0, p1, percent) {
  3128. return (p1 - p0) * percent + p0;
  3129. }
  3130. /**
  3131. * @param {string} p0
  3132. * @param {string} p1
  3133. * @param {number} percent
  3134. * @return {string}
  3135. */
  3136. function interpolateString(p0, p1, percent) {
  3137. return percent > 0.5 ? p1 : p0;
  3138. }
  3139. /**
  3140. * @param {Array} p0
  3141. * @param {Array} p1
  3142. * @param {number} percent
  3143. * @param {Array} out
  3144. * @param {number} arrDim
  3145. */
  3146. function interpolateArray(p0, p1, percent, out, arrDim) {
  3147. var len = p0.length;
  3148. if (arrDim == 1) {
  3149. for (var i = 0; i < len; i++) {
  3150. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3151. }
  3152. }
  3153. else {
  3154. var len2 = len && p0[0].length;
  3155. for (var i = 0; i < len; i++) {
  3156. for (var j = 0; j < len2; j++) {
  3157. out[i][j] = interpolateNumber(
  3158. p0[i][j], p1[i][j], percent
  3159. );
  3160. }
  3161. }
  3162. }
  3163. }
  3164. // arr0 is source array, arr1 is target array.
  3165. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3166. function fillArr(arr0, arr1, arrDim) {
  3167. var arr0Len = arr0.length;
  3168. var arr1Len = arr1.length;
  3169. if (arr0Len !== arr1Len) {
  3170. // FIXME Not work for TypedArray
  3171. var isPreviousLarger = arr0Len > arr1Len;
  3172. if (isPreviousLarger) {
  3173. // Cut the previous
  3174. arr0.length = arr1Len;
  3175. }
  3176. else {
  3177. // Fill the previous
  3178. for (var i = arr0Len; i < arr1Len; i++) {
  3179. arr0.push(
  3180. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3181. );
  3182. }
  3183. }
  3184. }
  3185. // Handling NaN value
  3186. var len2 = arr0[0] && arr0[0].length;
  3187. for (var i = 0; i < arr0.length; i++) {
  3188. if (arrDim === 1) {
  3189. if (isNaN(arr0[i])) {
  3190. arr0[i] = arr1[i];
  3191. }
  3192. }
  3193. else {
  3194. for (var j = 0; j < len2; j++) {
  3195. if (isNaN(arr0[i][j])) {
  3196. arr0[i][j] = arr1[i][j];
  3197. }
  3198. }
  3199. }
  3200. }
  3201. }
  3202. /**
  3203. * @param {Array} arr0
  3204. * @param {Array} arr1
  3205. * @param {number} arrDim
  3206. * @return {boolean}
  3207. */
  3208. function isArraySame(arr0, arr1, arrDim) {
  3209. if (arr0 === arr1) {
  3210. return true;
  3211. }
  3212. var len = arr0.length;
  3213. if (len !== arr1.length) {
  3214. return false;
  3215. }
  3216. if (arrDim === 1) {
  3217. for (var i = 0; i < len; i++) {
  3218. if (arr0[i] !== arr1[i]) {
  3219. return false;
  3220. }
  3221. }
  3222. }
  3223. else {
  3224. var len2 = arr0[0].length;
  3225. for (var i = 0; i < len; i++) {
  3226. for (var j = 0; j < len2; j++) {
  3227. if (arr0[i][j] !== arr1[i][j]) {
  3228. return false;
  3229. }
  3230. }
  3231. }
  3232. }
  3233. return true;
  3234. }
  3235. /**
  3236. * Catmull Rom interpolate array
  3237. * @param {Array} p0
  3238. * @param {Array} p1
  3239. * @param {Array} p2
  3240. * @param {Array} p3
  3241. * @param {number} t
  3242. * @param {number} t2
  3243. * @param {number} t3
  3244. * @param {Array} out
  3245. * @param {number} arrDim
  3246. */
  3247. function catmullRomInterpolateArray(
  3248. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3249. ) {
  3250. var len = p0.length;
  3251. if (arrDim == 1) {
  3252. for (var i = 0; i < len; i++) {
  3253. out[i] = catmullRomInterpolate(
  3254. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3255. );
  3256. }
  3257. }
  3258. else {
  3259. var len2 = p0[0].length;
  3260. for (var i = 0; i < len; i++) {
  3261. for (var j = 0; j < len2; j++) {
  3262. out[i][j] = catmullRomInterpolate(
  3263. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3264. t, t2, t3
  3265. );
  3266. }
  3267. }
  3268. }
  3269. }
  3270. /**
  3271. * Catmull Rom interpolate number
  3272. * @param {number} p0
  3273. * @param {number} p1
  3274. * @param {number} p2
  3275. * @param {number} p3
  3276. * @param {number} t
  3277. * @param {number} t2
  3278. * @param {number} t3
  3279. * @return {number}
  3280. */
  3281. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3282. var v0 = (p2 - p0) * 0.5;
  3283. var v1 = (p3 - p1) * 0.5;
  3284. return (2 * (p1 - p2) + v0 + v1) * t3
  3285. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3286. + v0 * t + p1;
  3287. }
  3288. function cloneValue(value) {
  3289. if (isArrayLike(value)) {
  3290. var len = value.length;
  3291. if (isArrayLike(value[0])) {
  3292. var ret = [];
  3293. for (var i = 0; i < len; i++) {
  3294. ret.push(arraySlice.call(value[i]));
  3295. }
  3296. return ret;
  3297. }
  3298. return arraySlice.call(value);
  3299. }
  3300. return value;
  3301. }
  3302. function rgba2String(rgba) {
  3303. rgba[0] = Math.floor(rgba[0]);
  3304. rgba[1] = Math.floor(rgba[1]);
  3305. rgba[2] = Math.floor(rgba[2]);
  3306. return 'rgba(' + rgba.join(',') + ')';
  3307. }
  3308. function getArrayDim(keyframes) {
  3309. var lastValue = keyframes[keyframes.length - 1].value;
  3310. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3311. }
  3312. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3313. var getter = animator._getter;
  3314. var setter = animator._setter;
  3315. var useSpline = easing === 'spline';
  3316. var trackLen = keyframes.length;
  3317. if (!trackLen) {
  3318. return;
  3319. }
  3320. // Guess data type
  3321. var firstVal = keyframes[0].value;
  3322. var isValueArray = isArrayLike(firstVal);
  3323. var isValueColor = false;
  3324. var isValueString = false;
  3325. // For vertices morphing
  3326. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3327. var trackMaxTime;
  3328. // Sort keyframe as ascending
  3329. keyframes.sort(function(a, b) {
  3330. return a.time - b.time;
  3331. });
  3332. trackMaxTime = keyframes[trackLen - 1].time;
  3333. // Percents of each keyframe
  3334. var kfPercents = [];
  3335. // Value of each keyframe
  3336. var kfValues = [];
  3337. var prevValue = keyframes[0].value;
  3338. var isAllValueEqual = true;
  3339. for (var i = 0; i < trackLen; i++) {
  3340. kfPercents.push(keyframes[i].time / trackMaxTime);
  3341. // Assume value is a color when it is a string
  3342. var value = keyframes[i].value;
  3343. // Check if value is equal, deep check if value is array
  3344. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3345. || (!isValueArray && value === prevValue))) {
  3346. isAllValueEqual = false;
  3347. }
  3348. prevValue = value;
  3349. // Try converting a string to a color array
  3350. if (typeof value == 'string') {
  3351. var colorArray = parse(value);
  3352. if (colorArray) {
  3353. value = colorArray;
  3354. isValueColor = true;
  3355. }
  3356. else {
  3357. isValueString = true;
  3358. }
  3359. }
  3360. kfValues.push(value);
  3361. }
  3362. if (!forceAnimate && isAllValueEqual) {
  3363. return;
  3364. }
  3365. var lastValue = kfValues[trackLen - 1];
  3366. // Polyfill array and NaN value
  3367. for (var i = 0; i < trackLen - 1; i++) {
  3368. if (isValueArray) {
  3369. fillArr(kfValues[i], lastValue, arrDim);
  3370. }
  3371. else {
  3372. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3373. kfValues[i] = lastValue;
  3374. }
  3375. }
  3376. }
  3377. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3378. // Cache the key of last frame to speed up when
  3379. // animation playback is sequency
  3380. var lastFrame = 0;
  3381. var lastFramePercent = 0;
  3382. var start;
  3383. var w;
  3384. var p0;
  3385. var p1;
  3386. var p2;
  3387. var p3;
  3388. if (isValueColor) {
  3389. var rgba = [0, 0, 0, 0];
  3390. }
  3391. var onframe = function (target, percent) {
  3392. // Find the range keyframes
  3393. // kf1-----kf2---------current--------kf3
  3394. // find kf2 and kf3 and do interpolation
  3395. var frame;
  3396. // In the easing function like elasticOut, percent may less than 0
  3397. if (percent < 0) {
  3398. frame = 0;
  3399. }
  3400. else if (percent < lastFramePercent) {
  3401. // Start from next key
  3402. // PENDING start from lastFrame ?
  3403. start = Math.min(lastFrame + 1, trackLen - 1);
  3404. for (frame = start; frame >= 0; frame--) {
  3405. if (kfPercents[frame] <= percent) {
  3406. break;
  3407. }
  3408. }
  3409. // PENDING really need to do this ?
  3410. frame = Math.min(frame, trackLen - 2);
  3411. }
  3412. else {
  3413. for (frame = lastFrame; frame < trackLen; frame++) {
  3414. if (kfPercents[frame] > percent) {
  3415. break;
  3416. }
  3417. }
  3418. frame = Math.min(frame - 1, trackLen - 2);
  3419. }
  3420. lastFrame = frame;
  3421. lastFramePercent = percent;
  3422. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3423. if (range === 0) {
  3424. return;
  3425. }
  3426. else {
  3427. w = (percent - kfPercents[frame]) / range;
  3428. }
  3429. if (useSpline) {
  3430. p1 = kfValues[frame];
  3431. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3432. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3433. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3434. if (isValueArray) {
  3435. catmullRomInterpolateArray(
  3436. p0, p1, p2, p3, w, w * w, w * w * w,
  3437. getter(target, propName),
  3438. arrDim
  3439. );
  3440. }
  3441. else {
  3442. var value;
  3443. if (isValueColor) {
  3444. value = catmullRomInterpolateArray(
  3445. p0, p1, p2, p3, w, w * w, w * w * w,
  3446. rgba, 1
  3447. );
  3448. value = rgba2String(rgba);
  3449. }
  3450. else if (isValueString) {
  3451. // String is step(0.5)
  3452. return interpolateString(p1, p2, w);
  3453. }
  3454. else {
  3455. value = catmullRomInterpolate(
  3456. p0, p1, p2, p3, w, w * w, w * w * w
  3457. );
  3458. }
  3459. setter(
  3460. target,
  3461. propName,
  3462. value
  3463. );
  3464. }
  3465. }
  3466. else {
  3467. if (isValueArray) {
  3468. interpolateArray(
  3469. kfValues[frame], kfValues[frame + 1], w,
  3470. getter(target, propName),
  3471. arrDim
  3472. );
  3473. }
  3474. else {
  3475. var value;
  3476. if (isValueColor) {
  3477. interpolateArray(
  3478. kfValues[frame], kfValues[frame + 1], w,
  3479. rgba, 1
  3480. );
  3481. value = rgba2String(rgba);
  3482. }
  3483. else if (isValueString) {
  3484. // String is step(0.5)
  3485. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3486. }
  3487. else {
  3488. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3489. }
  3490. setter(
  3491. target,
  3492. propName,
  3493. value
  3494. );
  3495. }
  3496. }
  3497. };
  3498. var clip = new Clip({
  3499. target: animator._target,
  3500. life: trackMaxTime,
  3501. loop: animator._loop,
  3502. delay: animator._delay,
  3503. onframe: onframe,
  3504. ondestroy: oneTrackDone
  3505. });
  3506. if (easing && easing !== 'spline') {
  3507. clip.easing = easing;
  3508. }
  3509. return clip;
  3510. }
  3511. /**
  3512. * @alias module:zrender/animation/Animator
  3513. * @constructor
  3514. * @param {Object} target
  3515. * @param {boolean} loop
  3516. * @param {Function} getter
  3517. * @param {Function} setter
  3518. */
  3519. var Animator = function(target, loop, getter, setter) {
  3520. this._tracks = {};
  3521. this._target = target;
  3522. this._loop = loop || false;
  3523. this._getter = getter || defaultGetter;
  3524. this._setter = setter || defaultSetter;
  3525. this._clipCount = 0;
  3526. this._delay = 0;
  3527. this._doneList = [];
  3528. this._onframeList = [];
  3529. this._clipList = [];
  3530. };
  3531. Animator.prototype = {
  3532. /**
  3533. * 设置动画关键帧
  3534. * @param {number} time 关键帧时间,单位是ms
  3535. * @param {Object} props 关键帧的属性值,key-value表示
  3536. * @return {module:zrender/animation/Animator}
  3537. */
  3538. when: function(time /* ms */, props) {
  3539. var tracks = this._tracks;
  3540. for (var propName in props) {
  3541. if (!props.hasOwnProperty(propName)) {
  3542. continue;
  3543. }
  3544. if (!tracks[propName]) {
  3545. tracks[propName] = [];
  3546. // Invalid value
  3547. var value = this._getter(this._target, propName);
  3548. if (value == null) {
  3549. // zrLog('Invalid property ' + propName);
  3550. continue;
  3551. }
  3552. // If time is 0
  3553. // Then props is given initialize value
  3554. // Else
  3555. // Initialize value from current prop value
  3556. if (time !== 0) {
  3557. tracks[propName].push({
  3558. time: 0,
  3559. value: cloneValue(value)
  3560. });
  3561. }
  3562. }
  3563. tracks[propName].push({
  3564. time: time,
  3565. value: props[propName]
  3566. });
  3567. }
  3568. return this;
  3569. },
  3570. /**
  3571. * 添加动画每一帧的回调函数
  3572. * @param {Function} callback
  3573. * @return {module:zrender/animation/Animator}
  3574. */
  3575. during: function (callback) {
  3576. this._onframeList.push(callback);
  3577. return this;
  3578. },
  3579. pause: function () {
  3580. for (var i = 0; i < this._clipList.length; i++) {
  3581. this._clipList[i].pause();
  3582. }
  3583. this._paused = true;
  3584. },
  3585. resume: function () {
  3586. for (var i = 0; i < this._clipList.length; i++) {
  3587. this._clipList[i].resume();
  3588. }
  3589. this._paused = false;
  3590. },
  3591. isPaused: function () {
  3592. return !!this._paused;
  3593. },
  3594. _doneCallback: function () {
  3595. // Clear all tracks
  3596. this._tracks = {};
  3597. // Clear all clips
  3598. this._clipList.length = 0;
  3599. var doneList = this._doneList;
  3600. var len = doneList.length;
  3601. for (var i = 0; i < len; i++) {
  3602. doneList[i].call(this);
  3603. }
  3604. },
  3605. /**
  3606. * 开始执行动画
  3607. * @param {string|Function} [easing]
  3608. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3609. * @param {boolean} forceAnimate
  3610. * @return {module:zrender/animation/Animator}
  3611. */
  3612. start: function (easing, forceAnimate) {
  3613. var self = this;
  3614. var clipCount = 0;
  3615. var oneTrackDone = function() {
  3616. clipCount--;
  3617. if (!clipCount) {
  3618. self._doneCallback();
  3619. }
  3620. };
  3621. var lastClip;
  3622. for (var propName in this._tracks) {
  3623. if (!this._tracks.hasOwnProperty(propName)) {
  3624. continue;
  3625. }
  3626. var clip = createTrackClip(
  3627. this, easing, oneTrackDone,
  3628. this._tracks[propName], propName, forceAnimate
  3629. );
  3630. if (clip) {
  3631. this._clipList.push(clip);
  3632. clipCount++;
  3633. // If start after added to animation
  3634. if (this.animation) {
  3635. this.animation.addClip(clip);
  3636. }
  3637. lastClip = clip;
  3638. }
  3639. }
  3640. // Add during callback on the last clip
  3641. if (lastClip) {
  3642. var oldOnFrame = lastClip.onframe;
  3643. lastClip.onframe = function (target, percent) {
  3644. oldOnFrame(target, percent);
  3645. for (var i = 0; i < self._onframeList.length; i++) {
  3646. self._onframeList[i](target, percent);
  3647. }
  3648. };
  3649. }
  3650. // This optimization will help the case that in the upper application
  3651. // the view may be refreshed frequently, where animation will be
  3652. // called repeatly but nothing changed.
  3653. if (!clipCount) {
  3654. this._doneCallback();
  3655. }
  3656. return this;
  3657. },
  3658. /**
  3659. * 停止动画
  3660. * @param {boolean} forwardToLast If move to last frame before stop
  3661. */
  3662. stop: function (forwardToLast) {
  3663. var clipList = this._clipList;
  3664. var animation = this.animation;
  3665. for (var i = 0; i < clipList.length; i++) {
  3666. var clip = clipList[i];
  3667. if (forwardToLast) {
  3668. // Move to last frame before stop
  3669. clip.onframe(this._target, 1);
  3670. }
  3671. animation && animation.removeClip(clip);
  3672. }
  3673. clipList.length = 0;
  3674. },
  3675. /**
  3676. * 设置动画延迟开始的时间
  3677. * @param {number} time 单位ms
  3678. * @return {module:zrender/animation/Animator}
  3679. */
  3680. delay: function (time) {
  3681. this._delay = time;
  3682. return this;
  3683. },
  3684. /**
  3685. * 添加动画结束的回调
  3686. * @param {Function} cb
  3687. * @return {module:zrender/animation/Animator}
  3688. */
  3689. done: function(cb) {
  3690. if (cb) {
  3691. this._doneList.push(cb);
  3692. }
  3693. return this;
  3694. },
  3695. /**
  3696. * @return {Array.<module:zrender/animation/Clip>}
  3697. */
  3698. getClips: function () {
  3699. return this._clipList;
  3700. }
  3701. };
  3702. var dpr = 1;
  3703. // If in browser environment
  3704. if (typeof window !== 'undefined') {
  3705. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3706. }
  3707. /**
  3708. * config默认配置项
  3709. * @exports zrender/config
  3710. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3711. */
  3712. /**
  3713. * debug日志选项:catchBrushException为true下有效
  3714. * 0 : 不生成debug数据,发布用
  3715. * 1 : 异常抛出,调试用
  3716. * 2 : 控制台输出,调试用
  3717. */
  3718. var debugMode = 0;
  3719. // retina 屏幕优化
  3720. var devicePixelRatio = dpr;
  3721. var log = function () {
  3722. };
  3723. if (debugMode === 1) {
  3724. log = function () {
  3725. for (var k in arguments) {
  3726. throw new Error(arguments[k]);
  3727. }
  3728. };
  3729. }
  3730. else if (debugMode > 1) {
  3731. log = function () {
  3732. for (var k in arguments) {
  3733. console.log(arguments[k]);
  3734. }
  3735. };
  3736. }
  3737. var zrLog = log;
  3738. /**
  3739. * @alias modue:zrender/mixin/Animatable
  3740. * @constructor
  3741. */
  3742. var Animatable = function () {
  3743. /**
  3744. * @type {Array.<module:zrender/animation/Animator>}
  3745. * @readOnly
  3746. */
  3747. this.animators = [];
  3748. };
  3749. Animatable.prototype = {
  3750. constructor: Animatable,
  3751. /**
  3752. * 动画
  3753. *
  3754. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3755. * @param {boolean} [loop] Whether to loop animation.
  3756. * @return {module:zrender/animation/Animator}
  3757. * @example:
  3758. * el.animate('style', false)
  3759. * .when(1000, {x: 10} )
  3760. * .done(function(){ // Animation done })
  3761. * .start()
  3762. */
  3763. animate: function (path, loop) {
  3764. var target;
  3765. var animatingShape = false;
  3766. var el = this;
  3767. var zr = this.__zr;
  3768. if (path) {
  3769. var pathSplitted = path.split('.');
  3770. var prop = el;
  3771. // If animating shape
  3772. animatingShape = pathSplitted[0] === 'shape';
  3773. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3774. if (!prop) {
  3775. continue;
  3776. }
  3777. prop = prop[pathSplitted[i]];
  3778. }
  3779. if (prop) {
  3780. target = prop;
  3781. }
  3782. }
  3783. else {
  3784. target = el;
  3785. }
  3786. if (!target) {
  3787. zrLog(
  3788. 'Property "'
  3789. + path
  3790. + '" is not existed in element '
  3791. + el.id
  3792. );
  3793. return;
  3794. }
  3795. var animators = el.animators;
  3796. var animator = new Animator(target, loop);
  3797. animator.during(function (target) {
  3798. el.dirty(animatingShape);
  3799. })
  3800. .done(function () {
  3801. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3802. animators.splice(indexOf(animators, animator), 1);
  3803. });
  3804. animators.push(animator);
  3805. // If animate after added to the zrender
  3806. if (zr) {
  3807. zr.animation.addAnimator(animator);
  3808. }
  3809. return animator;
  3810. },
  3811. /**
  3812. * 停止动画
  3813. * @param {boolean} forwardToLast If move to last frame before stop
  3814. */
  3815. stopAnimation: function (forwardToLast) {
  3816. var animators = this.animators;
  3817. var len = animators.length;
  3818. for (var i = 0; i < len; i++) {
  3819. animators[i].stop(forwardToLast);
  3820. }
  3821. animators.length = 0;
  3822. return this;
  3823. },
  3824. /**
  3825. * Caution: this method will stop previous animation.
  3826. * So do not use this method to one element twice before
  3827. * animation starts, unless you know what you are doing.
  3828. * @param {Object} target
  3829. * @param {number} [time=500] Time in ms
  3830. * @param {string} [easing='linear']
  3831. * @param {number} [delay=0]
  3832. * @param {Function} [callback]
  3833. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3834. * immediently when target values are the same as current values.
  3835. *
  3836. * @example
  3837. * // Animate position
  3838. * el.animateTo({
  3839. * position: [10, 10]
  3840. * }, function () { // done })
  3841. *
  3842. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3843. * el.animateTo({
  3844. * shape: {
  3845. * width: 500
  3846. * },
  3847. * style: {
  3848. * fill: 'red'
  3849. * }
  3850. * position: [10, 10]
  3851. * }, 100, 100, 'cubicOut', function () { // done })
  3852. */
  3853. // TODO Return animation key
  3854. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3855. // animateTo(target, time, easing, callback);
  3856. if (isString(delay)) {
  3857. callback = easing;
  3858. easing = delay;
  3859. delay = 0;
  3860. }
  3861. // animateTo(target, time, delay, callback);
  3862. else if (isFunction$1(easing)) {
  3863. callback = easing;
  3864. easing = 'linear';
  3865. delay = 0;
  3866. }
  3867. // animateTo(target, time, callback);
  3868. else if (isFunction$1(delay)) {
  3869. callback = delay;
  3870. delay = 0;
  3871. }
  3872. // animateTo(target, callback)
  3873. else if (isFunction$1(time)) {
  3874. callback = time;
  3875. time = 500;
  3876. }
  3877. // animateTo(target)
  3878. else if (!time) {
  3879. time = 500;
  3880. }
  3881. // Stop all previous animations
  3882. this.stopAnimation();
  3883. this._animateToShallow('', this, target, time, delay);
  3884. // Animators may be removed immediately after start
  3885. // if there is nothing to animate
  3886. var animators = this.animators.slice();
  3887. var count = animators.length;
  3888. function done() {
  3889. count--;
  3890. if (!count) {
  3891. callback && callback();
  3892. }
  3893. }
  3894. // No animators. This should be checked before animators[i].start(),
  3895. // because 'done' may be executed immediately if no need to animate.
  3896. if (!count) {
  3897. callback && callback();
  3898. }
  3899. // Start after all animators created
  3900. // Incase any animator is done immediately when all animation properties are not changed
  3901. for (var i = 0; i < animators.length; i++) {
  3902. animators[i]
  3903. .done(done)
  3904. .start(easing, forceAnimate);
  3905. }
  3906. },
  3907. /**
  3908. * @private
  3909. * @param {string} path=''
  3910. * @param {Object} source=this
  3911. * @param {Object} target
  3912. * @param {number} [time=500]
  3913. * @param {number} [delay=0]
  3914. *
  3915. * @example
  3916. * // Animate position
  3917. * el._animateToShallow({
  3918. * position: [10, 10]
  3919. * })
  3920. *
  3921. * // Animate shape, style and position in 100ms, delayed 100ms
  3922. * el._animateToShallow({
  3923. * shape: {
  3924. * width: 500
  3925. * },
  3926. * style: {
  3927. * fill: 'red'
  3928. * }
  3929. * position: [10, 10]
  3930. * }, 100, 100)
  3931. */
  3932. _animateToShallow: function (path, source, target, time, delay) {
  3933. var objShallow = {};
  3934. var propertyCount = 0;
  3935. for (var name in target) {
  3936. if (!target.hasOwnProperty(name)) {
  3937. continue;
  3938. }
  3939. if (source[name] != null) {
  3940. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3941. this._animateToShallow(
  3942. path ? path + '.' + name : name,
  3943. source[name],
  3944. target[name],
  3945. time,
  3946. delay
  3947. );
  3948. }
  3949. else {
  3950. objShallow[name] = target[name];
  3951. propertyCount++;
  3952. }
  3953. }
  3954. else if (target[name] != null) {
  3955. // Attr directly if not has property
  3956. // FIXME, if some property not needed for element ?
  3957. if (!path) {
  3958. this.attr(name, target[name]);
  3959. }
  3960. else { // Shape or style
  3961. var props = {};
  3962. props[path] = {};
  3963. props[path][name] = target[name];
  3964. this.attr(props);
  3965. }
  3966. }
  3967. }
  3968. if (propertyCount > 0) {
  3969. this.animate(path, false)
  3970. .when(time == null ? 500 : time, objShallow)
  3971. .delay(delay || 0);
  3972. }
  3973. return this;
  3974. }
  3975. };
  3976. /**
  3977. * @alias module:zrender/Element
  3978. * @constructor
  3979. * @extends {module:zrender/mixin/Animatable}
  3980. * @extends {module:zrender/mixin/Transformable}
  3981. * @extends {module:zrender/mixin/Eventful}
  3982. */
  3983. var Element = function (opts) { // jshint ignore:line
  3984. Transformable.call(this, opts);
  3985. Eventful.call(this, opts);
  3986. Animatable.call(this, opts);
  3987. /**
  3988. * 画布元素ID
  3989. * @type {string}
  3990. */
  3991. this.id = opts.id || guid();
  3992. };
  3993. Element.prototype = {
  3994. /**
  3995. * 元素类型
  3996. * Element type
  3997. * @type {string}
  3998. */
  3999. type: 'element',
  4000. /**
  4001. * 元素名字
  4002. * Element name
  4003. * @type {string}
  4004. */
  4005. name: '',
  4006. /**
  4007. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4008. * ZRender instance will be assigned when element is associated with zrender
  4009. * @name module:/zrender/Element#__zr
  4010. * @type {module:zrender/ZRender}
  4011. */
  4012. __zr: null,
  4013. /**
  4014. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4015. * If ignore drawing and events of the element object
  4016. * @name module:/zrender/Element#ignore
  4017. * @type {boolean}
  4018. * @default false
  4019. */
  4020. ignore: false,
  4021. /**
  4022. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4023. * 该路径会继承被裁减对象的变换
  4024. * @type {module:zrender/graphic/Path}
  4025. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4026. * @readOnly
  4027. */
  4028. clipPath: null,
  4029. /**
  4030. * 是否是 Group
  4031. * @type {boolean}
  4032. */
  4033. isGroup: false,
  4034. /**
  4035. * Drift element
  4036. * @param {number} dx dx on the global space
  4037. * @param {number} dy dy on the global space
  4038. */
  4039. drift: function (dx, dy) {
  4040. switch (this.draggable) {
  4041. case 'horizontal':
  4042. dy = 0;
  4043. break;
  4044. case 'vertical':
  4045. dx = 0;
  4046. break;
  4047. }
  4048. var m = this.transform;
  4049. if (!m) {
  4050. m = this.transform = [1, 0, 0, 1, 0, 0];
  4051. }
  4052. m[4] += dx;
  4053. m[5] += dy;
  4054. this.decomposeTransform();
  4055. this.dirty(false);
  4056. },
  4057. /**
  4058. * Hook before update
  4059. */
  4060. beforeUpdate: function () {},
  4061. /**
  4062. * Hook after update
  4063. */
  4064. afterUpdate: function () {},
  4065. /**
  4066. * Update each frame
  4067. */
  4068. update: function () {
  4069. this.updateTransform();
  4070. },
  4071. /**
  4072. * @param {Function} cb
  4073. * @param {} context
  4074. */
  4075. traverse: function (cb, context) {},
  4076. /**
  4077. * @protected
  4078. */
  4079. attrKV: function (key, value) {
  4080. if (key === 'position' || key === 'scale' || key === 'origin') {
  4081. // Copy the array
  4082. if (value) {
  4083. var target = this[key];
  4084. if (!target) {
  4085. target = this[key] = [];
  4086. }
  4087. target[0] = value[0];
  4088. target[1] = value[1];
  4089. }
  4090. }
  4091. else {
  4092. this[key] = value;
  4093. }
  4094. },
  4095. /**
  4096. * Hide the element
  4097. */
  4098. hide: function () {
  4099. this.ignore = true;
  4100. this.__zr && this.__zr.refresh();
  4101. },
  4102. /**
  4103. * Show the element
  4104. */
  4105. show: function () {
  4106. this.ignore = false;
  4107. this.__zr && this.__zr.refresh();
  4108. },
  4109. /**
  4110. * @param {string|Object} key
  4111. * @param {*} value
  4112. */
  4113. attr: function (key, value) {
  4114. if (typeof key === 'string') {
  4115. this.attrKV(key, value);
  4116. }
  4117. else if (isObject$1(key)) {
  4118. for (var name in key) {
  4119. if (key.hasOwnProperty(name)) {
  4120. this.attrKV(name, key[name]);
  4121. }
  4122. }
  4123. }
  4124. this.dirty(false);
  4125. return this;
  4126. },
  4127. /**
  4128. * @param {module:zrender/graphic/Path} clipPath
  4129. */
  4130. setClipPath: function (clipPath) {
  4131. var zr = this.__zr;
  4132. if (zr) {
  4133. clipPath.addSelfToZr(zr);
  4134. }
  4135. // Remove previous clip path
  4136. if (this.clipPath && this.clipPath !== clipPath) {
  4137. this.removeClipPath();
  4138. }
  4139. this.clipPath = clipPath;
  4140. clipPath.__zr = zr;
  4141. clipPath.__clipTarget = this;
  4142. this.dirty(false);
  4143. },
  4144. /**
  4145. */
  4146. removeClipPath: function () {
  4147. var clipPath = this.clipPath;
  4148. if (clipPath) {
  4149. if (clipPath.__zr) {
  4150. clipPath.removeSelfFromZr(clipPath.__zr);
  4151. }
  4152. clipPath.__zr = null;
  4153. clipPath.__clipTarget = null;
  4154. this.clipPath = null;
  4155. this.dirty(false);
  4156. }
  4157. },
  4158. /**
  4159. * Add self from zrender instance.
  4160. * Not recursively because it will be invoked when element added to storage.
  4161. * @param {module:zrender/ZRender} zr
  4162. */
  4163. addSelfToZr: function (zr) {
  4164. this.__zr = zr;
  4165. // 添加动画
  4166. var animators = this.animators;
  4167. if (animators) {
  4168. for (var i = 0; i < animators.length; i++) {
  4169. zr.animation.addAnimator(animators[i]);
  4170. }
  4171. }
  4172. if (this.clipPath) {
  4173. this.clipPath.addSelfToZr(zr);
  4174. }
  4175. },
  4176. /**
  4177. * Remove self from zrender instance.
  4178. * Not recursively because it will be invoked when element added to storage.
  4179. * @param {module:zrender/ZRender} zr
  4180. */
  4181. removeSelfFromZr: function (zr) {
  4182. this.__zr = null;
  4183. // 移除动画
  4184. var animators = this.animators;
  4185. if (animators) {
  4186. for (var i = 0; i < animators.length; i++) {
  4187. zr.animation.removeAnimator(animators[i]);
  4188. }
  4189. }
  4190. if (this.clipPath) {
  4191. this.clipPath.removeSelfFromZr(zr);
  4192. }
  4193. }
  4194. };
  4195. mixin(Element, Animatable);
  4196. mixin(Element, Transformable);
  4197. mixin(Element, Eventful);
  4198. /**
  4199. * @module echarts/core/BoundingRect
  4200. */
  4201. var v2ApplyTransform = applyTransform;
  4202. var mathMin = Math.min;
  4203. var mathMax = Math.max;
  4204. /**
  4205. * @alias module:echarts/core/BoundingRect
  4206. */
  4207. function BoundingRect(x, y, width, height) {
  4208. if (width < 0) {
  4209. x = x + width;
  4210. width = -width;
  4211. }
  4212. if (height < 0) {
  4213. y = y + height;
  4214. height = -height;
  4215. }
  4216. /**
  4217. * @type {number}
  4218. */
  4219. this.x = x;
  4220. /**
  4221. * @type {number}
  4222. */
  4223. this.y = y;
  4224. /**
  4225. * @type {number}
  4226. */
  4227. this.width = width;
  4228. /**
  4229. * @type {number}
  4230. */
  4231. this.height = height;
  4232. }
  4233. BoundingRect.prototype = {
  4234. constructor: BoundingRect,
  4235. /**
  4236. * @param {module:echarts/core/BoundingRect} other
  4237. */
  4238. union: function (other) {
  4239. var x = mathMin(other.x, this.x);
  4240. var y = mathMin(other.y, this.y);
  4241. this.width = mathMax(
  4242. other.x + other.width,
  4243. this.x + this.width
  4244. ) - x;
  4245. this.height = mathMax(
  4246. other.y + other.height,
  4247. this.y + this.height
  4248. ) - y;
  4249. this.x = x;
  4250. this.y = y;
  4251. },
  4252. /**
  4253. * @param {Array.<number>} m
  4254. * @methods
  4255. */
  4256. applyTransform: (function () {
  4257. var lt = [];
  4258. var rb = [];
  4259. var lb = [];
  4260. var rt = [];
  4261. return function (m) {
  4262. // In case usage like this
  4263. // el.getBoundingRect().applyTransform(el.transform)
  4264. // And element has no transform
  4265. if (!m) {
  4266. return;
  4267. }
  4268. lt[0] = lb[0] = this.x;
  4269. lt[1] = rt[1] = this.y;
  4270. rb[0] = rt[0] = this.x + this.width;
  4271. rb[1] = lb[1] = this.y + this.height;
  4272. v2ApplyTransform(lt, lt, m);
  4273. v2ApplyTransform(rb, rb, m);
  4274. v2ApplyTransform(lb, lb, m);
  4275. v2ApplyTransform(rt, rt, m);
  4276. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4277. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4278. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4279. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4280. this.width = maxX - this.x;
  4281. this.height = maxY - this.y;
  4282. };
  4283. })(),
  4284. /**
  4285. * Calculate matrix of transforming from self to target rect
  4286. * @param {module:zrender/core/BoundingRect} b
  4287. * @return {Array.<number>}
  4288. */
  4289. calculateTransform: function (b) {
  4290. var a = this;
  4291. var sx = b.width / a.width;
  4292. var sy = b.height / a.height;
  4293. var m = create$1();
  4294. // 矩阵右乘
  4295. translate(m, m, [-a.x, -a.y]);
  4296. scale$1(m, m, [sx, sy]);
  4297. translate(m, m, [b.x, b.y]);
  4298. return m;
  4299. },
  4300. /**
  4301. * @param {(module:echarts/core/BoundingRect|Object)} b
  4302. * @return {boolean}
  4303. */
  4304. intersect: function (b) {
  4305. if (!b) {
  4306. return false;
  4307. }
  4308. if (!(b instanceof BoundingRect)) {
  4309. // Normalize negative width/height.
  4310. b = BoundingRect.create(b);
  4311. }
  4312. var a = this;
  4313. var ax0 = a.x;
  4314. var ax1 = a.x + a.width;
  4315. var ay0 = a.y;
  4316. var ay1 = a.y + a.height;
  4317. var bx0 = b.x;
  4318. var bx1 = b.x + b.width;
  4319. var by0 = b.y;
  4320. var by1 = b.y + b.height;
  4321. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4322. },
  4323. contain: function (x, y) {
  4324. var rect = this;
  4325. return x >= rect.x
  4326. && x <= (rect.x + rect.width)
  4327. && y >= rect.y
  4328. && y <= (rect.y + rect.height);
  4329. },
  4330. /**
  4331. * @return {module:echarts/core/BoundingRect}
  4332. */
  4333. clone: function () {
  4334. return new BoundingRect(this.x, this.y, this.width, this.height);
  4335. },
  4336. /**
  4337. * Copy from another rect
  4338. */
  4339. copy: function (other) {
  4340. this.x = other.x;
  4341. this.y = other.y;
  4342. this.width = other.width;
  4343. this.height = other.height;
  4344. },
  4345. plain: function () {
  4346. return {
  4347. x: this.x,
  4348. y: this.y,
  4349. width: this.width,
  4350. height: this.height
  4351. };
  4352. }
  4353. };
  4354. /**
  4355. * @param {Object|module:zrender/core/BoundingRect} rect
  4356. * @param {number} rect.x
  4357. * @param {number} rect.y
  4358. * @param {number} rect.width
  4359. * @param {number} rect.height
  4360. * @return {module:zrender/core/BoundingRect}
  4361. */
  4362. BoundingRect.create = function (rect) {
  4363. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4364. };
  4365. /**
  4366. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4367. * @module zrender/graphic/Group
  4368. * @example
  4369. * var Group = require('zrender/container/Group');
  4370. * var Circle = require('zrender/graphic/shape/Circle');
  4371. * var g = new Group();
  4372. * g.position[0] = 100;
  4373. * g.position[1] = 100;
  4374. * g.add(new Circle({
  4375. * style: {
  4376. * x: 100,
  4377. * y: 100,
  4378. * r: 20,
  4379. * }
  4380. * }));
  4381. * zr.add(g);
  4382. */
  4383. /**
  4384. * @alias module:zrender/graphic/Group
  4385. * @constructor
  4386. * @extends module:zrender/mixin/Transformable
  4387. * @extends module:zrender/mixin/Eventful
  4388. */
  4389. var Group = function (opts) {
  4390. opts = opts || {};
  4391. Element.call(this, opts);
  4392. for (var key in opts) {
  4393. if (opts.hasOwnProperty(key)) {
  4394. this[key] = opts[key];
  4395. }
  4396. }
  4397. this._children = [];
  4398. this.__storage = null;
  4399. this.__dirty = true;
  4400. };
  4401. Group.prototype = {
  4402. constructor: Group,
  4403. isGroup: true,
  4404. /**
  4405. * @type {string}
  4406. */
  4407. type: 'group',
  4408. /**
  4409. * 所有子孙元素是否响应鼠标事件
  4410. * @name module:/zrender/container/Group#silent
  4411. * @type {boolean}
  4412. * @default false
  4413. */
  4414. silent: false,
  4415. /**
  4416. * @return {Array.<module:zrender/Element>}
  4417. */
  4418. children: function () {
  4419. return this._children.slice();
  4420. },
  4421. /**
  4422. * 获取指定 index 的儿子节点
  4423. * @param {number} idx
  4424. * @return {module:zrender/Element}
  4425. */
  4426. childAt: function (idx) {
  4427. return this._children[idx];
  4428. },
  4429. /**
  4430. * 获取指定名字的儿子节点
  4431. * @param {string} name
  4432. * @return {module:zrender/Element}
  4433. */
  4434. childOfName: function (name) {
  4435. var children = this._children;
  4436. for (var i = 0; i < children.length; i++) {
  4437. if (children[i].name === name) {
  4438. return children[i];
  4439. }
  4440. }
  4441. },
  4442. /**
  4443. * @return {number}
  4444. */
  4445. childCount: function () {
  4446. return this._children.length;
  4447. },
  4448. /**
  4449. * 添加子节点到最后
  4450. * @param {module:zrender/Element} child
  4451. */
  4452. add: function (child) {
  4453. if (child && child !== this && child.parent !== this) {
  4454. this._children.push(child);
  4455. this._doAdd(child);
  4456. }
  4457. return this;
  4458. },
  4459. /**
  4460. * 添加子节点在 nextSibling 之前
  4461. * @param {module:zrender/Element} child
  4462. * @param {module:zrender/Element} nextSibling
  4463. */
  4464. addBefore: function (child, nextSibling) {
  4465. if (child && child !== this && child.parent !== this
  4466. && nextSibling && nextSibling.parent === this) {
  4467. var children = this._children;
  4468. var idx = children.indexOf(nextSibling);
  4469. if (idx >= 0) {
  4470. children.splice(idx, 0, child);
  4471. this._doAdd(child);
  4472. }
  4473. }
  4474. return this;
  4475. },
  4476. _doAdd: function (child) {
  4477. if (child.parent) {
  4478. child.parent.remove(child);
  4479. }
  4480. child.parent = this;
  4481. var storage = this.__storage;
  4482. var zr = this.__zr;
  4483. if (storage && storage !== child.__storage) {
  4484. storage.addToStorage(child);
  4485. if (child instanceof Group) {
  4486. child.addChildrenToStorage(storage);
  4487. }
  4488. }
  4489. zr && zr.refresh();
  4490. },
  4491. /**
  4492. * 移除子节点
  4493. * @param {module:zrender/Element} child
  4494. */
  4495. remove: function (child) {
  4496. var zr = this.__zr;
  4497. var storage = this.__storage;
  4498. var children = this._children;
  4499. var idx = indexOf(children, child);
  4500. if (idx < 0) {
  4501. return this;
  4502. }
  4503. children.splice(idx, 1);
  4504. child.parent = null;
  4505. if (storage) {
  4506. storage.delFromStorage(child);
  4507. if (child instanceof Group) {
  4508. child.delChildrenFromStorage(storage);
  4509. }
  4510. }
  4511. zr && zr.refresh();
  4512. return this;
  4513. },
  4514. /**
  4515. * 移除所有子节点
  4516. */
  4517. removeAll: function () {
  4518. var children = this._children;
  4519. var storage = this.__storage;
  4520. var child;
  4521. var i;
  4522. for (i = 0; i < children.length; i++) {
  4523. child = children[i];
  4524. if (storage) {
  4525. storage.delFromStorage(child);
  4526. if (child instanceof Group) {
  4527. child.delChildrenFromStorage(storage);
  4528. }
  4529. }
  4530. child.parent = null;
  4531. }
  4532. children.length = 0;
  4533. return this;
  4534. },
  4535. /**
  4536. * 遍历所有子节点
  4537. * @param {Function} cb
  4538. * @param {} context
  4539. */
  4540. eachChild: function (cb, context) {
  4541. var children = this._children;
  4542. for (var i = 0; i < children.length; i++) {
  4543. var child = children[i];
  4544. cb.call(context, child, i);
  4545. }
  4546. return this;
  4547. },
  4548. /**
  4549. * 深度优先遍历所有子孙节点
  4550. * @param {Function} cb
  4551. * @param {} context
  4552. */
  4553. traverse: function (cb, context) {
  4554. for (var i = 0; i < this._children.length; i++) {
  4555. var child = this._children[i];
  4556. cb.call(context, child);
  4557. if (child.type === 'group') {
  4558. child.traverse(cb, context);
  4559. }
  4560. }
  4561. return this;
  4562. },
  4563. addChildrenToStorage: function (storage) {
  4564. for (var i = 0; i < this._children.length; i++) {
  4565. var child = this._children[i];
  4566. storage.addToStorage(child);
  4567. if (child instanceof Group) {
  4568. child.addChildrenToStorage(storage);
  4569. }
  4570. }
  4571. },
  4572. delChildrenFromStorage: function (storage) {
  4573. for (var i = 0; i < this._children.length; i++) {
  4574. var child = this._children[i];
  4575. storage.delFromStorage(child);
  4576. if (child instanceof Group) {
  4577. child.delChildrenFromStorage(storage);
  4578. }
  4579. }
  4580. },
  4581. dirty: function () {
  4582. this.__dirty = true;
  4583. this.__zr && this.__zr.refresh();
  4584. return this;
  4585. },
  4586. /**
  4587. * @return {module:zrender/core/BoundingRect}
  4588. */
  4589. getBoundingRect: function (includeChildren) {
  4590. // TODO Caching
  4591. var rect = null;
  4592. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4593. var children = includeChildren || this._children;
  4594. var tmpMat = [];
  4595. for (var i = 0; i < children.length; i++) {
  4596. var child = children[i];
  4597. if (child.ignore || child.invisible) {
  4598. continue;
  4599. }
  4600. var childRect = child.getBoundingRect();
  4601. var transform = child.getLocalTransform(tmpMat);
  4602. // TODO
  4603. // The boundingRect cacluated by transforming original
  4604. // rect may be bigger than the actual bundingRect when rotation
  4605. // is used. (Consider a circle rotated aginst its center, where
  4606. // the actual boundingRect should be the same as that not be
  4607. // rotated.) But we can not find better approach to calculate
  4608. // actual boundingRect yet, considering performance.
  4609. if (transform) {
  4610. tmpRect.copy(childRect);
  4611. tmpRect.applyTransform(transform);
  4612. rect = rect || tmpRect.clone();
  4613. rect.union(tmpRect);
  4614. }
  4615. else {
  4616. rect = rect || childRect.clone();
  4617. rect.union(childRect);
  4618. }
  4619. }
  4620. return rect || tmpRect;
  4621. }
  4622. };
  4623. inherits(Group, Element);
  4624. // https://github.com/mziccard/node-timsort
  4625. var DEFAULT_MIN_MERGE = 32;
  4626. var DEFAULT_MIN_GALLOPING = 7;
  4627. function minRunLength(n) {
  4628. var r = 0;
  4629. while (n >= DEFAULT_MIN_MERGE) {
  4630. r |= n & 1;
  4631. n >>= 1;
  4632. }
  4633. return n + r;
  4634. }
  4635. function makeAscendingRun(array, lo, hi, compare) {
  4636. var runHi = lo + 1;
  4637. if (runHi === hi) {
  4638. return 1;
  4639. }
  4640. if (compare(array[runHi++], array[lo]) < 0) {
  4641. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4642. runHi++;
  4643. }
  4644. reverseRun(array, lo, runHi);
  4645. }
  4646. else {
  4647. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4648. runHi++;
  4649. }
  4650. }
  4651. return runHi - lo;
  4652. }
  4653. function reverseRun(array, lo, hi) {
  4654. hi--;
  4655. while (lo < hi) {
  4656. var t = array[lo];
  4657. array[lo++] = array[hi];
  4658. array[hi--] = t;
  4659. }
  4660. }
  4661. function binaryInsertionSort(array, lo, hi, start, compare) {
  4662. if (start === lo) {
  4663. start++;
  4664. }
  4665. for (; start < hi; start++) {
  4666. var pivot = array[start];
  4667. var left = lo;
  4668. var right = start;
  4669. var mid;
  4670. while (left < right) {
  4671. mid = left + right >>> 1;
  4672. if (compare(pivot, array[mid]) < 0) {
  4673. right = mid;
  4674. }
  4675. else {
  4676. left = mid + 1;
  4677. }
  4678. }
  4679. var n = start - left;
  4680. switch (n) {
  4681. case 3:
  4682. array[left + 3] = array[left + 2];
  4683. case 2:
  4684. array[left + 2] = array[left + 1];
  4685. case 1:
  4686. array[left + 1] = array[left];
  4687. break;
  4688. default:
  4689. while (n > 0) {
  4690. array[left + n] = array[left + n - 1];
  4691. n--;
  4692. }
  4693. }
  4694. array[left] = pivot;
  4695. }
  4696. }
  4697. function gallopLeft(value, array, start, length, hint, compare) {
  4698. var lastOffset = 0;
  4699. var maxOffset = 0;
  4700. var offset = 1;
  4701. if (compare(value, array[start + hint]) > 0) {
  4702. maxOffset = length - hint;
  4703. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4704. lastOffset = offset;
  4705. offset = (offset << 1) + 1;
  4706. if (offset <= 0) {
  4707. offset = maxOffset;
  4708. }
  4709. }
  4710. if (offset > maxOffset) {
  4711. offset = maxOffset;
  4712. }
  4713. lastOffset += hint;
  4714. offset += hint;
  4715. }
  4716. else {
  4717. maxOffset = hint + 1;
  4718. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4719. lastOffset = offset;
  4720. offset = (offset << 1) + 1;
  4721. if (offset <= 0) {
  4722. offset = maxOffset;
  4723. }
  4724. }
  4725. if (offset > maxOffset) {
  4726. offset = maxOffset;
  4727. }
  4728. var tmp = lastOffset;
  4729. lastOffset = hint - offset;
  4730. offset = hint - tmp;
  4731. }
  4732. lastOffset++;
  4733. while (lastOffset < offset) {
  4734. var m = lastOffset + (offset - lastOffset >>> 1);
  4735. if (compare(value, array[start + m]) > 0) {
  4736. lastOffset = m + 1;
  4737. }
  4738. else {
  4739. offset = m;
  4740. }
  4741. }
  4742. return offset;
  4743. }
  4744. function gallopRight(value, array, start, length, hint, compare) {
  4745. var lastOffset = 0;
  4746. var maxOffset = 0;
  4747. var offset = 1;
  4748. if (compare(value, array[start + hint]) < 0) {
  4749. maxOffset = hint + 1;
  4750. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4751. lastOffset = offset;
  4752. offset = (offset << 1) + 1;
  4753. if (offset <= 0) {
  4754. offset = maxOffset;
  4755. }
  4756. }
  4757. if (offset > maxOffset) {
  4758. offset = maxOffset;
  4759. }
  4760. var tmp = lastOffset;
  4761. lastOffset = hint - offset;
  4762. offset = hint - tmp;
  4763. }
  4764. else {
  4765. maxOffset = length - hint;
  4766. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4767. lastOffset = offset;
  4768. offset = (offset << 1) + 1;
  4769. if (offset <= 0) {
  4770. offset = maxOffset;
  4771. }
  4772. }
  4773. if (offset > maxOffset) {
  4774. offset = maxOffset;
  4775. }
  4776. lastOffset += hint;
  4777. offset += hint;
  4778. }
  4779. lastOffset++;
  4780. while (lastOffset < offset) {
  4781. var m = lastOffset + (offset - lastOffset >>> 1);
  4782. if (compare(value, array[start + m]) < 0) {
  4783. offset = m;
  4784. }
  4785. else {
  4786. lastOffset = m + 1;
  4787. }
  4788. }
  4789. return offset;
  4790. }
  4791. function TimSort(array, compare) {
  4792. var minGallop = DEFAULT_MIN_GALLOPING;
  4793. var runStart;
  4794. var runLength;
  4795. var stackSize = 0;
  4796. var tmp = [];
  4797. runStart = [];
  4798. runLength = [];
  4799. function pushRun(_runStart, _runLength) {
  4800. runStart[stackSize] = _runStart;
  4801. runLength[stackSize] = _runLength;
  4802. stackSize += 1;
  4803. }
  4804. function mergeRuns() {
  4805. while (stackSize > 1) {
  4806. var n = stackSize - 2;
  4807. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4808. if (runLength[n - 1] < runLength[n + 1]) {
  4809. n--;
  4810. }
  4811. }
  4812. else if (runLength[n] > runLength[n + 1]) {
  4813. break;
  4814. }
  4815. mergeAt(n);
  4816. }
  4817. }
  4818. function forceMergeRuns() {
  4819. while (stackSize > 1) {
  4820. var n = stackSize - 2;
  4821. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4822. n--;
  4823. }
  4824. mergeAt(n);
  4825. }
  4826. }
  4827. function mergeAt(i) {
  4828. var start1 = runStart[i];
  4829. var length1 = runLength[i];
  4830. var start2 = runStart[i + 1];
  4831. var length2 = runLength[i + 1];
  4832. runLength[i] = length1 + length2;
  4833. if (i === stackSize - 3) {
  4834. runStart[i + 1] = runStart[i + 2];
  4835. runLength[i + 1] = runLength[i + 2];
  4836. }
  4837. stackSize--;
  4838. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4839. start1 += k;
  4840. length1 -= k;
  4841. if (length1 === 0) {
  4842. return;
  4843. }
  4844. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4845. if (length2 === 0) {
  4846. return;
  4847. }
  4848. if (length1 <= length2) {
  4849. mergeLow(start1, length1, start2, length2);
  4850. }
  4851. else {
  4852. mergeHigh(start1, length1, start2, length2);
  4853. }
  4854. }
  4855. function mergeLow(start1, length1, start2, length2) {
  4856. var i = 0;
  4857. for (i = 0; i < length1; i++) {
  4858. tmp[i] = array[start1 + i];
  4859. }
  4860. var cursor1 = 0;
  4861. var cursor2 = start2;
  4862. var dest = start1;
  4863. array[dest++] = array[cursor2++];
  4864. if (--length2 === 0) {
  4865. for (i = 0; i < length1; i++) {
  4866. array[dest + i] = tmp[cursor1 + i];
  4867. }
  4868. return;
  4869. }
  4870. if (length1 === 1) {
  4871. for (i = 0; i < length2; i++) {
  4872. array[dest + i] = array[cursor2 + i];
  4873. }
  4874. array[dest + length2] = tmp[cursor1];
  4875. return;
  4876. }
  4877. var _minGallop = minGallop;
  4878. var count1, count2, exit;
  4879. while (1) {
  4880. count1 = 0;
  4881. count2 = 0;
  4882. exit = false;
  4883. do {
  4884. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4885. array[dest++] = array[cursor2++];
  4886. count2++;
  4887. count1 = 0;
  4888. if (--length2 === 0) {
  4889. exit = true;
  4890. break;
  4891. }
  4892. }
  4893. else {
  4894. array[dest++] = tmp[cursor1++];
  4895. count1++;
  4896. count2 = 0;
  4897. if (--length1 === 1) {
  4898. exit = true;
  4899. break;
  4900. }
  4901. }
  4902. } while ((count1 | count2) < _minGallop);
  4903. if (exit) {
  4904. break;
  4905. }
  4906. do {
  4907. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4908. if (count1 !== 0) {
  4909. for (i = 0; i < count1; i++) {
  4910. array[dest + i] = tmp[cursor1 + i];
  4911. }
  4912. dest += count1;
  4913. cursor1 += count1;
  4914. length1 -= count1;
  4915. if (length1 <= 1) {
  4916. exit = true;
  4917. break;
  4918. }
  4919. }
  4920. array[dest++] = array[cursor2++];
  4921. if (--length2 === 0) {
  4922. exit = true;
  4923. break;
  4924. }
  4925. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4926. if (count2 !== 0) {
  4927. for (i = 0; i < count2; i++) {
  4928. array[dest + i] = array[cursor2 + i];
  4929. }
  4930. dest += count2;
  4931. cursor2 += count2;
  4932. length2 -= count2;
  4933. if (length2 === 0) {
  4934. exit = true;
  4935. break;
  4936. }
  4937. }
  4938. array[dest++] = tmp[cursor1++];
  4939. if (--length1 === 1) {
  4940. exit = true;
  4941. break;
  4942. }
  4943. _minGallop--;
  4944. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4945. if (exit) {
  4946. break;
  4947. }
  4948. if (_minGallop < 0) {
  4949. _minGallop = 0;
  4950. }
  4951. _minGallop += 2;
  4952. }
  4953. minGallop = _minGallop;
  4954. minGallop < 1 && (minGallop = 1);
  4955. if (length1 === 1) {
  4956. for (i = 0; i < length2; i++) {
  4957. array[dest + i] = array[cursor2 + i];
  4958. }
  4959. array[dest + length2] = tmp[cursor1];
  4960. }
  4961. else if (length1 === 0) {
  4962. throw new Error();
  4963. // throw new Error('mergeLow preconditions were not respected');
  4964. }
  4965. else {
  4966. for (i = 0; i < length1; i++) {
  4967. array[dest + i] = tmp[cursor1 + i];
  4968. }
  4969. }
  4970. }
  4971. function mergeHigh (start1, length1, start2, length2) {
  4972. var i = 0;
  4973. for (i = 0; i < length2; i++) {
  4974. tmp[i] = array[start2 + i];
  4975. }
  4976. var cursor1 = start1 + length1 - 1;
  4977. var cursor2 = length2 - 1;
  4978. var dest = start2 + length2 - 1;
  4979. var customCursor = 0;
  4980. var customDest = 0;
  4981. array[dest--] = array[cursor1--];
  4982. if (--length1 === 0) {
  4983. customCursor = dest - (length2 - 1);
  4984. for (i = 0; i < length2; i++) {
  4985. array[customCursor + i] = tmp[i];
  4986. }
  4987. return;
  4988. }
  4989. if (length2 === 1) {
  4990. dest -= length1;
  4991. cursor1 -= length1;
  4992. customDest = dest + 1;
  4993. customCursor = cursor1 + 1;
  4994. for (i = length1 - 1; i >= 0; i--) {
  4995. array[customDest + i] = array[customCursor + i];
  4996. }
  4997. array[dest] = tmp[cursor2];
  4998. return;
  4999. }
  5000. var _minGallop = minGallop;
  5001. while (true) {
  5002. var count1 = 0;
  5003. var count2 = 0;
  5004. var exit = false;
  5005. do {
  5006. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5007. array[dest--] = array[cursor1--];
  5008. count1++;
  5009. count2 = 0;
  5010. if (--length1 === 0) {
  5011. exit = true;
  5012. break;
  5013. }
  5014. }
  5015. else {
  5016. array[dest--] = tmp[cursor2--];
  5017. count2++;
  5018. count1 = 0;
  5019. if (--length2 === 1) {
  5020. exit = true;
  5021. break;
  5022. }
  5023. }
  5024. } while ((count1 | count2) < _minGallop);
  5025. if (exit) {
  5026. break;
  5027. }
  5028. do {
  5029. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5030. if (count1 !== 0) {
  5031. dest -= count1;
  5032. cursor1 -= count1;
  5033. length1 -= count1;
  5034. customDest = dest + 1;
  5035. customCursor = cursor1 + 1;
  5036. for (i = count1 - 1; i >= 0; i--) {
  5037. array[customDest + i] = array[customCursor + i];
  5038. }
  5039. if (length1 === 0) {
  5040. exit = true;
  5041. break;
  5042. }
  5043. }
  5044. array[dest--] = tmp[cursor2--];
  5045. if (--length2 === 1) {
  5046. exit = true;
  5047. break;
  5048. }
  5049. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5050. if (count2 !== 0) {
  5051. dest -= count2;
  5052. cursor2 -= count2;
  5053. length2 -= count2;
  5054. customDest = dest + 1;
  5055. customCursor = cursor2 + 1;
  5056. for (i = 0; i < count2; i++) {
  5057. array[customDest + i] = tmp[customCursor + i];
  5058. }
  5059. if (length2 <= 1) {
  5060. exit = true;
  5061. break;
  5062. }
  5063. }
  5064. array[dest--] = array[cursor1--];
  5065. if (--length1 === 0) {
  5066. exit = true;
  5067. break;
  5068. }
  5069. _minGallop--;
  5070. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5071. if (exit) {
  5072. break;
  5073. }
  5074. if (_minGallop < 0) {
  5075. _minGallop = 0;
  5076. }
  5077. _minGallop += 2;
  5078. }
  5079. minGallop = _minGallop;
  5080. if (minGallop < 1) {
  5081. minGallop = 1;
  5082. }
  5083. if (length2 === 1) {
  5084. dest -= length1;
  5085. cursor1 -= length1;
  5086. customDest = dest + 1;
  5087. customCursor = cursor1 + 1;
  5088. for (i = length1 - 1; i >= 0; i--) {
  5089. array[customDest + i] = array[customCursor + i];
  5090. }
  5091. array[dest] = tmp[cursor2];
  5092. }
  5093. else if (length2 === 0) {
  5094. throw new Error();
  5095. // throw new Error('mergeHigh preconditions were not respected');
  5096. }
  5097. else {
  5098. customCursor = dest - (length2 - 1);
  5099. for (i = 0; i < length2; i++) {
  5100. array[customCursor + i] = tmp[i];
  5101. }
  5102. }
  5103. }
  5104. this.mergeRuns = mergeRuns;
  5105. this.forceMergeRuns = forceMergeRuns;
  5106. this.pushRun = pushRun;
  5107. }
  5108. function sort(array, compare, lo, hi) {
  5109. if (!lo) {
  5110. lo = 0;
  5111. }
  5112. if (!hi) {
  5113. hi = array.length;
  5114. }
  5115. var remaining = hi - lo;
  5116. if (remaining < 2) {
  5117. return;
  5118. }
  5119. var runLength = 0;
  5120. if (remaining < DEFAULT_MIN_MERGE) {
  5121. runLength = makeAscendingRun(array, lo, hi, compare);
  5122. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5123. return;
  5124. }
  5125. var ts = new TimSort(array, compare);
  5126. var minRun = minRunLength(remaining);
  5127. do {
  5128. runLength = makeAscendingRun(array, lo, hi, compare);
  5129. if (runLength < minRun) {
  5130. var force = remaining;
  5131. if (force > minRun) {
  5132. force = minRun;
  5133. }
  5134. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5135. runLength = force;
  5136. }
  5137. ts.pushRun(lo, runLength);
  5138. ts.mergeRuns();
  5139. remaining -= runLength;
  5140. lo += runLength;
  5141. } while (remaining !== 0);
  5142. ts.forceMergeRuns();
  5143. }
  5144. // Use timsort because in most case elements are partially sorted
  5145. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5146. function shapeCompareFunc(a, b) {
  5147. if (a.zlevel === b.zlevel) {
  5148. if (a.z === b.z) {
  5149. // if (a.z2 === b.z2) {
  5150. // // FIXME Slow has renderidx compare
  5151. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5152. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5153. // return a.__renderidx - b.__renderidx;
  5154. // }
  5155. return a.z2 - b.z2;
  5156. }
  5157. return a.z - b.z;
  5158. }
  5159. return a.zlevel - b.zlevel;
  5160. }
  5161. /**
  5162. * 内容仓库 (M)
  5163. * @alias module:zrender/Storage
  5164. * @constructor
  5165. */
  5166. var Storage = function () { // jshint ignore:line
  5167. this._roots = [];
  5168. this._displayList = [];
  5169. this._displayListLen = 0;
  5170. };
  5171. Storage.prototype = {
  5172. constructor: Storage,
  5173. /**
  5174. * @param {Function} cb
  5175. *
  5176. */
  5177. traverse: function (cb, context) {
  5178. for (var i = 0; i < this._roots.length; i++) {
  5179. this._roots[i].traverse(cb, context);
  5180. }
  5181. },
  5182. /**
  5183. * 返回所有图形的绘制队列
  5184. * @param {boolean} [update=false] 是否在返回前更新该数组
  5185. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5186. *
  5187. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5188. * @return {Array.<module:zrender/graphic/Displayable>}
  5189. */
  5190. getDisplayList: function (update, includeIgnore) {
  5191. includeIgnore = includeIgnore || false;
  5192. if (update) {
  5193. this.updateDisplayList(includeIgnore);
  5194. }
  5195. return this._displayList;
  5196. },
  5197. /**
  5198. * 更新图形的绘制队列。
  5199. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5200. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5201. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5202. */
  5203. updateDisplayList: function (includeIgnore) {
  5204. this._displayListLen = 0;
  5205. var roots = this._roots;
  5206. var displayList = this._displayList;
  5207. for (var i = 0, len = roots.length; i < len; i++) {
  5208. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5209. }
  5210. displayList.length = this._displayListLen;
  5211. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5212. },
  5213. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5214. if (el.ignore && !includeIgnore) {
  5215. return;
  5216. }
  5217. el.beforeUpdate();
  5218. if (el.__dirty) {
  5219. el.update();
  5220. }
  5221. el.afterUpdate();
  5222. var userSetClipPath = el.clipPath;
  5223. if (userSetClipPath) {
  5224. // FIXME 效率影响
  5225. if (clipPaths) {
  5226. clipPaths = clipPaths.slice();
  5227. }
  5228. else {
  5229. clipPaths = [];
  5230. }
  5231. var currentClipPath = userSetClipPath;
  5232. var parentClipPath = el;
  5233. // Recursively add clip path
  5234. while (currentClipPath) {
  5235. // clipPath 的变换是基于使用这个 clipPath 的元素
  5236. currentClipPath.parent = parentClipPath;
  5237. currentClipPath.updateTransform();
  5238. clipPaths.push(currentClipPath);
  5239. parentClipPath = currentClipPath;
  5240. currentClipPath = currentClipPath.clipPath;
  5241. }
  5242. }
  5243. if (el.isGroup) {
  5244. var children = el._children;
  5245. for (var i = 0; i < children.length; i++) {
  5246. var child = children[i];
  5247. // Force to mark as dirty if group is dirty
  5248. // FIXME __dirtyPath ?
  5249. if (el.__dirty) {
  5250. child.__dirty = true;
  5251. }
  5252. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5253. }
  5254. // Mark group clean here
  5255. el.__dirty = false;
  5256. }
  5257. else {
  5258. el.__clipPaths = clipPaths;
  5259. this._displayList[this._displayListLen++] = el;
  5260. }
  5261. },
  5262. /**
  5263. * 添加图形(Shape)或者组(Group)到根节点
  5264. * @param {module:zrender/Element} el
  5265. */
  5266. addRoot: function (el) {
  5267. if (el.__storage === this) {
  5268. return;
  5269. }
  5270. if (el instanceof Group) {
  5271. el.addChildrenToStorage(this);
  5272. }
  5273. this.addToStorage(el);
  5274. this._roots.push(el);
  5275. },
  5276. /**
  5277. * 删除指定的图形(Shape)或者组(Group)
  5278. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5279. */
  5280. delRoot: function (el) {
  5281. if (el == null) {
  5282. // 不指定el清空
  5283. for (var i = 0; i < this._roots.length; i++) {
  5284. var root = this._roots[i];
  5285. if (root instanceof Group) {
  5286. root.delChildrenFromStorage(this);
  5287. }
  5288. }
  5289. this._roots = [];
  5290. this._displayList = [];
  5291. this._displayListLen = 0;
  5292. return;
  5293. }
  5294. if (el instanceof Array) {
  5295. for (var i = 0, l = el.length; i < l; i++) {
  5296. this.delRoot(el[i]);
  5297. }
  5298. return;
  5299. }
  5300. var idx = indexOf(this._roots, el);
  5301. if (idx >= 0) {
  5302. this.delFromStorage(el);
  5303. this._roots.splice(idx, 1);
  5304. if (el instanceof Group) {
  5305. el.delChildrenFromStorage(this);
  5306. }
  5307. }
  5308. },
  5309. addToStorage: function (el) {
  5310. if (el) {
  5311. el.__storage = this;
  5312. el.dirty(false);
  5313. }
  5314. return this;
  5315. },
  5316. delFromStorage: function (el) {
  5317. if (el) {
  5318. el.__storage = null;
  5319. }
  5320. return this;
  5321. },
  5322. /**
  5323. * 清空并且释放Storage
  5324. */
  5325. dispose: function () {
  5326. this._renderList =
  5327. this._roots = null;
  5328. },
  5329. displayableSortFunc: shapeCompareFunc
  5330. };
  5331. var SHADOW_PROPS = {
  5332. 'shadowBlur': 1,
  5333. 'shadowOffsetX': 1,
  5334. 'shadowOffsetY': 1,
  5335. 'textShadowBlur': 1,
  5336. 'textShadowOffsetX': 1,
  5337. 'textShadowOffsetY': 1,
  5338. 'textBoxShadowBlur': 1,
  5339. 'textBoxShadowOffsetX': 1,
  5340. 'textBoxShadowOffsetY': 1
  5341. };
  5342. var fixShadow = function (ctx, propName, value) {
  5343. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5344. return value *= ctx.dpr;
  5345. }
  5346. return value;
  5347. };
  5348. var STYLE_COMMON_PROPS = [
  5349. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5350. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5351. ];
  5352. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5353. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5354. var Style = function (opts, host) {
  5355. this.extendFrom(opts, false);
  5356. this.host = host;
  5357. };
  5358. function createLinearGradient(ctx, obj, rect) {
  5359. var x = obj.x == null ? 0 : obj.x;
  5360. var x2 = obj.x2 == null ? 1 : obj.x2;
  5361. var y = obj.y == null ? 0 : obj.y;
  5362. var y2 = obj.y2 == null ? 0 : obj.y2;
  5363. if (!obj.global) {
  5364. x = x * rect.width + rect.x;
  5365. x2 = x2 * rect.width + rect.x;
  5366. y = y * rect.height + rect.y;
  5367. y2 = y2 * rect.height + rect.y;
  5368. }
  5369. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5370. return canvasGradient;
  5371. }
  5372. function createRadialGradient(ctx, obj, rect) {
  5373. var width = rect.width;
  5374. var height = rect.height;
  5375. var min = Math.min(width, height);
  5376. var x = obj.x == null ? 0.5 : obj.x;
  5377. var y = obj.y == null ? 0.5 : obj.y;
  5378. var r = obj.r == null ? 0.5 : obj.r;
  5379. if (!obj.global) {
  5380. x = x * width + rect.x;
  5381. y = y * height + rect.y;
  5382. r = r * min;
  5383. }
  5384. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5385. return canvasGradient;
  5386. }
  5387. Style.prototype = {
  5388. constructor: Style,
  5389. /**
  5390. * @type {module:zrender/graphic/Displayable}
  5391. */
  5392. host: null,
  5393. /**
  5394. * @type {string}
  5395. */
  5396. fill: '#000',
  5397. /**
  5398. * @type {string}
  5399. */
  5400. stroke: null,
  5401. /**
  5402. * @type {number}
  5403. */
  5404. opacity: 1,
  5405. /**
  5406. * @type {Array.<number>}
  5407. */
  5408. lineDash: null,
  5409. /**
  5410. * @type {number}
  5411. */
  5412. lineDashOffset: 0,
  5413. /**
  5414. * @type {number}
  5415. */
  5416. shadowBlur: 0,
  5417. /**
  5418. * @type {number}
  5419. */
  5420. shadowOffsetX: 0,
  5421. /**
  5422. * @type {number}
  5423. */
  5424. shadowOffsetY: 0,
  5425. /**
  5426. * @type {number}
  5427. */
  5428. lineWidth: 1,
  5429. /**
  5430. * If stroke ignore scale
  5431. * @type {Boolean}
  5432. */
  5433. strokeNoScale: false,
  5434. // Bounding rect text configuration
  5435. // Not affected by element transform
  5436. /**
  5437. * @type {string}
  5438. */
  5439. text: null,
  5440. /**
  5441. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5442. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5443. * So do not visit it directly in upper application (like echarts),
  5444. * but use `contain/text#makeFont` instead.
  5445. * @type {string}
  5446. */
  5447. font: null,
  5448. /**
  5449. * The same as font. Use font please.
  5450. * @deprecated
  5451. * @type {string}
  5452. */
  5453. textFont: null,
  5454. /**
  5455. * It helps merging respectively, rather than parsing an entire font string.
  5456. * @type {string}
  5457. */
  5458. fontStyle: null,
  5459. /**
  5460. * It helps merging respectively, rather than parsing an entire font string.
  5461. * @type {string}
  5462. */
  5463. fontWeight: null,
  5464. /**
  5465. * It helps merging respectively, rather than parsing an entire font string.
  5466. * Should be 12 but not '12px'.
  5467. * @type {number}
  5468. */
  5469. fontSize: null,
  5470. /**
  5471. * It helps merging respectively, rather than parsing an entire font string.
  5472. * @type {string}
  5473. */
  5474. fontFamily: null,
  5475. /**
  5476. * Reserved for special functinality, like 'hr'.
  5477. * @type {string}
  5478. */
  5479. textTag: null,
  5480. /**
  5481. * @type {string}
  5482. */
  5483. textFill: '#000',
  5484. /**
  5485. * @type {string}
  5486. */
  5487. textStroke: null,
  5488. /**
  5489. * @type {number}
  5490. */
  5491. textWidth: null,
  5492. /**
  5493. * Only for textBackground.
  5494. * @type {number}
  5495. */
  5496. textHeight: null,
  5497. /**
  5498. * textStroke may be set as some color as a default
  5499. * value in upper applicaion, where the default value
  5500. * of textStrokeWidth should be 0 to make sure that
  5501. * user can choose to do not use text stroke.
  5502. * @type {number}
  5503. */
  5504. textStrokeWidth: 0,
  5505. /**
  5506. * @type {number}
  5507. */
  5508. textLineHeight: null,
  5509. /**
  5510. * 'inside', 'left', 'right', 'top', 'bottom'
  5511. * [x, y]
  5512. * Based on x, y of rect.
  5513. * @type {string|Array.<number>}
  5514. * @default 'inside'
  5515. */
  5516. textPosition: 'inside',
  5517. /**
  5518. * If not specified, use the boundingRect of a `displayable`.
  5519. * @type {Object}
  5520. */
  5521. textRect: null,
  5522. /**
  5523. * [x, y]
  5524. * @type {Array.<number>}
  5525. */
  5526. textOffset: null,
  5527. /**
  5528. * @type {string}
  5529. */
  5530. textAlign: null,
  5531. /**
  5532. * @type {string}
  5533. */
  5534. textVerticalAlign: null,
  5535. /**
  5536. * @type {number}
  5537. */
  5538. textDistance: 5,
  5539. /**
  5540. * @type {string}
  5541. */
  5542. textShadowColor: 'transparent',
  5543. /**
  5544. * @type {number}
  5545. */
  5546. textShadowBlur: 0,
  5547. /**
  5548. * @type {number}
  5549. */
  5550. textShadowOffsetX: 0,
  5551. /**
  5552. * @type {number}
  5553. */
  5554. textShadowOffsetY: 0,
  5555. /**
  5556. * @type {string}
  5557. */
  5558. textBoxShadowColor: 'transparent',
  5559. /**
  5560. * @type {number}
  5561. */
  5562. textBoxShadowBlur: 0,
  5563. /**
  5564. * @type {number}
  5565. */
  5566. textBoxShadowOffsetX: 0,
  5567. /**
  5568. * @type {number}
  5569. */
  5570. textBoxShadowOffsetY: 0,
  5571. /**
  5572. * Whether transform text.
  5573. * Only useful in Path and Image element
  5574. * @type {boolean}
  5575. */
  5576. transformText: false,
  5577. /**
  5578. * Text rotate around position of Path or Image
  5579. * Only useful in Path and Image element and transformText is false.
  5580. */
  5581. textRotation: 0,
  5582. /**
  5583. * Text origin of text rotation, like [10, 40].
  5584. * Based on x, y of rect.
  5585. * Useful in label rotation of circular symbol.
  5586. * By default, this origin is textPosition.
  5587. * Can be 'center'.
  5588. * @type {string|Array.<number>}
  5589. */
  5590. textOrigin: null,
  5591. /**
  5592. * @type {string}
  5593. */
  5594. textBackgroundColor: null,
  5595. /**
  5596. * @type {string}
  5597. */
  5598. textBorderColor: null,
  5599. /**
  5600. * @type {number}
  5601. */
  5602. textBorderWidth: 0,
  5603. /**
  5604. * @type {number}
  5605. */
  5606. textBorderRadius: 0,
  5607. /**
  5608. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5609. * @type {number|Array.<number>}
  5610. */
  5611. textPadding: null,
  5612. /**
  5613. * Text styles for rich text.
  5614. * @type {Object}
  5615. */
  5616. rich: null,
  5617. /**
  5618. * {outerWidth, outerHeight, ellipsis, placeholder}
  5619. * @type {Object}
  5620. */
  5621. truncate: null,
  5622. /**
  5623. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5624. * @type {string}
  5625. */
  5626. blend: null,
  5627. /**
  5628. * @param {CanvasRenderingContext2D} ctx
  5629. */
  5630. bind: function (ctx, el, prevEl) {
  5631. var style = this;
  5632. var prevStyle = prevEl && prevEl.style;
  5633. var firstDraw = !prevStyle;
  5634. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5635. var prop = STYLE_COMMON_PROPS[i];
  5636. var styleName = prop[0];
  5637. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5638. // FIXME Invalid property value will cause style leak from previous element.
  5639. ctx[styleName] =
  5640. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5641. }
  5642. }
  5643. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5644. ctx.fillStyle = style.fill;
  5645. }
  5646. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5647. ctx.strokeStyle = style.stroke;
  5648. }
  5649. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5650. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5651. }
  5652. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5653. ctx.globalCompositeOperation = style.blend || 'source-over';
  5654. }
  5655. if (this.hasStroke()) {
  5656. var lineWidth = style.lineWidth;
  5657. ctx.lineWidth = lineWidth / (
  5658. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5659. );
  5660. }
  5661. },
  5662. hasFill: function () {
  5663. var fill = this.fill;
  5664. return fill != null && fill !== 'none';
  5665. },
  5666. hasStroke: function () {
  5667. var stroke = this.stroke;
  5668. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5669. },
  5670. /**
  5671. * Extend from other style
  5672. * @param {zrender/graphic/Style} otherStyle
  5673. * @param {boolean} overwrite true: overwrirte any way.
  5674. * false: overwrite only when !target.hasOwnProperty
  5675. * others: overwrite when property is not null/undefined.
  5676. */
  5677. extendFrom: function (otherStyle, overwrite) {
  5678. if (otherStyle) {
  5679. for (var name in otherStyle) {
  5680. if (otherStyle.hasOwnProperty(name)
  5681. && (overwrite === true
  5682. || (
  5683. overwrite === false
  5684. ? !this.hasOwnProperty(name)
  5685. : otherStyle[name] != null
  5686. )
  5687. )
  5688. ) {
  5689. this[name] = otherStyle[name];
  5690. }
  5691. }
  5692. }
  5693. },
  5694. /**
  5695. * Batch setting style with a given object
  5696. * @param {Object|string} obj
  5697. * @param {*} [obj]
  5698. */
  5699. set: function (obj, value) {
  5700. if (typeof obj === 'string') {
  5701. this[obj] = value;
  5702. }
  5703. else {
  5704. this.extendFrom(obj, true);
  5705. }
  5706. },
  5707. /**
  5708. * Clone
  5709. * @return {zrender/graphic/Style} [description]
  5710. */
  5711. clone: function () {
  5712. var newStyle = new this.constructor();
  5713. newStyle.extendFrom(this, true);
  5714. return newStyle;
  5715. },
  5716. getGradient: function (ctx, obj, rect) {
  5717. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5718. var canvasGradient = method(ctx, obj, rect);
  5719. var colorStops = obj.colorStops;
  5720. for (var i = 0; i < colorStops.length; i++) {
  5721. canvasGradient.addColorStop(
  5722. colorStops[i].offset, colorStops[i].color
  5723. );
  5724. }
  5725. return canvasGradient;
  5726. }
  5727. };
  5728. var styleProto = Style.prototype;
  5729. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5730. var prop = STYLE_COMMON_PROPS[i];
  5731. if (!(prop[0] in styleProto)) {
  5732. styleProto[prop[0]] = prop[1];
  5733. }
  5734. }
  5735. // Provide for others
  5736. Style.getGradient = styleProto.getGradient;
  5737. var Pattern = function (image, repeat) {
  5738. // Should do nothing more in this constructor. Because gradient can be
  5739. // declard by `color: {image: ...}`, where this constructor will not be called.
  5740. this.image = image;
  5741. this.repeat = repeat;
  5742. // Can be cloned
  5743. this.type = 'pattern';
  5744. };
  5745. Pattern.prototype.getCanvasPattern = function (ctx) {
  5746. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5747. };
  5748. /**
  5749. * @module zrender/Layer
  5750. * @author pissang(https://www.github.com/pissang)
  5751. */
  5752. function returnFalse() {
  5753. return false;
  5754. }
  5755. /**
  5756. * 创建dom
  5757. *
  5758. * @inner
  5759. * @param {string} id dom id 待用
  5760. * @param {Painter} painter painter instance
  5761. * @param {number} number
  5762. */
  5763. function createDom(id, painter, dpr) {
  5764. var newDom = createCanvas();
  5765. var width = painter.getWidth();
  5766. var height = painter.getHeight();
  5767. var newDomStyle = newDom.style;
  5768. if (newDomStyle) { // In node or some other non-browser environment
  5769. newDomStyle.position = 'absolute';
  5770. newDomStyle.left = 0;
  5771. newDomStyle.top = 0;
  5772. newDomStyle.width = width + 'px';
  5773. newDomStyle.height = height + 'px';
  5774. newDom.setAttribute('data-zr-dom-id', id);
  5775. }
  5776. newDom.width = width * dpr;
  5777. newDom.height = height * dpr;
  5778. return newDom;
  5779. }
  5780. /**
  5781. * @alias module:zrender/Layer
  5782. * @constructor
  5783. * @extends module:zrender/mixin/Transformable
  5784. * @param {string} id
  5785. * @param {module:zrender/Painter} painter
  5786. * @param {number} [dpr]
  5787. */
  5788. var Layer = function(id, painter, dpr) {
  5789. var dom;
  5790. dpr = dpr || devicePixelRatio;
  5791. if (typeof id === 'string') {
  5792. dom = createDom(id, painter, dpr);
  5793. }
  5794. // Not using isDom because in node it will return false
  5795. else if (isObject$1(id)) {
  5796. dom = id;
  5797. id = dom.id;
  5798. }
  5799. this.id = id;
  5800. this.dom = dom;
  5801. var domStyle = dom.style;
  5802. if (domStyle) { // Not in node
  5803. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5804. domStyle['-webkit-user-select'] = 'none';
  5805. domStyle['user-select'] = 'none';
  5806. domStyle['-webkit-touch-callout'] = 'none';
  5807. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5808. domStyle['padding'] = 0;
  5809. domStyle['margin'] = 0;
  5810. domStyle['border-width'] = 0;
  5811. }
  5812. this.domBack = null;
  5813. this.ctxBack = null;
  5814. this.painter = painter;
  5815. this.config = null;
  5816. // Configs
  5817. /**
  5818. * 每次清空画布的颜色
  5819. * @type {string}
  5820. * @default 0
  5821. */
  5822. this.clearColor = 0;
  5823. /**
  5824. * 是否开启动态模糊
  5825. * @type {boolean}
  5826. * @default false
  5827. */
  5828. this.motionBlur = false;
  5829. /**
  5830. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5831. * @type {number}
  5832. * @default 0.7
  5833. */
  5834. this.lastFrameAlpha = 0.7;
  5835. /**
  5836. * Layer dpr
  5837. * @type {number}
  5838. */
  5839. this.dpr = dpr;
  5840. };
  5841. Layer.prototype = {
  5842. constructor: Layer,
  5843. __dirty: true,
  5844. __used: false,
  5845. __drawIndex: 0,
  5846. __startIndex: 0,
  5847. __endIndex: 0,
  5848. incremental: false,
  5849. getElementCount: function () {
  5850. return this.__endIndex - this.__startIndex;
  5851. },
  5852. initContext: function () {
  5853. this.ctx = this.dom.getContext('2d');
  5854. this.ctx.dpr = this.dpr;
  5855. },
  5856. createBackBuffer: function () {
  5857. var dpr = this.dpr;
  5858. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5859. this.ctxBack = this.domBack.getContext('2d');
  5860. if (dpr != 1) {
  5861. this.ctxBack.scale(dpr, dpr);
  5862. }
  5863. },
  5864. /**
  5865. * @param {number} width
  5866. * @param {number} height
  5867. */
  5868. resize: function (width, height) {
  5869. var dpr = this.dpr;
  5870. var dom = this.dom;
  5871. var domStyle = dom.style;
  5872. var domBack = this.domBack;
  5873. domStyle.width = width + 'px';
  5874. domStyle.height = height + 'px';
  5875. dom.width = width * dpr;
  5876. dom.height = height * dpr;
  5877. if (domBack) {
  5878. domBack.width = width * dpr;
  5879. domBack.height = height * dpr;
  5880. if (dpr != 1) {
  5881. this.ctxBack.scale(dpr, dpr);
  5882. }
  5883. }
  5884. },
  5885. /**
  5886. * 清空该层画布
  5887. * @param {boolean} clearAll Clear all with out motion blur
  5888. */
  5889. clear: function (clearAll) {
  5890. var dom = this.dom;
  5891. var ctx = this.ctx;
  5892. var width = dom.width;
  5893. var height = dom.height;
  5894. var clearColor = this.clearColor;
  5895. var haveMotionBLur = this.motionBlur && !clearAll;
  5896. var lastFrameAlpha = this.lastFrameAlpha;
  5897. var dpr = this.dpr;
  5898. if (haveMotionBLur) {
  5899. if (!this.domBack) {
  5900. this.createBackBuffer();
  5901. }
  5902. this.ctxBack.globalCompositeOperation = 'copy';
  5903. this.ctxBack.drawImage(
  5904. dom, 0, 0,
  5905. width / dpr,
  5906. height / dpr
  5907. );
  5908. }
  5909. ctx.clearRect(0, 0, width, height);
  5910. if (clearColor) {
  5911. var clearColorGradientOrPattern;
  5912. // Gradient
  5913. if (clearColor.colorStops) {
  5914. // Cache canvas gradient
  5915. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5916. x: 0,
  5917. y: 0,
  5918. width: width,
  5919. height: height
  5920. });
  5921. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5922. }
  5923. // Pattern
  5924. else if (clearColor.image) {
  5925. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5926. }
  5927. ctx.save();
  5928. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5929. ctx.fillRect(0, 0, width, height);
  5930. ctx.restore();
  5931. }
  5932. if (haveMotionBLur) {
  5933. var domBack = this.domBack;
  5934. ctx.save();
  5935. ctx.globalAlpha = lastFrameAlpha;
  5936. ctx.drawImage(domBack, 0, 0, width, height);
  5937. ctx.restore();
  5938. }
  5939. }
  5940. };
  5941. var requestAnimationFrame = (
  5942. typeof window !== 'undefined'
  5943. && (
  5944. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5945. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5946. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5947. || window.mozRequestAnimationFrame
  5948. || window.webkitRequestAnimationFrame
  5949. )
  5950. ) || function (func) {
  5951. setTimeout(func, 16);
  5952. };
  5953. var globalImageCache = new LRU(50);
  5954. /**
  5955. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5956. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5957. */
  5958. function findExistImage(newImageOrSrc) {
  5959. if (typeof newImageOrSrc === 'string') {
  5960. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5961. return cachedImgObj && cachedImgObj.image;
  5962. }
  5963. else {
  5964. return newImageOrSrc;
  5965. }
  5966. }
  5967. /**
  5968. * Caution: User should cache loaded images, but not just count on LRU.
  5969. * Consider if required images more than LRU size, will dead loop occur?
  5970. *
  5971. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5972. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  5973. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  5974. * @param {Function} [cb] params: (image, cbPayload)
  5975. * @param {Object} [cbPayload] Payload on cb calling.
  5976. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5977. */
  5978. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  5979. if (!newImageOrSrc) {
  5980. return image;
  5981. }
  5982. else if (typeof newImageOrSrc === 'string') {
  5983. // Image should not be loaded repeatly.
  5984. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  5985. return image;
  5986. }
  5987. // Only when there is no existent image or existent image src
  5988. // is different, this method is responsible for load.
  5989. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5990. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  5991. if (cachedImgObj) {
  5992. image = cachedImgObj.image;
  5993. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  5994. }
  5995. else {
  5996. !image && (image = new Image());
  5997. image.onload = imageOnLoad;
  5998. globalImageCache.put(
  5999. newImageOrSrc,
  6000. image.__cachedImgObj = {
  6001. image: image,
  6002. pending: [pendingWrap]
  6003. }
  6004. );
  6005. image.src = image.__zrImageSrc = newImageOrSrc;
  6006. }
  6007. return image;
  6008. }
  6009. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6010. else {
  6011. return newImageOrSrc;
  6012. }
  6013. }
  6014. function imageOnLoad() {
  6015. var cachedImgObj = this.__cachedImgObj;
  6016. this.onload = this.__cachedImgObj = null;
  6017. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6018. var pendingWrap = cachedImgObj.pending[i];
  6019. var cb = pendingWrap.cb;
  6020. cb && cb(this, pendingWrap.cbPayload);
  6021. pendingWrap.hostEl.dirty();
  6022. }
  6023. cachedImgObj.pending.length = 0;
  6024. }
  6025. function isImageReady(image) {
  6026. return image && image.width && image.height;
  6027. }
  6028. var textWidthCache = {};
  6029. var textWidthCacheCounter = 0;
  6030. var TEXT_CACHE_MAX = 5000;
  6031. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6032. var DEFAULT_FONT = '12px sans-serif';
  6033. // Avoid assign to an exported variable, for transforming to cjs.
  6034. var methods$1 = {};
  6035. function $override$1(name, fn) {
  6036. methods$1[name] = fn;
  6037. }
  6038. /**
  6039. * @public
  6040. * @param {string} text
  6041. * @param {string} font
  6042. * @return {number} width
  6043. */
  6044. function getWidth(text, font) {
  6045. font = font || DEFAULT_FONT;
  6046. var key = text + ':' + font;
  6047. if (textWidthCache[key]) {
  6048. return textWidthCache[key];
  6049. }
  6050. var textLines = (text + '').split('\n');
  6051. var width = 0;
  6052. for (var i = 0, l = textLines.length; i < l; i++) {
  6053. // textContain.measureText may be overrided in SVG or VML
  6054. width = Math.max(measureText(textLines[i], font).width, width);
  6055. }
  6056. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6057. textWidthCacheCounter = 0;
  6058. textWidthCache = {};
  6059. }
  6060. textWidthCacheCounter++;
  6061. textWidthCache[key] = width;
  6062. return width;
  6063. }
  6064. /**
  6065. * @public
  6066. * @param {string} text
  6067. * @param {string} font
  6068. * @param {string} [textAlign='left']
  6069. * @param {string} [textVerticalAlign='top']
  6070. * @param {Array.<number>} [textPadding]
  6071. * @param {Object} [rich]
  6072. * @param {Object} [truncate]
  6073. * @return {Object} {x, y, width, height, lineHeight}
  6074. */
  6075. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6076. return rich
  6077. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6078. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6079. }
  6080. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6081. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6082. var outerWidth = getWidth(text, font);
  6083. if (textPadding) {
  6084. outerWidth += textPadding[1] + textPadding[3];
  6085. }
  6086. var outerHeight = contentBlock.outerHeight;
  6087. var x = adjustTextX(0, outerWidth, textAlign);
  6088. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6089. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6090. rect.lineHeight = contentBlock.lineHeight;
  6091. return rect;
  6092. }
  6093. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6094. var contentBlock = parseRichText(text, {
  6095. rich: rich,
  6096. truncate: truncate,
  6097. font: font,
  6098. textAlign: textAlign,
  6099. textPadding: textPadding
  6100. });
  6101. var outerWidth = contentBlock.outerWidth;
  6102. var outerHeight = contentBlock.outerHeight;
  6103. var x = adjustTextX(0, outerWidth, textAlign);
  6104. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6105. return new BoundingRect(x, y, outerWidth, outerHeight);
  6106. }
  6107. /**
  6108. * @public
  6109. * @param {number} x
  6110. * @param {number} width
  6111. * @param {string} [textAlign='left']
  6112. * @return {number} Adjusted x.
  6113. */
  6114. function adjustTextX(x, width, textAlign) {
  6115. // FIXME Right to left language
  6116. if (textAlign === 'right') {
  6117. x -= width;
  6118. }
  6119. else if (textAlign === 'center') {
  6120. x -= width / 2;
  6121. }
  6122. return x;
  6123. }
  6124. /**
  6125. * @public
  6126. * @param {number} y
  6127. * @param {number} height
  6128. * @param {string} [textVerticalAlign='top']
  6129. * @return {number} Adjusted y.
  6130. */
  6131. function adjustTextY(y, height, textVerticalAlign) {
  6132. if (textVerticalAlign === 'middle') {
  6133. y -= height / 2;
  6134. }
  6135. else if (textVerticalAlign === 'bottom') {
  6136. y -= height;
  6137. }
  6138. return y;
  6139. }
  6140. /**
  6141. * @public
  6142. * @param {stirng} textPosition
  6143. * @param {Object} rect {x, y, width, height}
  6144. * @param {number} distance
  6145. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6146. */
  6147. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6148. var x = rect.x;
  6149. var y = rect.y;
  6150. var height = rect.height;
  6151. var width = rect.width;
  6152. var halfHeight = height / 2;
  6153. var textAlign = 'left';
  6154. var textVerticalAlign = 'top';
  6155. switch (textPosition) {
  6156. case 'left':
  6157. x -= distance;
  6158. y += halfHeight;
  6159. textAlign = 'right';
  6160. textVerticalAlign = 'middle';
  6161. break;
  6162. case 'right':
  6163. x += distance + width;
  6164. y += halfHeight;
  6165. textVerticalAlign = 'middle';
  6166. break;
  6167. case 'top':
  6168. x += width / 2;
  6169. y -= distance;
  6170. textAlign = 'center';
  6171. textVerticalAlign = 'bottom';
  6172. break;
  6173. case 'bottom':
  6174. x += width / 2;
  6175. y += height + distance;
  6176. textAlign = 'center';
  6177. break;
  6178. case 'inside':
  6179. x += width / 2;
  6180. y += halfHeight;
  6181. textAlign = 'center';
  6182. textVerticalAlign = 'middle';
  6183. break;
  6184. case 'insideLeft':
  6185. x += distance;
  6186. y += halfHeight;
  6187. textVerticalAlign = 'middle';
  6188. break;
  6189. case 'insideRight':
  6190. x += width - distance;
  6191. y += halfHeight;
  6192. textAlign = 'right';
  6193. textVerticalAlign = 'middle';
  6194. break;
  6195. case 'insideTop':
  6196. x += width / 2;
  6197. y += distance;
  6198. textAlign = 'center';
  6199. break;
  6200. case 'insideBottom':
  6201. x += width / 2;
  6202. y += height - distance;
  6203. textAlign = 'center';
  6204. textVerticalAlign = 'bottom';
  6205. break;
  6206. case 'insideTopLeft':
  6207. x += distance;
  6208. y += distance;
  6209. break;
  6210. case 'insideTopRight':
  6211. x += width - distance;
  6212. y += distance;
  6213. textAlign = 'right';
  6214. break;
  6215. case 'insideBottomLeft':
  6216. x += distance;
  6217. y += height - distance;
  6218. textVerticalAlign = 'bottom';
  6219. break;
  6220. case 'insideBottomRight':
  6221. x += width - distance;
  6222. y += height - distance;
  6223. textAlign = 'right';
  6224. textVerticalAlign = 'bottom';
  6225. break;
  6226. }
  6227. return {
  6228. x: x,
  6229. y: y,
  6230. textAlign: textAlign,
  6231. textVerticalAlign: textVerticalAlign
  6232. };
  6233. }
  6234. /**
  6235. * Show ellipsis if overflow.
  6236. *
  6237. * @public
  6238. * @param {string} text
  6239. * @param {string} containerWidth
  6240. * @param {string} font
  6241. * @param {number} [ellipsis='...']
  6242. * @param {Object} [options]
  6243. * @param {number} [options.maxIterations=3]
  6244. * @param {number} [options.minChar=0] If truncate result are less
  6245. * then minChar, ellipsis will not show, which is
  6246. * better for user hint in some cases.
  6247. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6248. * @return {string}
  6249. */
  6250. function truncateText(text, containerWidth, font, ellipsis, options) {
  6251. if (!containerWidth) {
  6252. return '';
  6253. }
  6254. var textLines = (text + '').split('\n');
  6255. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6256. // FIXME
  6257. // It is not appropriate that every line has '...' when truncate multiple lines.
  6258. for (var i = 0, len = textLines.length; i < len; i++) {
  6259. textLines[i] = truncateSingleLine(textLines[i], options);
  6260. }
  6261. return textLines.join('\n');
  6262. }
  6263. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6264. options = extend({}, options);
  6265. options.font = font;
  6266. var ellipsis = retrieve2(ellipsis, '...');
  6267. options.maxIterations = retrieve2(options.maxIterations, 2);
  6268. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6269. // FIXME
  6270. // Other languages?
  6271. options.cnCharWidth = getWidth('国', font);
  6272. // FIXME
  6273. // Consider proportional font?
  6274. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6275. options.placeholder = retrieve2(options.placeholder, '');
  6276. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6277. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6278. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6279. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6280. contentWidth -= ascCharWidth;
  6281. }
  6282. var ellipsisWidth = getWidth(ellipsis);
  6283. if (ellipsisWidth > contentWidth) {
  6284. ellipsis = '';
  6285. ellipsisWidth = 0;
  6286. }
  6287. contentWidth = containerWidth - ellipsisWidth;
  6288. options.ellipsis = ellipsis;
  6289. options.ellipsisWidth = ellipsisWidth;
  6290. options.contentWidth = contentWidth;
  6291. options.containerWidth = containerWidth;
  6292. return options;
  6293. }
  6294. function truncateSingleLine(textLine, options) {
  6295. var containerWidth = options.containerWidth;
  6296. var font = options.font;
  6297. var contentWidth = options.contentWidth;
  6298. if (!containerWidth) {
  6299. return '';
  6300. }
  6301. var lineWidth = getWidth(textLine, font);
  6302. if (lineWidth <= containerWidth) {
  6303. return textLine;
  6304. }
  6305. for (var j = 0;; j++) {
  6306. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6307. textLine += options.ellipsis;
  6308. break;
  6309. }
  6310. var subLength = j === 0
  6311. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6312. : lineWidth > 0
  6313. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6314. : 0;
  6315. textLine = textLine.substr(0, subLength);
  6316. lineWidth = getWidth(textLine, font);
  6317. }
  6318. if (textLine === '') {
  6319. textLine = options.placeholder;
  6320. }
  6321. return textLine;
  6322. }
  6323. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6324. var width = 0;
  6325. var i = 0;
  6326. for (var len = text.length; i < len && width < contentWidth; i++) {
  6327. var charCode = text.charCodeAt(i);
  6328. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6329. }
  6330. return i;
  6331. }
  6332. /**
  6333. * @public
  6334. * @param {string} font
  6335. * @return {number} line height
  6336. */
  6337. function getLineHeight(font) {
  6338. // FIXME A rough approach.
  6339. return getWidth('国', font);
  6340. }
  6341. /**
  6342. * @public
  6343. * @param {string} text
  6344. * @param {string} font
  6345. * @return {Object} width
  6346. */
  6347. function measureText(text, font) {
  6348. return methods$1.measureText(text, font);
  6349. }
  6350. // Avoid assign to an exported variable, for transforming to cjs.
  6351. methods$1.measureText = function (text, font) {
  6352. var ctx = getContext();
  6353. ctx.font = font || DEFAULT_FONT;
  6354. return ctx.measureText(text);
  6355. };
  6356. /**
  6357. * @public
  6358. * @param {string} text
  6359. * @param {string} font
  6360. * @param {Object} [truncate]
  6361. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6362. * Notice: for performance, do not calculate outerWidth util needed.
  6363. */
  6364. function parsePlainText(text, font, padding, truncate) {
  6365. text != null && (text += '');
  6366. var lineHeight = getLineHeight(font);
  6367. var lines = text ? text.split('\n') : [];
  6368. var height = lines.length * lineHeight;
  6369. var outerHeight = height;
  6370. if (padding) {
  6371. outerHeight += padding[0] + padding[2];
  6372. }
  6373. if (text && truncate) {
  6374. var truncOuterHeight = truncate.outerHeight;
  6375. var truncOuterWidth = truncate.outerWidth;
  6376. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6377. text = '';
  6378. lines = [];
  6379. }
  6380. else if (truncOuterWidth != null) {
  6381. var options = prepareTruncateOptions(
  6382. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6383. font,
  6384. truncate.ellipsis,
  6385. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6386. );
  6387. // FIXME
  6388. // It is not appropriate that every line has '...' when truncate multiple lines.
  6389. for (var i = 0, len = lines.length; i < len; i++) {
  6390. lines[i] = truncateSingleLine(lines[i], options);
  6391. }
  6392. }
  6393. }
  6394. return {
  6395. lines: lines,
  6396. height: height,
  6397. outerHeight: outerHeight,
  6398. lineHeight: lineHeight
  6399. };
  6400. }
  6401. /**
  6402. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6403. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6404. *
  6405. * @public
  6406. * @param {string} text
  6407. * @param {Object} style
  6408. * @return {Object} block
  6409. * {
  6410. * width,
  6411. * height,
  6412. * lines: [{
  6413. * lineHeight,
  6414. * width,
  6415. * tokens: [[{
  6416. * styleName,
  6417. * text,
  6418. * width, // include textPadding
  6419. * height, // include textPadding
  6420. * textWidth, // pure text width
  6421. * textHeight, // pure text height
  6422. * lineHeihgt,
  6423. * font,
  6424. * textAlign,
  6425. * textVerticalAlign
  6426. * }], [...], ...]
  6427. * }, ...]
  6428. * }
  6429. * If styleName is undefined, it is plain text.
  6430. */
  6431. function parseRichText(text, style) {
  6432. var contentBlock = {lines: [], width: 0, height: 0};
  6433. text != null && (text += '');
  6434. if (!text) {
  6435. return contentBlock;
  6436. }
  6437. var lastIndex = STYLE_REG.lastIndex = 0;
  6438. var result;
  6439. while ((result = STYLE_REG.exec(text)) != null) {
  6440. var matchedIndex = result.index;
  6441. if (matchedIndex > lastIndex) {
  6442. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6443. }
  6444. pushTokens(contentBlock, result[2], result[1]);
  6445. lastIndex = STYLE_REG.lastIndex;
  6446. }
  6447. if (lastIndex < text.length) {
  6448. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6449. }
  6450. var lines = contentBlock.lines;
  6451. var contentHeight = 0;
  6452. var contentWidth = 0;
  6453. // For `textWidth: 100%`
  6454. var pendingList = [];
  6455. var stlPadding = style.textPadding;
  6456. var truncate = style.truncate;
  6457. var truncateWidth = truncate && truncate.outerWidth;
  6458. var truncateHeight = truncate && truncate.outerHeight;
  6459. if (stlPadding) {
  6460. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6461. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6462. }
  6463. // Calculate layout info of tokens.
  6464. for (var i = 0; i < lines.length; i++) {
  6465. var line = lines[i];
  6466. var lineHeight = 0;
  6467. var lineWidth = 0;
  6468. for (var j = 0; j < line.tokens.length; j++) {
  6469. var token = line.tokens[j];
  6470. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6471. // textPadding should not inherit from style.
  6472. var textPadding = token.textPadding = tokenStyle.textPadding;
  6473. // textFont has been asigned to font by `normalizeStyle`.
  6474. var font = token.font = tokenStyle.font || style.font;
  6475. // textHeight can be used when textVerticalAlign is specified in token.
  6476. var tokenHeight = token.textHeight = retrieve2(
  6477. // textHeight should not be inherited, consider it can be specified
  6478. // as box height of the block.
  6479. tokenStyle.textHeight, getLineHeight(font)
  6480. );
  6481. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6482. token.height = tokenHeight;
  6483. token.lineHeight = retrieve3(
  6484. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6485. );
  6486. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6487. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6488. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6489. return {lines: [], width: 0, height: 0};
  6490. }
  6491. token.textWidth = getWidth(token.text, font);
  6492. var tokenWidth = tokenStyle.textWidth;
  6493. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6494. // Percent width, can be `100%`, can be used in drawing separate
  6495. // line when box width is needed to be auto.
  6496. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6497. token.percentWidth = tokenWidth;
  6498. pendingList.push(token);
  6499. tokenWidth = 0;
  6500. // Do not truncate in this case, because there is no user case
  6501. // and it is too complicated.
  6502. }
  6503. else {
  6504. if (tokenWidthNotSpecified) {
  6505. tokenWidth = token.textWidth;
  6506. // FIXME: If image is not loaded and textWidth is not specified, calling
  6507. // `getBoundingRect()` will not get correct result.
  6508. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6509. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6510. // Use cases:
  6511. // (1) If image is not loaded, it will be loaded at render phase and call
  6512. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6513. // image, and then the right size will be calculated here at the next tick.
  6514. // See `graphic/helper/text.js`.
  6515. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6516. // use `imageHelper.findExistImage` to find cached image.
  6517. // `imageHelper.findExistImage` will always be called here before
  6518. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6519. // which ensures that image will not be rendered before correct size calcualted.
  6520. if (bgImg) {
  6521. bgImg = findExistImage(bgImg);
  6522. if (isImageReady(bgImg)) {
  6523. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6524. }
  6525. }
  6526. }
  6527. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6528. tokenWidth += paddingW;
  6529. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6530. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6531. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6532. token.text = '';
  6533. token.textWidth = tokenWidth = 0;
  6534. }
  6535. else {
  6536. token.text = truncateText(
  6537. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6538. {minChar: truncate.minChar}
  6539. );
  6540. token.textWidth = getWidth(token.text, font);
  6541. tokenWidth = token.textWidth + paddingW;
  6542. }
  6543. }
  6544. }
  6545. lineWidth += (token.width = tokenWidth);
  6546. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6547. }
  6548. line.width = lineWidth;
  6549. line.lineHeight = lineHeight;
  6550. contentHeight += lineHeight;
  6551. contentWidth = Math.max(contentWidth, lineWidth);
  6552. }
  6553. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6554. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6555. if (stlPadding) {
  6556. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6557. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6558. }
  6559. for (var i = 0; i < pendingList.length; i++) {
  6560. var token = pendingList[i];
  6561. var percentWidth = token.percentWidth;
  6562. // Should not base on outerWidth, because token can not be placed out of padding.
  6563. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6564. }
  6565. return contentBlock;
  6566. }
  6567. function pushTokens(block, str, styleName) {
  6568. var isEmptyStr = str === '';
  6569. var strs = str.split('\n');
  6570. var lines = block.lines;
  6571. for (var i = 0; i < strs.length; i++) {
  6572. var text = strs[i];
  6573. var token = {
  6574. styleName: styleName,
  6575. text: text,
  6576. isLineHolder: !text && !isEmptyStr
  6577. };
  6578. // The first token should be appended to the last line.
  6579. if (!i) {
  6580. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6581. // Consider cases:
  6582. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6583. // (which is a placeholder) should be replaced by new token.
  6584. // (2) A image backage, where token likes {a|}.
  6585. // (3) A redundant '' will affect textAlign in line.
  6586. // (4) tokens with the same tplName should not be merged, because
  6587. // they should be displayed in different box (with border and padding).
  6588. var tokensLen = tokens.length;
  6589. (tokensLen === 1 && tokens[0].isLineHolder)
  6590. ? (tokens[0] = token)
  6591. // Consider text is '', only insert when it is the "lineHolder" or
  6592. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6593. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6594. }
  6595. // Other tokens always start a new line.
  6596. else {
  6597. // If there is '', insert it as a placeholder.
  6598. lines.push({tokens: [token]});
  6599. }
  6600. }
  6601. }
  6602. function makeFont(style) {
  6603. // FIXME in node-canvas fontWeight is before fontStyle
  6604. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6605. var font = (style.fontSize || style.fontFamily) && [
  6606. style.fontStyle,
  6607. style.fontWeight,
  6608. (style.fontSize || 12) + 'px',
  6609. // If font properties are defined, `fontFamily` should not be ignored.
  6610. style.fontFamily || 'sans-serif'
  6611. ].join(' ');
  6612. return font && trim(font) || style.textFont || style.font;
  6613. }
  6614. function buildPath(ctx, shape) {
  6615. var x = shape.x;
  6616. var y = shape.y;
  6617. var width = shape.width;
  6618. var height = shape.height;
  6619. var r = shape.r;
  6620. var r1;
  6621. var r2;
  6622. var r3;
  6623. var r4;
  6624. // Convert width and height to positive for better borderRadius
  6625. if (width < 0) {
  6626. x = x + width;
  6627. width = -width;
  6628. }
  6629. if (height < 0) {
  6630. y = y + height;
  6631. height = -height;
  6632. }
  6633. if (typeof r === 'number') {
  6634. r1 = r2 = r3 = r4 = r;
  6635. }
  6636. else if (r instanceof Array) {
  6637. if (r.length === 1) {
  6638. r1 = r2 = r3 = r4 = r[0];
  6639. }
  6640. else if (r.length === 2) {
  6641. r1 = r3 = r[0];
  6642. r2 = r4 = r[1];
  6643. }
  6644. else if (r.length === 3) {
  6645. r1 = r[0];
  6646. r2 = r4 = r[1];
  6647. r3 = r[2];
  6648. }
  6649. else {
  6650. r1 = r[0];
  6651. r2 = r[1];
  6652. r3 = r[2];
  6653. r4 = r[3];
  6654. }
  6655. }
  6656. else {
  6657. r1 = r2 = r3 = r4 = 0;
  6658. }
  6659. var total;
  6660. if (r1 + r2 > width) {
  6661. total = r1 + r2;
  6662. r1 *= width / total;
  6663. r2 *= width / total;
  6664. }
  6665. if (r3 + r4 > width) {
  6666. total = r3 + r4;
  6667. r3 *= width / total;
  6668. r4 *= width / total;
  6669. }
  6670. if (r2 + r3 > height) {
  6671. total = r2 + r3;
  6672. r2 *= height / total;
  6673. r3 *= height / total;
  6674. }
  6675. if (r1 + r4 > height) {
  6676. total = r1 + r4;
  6677. r1 *= height / total;
  6678. r4 *= height / total;
  6679. }
  6680. ctx.moveTo(x + r1, y);
  6681. ctx.lineTo(x + width - r2, y);
  6682. r2 !== 0 && ctx.quadraticCurveTo(
  6683. x + width, y, x + width, y + r2
  6684. );
  6685. ctx.lineTo(x + width, y + height - r3);
  6686. r3 !== 0 && ctx.quadraticCurveTo(
  6687. x + width, y + height, x + width - r3, y + height
  6688. );
  6689. ctx.lineTo(x + r4, y + height);
  6690. r4 !== 0 && ctx.quadraticCurveTo(
  6691. x, y + height, x, y + height - r4
  6692. );
  6693. ctx.lineTo(x, y + r1);
  6694. r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y);
  6695. }
  6696. // TODO: Have not support 'start', 'end' yet.
  6697. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6698. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6699. /**
  6700. * @param {module:zrender/graphic/Style} style
  6701. * @return {module:zrender/graphic/Style} The input style.
  6702. */
  6703. function normalizeTextStyle(style) {
  6704. normalizeStyle(style);
  6705. each$1(style.rich, normalizeStyle);
  6706. return style;
  6707. }
  6708. function normalizeStyle(style) {
  6709. if (style) {
  6710. style.font = makeFont(style);
  6711. var textAlign = style.textAlign;
  6712. textAlign === 'middle' && (textAlign = 'center');
  6713. style.textAlign = (
  6714. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6715. ) ? textAlign : 'left';
  6716. // Compatible with textBaseline.
  6717. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6718. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6719. style.textVerticalAlign = (
  6720. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6721. ) ? textVerticalAlign : 'top';
  6722. var textPadding = style.textPadding;
  6723. if (textPadding) {
  6724. style.textPadding = normalizeCssArray(style.textPadding);
  6725. }
  6726. }
  6727. }
  6728. /**
  6729. * @param {CanvasRenderingContext2D} ctx
  6730. * @param {string} text
  6731. * @param {module:zrender/graphic/Style} style
  6732. * @param {Object|boolean} [rect] {x, y, width, height}
  6733. * If set false, rect text is not used.
  6734. */
  6735. function renderText(hostEl, ctx, text, style, rect) {
  6736. style.rich
  6737. ? renderRichText(hostEl, ctx, text, style, rect)
  6738. : renderPlainText(hostEl, ctx, text, style, rect);
  6739. }
  6740. function renderPlainText(hostEl, ctx, text, style, rect) {
  6741. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6742. var textPadding = style.textPadding;
  6743. var contentBlock = hostEl.__textCotentBlock;
  6744. if (!contentBlock || hostEl.__dirty) {
  6745. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6746. text, font, textPadding, style.truncate
  6747. );
  6748. }
  6749. var outerHeight = contentBlock.outerHeight;
  6750. var textLines = contentBlock.lines;
  6751. var lineHeight = contentBlock.lineHeight;
  6752. var boxPos = getBoxPosition(outerHeight, style, rect);
  6753. var baseX = boxPos.baseX;
  6754. var baseY = boxPos.baseY;
  6755. var textAlign = boxPos.textAlign;
  6756. var textVerticalAlign = boxPos.textVerticalAlign;
  6757. // Origin of textRotation should be the base point of text drawing.
  6758. applyTextRotation(ctx, style, rect, baseX, baseY);
  6759. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6760. var textX = baseX;
  6761. var textY = boxY;
  6762. var needDrawBg = needDrawBackground(style);
  6763. if (needDrawBg || textPadding) {
  6764. // Consider performance, do not call getTextWidth util necessary.
  6765. var textWidth = getWidth(text, font);
  6766. var outerWidth = textWidth;
  6767. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6768. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6769. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6770. if (textPadding) {
  6771. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6772. textY += textPadding[0];
  6773. }
  6774. }
  6775. setCtx(ctx, 'textAlign', textAlign || 'left');
  6776. // Force baseline to be "middle". Otherwise, if using "top", the
  6777. // text will offset downward a little bit in font "Microsoft YaHei".
  6778. setCtx(ctx, 'textBaseline', 'middle');
  6779. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6780. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6781. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6782. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6783. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6784. // `textBaseline` is set as 'middle'.
  6785. textY += lineHeight / 2;
  6786. var textStrokeWidth = style.textStrokeWidth;
  6787. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6788. var textFill = getFill(style.textFill);
  6789. if (textStroke) {
  6790. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6791. setCtx(ctx, 'strokeStyle', textStroke);
  6792. }
  6793. if (textFill) {
  6794. setCtx(ctx, 'fillStyle', textFill);
  6795. }
  6796. for (var i = 0; i < textLines.length; i++) {
  6797. // Fill after stroke so the outline will not cover the main part.
  6798. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6799. textFill && ctx.fillText(textLines[i], textX, textY);
  6800. textY += lineHeight;
  6801. }
  6802. }
  6803. function renderRichText(hostEl, ctx, text, style, rect) {
  6804. var contentBlock = hostEl.__textCotentBlock;
  6805. if (!contentBlock || hostEl.__dirty) {
  6806. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6807. }
  6808. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6809. }
  6810. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6811. var contentWidth = contentBlock.width;
  6812. var outerWidth = contentBlock.outerWidth;
  6813. var outerHeight = contentBlock.outerHeight;
  6814. var textPadding = style.textPadding;
  6815. var boxPos = getBoxPosition(outerHeight, style, rect);
  6816. var baseX = boxPos.baseX;
  6817. var baseY = boxPos.baseY;
  6818. var textAlign = boxPos.textAlign;
  6819. var textVerticalAlign = boxPos.textVerticalAlign;
  6820. // Origin of textRotation should be the base point of text drawing.
  6821. applyTextRotation(ctx, style, rect, baseX, baseY);
  6822. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6823. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6824. var xLeft = boxX;
  6825. var lineTop = boxY;
  6826. if (textPadding) {
  6827. xLeft += textPadding[3];
  6828. lineTop += textPadding[0];
  6829. }
  6830. var xRight = xLeft + contentWidth;
  6831. needDrawBackground(style) && drawBackground(
  6832. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6833. );
  6834. for (var i = 0; i < contentBlock.lines.length; i++) {
  6835. var line = contentBlock.lines[i];
  6836. var tokens = line.tokens;
  6837. var tokenCount = tokens.length;
  6838. var lineHeight = line.lineHeight;
  6839. var usedWidth = line.width;
  6840. var leftIndex = 0;
  6841. var lineXLeft = xLeft;
  6842. var lineXRight = xRight;
  6843. var rightIndex = tokenCount - 1;
  6844. var token;
  6845. while (
  6846. leftIndex < tokenCount
  6847. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6848. ) {
  6849. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6850. usedWidth -= token.width;
  6851. lineXLeft += token.width;
  6852. leftIndex++;
  6853. }
  6854. while (
  6855. rightIndex >= 0
  6856. && (token = tokens[rightIndex], token.textAlign === 'right')
  6857. ) {
  6858. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6859. usedWidth -= token.width;
  6860. lineXRight -= token.width;
  6861. rightIndex--;
  6862. }
  6863. // The other tokens are placed as textAlign 'center' if there is enough space.
  6864. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6865. while (leftIndex <= rightIndex) {
  6866. token = tokens[leftIndex];
  6867. // Consider width specified by user, use 'center' rather than 'left'.
  6868. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6869. lineXLeft += token.width;
  6870. leftIndex++;
  6871. }
  6872. lineTop += lineHeight;
  6873. }
  6874. }
  6875. function applyTextRotation(ctx, style, rect, x, y) {
  6876. // textRotation only apply in RectText.
  6877. if (rect && style.textRotation) {
  6878. var origin = style.textOrigin;
  6879. if (origin === 'center') {
  6880. x = rect.width / 2 + rect.x;
  6881. y = rect.height / 2 + rect.y;
  6882. }
  6883. else if (origin) {
  6884. x = origin[0] + rect.x;
  6885. y = origin[1] + rect.y;
  6886. }
  6887. ctx.translate(x, y);
  6888. // Positive: anticlockwise
  6889. ctx.rotate(-style.textRotation);
  6890. ctx.translate(-x, -y);
  6891. }
  6892. }
  6893. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6894. var tokenStyle = style.rich[token.styleName] || {};
  6895. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6896. // the bias of "Microsoft YaHei".
  6897. var textVerticalAlign = token.textVerticalAlign;
  6898. var y = lineTop + lineHeight / 2;
  6899. if (textVerticalAlign === 'top') {
  6900. y = lineTop + token.height / 2;
  6901. }
  6902. else if (textVerticalAlign === 'bottom') {
  6903. y = lineTop + lineHeight - token.height / 2;
  6904. }
  6905. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6906. hostEl,
  6907. ctx,
  6908. tokenStyle,
  6909. textAlign === 'right'
  6910. ? x - token.width
  6911. : textAlign === 'center'
  6912. ? x - token.width / 2
  6913. : x,
  6914. y - token.height / 2,
  6915. token.width,
  6916. token.height
  6917. );
  6918. var textPadding = token.textPadding;
  6919. if (textPadding) {
  6920. x = getTextXForPadding(x, textAlign, textPadding);
  6921. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6922. }
  6923. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6924. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6925. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6926. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6927. setCtx(ctx, 'textAlign', textAlign);
  6928. // Force baseline to be "middle". Otherwise, if using "top", the
  6929. // text will offset downward a little bit in font "Microsoft YaHei".
  6930. setCtx(ctx, 'textBaseline', 'middle');
  6931. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6932. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6933. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6934. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6935. // Fill after stroke so the outline will not cover the main part.
  6936. if (textStroke) {
  6937. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6938. setCtx(ctx, 'strokeStyle', textStroke);
  6939. ctx.strokeText(token.text, x, y);
  6940. }
  6941. if (textFill) {
  6942. setCtx(ctx, 'fillStyle', textFill);
  6943. ctx.fillText(token.text, x, y);
  6944. }
  6945. }
  6946. function needDrawBackground(style) {
  6947. return style.textBackgroundColor
  6948. || (style.textBorderWidth && style.textBorderColor);
  6949. }
  6950. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6951. // shape: {x, y, width, height}
  6952. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6953. var textBackgroundColor = style.textBackgroundColor;
  6954. var textBorderWidth = style.textBorderWidth;
  6955. var textBorderColor = style.textBorderColor;
  6956. var isPlainBg = isString(textBackgroundColor);
  6957. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6958. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6959. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6960. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6961. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6962. ctx.beginPath();
  6963. var textBorderRadius = style.textBorderRadius;
  6964. if (!textBorderRadius) {
  6965. ctx.rect(x, y, width, height);
  6966. }
  6967. else {
  6968. buildPath(ctx, {
  6969. x: x, y: y, width: width, height: height, r: textBorderRadius
  6970. });
  6971. }
  6972. ctx.closePath();
  6973. }
  6974. if (isPlainBg) {
  6975. setCtx(ctx, 'fillStyle', textBackgroundColor);
  6976. ctx.fill();
  6977. }
  6978. else if (isObject$1(textBackgroundColor)) {
  6979. var image = textBackgroundColor.image;
  6980. image = createOrUpdateImage(
  6981. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  6982. );
  6983. if (image && isImageReady(image)) {
  6984. ctx.drawImage(image, x, y, width, height);
  6985. }
  6986. }
  6987. if (textBorderWidth && textBorderColor) {
  6988. setCtx(ctx, 'lineWidth', textBorderWidth);
  6989. setCtx(ctx, 'strokeStyle', textBorderColor);
  6990. ctx.stroke();
  6991. }
  6992. }
  6993. function onBgImageLoaded(image, textBackgroundColor) {
  6994. // Replace image, so that `contain/text.js#parseRichText`
  6995. // will get correct result in next tick.
  6996. textBackgroundColor.image = image;
  6997. }
  6998. function getBoxPosition(blockHeiht, style, rect) {
  6999. var baseX = style.x || 0;
  7000. var baseY = style.y || 0;
  7001. var textAlign = style.textAlign;
  7002. var textVerticalAlign = style.textVerticalAlign;
  7003. // Text position represented by coord
  7004. if (rect) {
  7005. var textPosition = style.textPosition;
  7006. if (textPosition instanceof Array) {
  7007. // Percent
  7008. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7009. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7010. }
  7011. else {
  7012. var res = adjustTextPositionOnRect(
  7013. textPosition, rect, style.textDistance
  7014. );
  7015. baseX = res.x;
  7016. baseY = res.y;
  7017. // Default align and baseline when has textPosition
  7018. textAlign = textAlign || res.textAlign;
  7019. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7020. }
  7021. // textOffset is only support in RectText, otherwise
  7022. // we have to adjust boundingRect for textOffset.
  7023. var textOffset = style.textOffset;
  7024. if (textOffset) {
  7025. baseX += textOffset[0];
  7026. baseY += textOffset[1];
  7027. }
  7028. }
  7029. return {
  7030. baseX: baseX,
  7031. baseY: baseY,
  7032. textAlign: textAlign,
  7033. textVerticalAlign: textVerticalAlign
  7034. };
  7035. }
  7036. function setCtx(ctx, prop, value) {
  7037. ctx[prop] = fixShadow(ctx, prop, value);
  7038. return ctx[prop];
  7039. }
  7040. /**
  7041. * @param {string} [stroke] If specified, do not check style.textStroke.
  7042. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7043. * @param {number} style
  7044. */
  7045. function getStroke(stroke, lineWidth) {
  7046. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7047. ? null
  7048. // TODO pattern and gradient?
  7049. : (stroke.image || stroke.colorStops)
  7050. ? '#000'
  7051. : stroke;
  7052. }
  7053. function getFill(fill) {
  7054. return (fill == null || fill === 'none')
  7055. ? null
  7056. // TODO pattern and gradient?
  7057. : (fill.image || fill.colorStops)
  7058. ? '#000'
  7059. : fill;
  7060. }
  7061. function parsePercent(value, maxValue) {
  7062. if (typeof value === 'string') {
  7063. if (value.lastIndexOf('%') >= 0) {
  7064. return parseFloat(value) / 100 * maxValue;
  7065. }
  7066. return parseFloat(value);
  7067. }
  7068. return value;
  7069. }
  7070. function getTextXForPadding(x, textAlign, textPadding) {
  7071. return textAlign === 'right'
  7072. ? (x - textPadding[1])
  7073. : textAlign === 'center'
  7074. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7075. : (x + textPadding[3]);
  7076. }
  7077. /**
  7078. * @param {string} text
  7079. * @param {module:zrender/Style} style
  7080. * @return {boolean}
  7081. */
  7082. function needDrawText(text, style) {
  7083. return text != null
  7084. && (text
  7085. || style.textBackgroundColor
  7086. || (style.textBorderWidth && style.textBorderColor)
  7087. || style.textPadding
  7088. );
  7089. }
  7090. /**
  7091. * Mixin for drawing text in a element bounding rect
  7092. * @module zrender/mixin/RectText
  7093. */
  7094. var tmpRect$1 = new BoundingRect();
  7095. var RectText = function () {};
  7096. RectText.prototype = {
  7097. constructor: RectText,
  7098. /**
  7099. * Draw text in a rect with specified position.
  7100. * @param {CanvasRenderingContext2D} ctx
  7101. * @param {Object} rect Displayable rect
  7102. */
  7103. drawRectText: function (ctx, rect) {
  7104. var style = this.style;
  7105. rect = style.textRect || rect;
  7106. // Optimize, avoid normalize every time.
  7107. this.__dirty && normalizeTextStyle(style, true);
  7108. var text = style.text;
  7109. // Convert to string
  7110. text != null && (text += '');
  7111. if (!needDrawText(text, style)) {
  7112. return;
  7113. }
  7114. // FIXME
  7115. ctx.save();
  7116. // Transform rect to view space
  7117. var transform = this.transform;
  7118. if (!style.transformText) {
  7119. if (transform) {
  7120. tmpRect$1.copy(rect);
  7121. tmpRect$1.applyTransform(transform);
  7122. rect = tmpRect$1;
  7123. }
  7124. }
  7125. else {
  7126. this.setTransform(ctx);
  7127. }
  7128. // transformText and textRotation can not be used at the same time.
  7129. renderText(this, ctx, text, style, rect);
  7130. ctx.restore();
  7131. }
  7132. };
  7133. /**
  7134. * 可绘制的图形基类
  7135. * Base class of all displayable graphic objects
  7136. * @module zrender/graphic/Displayable
  7137. */
  7138. /**
  7139. * @alias module:zrender/graphic/Displayable
  7140. * @extends module:zrender/Element
  7141. * @extends module:zrender/graphic/mixin/RectText
  7142. */
  7143. function Displayable(opts) {
  7144. opts = opts || {};
  7145. Element.call(this, opts);
  7146. // Extend properties
  7147. for (var name in opts) {
  7148. if (
  7149. opts.hasOwnProperty(name) &&
  7150. name !== 'style'
  7151. ) {
  7152. this[name] = opts[name];
  7153. }
  7154. }
  7155. /**
  7156. * @type {module:zrender/graphic/Style}
  7157. */
  7158. this.style = new Style(opts.style, this);
  7159. this._rect = null;
  7160. // Shapes for cascade clipping.
  7161. this.__clipPaths = [];
  7162. // FIXME Stateful must be mixined after style is setted
  7163. // Stateful.call(this, opts);
  7164. }
  7165. Displayable.prototype = {
  7166. constructor: Displayable,
  7167. type: 'displayable',
  7168. /**
  7169. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7170. * Dirty flag. From which painter will determine if this displayable object needs brush
  7171. * @name module:zrender/graphic/Displayable#__dirty
  7172. * @type {boolean}
  7173. */
  7174. __dirty: true,
  7175. /**
  7176. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7177. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7178. * @name module:/zrender/graphic/Displayable#invisible
  7179. * @type {boolean}
  7180. * @default false
  7181. */
  7182. invisible: false,
  7183. /**
  7184. * @name module:/zrender/graphic/Displayable#z
  7185. * @type {number}
  7186. * @default 0
  7187. */
  7188. z: 0,
  7189. /**
  7190. * @name module:/zrender/graphic/Displayable#z
  7191. * @type {number}
  7192. * @default 0
  7193. */
  7194. z2: 0,
  7195. /**
  7196. * z层level,决定绘画在哪层canvas中
  7197. * @name module:/zrender/graphic/Displayable#zlevel
  7198. * @type {number}
  7199. * @default 0
  7200. */
  7201. zlevel: 0,
  7202. /**
  7203. * 是否可拖拽
  7204. * @name module:/zrender/graphic/Displayable#draggable
  7205. * @type {boolean}
  7206. * @default false
  7207. */
  7208. draggable: false,
  7209. /**
  7210. * 是否正在拖拽
  7211. * @name module:/zrender/graphic/Displayable#draggable
  7212. * @type {boolean}
  7213. * @default false
  7214. */
  7215. dragging: false,
  7216. /**
  7217. * 是否相应鼠标事件
  7218. * @name module:/zrender/graphic/Displayable#silent
  7219. * @type {boolean}
  7220. * @default false
  7221. */
  7222. silent: false,
  7223. /**
  7224. * If enable culling
  7225. * @type {boolean}
  7226. * @default false
  7227. */
  7228. culling: false,
  7229. /**
  7230. * Mouse cursor when hovered
  7231. * @name module:/zrender/graphic/Displayable#cursor
  7232. * @type {string}
  7233. */
  7234. cursor: 'pointer',
  7235. /**
  7236. * If hover area is bounding rect
  7237. * @name module:/zrender/graphic/Displayable#rectHover
  7238. * @type {string}
  7239. */
  7240. rectHover: false,
  7241. /**
  7242. * Render the element progressively when the value >= 0,
  7243. * usefull for large data.
  7244. * @type {boolean}
  7245. */
  7246. progressive: false,
  7247. /**
  7248. * @type {boolean}
  7249. */
  7250. incremental: false,
  7251. // inplace is used with incremental
  7252. inplace: false,
  7253. beforeBrush: function (ctx) {},
  7254. afterBrush: function (ctx) {},
  7255. /**
  7256. * 图形绘制方法
  7257. * @param {CanvasRenderingContext2D} ctx
  7258. */
  7259. // Interface
  7260. brush: function (ctx, prevEl) {},
  7261. /**
  7262. * 获取最小包围盒
  7263. * @return {module:zrender/core/BoundingRect}
  7264. */
  7265. // Interface
  7266. getBoundingRect: function () {},
  7267. /**
  7268. * 判断坐标 x, y 是否在图形上
  7269. * If displayable element contain coord x, y
  7270. * @param {number} x
  7271. * @param {number} y
  7272. * @return {boolean}
  7273. */
  7274. contain: function (x, y) {
  7275. return this.rectContain(x, y);
  7276. },
  7277. /**
  7278. * @param {Function} cb
  7279. * @param {} context
  7280. */
  7281. traverse: function (cb, context) {
  7282. cb.call(context, this);
  7283. },
  7284. /**
  7285. * 判断坐标 x, y 是否在图形的包围盒上
  7286. * If bounding rect of element contain coord x, y
  7287. * @param {number} x
  7288. * @param {number} y
  7289. * @return {boolean}
  7290. */
  7291. rectContain: function (x, y) {
  7292. var coord = this.transformCoordToLocal(x, y);
  7293. var rect = this.getBoundingRect();
  7294. return rect.contain(coord[0], coord[1]);
  7295. },
  7296. /**
  7297. * 标记图形元素为脏,并且在下一帧重绘
  7298. * Mark displayable element dirty and refresh next frame
  7299. */
  7300. dirty: function () {
  7301. this.__dirty = true;
  7302. this._rect = null;
  7303. this.__zr && this.__zr.refresh();
  7304. },
  7305. /**
  7306. * 图形是否会触发事件
  7307. * If displayable object binded any event
  7308. * @return {boolean}
  7309. */
  7310. // TODO, 通过 bind 绑定的事件
  7311. // isSilent: function () {
  7312. // return !(
  7313. // this.hoverable || this.draggable
  7314. // || this.onmousemove || this.onmouseover || this.onmouseout
  7315. // || this.onmousedown || this.onmouseup || this.onclick
  7316. // || this.ondragenter || this.ondragover || this.ondragleave
  7317. // || this.ondrop
  7318. // );
  7319. // },
  7320. /**
  7321. * Alias for animate('style')
  7322. * @param {boolean} loop
  7323. */
  7324. animateStyle: function (loop) {
  7325. return this.animate('style', loop);
  7326. },
  7327. attrKV: function (key, value) {
  7328. if (key !== 'style') {
  7329. Element.prototype.attrKV.call(this, key, value);
  7330. }
  7331. else {
  7332. this.style.set(value);
  7333. }
  7334. },
  7335. /**
  7336. * @param {Object|string} key
  7337. * @param {*} value
  7338. */
  7339. setStyle: function (key, value) {
  7340. this.style.set(key, value);
  7341. this.dirty(false);
  7342. return this;
  7343. },
  7344. /**
  7345. * Use given style object
  7346. * @param {Object} obj
  7347. */
  7348. useStyle: function (obj) {
  7349. this.style = new Style(obj, this);
  7350. this.dirty(false);
  7351. return this;
  7352. }
  7353. };
  7354. inherits(Displayable, Element);
  7355. mixin(Displayable, RectText);
  7356. /**
  7357. * @alias zrender/graphic/Image
  7358. * @extends module:zrender/graphic/Displayable
  7359. * @constructor
  7360. * @param {Object} opts
  7361. */
  7362. function ZImage(opts) {
  7363. Displayable.call(this, opts);
  7364. }
  7365. ZImage.prototype = {
  7366. constructor: ZImage,
  7367. type: 'image',
  7368. brush: function (ctx, prevEl) {
  7369. var style = this.style;
  7370. var src = style.image;
  7371. // Must bind each time
  7372. style.bind(ctx, this, prevEl);
  7373. var image = this._image = createOrUpdateImage(
  7374. src,
  7375. this._image,
  7376. this,
  7377. this.onload
  7378. );
  7379. if (!image || !isImageReady(image)) {
  7380. return;
  7381. }
  7382. // 图片已经加载完成
  7383. // if (image.nodeName.toUpperCase() == 'IMG') {
  7384. // if (!image.complete) {
  7385. // return;
  7386. // }
  7387. // }
  7388. // Else is canvas
  7389. var x = style.x || 0;
  7390. var y = style.y || 0;
  7391. var width = style.width;
  7392. var height = style.height;
  7393. var aspect = image.width / image.height;
  7394. if (width == null && height != null) {
  7395. // Keep image/height ratio
  7396. width = height * aspect;
  7397. }
  7398. else if (height == null && width != null) {
  7399. height = width / aspect;
  7400. }
  7401. else if (width == null && height == null) {
  7402. width = image.width;
  7403. height = image.height;
  7404. }
  7405. // 设置transform
  7406. this.setTransform(ctx);
  7407. if (style.sWidth && style.sHeight) {
  7408. var sx = style.sx || 0;
  7409. var sy = style.sy || 0;
  7410. ctx.drawImage(
  7411. image,
  7412. sx, sy, style.sWidth, style.sHeight,
  7413. x, y, width, height
  7414. );
  7415. }
  7416. else if (style.sx && style.sy) {
  7417. var sx = style.sx;
  7418. var sy = style.sy;
  7419. var sWidth = width - sx;
  7420. var sHeight = height - sy;
  7421. ctx.drawImage(
  7422. image,
  7423. sx, sy, sWidth, sHeight,
  7424. x, y, width, height
  7425. );
  7426. }
  7427. else {
  7428. ctx.drawImage(image, x, y, width, height);
  7429. }
  7430. // Draw rect text
  7431. if (style.text != null) {
  7432. // Only restore transform when needs draw text.
  7433. this.restoreTransform(ctx);
  7434. this.drawRectText(ctx, this.getBoundingRect());
  7435. }
  7436. },
  7437. getBoundingRect: function () {
  7438. var style = this.style;
  7439. if (! this._rect) {
  7440. this._rect = new BoundingRect(
  7441. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7442. );
  7443. }
  7444. return this._rect;
  7445. }
  7446. };
  7447. inherits(ZImage, Displayable);
  7448. var HOVER_LAYER_ZLEVEL = 1e5;
  7449. var CANVAS_ZLEVEL = 314159;
  7450. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7451. var INCREMENTAL_INC = 0.001;
  7452. function parseInt10(val) {
  7453. return parseInt(val, 10);
  7454. }
  7455. function isLayerValid(layer) {
  7456. if (!layer) {
  7457. return false;
  7458. }
  7459. if (layer.__builtin__) {
  7460. return true;
  7461. }
  7462. if (typeof(layer.resize) !== 'function'
  7463. || typeof(layer.refresh) !== 'function'
  7464. ) {
  7465. return false;
  7466. }
  7467. return true;
  7468. }
  7469. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7470. var viewRect = new BoundingRect(0, 0, 0, 0);
  7471. function isDisplayableCulled(el, width, height) {
  7472. tmpRect.copy(el.getBoundingRect());
  7473. if (el.transform) {
  7474. tmpRect.applyTransform(el.transform);
  7475. }
  7476. viewRect.width = width;
  7477. viewRect.height = height;
  7478. return !tmpRect.intersect(viewRect);
  7479. }
  7480. function isClipPathChanged(clipPaths, prevClipPaths) {
  7481. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7482. return false;
  7483. }
  7484. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7485. return true;
  7486. }
  7487. for (var i = 0; i < clipPaths.length; i++) {
  7488. if (clipPaths[i] !== prevClipPaths[i]) {
  7489. return true;
  7490. }
  7491. }
  7492. }
  7493. function doClip(clipPaths, ctx) {
  7494. for (var i = 0; i < clipPaths.length; i++) {
  7495. var clipPath = clipPaths[i];
  7496. clipPath.setTransform(ctx);
  7497. ctx.beginPath();
  7498. clipPath.buildPath(ctx, clipPath.shape);
  7499. ctx.clip();
  7500. // Transform back
  7501. clipPath.restoreTransform(ctx);
  7502. }
  7503. }
  7504. function createRoot(width, height) {
  7505. var domRoot = document.createElement('div');
  7506. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7507. domRoot.style.cssText = [
  7508. 'position:relative',
  7509. 'overflow:hidden',
  7510. 'width:' + width + 'px',
  7511. 'height:' + height + 'px',
  7512. 'padding:0',
  7513. 'margin:0',
  7514. 'border-width:0'
  7515. ].join(';') + ';';
  7516. return domRoot;
  7517. }
  7518. /**
  7519. * @alias module:zrender/Painter
  7520. * @constructor
  7521. * @param {HTMLElement} root 绘图容器
  7522. * @param {module:zrender/Storage} storage
  7523. * @param {Object} opts
  7524. */
  7525. var Painter = function (root, storage, opts) {
  7526. this.type = 'canvas';
  7527. // In node environment using node-canvas
  7528. var singleCanvas = !root.nodeName // In node ?
  7529. || root.nodeName.toUpperCase() === 'CANVAS';
  7530. this._opts = opts = extend({}, opts || {});
  7531. /**
  7532. * @type {number}
  7533. */
  7534. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7535. /**
  7536. * @type {boolean}
  7537. * @private
  7538. */
  7539. this._singleCanvas = singleCanvas;
  7540. /**
  7541. * 绘图容器
  7542. * @type {HTMLElement}
  7543. */
  7544. this.root = root;
  7545. var rootStyle = root.style;
  7546. if (rootStyle) {
  7547. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7548. rootStyle['-webkit-user-select'] =
  7549. rootStyle['user-select'] =
  7550. rootStyle['-webkit-touch-callout'] = 'none';
  7551. root.innerHTML = '';
  7552. }
  7553. /**
  7554. * @type {module:zrender/Storage}
  7555. */
  7556. this.storage = storage;
  7557. /**
  7558. * @type {Array.<number>}
  7559. * @private
  7560. */
  7561. var zlevelList = this._zlevelList = [];
  7562. /**
  7563. * @type {Object.<string, module:zrender/Layer>}
  7564. * @private
  7565. */
  7566. var layers = this._layers = {};
  7567. /**
  7568. * @type {Object.<string, Object>}
  7569. * @private
  7570. */
  7571. this._layerConfig = {};
  7572. /**
  7573. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7574. */
  7575. this._needsManuallyCompositing = false;
  7576. if (!singleCanvas) {
  7577. this._width = this._getSize(0);
  7578. this._height = this._getSize(1);
  7579. var domRoot = this._domRoot = createRoot(
  7580. this._width, this._height
  7581. );
  7582. root.appendChild(domRoot);
  7583. }
  7584. else {
  7585. if (opts.width != null) {
  7586. root.width = opts.width;
  7587. }
  7588. if (opts.height != null) {
  7589. root.height = opts.height;
  7590. }
  7591. // Use canvas width and height directly
  7592. var width = root.width;
  7593. var height = root.height;
  7594. this._width = width;
  7595. this._height = height;
  7596. // Create layer if only one given canvas
  7597. // Device pixel ratio is fixed to 1 because given canvas has its specified width and height
  7598. var mainLayer = new Layer(root, this, 1);
  7599. mainLayer.__builtin__ = true;
  7600. mainLayer.initContext();
  7601. // FIXME Use canvas width and height
  7602. // mainLayer.resize(width, height);
  7603. layers[CANVAS_ZLEVEL] = mainLayer;
  7604. // Not use common zlevel.
  7605. zlevelList.push(CANVAS_ZLEVEL);
  7606. this._domRoot = root;
  7607. }
  7608. /**
  7609. * @type {module:zrender/Layer}
  7610. * @private
  7611. */
  7612. this._hoverlayer = null;
  7613. this._hoverElements = [];
  7614. };
  7615. Painter.prototype = {
  7616. constructor: Painter,
  7617. getType: function () {
  7618. return 'canvas';
  7619. },
  7620. /**
  7621. * If painter use a single canvas
  7622. * @return {boolean}
  7623. */
  7624. isSingleCanvas: function () {
  7625. return this._singleCanvas;
  7626. },
  7627. /**
  7628. * @return {HTMLDivElement}
  7629. */
  7630. getViewportRoot: function () {
  7631. return this._domRoot;
  7632. },
  7633. getViewportRootOffset: function () {
  7634. var viewportRoot = this.getViewportRoot();
  7635. if (viewportRoot) {
  7636. return {
  7637. offsetLeft: viewportRoot.offsetLeft || 0,
  7638. offsetTop: viewportRoot.offsetTop || 0
  7639. };
  7640. }
  7641. },
  7642. /**
  7643. * 刷新
  7644. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7645. */
  7646. refresh: function (paintAll) {
  7647. var list = this.storage.getDisplayList(true);
  7648. var zlevelList = this._zlevelList;
  7649. this._redrawId = Math.random();
  7650. this._paintList(list, paintAll, this._redrawId);
  7651. // Paint custum layers
  7652. for (var i = 0; i < zlevelList.length; i++) {
  7653. var z = zlevelList[i];
  7654. var layer = this._layers[z];
  7655. if (!layer.__builtin__ && layer.refresh) {
  7656. layer.refresh();
  7657. }
  7658. }
  7659. this.refreshHover();
  7660. return this;
  7661. },
  7662. addHover: function (el, hoverStyle) {
  7663. if (el.__hoverMir) {
  7664. return;
  7665. }
  7666. var elMirror = new el.constructor({
  7667. style: el.style,
  7668. shape: el.shape
  7669. });
  7670. elMirror.__from = el;
  7671. el.__hoverMir = elMirror;
  7672. elMirror.setStyle(hoverStyle);
  7673. this._hoverElements.push(elMirror);
  7674. },
  7675. removeHover: function (el) {
  7676. var elMirror = el.__hoverMir;
  7677. var hoverElements = this._hoverElements;
  7678. var idx = indexOf(hoverElements, elMirror);
  7679. if (idx >= 0) {
  7680. hoverElements.splice(idx, 1);
  7681. }
  7682. el.__hoverMir = null;
  7683. },
  7684. clearHover: function (el) {
  7685. var hoverElements = this._hoverElements;
  7686. for (var i = 0; i < hoverElements.length; i++) {
  7687. var from = hoverElements[i].__from;
  7688. if (from) {
  7689. from.__hoverMir = null;
  7690. }
  7691. }
  7692. hoverElements.length = 0;
  7693. },
  7694. refreshHover: function () {
  7695. var hoverElements = this._hoverElements;
  7696. var len = hoverElements.length;
  7697. var hoverLayer = this._hoverlayer;
  7698. hoverLayer && hoverLayer.clear();
  7699. if (!len) {
  7700. return;
  7701. }
  7702. sort(hoverElements, this.storage.displayableSortFunc);
  7703. // Use a extream large zlevel
  7704. // FIXME?
  7705. if (!hoverLayer) {
  7706. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7707. }
  7708. var scope = {};
  7709. hoverLayer.ctx.save();
  7710. for (var i = 0; i < len;) {
  7711. var el = hoverElements[i];
  7712. var originalEl = el.__from;
  7713. // Original el is removed
  7714. // PENDING
  7715. if (!(originalEl && originalEl.__zr)) {
  7716. hoverElements.splice(i, 1);
  7717. originalEl.__hoverMir = null;
  7718. len--;
  7719. continue;
  7720. }
  7721. i++;
  7722. // Use transform
  7723. // FIXME style and shape ?
  7724. if (!originalEl.invisible) {
  7725. el.transform = originalEl.transform;
  7726. el.invTransform = originalEl.invTransform;
  7727. el.__clipPaths = originalEl.__clipPaths;
  7728. // el.
  7729. this._doPaintEl(el, hoverLayer, true, scope);
  7730. }
  7731. }
  7732. hoverLayer.ctx.restore();
  7733. },
  7734. getHoverLayer: function () {
  7735. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7736. },
  7737. _paintList: function (list, paintAll, redrawId) {
  7738. if (this._redrawId !== redrawId) {
  7739. return;
  7740. }
  7741. paintAll = paintAll || false;
  7742. this._updateLayerStatus(list);
  7743. var finished = this._doPaintList(list, paintAll);
  7744. if (this._needsManuallyCompositing) {
  7745. this._compositeManually();
  7746. }
  7747. if (!finished) {
  7748. var self = this;
  7749. requestAnimationFrame(function () {
  7750. self._paintList(list, paintAll, redrawId);
  7751. });
  7752. }
  7753. },
  7754. _compositeManually: function () {
  7755. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7756. var width = this._domRoot.width;
  7757. var height = this._domRoot.height;
  7758. ctx.clearRect(0, 0, width, height);
  7759. // PENDING, If only builtin layer?
  7760. this.eachBuiltinLayer(function (layer) {
  7761. if (layer.virtual) {
  7762. ctx.drawImage(layer.dom, 0, 0, width, height);
  7763. }
  7764. });
  7765. },
  7766. _doPaintList: function (list, paintAll) {
  7767. var layerList = [];
  7768. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7769. var zlevel = this._zlevelList[zi];
  7770. var layer = this._layers[zlevel];
  7771. if (layer.__builtin__
  7772. && layer !== this._hoverlayer
  7773. && (layer.__dirty || paintAll)
  7774. ) {
  7775. layerList.push(layer);
  7776. }
  7777. }
  7778. var finished = true;
  7779. for (var k = 0; k < layerList.length; k++) {
  7780. var layer = layerList[k];
  7781. var ctx = layer.ctx;
  7782. var scope = {};
  7783. ctx.save();
  7784. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7785. var useTimer = !paintAll && layer.incremental && Date.now;
  7786. var startTime = useTimer && Date.now();
  7787. // All elements in this layer are cleared.
  7788. if (layer.__startIndex === layer.__endIndex) {
  7789. layer.clear();
  7790. }
  7791. else if (start === layer.__startIndex) {
  7792. var firstEl = list[start];
  7793. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7794. layer.clear();
  7795. }
  7796. }
  7797. if (start === -1) {
  7798. console.error('For some unknown reason. drawIndex is -1');
  7799. start = layer.__startIndex;
  7800. }
  7801. for (var i = start; i < layer.__endIndex; i++) {
  7802. var el = list[i];
  7803. this._doPaintEl(el, layer, paintAll, scope);
  7804. el.__dirty = false;
  7805. if (useTimer) {
  7806. // Date.now can be executed in 13,025,305 ops/second.
  7807. var dTime = Date.now() - startTime;
  7808. // Give 15 millisecond to draw.
  7809. // The rest elements will be drawn in the next frame.
  7810. if (dTime > 15) {
  7811. break;
  7812. }
  7813. }
  7814. }
  7815. layer.__drawIndex = i;
  7816. if (layer.__drawIndex < layer.__endIndex) {
  7817. finished = false;
  7818. }
  7819. if (scope.prevElClipPaths) {
  7820. // Needs restore the state. If last drawn element is in the clipping area.
  7821. ctx.restore();
  7822. }
  7823. ctx.restore();
  7824. }
  7825. if (env$1.wxa) {
  7826. // Flush for weixin application
  7827. each$1(this._layers, function (layer) {
  7828. if (layer && layer.ctx && layer.ctx.draw) {
  7829. layer.ctx.draw();
  7830. }
  7831. });
  7832. }
  7833. return finished;
  7834. },
  7835. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7836. var ctx = currentLayer.ctx;
  7837. var m = el.transform;
  7838. if (
  7839. (currentLayer.__dirty || forcePaint)
  7840. // Ignore invisible element
  7841. && !el.invisible
  7842. // Ignore transparent element
  7843. && el.style.opacity !== 0
  7844. // Ignore scale 0 element, in some environment like node-canvas
  7845. // Draw a scale 0 element can cause all following draw wrong
  7846. // And setTransform with scale 0 will cause set back transform failed.
  7847. && !(m && !m[0] && !m[3])
  7848. // Ignore culled element
  7849. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7850. ) {
  7851. var clipPaths = el.__clipPaths;
  7852. // Optimize when clipping on group with several elements
  7853. if (!scope.prevElClipPaths
  7854. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7855. ) {
  7856. // If has previous clipping state, restore from it
  7857. if (scope.prevElClipPaths) {
  7858. currentLayer.ctx.restore();
  7859. scope.prevElClipPaths = null;
  7860. // Reset prevEl since context has been restored
  7861. scope.prevEl = null;
  7862. }
  7863. // New clipping state
  7864. if (clipPaths) {
  7865. ctx.save();
  7866. doClip(clipPaths, ctx);
  7867. scope.prevElClipPaths = clipPaths;
  7868. }
  7869. }
  7870. el.beforeBrush && el.beforeBrush(ctx);
  7871. el.brush(ctx, scope.prevEl || null);
  7872. scope.prevEl = el;
  7873. el.afterBrush && el.afterBrush(ctx);
  7874. }
  7875. },
  7876. /**
  7877. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7878. * @param {number} zlevel
  7879. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7880. * @return {module:zrender/Layer}
  7881. */
  7882. getLayer: function (zlevel, virtual) {
  7883. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7884. zlevel = CANVAS_ZLEVEL;
  7885. }
  7886. var layer = this._layers[zlevel];
  7887. if (!layer) {
  7888. // Create a new layer
  7889. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7890. layer.zlevel = zlevel;
  7891. layer.__builtin__ = true;
  7892. if (this._layerConfig[zlevel]) {
  7893. merge(layer, this._layerConfig[zlevel], true);
  7894. }
  7895. if (virtual) {
  7896. layer.virtual = virtual;
  7897. }
  7898. this.insertLayer(zlevel, layer);
  7899. // Context is created after dom inserted to document
  7900. // Or excanvas will get 0px clientWidth and clientHeight
  7901. layer.initContext();
  7902. }
  7903. return layer;
  7904. },
  7905. insertLayer: function (zlevel, layer) {
  7906. var layersMap = this._layers;
  7907. var zlevelList = this._zlevelList;
  7908. var len = zlevelList.length;
  7909. var prevLayer = null;
  7910. var i = -1;
  7911. var domRoot = this._domRoot;
  7912. if (layersMap[zlevel]) {
  7913. zrLog('ZLevel ' + zlevel + ' has been used already');
  7914. return;
  7915. }
  7916. // Check if is a valid layer
  7917. if (!isLayerValid(layer)) {
  7918. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7919. return;
  7920. }
  7921. if (len > 0 && zlevel > zlevelList[0]) {
  7922. for (i = 0; i < len - 1; i++) {
  7923. if (
  7924. zlevelList[i] < zlevel
  7925. && zlevelList[i + 1] > zlevel
  7926. ) {
  7927. break;
  7928. }
  7929. }
  7930. prevLayer = layersMap[zlevelList[i]];
  7931. }
  7932. zlevelList.splice(i + 1, 0, zlevel);
  7933. layersMap[zlevel] = layer;
  7934. // Vitual layer will not directly show on the screen.
  7935. // (It can be a WebGL layer and assigned to a ZImage element)
  7936. // But it still under management of zrender.
  7937. if (!layer.virtual) {
  7938. if (prevLayer) {
  7939. var prevDom = prevLayer.dom;
  7940. if (prevDom.nextSibling) {
  7941. domRoot.insertBefore(
  7942. layer.dom,
  7943. prevDom.nextSibling
  7944. );
  7945. }
  7946. else {
  7947. domRoot.appendChild(layer.dom);
  7948. }
  7949. }
  7950. else {
  7951. if (domRoot.firstChild) {
  7952. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7953. }
  7954. else {
  7955. domRoot.appendChild(layer.dom);
  7956. }
  7957. }
  7958. }
  7959. },
  7960. // Iterate each layer
  7961. eachLayer: function (cb, context) {
  7962. var zlevelList = this._zlevelList;
  7963. var z;
  7964. var i;
  7965. for (i = 0; i < zlevelList.length; i++) {
  7966. z = zlevelList[i];
  7967. cb.call(context, this._layers[z], z);
  7968. }
  7969. },
  7970. // Iterate each buildin layer
  7971. eachBuiltinLayer: function (cb, context) {
  7972. var zlevelList = this._zlevelList;
  7973. var layer;
  7974. var z;
  7975. var i;
  7976. for (i = 0; i < zlevelList.length; i++) {
  7977. z = zlevelList[i];
  7978. layer = this._layers[z];
  7979. if (layer.__builtin__) {
  7980. cb.call(context, layer, z);
  7981. }
  7982. }
  7983. },
  7984. // Iterate each other layer except buildin layer
  7985. eachOtherLayer: function (cb, context) {
  7986. var zlevelList = this._zlevelList;
  7987. var layer;
  7988. var z;
  7989. var i;
  7990. for (i = 0; i < zlevelList.length; i++) {
  7991. z = zlevelList[i];
  7992. layer = this._layers[z];
  7993. if (!layer.__builtin__) {
  7994. cb.call(context, layer, z);
  7995. }
  7996. }
  7997. },
  7998. /**
  7999. * 获取所有已创建的层
  8000. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8001. */
  8002. getLayers: function () {
  8003. return this._layers;
  8004. },
  8005. _updateLayerStatus: function (list) {
  8006. this.eachBuiltinLayer(function (layer, z) {
  8007. layer.__dirty = layer.__used = false;
  8008. });
  8009. function updatePrevLayer(idx) {
  8010. if (prevLayer) {
  8011. if (prevLayer.__endIndex !== idx) {
  8012. prevLayer.__dirty = true;
  8013. }
  8014. prevLayer.__endIndex = idx;
  8015. }
  8016. }
  8017. if (this._singleCanvas) {
  8018. for (var i = 1; i < list.length; i++) {
  8019. var el = list[i];
  8020. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8021. this._needsManuallyCompositing = true;
  8022. break;
  8023. }
  8024. }
  8025. }
  8026. var prevLayer = null;
  8027. var incrementalLayerCount = 0;
  8028. for (var i = 0; i < list.length; i++) {
  8029. var el = list[i];
  8030. var zlevel = el.zlevel;
  8031. var layer;
  8032. // PENDING If change one incremental element style ?
  8033. // TODO Where there are non-incremental elements between incremental elements.
  8034. if (el.incremental) {
  8035. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8036. layer.incremental = true;
  8037. incrementalLayerCount = 1;
  8038. }
  8039. else {
  8040. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8041. }
  8042. if (!layer.__builtin__) {
  8043. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8044. }
  8045. if (layer !== prevLayer) {
  8046. layer.__used = true;
  8047. if (layer.__startIndex !== i) {
  8048. layer.__dirty = true;
  8049. }
  8050. layer.__startIndex = i;
  8051. if (!layer.incremental) {
  8052. layer.__drawIndex = i;
  8053. }
  8054. else {
  8055. // Mark layer draw index needs to update.
  8056. layer.__drawIndex = -1;
  8057. }
  8058. updatePrevLayer(i);
  8059. prevLayer = layer;
  8060. }
  8061. if (el.__dirty) {
  8062. layer.__dirty = true;
  8063. if (layer.incremental && layer.__drawIndex < 0) {
  8064. // Start draw from the first dirty element.
  8065. layer.__drawIndex = i;
  8066. }
  8067. }
  8068. }
  8069. updatePrevLayer(i);
  8070. this.eachBuiltinLayer(function (layer, z) {
  8071. // Used in last frame but not in this frame. Needs clear
  8072. if (!layer.__used && layer.getElementCount() > 0) {
  8073. layer.__dirty = true;
  8074. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8075. }
  8076. // For incremental layer. In case start index changed and no elements are dirty.
  8077. if (layer.__dirty && layer.__drawIndex < 0) {
  8078. layer.__drawIndex = layer.__startIndex;
  8079. }
  8080. });
  8081. },
  8082. /**
  8083. * 清除hover层外所有内容
  8084. */
  8085. clear: function () {
  8086. this.eachBuiltinLayer(this._clearLayer);
  8087. return this;
  8088. },
  8089. _clearLayer: function (layer) {
  8090. layer.clear();
  8091. },
  8092. /**
  8093. * 修改指定zlevel的绘制参数
  8094. *
  8095. * @param {string} zlevel
  8096. * @param {Object} config 配置对象
  8097. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8098. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8099. * @param {number} [config.lastFrameAlpha=0.7]
  8100. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8101. */
  8102. configLayer: function (zlevel, config) {
  8103. if (config) {
  8104. var layerConfig = this._layerConfig;
  8105. if (!layerConfig[zlevel]) {
  8106. layerConfig[zlevel] = config;
  8107. }
  8108. else {
  8109. merge(layerConfig[zlevel], config, true);
  8110. }
  8111. for (var i = 0; i < this._zlevelList.length; i++) {
  8112. var _zlevel = this._zlevelList[i];
  8113. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8114. var layer = this._layers[_zlevel];
  8115. merge(layer, layerConfig[zlevel], true);
  8116. }
  8117. }
  8118. }
  8119. },
  8120. /**
  8121. * 删除指定层
  8122. * @param {number} zlevel 层所在的zlevel
  8123. */
  8124. delLayer: function (zlevel) {
  8125. var layers = this._layers;
  8126. var zlevelList = this._zlevelList;
  8127. var layer = layers[zlevel];
  8128. if (!layer) {
  8129. return;
  8130. }
  8131. layer.dom.parentNode.removeChild(layer.dom);
  8132. delete layers[zlevel];
  8133. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8134. },
  8135. /**
  8136. * 区域大小变化后重绘
  8137. */
  8138. resize: function (width, height) {
  8139. if (!this._domRoot.style) { // Maybe in node or worker
  8140. if (width == null || height == null) {
  8141. return;
  8142. }
  8143. this._width = width;
  8144. this._height = height;
  8145. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8146. }
  8147. else {
  8148. var domRoot = this._domRoot;
  8149. // FIXME Why ?
  8150. domRoot.style.display = 'none';
  8151. // Save input w/h
  8152. var opts = this._opts;
  8153. width != null && (opts.width = width);
  8154. height != null && (opts.height = height);
  8155. width = this._getSize(0);
  8156. height = this._getSize(1);
  8157. domRoot.style.display = '';
  8158. // 优化没有实际改变的resize
  8159. if (this._width != width || height != this._height) {
  8160. domRoot.style.width = width + 'px';
  8161. domRoot.style.height = height + 'px';
  8162. for (var id in this._layers) {
  8163. if (this._layers.hasOwnProperty(id)) {
  8164. this._layers[id].resize(width, height);
  8165. }
  8166. }
  8167. each$1(this._progressiveLayers, function (layer) {
  8168. layer.resize(width, height);
  8169. });
  8170. this.refresh(true);
  8171. }
  8172. this._width = width;
  8173. this._height = height;
  8174. }
  8175. return this;
  8176. },
  8177. /**
  8178. * 清除单独的一个层
  8179. * @param {number} zlevel
  8180. */
  8181. clearLayer: function (zlevel) {
  8182. var layer = this._layers[zlevel];
  8183. if (layer) {
  8184. layer.clear();
  8185. }
  8186. },
  8187. /**
  8188. * 释放
  8189. */
  8190. dispose: function () {
  8191. this.root.innerHTML = '';
  8192. this.root =
  8193. this.storage =
  8194. this._domRoot =
  8195. this._layers = null;
  8196. },
  8197. /**
  8198. * Get canvas which has all thing rendered
  8199. * @param {Object} opts
  8200. * @param {string} [opts.backgroundColor]
  8201. * @param {number} [opts.pixelRatio]
  8202. */
  8203. getRenderedCanvas: function (opts) {
  8204. opts = opts || {};
  8205. if (this._singleCanvas && !this._compositeManually) {
  8206. return this._layers[CANVAS_ZLEVEL].dom;
  8207. }
  8208. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8209. imageLayer.initContext();
  8210. imageLayer.clearColor = opts.backgroundColor;
  8211. imageLayer.clear();
  8212. if (opts.pixelRatio <= this.dpr) {
  8213. this.refresh();
  8214. var width = imageLayer.dom.width;
  8215. var height = imageLayer.dom.height;
  8216. var ctx = imageLayer.ctx;
  8217. this.eachLayer(function (layer) {
  8218. if (layer.__builtin__) {
  8219. ctx.drawImage(layer.dom, 0, 0, width, height);
  8220. }
  8221. else if (layer.renderToCanvas) {
  8222. imageLayer.ctx.save();
  8223. layer.renderToCanvas(imageLayer.ctx);
  8224. imageLayer.ctx.restore();
  8225. }
  8226. });
  8227. }
  8228. else {
  8229. // PENDING, echarts-gl and incremental rendering.
  8230. var scope = {};
  8231. var displayList = this.storage.getDisplayList(true);
  8232. for (var i = 0; i < displayList.length; i++) {
  8233. var el = displayList[i];
  8234. this._doPaintEl(el, imageLayer, true, scope);
  8235. }
  8236. }
  8237. return imageLayer.dom;
  8238. },
  8239. /**
  8240. * 获取绘图区域宽度
  8241. */
  8242. getWidth: function () {
  8243. return this._width;
  8244. },
  8245. /**
  8246. * 获取绘图区域高度
  8247. */
  8248. getHeight: function () {
  8249. return this._height;
  8250. },
  8251. _getSize: function (whIdx) {
  8252. var opts = this._opts;
  8253. var wh = ['width', 'height'][whIdx];
  8254. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8255. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8256. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8257. if (opts[wh] != null && opts[wh] !== 'auto') {
  8258. return parseFloat(opts[wh]);
  8259. }
  8260. var root = this.root;
  8261. // IE8 does not support getComputedStyle, but it use VML.
  8262. var stl = document.defaultView.getComputedStyle(root);
  8263. return (
  8264. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8265. - (parseInt10(stl[plt]) || 0)
  8266. - (parseInt10(stl[prb]) || 0)
  8267. ) | 0;
  8268. },
  8269. pathToImage: function (path, dpr) {
  8270. dpr = dpr || this.dpr;
  8271. var canvas = document.createElement('canvas');
  8272. var ctx = canvas.getContext('2d');
  8273. var rect = path.getBoundingRect();
  8274. var style = path.style;
  8275. var shadowBlurSize = style.shadowBlur * dpr;
  8276. var shadowOffsetX = style.shadowOffsetX * dpr;
  8277. var shadowOffsetY = style.shadowOffsetY * dpr;
  8278. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8279. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8280. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8281. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8282. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8283. var width = rect.width + leftMargin + rightMargin;
  8284. var height = rect.height + topMargin + bottomMargin;
  8285. canvas.width = width * dpr;
  8286. canvas.height = height * dpr;
  8287. ctx.scale(dpr, dpr);
  8288. ctx.clearRect(0, 0, width, height);
  8289. ctx.dpr = dpr;
  8290. var pathTransform = {
  8291. position: path.position,
  8292. rotation: path.rotation,
  8293. scale: path.scale
  8294. };
  8295. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8296. path.rotation = 0;
  8297. path.scale = [1, 1];
  8298. path.updateTransform();
  8299. if (path) {
  8300. path.brush(ctx);
  8301. }
  8302. var ImageShape = ZImage;
  8303. var imgShape = new ImageShape({
  8304. style: {
  8305. x: 0,
  8306. y: 0,
  8307. image: canvas
  8308. }
  8309. });
  8310. if (pathTransform.position != null) {
  8311. imgShape.position = path.position = pathTransform.position;
  8312. }
  8313. if (pathTransform.rotation != null) {
  8314. imgShape.rotation = path.rotation = pathTransform.rotation;
  8315. }
  8316. if (pathTransform.scale != null) {
  8317. imgShape.scale = path.scale = pathTransform.scale;
  8318. }
  8319. return imgShape;
  8320. }
  8321. };
  8322. /**
  8323. * 事件辅助类
  8324. * @module zrender/core/event
  8325. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8326. */
  8327. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8328. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8329. function getBoundingClientRect(el) {
  8330. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8331. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8332. }
  8333. // `calculate` is optional, default false
  8334. function clientToLocal(el, e, out, calculate) {
  8335. out = out || {};
  8336. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8337. // to the padding edge of the target element. The only browser using this convention
  8338. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8339. // not support the properties.
  8340. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8341. // In zr painter.dom, padding edge equals to border edge.
  8342. // FIXME
  8343. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8344. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8345. // is too complex. So css-transfrom dont support in this case temporarily.
  8346. if (calculate || !env$1.canvasSupported) {
  8347. defaultGetZrXY(el, e, out);
  8348. }
  8349. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8350. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8351. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8352. // zoom-factor, overflow / opacity layers, transforms ...)
  8353. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8354. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8355. // BTW3, In ff, offsetX/offsetY is always 0.
  8356. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8357. out.zrX = e.layerX;
  8358. out.zrY = e.layerY;
  8359. }
  8360. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8361. else if (e.offsetX != null) {
  8362. out.zrX = e.offsetX;
  8363. out.zrY = e.offsetY;
  8364. }
  8365. // For some other device, e.g., IOS safari.
  8366. else {
  8367. defaultGetZrXY(el, e, out);
  8368. }
  8369. return out;
  8370. }
  8371. function defaultGetZrXY(el, e, out) {
  8372. // This well-known method below does not support css transform.
  8373. var box = getBoundingClientRect(el);
  8374. out.zrX = e.clientX - box.left;
  8375. out.zrY = e.clientY - box.top;
  8376. }
  8377. /**
  8378. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8379. * `calculate` is optional, default false.
  8380. */
  8381. function normalizeEvent(el, e, calculate) {
  8382. e = e || window.event;
  8383. if (e.zrX != null) {
  8384. return e;
  8385. }
  8386. var eventType = e.type;
  8387. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8388. if (!isTouch) {
  8389. clientToLocal(el, e, e, calculate);
  8390. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8391. }
  8392. else {
  8393. var touch = eventType != 'touchend'
  8394. ? e.targetTouches[0]
  8395. : e.changedTouches[0];
  8396. touch && clientToLocal(el, touch, e, calculate);
  8397. }
  8398. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8399. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8400. // If e.which has been defined, if may be readonly,
  8401. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8402. var button = e.button;
  8403. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8404. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8405. }
  8406. return e;
  8407. }
  8408. function addEventListener(el, name, handler) {
  8409. if (isDomLevel2) {
  8410. el.addEventListener(name, handler);
  8411. }
  8412. else {
  8413. el.attachEvent('on' + name, handler);
  8414. }
  8415. }
  8416. function removeEventListener(el, name, handler) {
  8417. if (isDomLevel2) {
  8418. el.removeEventListener(name, handler);
  8419. }
  8420. else {
  8421. el.detachEvent('on' + name, handler);
  8422. }
  8423. }
  8424. /**
  8425. * preventDefault and stopPropagation.
  8426. * Notice: do not do that in zrender. Upper application
  8427. * do that if necessary.
  8428. *
  8429. * @memberOf module:zrender/core/event
  8430. * @method
  8431. * @param {Event} e : event对象
  8432. */
  8433. var stop = isDomLevel2
  8434. ? function (e) {
  8435. e.preventDefault();
  8436. e.stopPropagation();
  8437. e.cancelBubble = true;
  8438. }
  8439. : function (e) {
  8440. e.returnValue = false;
  8441. e.cancelBubble = true;
  8442. };
  8443. function notLeftMouse(e) {
  8444. // If e.which is undefined, considered as left mouse event.
  8445. return e.which > 1;
  8446. }
  8447. /**
  8448. * 动画主类, 调度和管理所有动画控制器
  8449. *
  8450. * @module zrender/animation/Animation
  8451. * @author pissang(https://github.com/pissang)
  8452. */
  8453. // TODO Additive animation
  8454. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8455. // https://developer.apple.com/videos/wwdc2014/#236
  8456. /**
  8457. * @typedef {Object} IZRenderStage
  8458. * @property {Function} update
  8459. */
  8460. /**
  8461. * @alias module:zrender/animation/Animation
  8462. * @constructor
  8463. * @param {Object} [options]
  8464. * @param {Function} [options.onframe]
  8465. * @param {IZRenderStage} [options.stage]
  8466. * @example
  8467. * var animation = new Animation();
  8468. * var obj = {
  8469. * x: 100,
  8470. * y: 100
  8471. * };
  8472. * animation.animate(node.position)
  8473. * .when(1000, {
  8474. * x: 500,
  8475. * y: 500
  8476. * })
  8477. * .when(2000, {
  8478. * x: 100,
  8479. * y: 100
  8480. * })
  8481. * .start('spline');
  8482. */
  8483. var Animation = function (options) {
  8484. options = options || {};
  8485. this.stage = options.stage || {};
  8486. this.onframe = options.onframe || function() {};
  8487. // private properties
  8488. this._clips = [];
  8489. this._running = false;
  8490. this._time;
  8491. this._pausedTime;
  8492. this._pauseStart;
  8493. this._paused = false;
  8494. Eventful.call(this);
  8495. };
  8496. Animation.prototype = {
  8497. constructor: Animation,
  8498. /**
  8499. * 添加 clip
  8500. * @param {module:zrender/animation/Clip} clip
  8501. */
  8502. addClip: function (clip) {
  8503. this._clips.push(clip);
  8504. },
  8505. /**
  8506. * 添加 animator
  8507. * @param {module:zrender/animation/Animator} animator
  8508. */
  8509. addAnimator: function (animator) {
  8510. animator.animation = this;
  8511. var clips = animator.getClips();
  8512. for (var i = 0; i < clips.length; i++) {
  8513. this.addClip(clips[i]);
  8514. }
  8515. },
  8516. /**
  8517. * 删除动画片段
  8518. * @param {module:zrender/animation/Clip} clip
  8519. */
  8520. removeClip: function(clip) {
  8521. var idx = indexOf(this._clips, clip);
  8522. if (idx >= 0) {
  8523. this._clips.splice(idx, 1);
  8524. }
  8525. },
  8526. /**
  8527. * 删除动画片段
  8528. * @param {module:zrender/animation/Animator} animator
  8529. */
  8530. removeAnimator: function (animator) {
  8531. var clips = animator.getClips();
  8532. for (var i = 0; i < clips.length; i++) {
  8533. this.removeClip(clips[i]);
  8534. }
  8535. animator.animation = null;
  8536. },
  8537. _update: function() {
  8538. var time = new Date().getTime() - this._pausedTime;
  8539. var delta = time - this._time;
  8540. var clips = this._clips;
  8541. var len = clips.length;
  8542. var deferredEvents = [];
  8543. var deferredClips = [];
  8544. for (var i = 0; i < len; i++) {
  8545. var clip = clips[i];
  8546. var e = clip.step(time, delta);
  8547. // Throw out the events need to be called after
  8548. // stage.update, like destroy
  8549. if (e) {
  8550. deferredEvents.push(e);
  8551. deferredClips.push(clip);
  8552. }
  8553. }
  8554. // Remove the finished clip
  8555. for (var i = 0; i < len;) {
  8556. if (clips[i]._needsRemove) {
  8557. clips[i] = clips[len - 1];
  8558. clips.pop();
  8559. len--;
  8560. }
  8561. else {
  8562. i++;
  8563. }
  8564. }
  8565. len = deferredEvents.length;
  8566. for (var i = 0; i < len; i++) {
  8567. deferredClips[i].fire(deferredEvents[i]);
  8568. }
  8569. this._time = time;
  8570. this.onframe(delta);
  8571. // Frame should before stage update. Upper application
  8572. // depends on the sequence (e.g., echarts-stream)
  8573. this.trigger('frame', delta);
  8574. if (this.stage.update) {
  8575. this.stage.update();
  8576. }
  8577. },
  8578. _startLoop: function () {
  8579. var self = this;
  8580. this._running = true;
  8581. function step() {
  8582. if (self._running) {
  8583. requestAnimationFrame(step);
  8584. !self._paused && self._update();
  8585. }
  8586. }
  8587. requestAnimationFrame(step);
  8588. },
  8589. /**
  8590. * 开始运行动画
  8591. */
  8592. start: function () {
  8593. this._time = new Date().getTime();
  8594. this._pausedTime = 0;
  8595. this._startLoop();
  8596. },
  8597. /**
  8598. * 停止运行动画
  8599. */
  8600. stop: function () {
  8601. this._running = false;
  8602. },
  8603. /**
  8604. * Pause
  8605. */
  8606. pause: function () {
  8607. if (!this._paused) {
  8608. this._pauseStart = new Date().getTime();
  8609. this._paused = true;
  8610. }
  8611. },
  8612. /**
  8613. * Resume
  8614. */
  8615. resume: function () {
  8616. if (this._paused) {
  8617. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8618. this._paused = false;
  8619. }
  8620. },
  8621. /**
  8622. * 清除所有动画片段
  8623. */
  8624. clear: function () {
  8625. this._clips = [];
  8626. },
  8627. /**
  8628. * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画
  8629. * @param {Object} target
  8630. * @param {Object} options
  8631. * @param {boolean} [options.loop=false] 是否循环播放动画
  8632. * @param {Function} [options.getter=null]
  8633. * 如果指定getter函数,会通过getter函数取属性值
  8634. * @param {Function} [options.setter=null]
  8635. * 如果指定setter函数,会通过setter函数设置属性值
  8636. * @return {module:zrender/animation/Animation~Animator}
  8637. */
  8638. // TODO Gap
  8639. animate: function (target, options) {
  8640. options = options || {};
  8641. var animator = new Animator(
  8642. target,
  8643. options.loop,
  8644. options.getter,
  8645. options.setter
  8646. );
  8647. this.addAnimator(animator);
  8648. return animator;
  8649. }
  8650. };
  8651. mixin(Animation, Eventful);
  8652. /**
  8653. * Only implements needed gestures for mobile.
  8654. */
  8655. var GestureMgr = function () {
  8656. /**
  8657. * @private
  8658. * @type {Array.<Object>}
  8659. */
  8660. this._track = [];
  8661. };
  8662. GestureMgr.prototype = {
  8663. constructor: GestureMgr,
  8664. recognize: function (event, target, root) {
  8665. this._doTrack(event, target, root);
  8666. return this._recognize(event);
  8667. },
  8668. clear: function () {
  8669. this._track.length = 0;
  8670. return this;
  8671. },
  8672. _doTrack: function (event, target, root) {
  8673. var touches = event.touches;
  8674. if (!touches) {
  8675. return;
  8676. }
  8677. var trackItem = {
  8678. points: [],
  8679. touches: [],
  8680. target: target,
  8681. event: event
  8682. };
  8683. for (var i = 0, len = touches.length; i < len; i++) {
  8684. var touch = touches[i];
  8685. var pos = clientToLocal(root, touch, {});
  8686. trackItem.points.push([pos.zrX, pos.zrY]);
  8687. trackItem.touches.push(touch);
  8688. }
  8689. this._track.push(trackItem);
  8690. },
  8691. _recognize: function (event) {
  8692. for (var eventName in recognizers) {
  8693. if (recognizers.hasOwnProperty(eventName)) {
  8694. var gestureInfo = recognizers[eventName](this._track, event);
  8695. if (gestureInfo) {
  8696. return gestureInfo;
  8697. }
  8698. }
  8699. }
  8700. }
  8701. };
  8702. function dist$1(pointPair) {
  8703. var dx = pointPair[1][0] - pointPair[0][0];
  8704. var dy = pointPair[1][1] - pointPair[0][1];
  8705. return Math.sqrt(dx * dx + dy * dy);
  8706. }
  8707. function center(pointPair) {
  8708. return [
  8709. (pointPair[0][0] + pointPair[1][0]) / 2,
  8710. (pointPair[0][1] + pointPair[1][1]) / 2
  8711. ];
  8712. }
  8713. var recognizers = {
  8714. pinch: function (track, event) {
  8715. var trackLen = track.length;
  8716. if (!trackLen) {
  8717. return;
  8718. }
  8719. var pinchEnd = (track[trackLen - 1] || {}).points;
  8720. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8721. if (pinchPre
  8722. && pinchPre.length > 1
  8723. && pinchEnd
  8724. && pinchEnd.length > 1
  8725. ) {
  8726. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8727. !isFinite(pinchScale) && (pinchScale = 1);
  8728. event.pinchScale = pinchScale;
  8729. var pinchCenter = center(pinchEnd);
  8730. event.pinchX = pinchCenter[0];
  8731. event.pinchY = pinchCenter[1];
  8732. return {
  8733. type: 'pinch',
  8734. target: track[0].target,
  8735. event: event
  8736. };
  8737. }
  8738. }
  8739. // Only pinch currently.
  8740. };
  8741. var TOUCH_CLICK_DELAY = 300;
  8742. var mouseHandlerNames = [
  8743. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8744. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8745. ];
  8746. var touchHandlerNames = [
  8747. 'touchstart', 'touchend', 'touchmove'
  8748. ];
  8749. var pointerEventNames = {
  8750. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8751. };
  8752. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8753. var nm = name.replace('mouse', 'pointer');
  8754. return pointerEventNames[nm] ? nm : name;
  8755. });
  8756. function eventNameFix(name) {
  8757. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8758. }
  8759. function processGesture(proxy, event, stage) {
  8760. var gestureMgr = proxy._gestureMgr;
  8761. stage === 'start' && gestureMgr.clear();
  8762. var gestureInfo = gestureMgr.recognize(
  8763. event,
  8764. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8765. proxy.dom
  8766. );
  8767. stage === 'end' && gestureMgr.clear();
  8768. // Do not do any preventDefault here. Upper application do that if necessary.
  8769. if (gestureInfo) {
  8770. var type = gestureInfo.type;
  8771. event.gestureEvent = type;
  8772. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8773. }
  8774. }
  8775. // function onMSGestureChange(proxy, event) {
  8776. // if (event.translationX || event.translationY) {
  8777. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8778. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8779. // }
  8780. // if (event.scale !== 1) {
  8781. // event.pinchX = event.offsetX;
  8782. // event.pinchY = event.offsetY;
  8783. // event.pinchScale = event.scale;
  8784. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8785. // }
  8786. // }
  8787. /**
  8788. * Prevent mouse event from being dispatched after Touch Events action
  8789. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8790. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8791. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8792. * Result: Blocking Mouse Events for 700ms.
  8793. */
  8794. function setTouchTimer(instance) {
  8795. instance._touching = true;
  8796. clearTimeout(instance._touchTimer);
  8797. instance._touchTimer = setTimeout(function () {
  8798. instance._touching = false;
  8799. }, 700);
  8800. }
  8801. var domHandlers = {
  8802. /**
  8803. * Mouse move handler
  8804. * @inner
  8805. * @param {Event} event
  8806. */
  8807. mousemove: function (event) {
  8808. event = normalizeEvent(this.dom, event);
  8809. this.trigger('mousemove', event);
  8810. },
  8811. /**
  8812. * Mouse out handler
  8813. * @inner
  8814. * @param {Event} event
  8815. */
  8816. mouseout: function (event) {
  8817. event = normalizeEvent(this.dom, event);
  8818. var element = event.toElement || event.relatedTarget;
  8819. if (element != this.dom) {
  8820. while (element && element.nodeType != 9) {
  8821. // 忽略包含在root中的dom引起的mouseOut
  8822. if (element === this.dom) {
  8823. return;
  8824. }
  8825. element = element.parentNode;
  8826. }
  8827. }
  8828. this.trigger('mouseout', event);
  8829. },
  8830. /**
  8831. * Touch开始响应函数
  8832. * @inner
  8833. * @param {Event} event
  8834. */
  8835. touchstart: function (event) {
  8836. // Default mouse behaviour should not be disabled here.
  8837. // For example, page may needs to be slided.
  8838. event = normalizeEvent(this.dom, event);
  8839. // Mark touch, which is useful in distinguish touch and
  8840. // mouse event in upper applicatoin.
  8841. event.zrByTouch = true;
  8842. this._lastTouchMoment = new Date();
  8843. processGesture(this, event, 'start');
  8844. // In touch device, trigger `mousemove`(`mouseover`) should
  8845. // be triggered, and must before `mousedown` triggered.
  8846. domHandlers.mousemove.call(this, event);
  8847. domHandlers.mousedown.call(this, event);
  8848. setTouchTimer(this);
  8849. },
  8850. /**
  8851. * Touch移动响应函数
  8852. * @inner
  8853. * @param {Event} event
  8854. */
  8855. touchmove: function (event) {
  8856. event = normalizeEvent(this.dom, event);
  8857. // Mark touch, which is useful in distinguish touch and
  8858. // mouse event in upper applicatoin.
  8859. event.zrByTouch = true;
  8860. processGesture(this, event, 'change');
  8861. // Mouse move should always be triggered no matter whether
  8862. // there is gestrue event, because mouse move and pinch may
  8863. // be used at the same time.
  8864. domHandlers.mousemove.call(this, event);
  8865. setTouchTimer(this);
  8866. },
  8867. /**
  8868. * Touch结束响应函数
  8869. * @inner
  8870. * @param {Event} event
  8871. */
  8872. touchend: function (event) {
  8873. event = normalizeEvent(this.dom, event);
  8874. // Mark touch, which is useful in distinguish touch and
  8875. // mouse event in upper applicatoin.
  8876. event.zrByTouch = true;
  8877. processGesture(this, event, 'end');
  8878. domHandlers.mouseup.call(this, event);
  8879. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8880. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8881. // we can conveniently implement "hover style" in both PC and touch device just
  8882. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8883. // to remove "hover style" on an element, without any additional code for
  8884. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8885. // style" will remain for user view)
  8886. // click event should always be triggered no matter whether
  8887. // there is gestrue event. System click can not be prevented.
  8888. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8889. domHandlers.click.call(this, event);
  8890. }
  8891. setTouchTimer(this);
  8892. },
  8893. pointerdown: function (event) {
  8894. domHandlers.mousedown.call(this, event);
  8895. // if (useMSGuesture(this, event)) {
  8896. // this._msGesture.addPointer(event.pointerId);
  8897. // }
  8898. },
  8899. pointermove: function (event) {
  8900. // FIXME
  8901. // pointermove is so sensitive that it always triggered when
  8902. // tap(click) on touch screen, which affect some judgement in
  8903. // upper application. So, we dont support mousemove on MS touch
  8904. // device yet.
  8905. if (!isPointerFromTouch(event)) {
  8906. domHandlers.mousemove.call(this, event);
  8907. }
  8908. },
  8909. pointerup: function (event) {
  8910. domHandlers.mouseup.call(this, event);
  8911. },
  8912. pointerout: function (event) {
  8913. // pointerout will be triggered when tap on touch screen
  8914. // (IE11+/Edge on MS Surface) after click event triggered,
  8915. // which is inconsistent with the mousout behavior we defined
  8916. // in touchend. So we unify them.
  8917. // (check domHandlers.touchend for detailed explanation)
  8918. if (!isPointerFromTouch(event)) {
  8919. domHandlers.mouseout.call(this, event);
  8920. }
  8921. }
  8922. };
  8923. function isPointerFromTouch(event) {
  8924. var pointerType = event.pointerType;
  8925. return pointerType === 'pen' || pointerType === 'touch';
  8926. }
  8927. // function useMSGuesture(handlerProxy, event) {
  8928. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8929. // }
  8930. // Common handlers
  8931. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8932. domHandlers[name] = function (event) {
  8933. event = normalizeEvent(this.dom, event);
  8934. this.trigger(name, event);
  8935. };
  8936. });
  8937. /**
  8938. * 为控制类实例初始化dom 事件处理函数
  8939. *
  8940. * @inner
  8941. * @param {module:zrender/Handler} instance 控制类实例
  8942. */
  8943. function initDomHandler(instance) {
  8944. each$1(touchHandlerNames, function (name) {
  8945. instance._handlers[name] = bind(domHandlers[name], instance);
  8946. });
  8947. each$1(pointerHandlerNames, function (name) {
  8948. instance._handlers[name] = bind(domHandlers[name], instance);
  8949. });
  8950. each$1(mouseHandlerNames, function (name) {
  8951. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  8952. });
  8953. function makeMouseHandler(fn, instance) {
  8954. return function () {
  8955. if (instance._touching) {
  8956. return;
  8957. }
  8958. return fn.apply(instance, arguments);
  8959. };
  8960. }
  8961. }
  8962. function HandlerDomProxy(dom) {
  8963. Eventful.call(this);
  8964. this.dom = dom;
  8965. /**
  8966. * @private
  8967. * @type {boolean}
  8968. */
  8969. this._touching = false;
  8970. /**
  8971. * @private
  8972. * @type {number}
  8973. */
  8974. this._touchTimer;
  8975. /**
  8976. * @private
  8977. * @type {module:zrender/core/GestureMgr}
  8978. */
  8979. this._gestureMgr = new GestureMgr();
  8980. this._handlers = {};
  8981. initDomHandler(this);
  8982. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  8983. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  8984. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  8985. // at the same time.
  8986. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  8987. // screen, which do not occurs in pointer event.
  8988. // So we use pointer event to both detect touch gesture and mouse behavior.
  8989. mountHandlers(pointerHandlerNames, this);
  8990. // FIXME
  8991. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  8992. // which does not prevent defuault behavior occasionally (which may cause view port
  8993. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  8994. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  8995. // touch screen. And we only support click behavior on MS touch screen now.
  8996. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  8997. // We dont support touch on IE on win7.
  8998. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  8999. // if (typeof MSGesture === 'function') {
  9000. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9001. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9002. // }
  9003. }
  9004. else {
  9005. if (env$1.touchEventsSupported) {
  9006. mountHandlers(touchHandlerNames, this);
  9007. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9008. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9009. }
  9010. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9011. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9012. // mouse event can not be handle in those devices.
  9013. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9014. // mouseevent after touch event triggered, see `setTouchTimer`.
  9015. mountHandlers(mouseHandlerNames, this);
  9016. }
  9017. function mountHandlers(handlerNames, instance) {
  9018. each$1(handlerNames, function (name) {
  9019. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9020. }, instance);
  9021. }
  9022. }
  9023. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9024. handlerDomProxyProto.dispose = function () {
  9025. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9026. for (var i = 0; i < handlerNames.length; i++) {
  9027. var name = handlerNames[i];
  9028. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9029. }
  9030. };
  9031. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9032. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9033. };
  9034. mixin(HandlerDomProxy, Eventful);
  9035. /*!
  9036. * ZRender, a high performance 2d drawing library.
  9037. *
  9038. * Copyright (c) 2013, Baidu Inc.
  9039. * All rights reserved.
  9040. *
  9041. * LICENSE
  9042. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9043. */
  9044. var useVML = !env$1.canvasSupported;
  9045. var painterCtors = {
  9046. canvas: Painter
  9047. };
  9048. var instances$1 = {}; // ZRender实例map索引
  9049. /**
  9050. * @type {string}
  9051. */
  9052. var version$1 = '4.0.1';
  9053. /**
  9054. * Initializing a zrender instance
  9055. * @param {HTMLElement} dom
  9056. * @param {Object} opts
  9057. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9058. * @param {number} [opts.devicePixelRatio]
  9059. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9060. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9061. * @return {module:zrender/ZRender}
  9062. */
  9063. function init$1(dom, opts) {
  9064. var zr = new ZRender(guid(), dom, opts);
  9065. instances$1[zr.id] = zr;
  9066. return zr;
  9067. }
  9068. /**
  9069. * Dispose zrender instance
  9070. * @param {module:zrender/ZRender} zr
  9071. */
  9072. function dispose$1(zr) {
  9073. if (zr) {
  9074. zr.dispose();
  9075. }
  9076. else {
  9077. for (var key in instances$1) {
  9078. if (instances$1.hasOwnProperty(key)) {
  9079. instances$1[key].dispose();
  9080. }
  9081. }
  9082. instances$1 = {};
  9083. }
  9084. return this;
  9085. }
  9086. /**
  9087. * Get zrender instance by id
  9088. * @param {string} id zrender instance id
  9089. * @return {module:zrender/ZRender}
  9090. */
  9091. function getInstance(id) {
  9092. return instances$1[id];
  9093. }
  9094. function registerPainter(name, Ctor) {
  9095. painterCtors[name] = Ctor;
  9096. }
  9097. function delInstance(id) {
  9098. delete instances$1[id];
  9099. }
  9100. /**
  9101. * @module zrender/ZRender
  9102. */
  9103. /**
  9104. * @constructor
  9105. * @alias module:zrender/ZRender
  9106. * @param {string} id
  9107. * @param {HTMLElement} dom
  9108. * @param {Object} opts
  9109. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9110. * @param {number} [opts.devicePixelRatio]
  9111. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9112. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9113. */
  9114. var ZRender = function (id, dom, opts) {
  9115. opts = opts || {};
  9116. /**
  9117. * @type {HTMLDomElement}
  9118. */
  9119. this.dom = dom;
  9120. /**
  9121. * @type {string}
  9122. */
  9123. this.id = id;
  9124. var self = this;
  9125. var storage = new Storage();
  9126. var rendererType = opts.renderer;
  9127. // TODO WebGL
  9128. if (useVML) {
  9129. if (!painterCtors.vml) {
  9130. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9131. }
  9132. rendererType = 'vml';
  9133. }
  9134. else if (!rendererType || !painterCtors[rendererType]) {
  9135. rendererType = 'canvas';
  9136. }
  9137. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9138. this.storage = storage;
  9139. this.painter = painter;
  9140. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9141. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9142. /**
  9143. * @type {module:zrender/animation/Animation}
  9144. */
  9145. this.animation = new Animation({
  9146. stage: {
  9147. update: bind(this.flush, this)
  9148. }
  9149. });
  9150. this.animation.start();
  9151. /**
  9152. * @type {boolean}
  9153. * @private
  9154. */
  9155. this._needsRefresh;
  9156. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9157. // FIXME 有点ugly
  9158. var oldDelFromStorage = storage.delFromStorage;
  9159. var oldAddToStorage = storage.addToStorage;
  9160. storage.delFromStorage = function (el) {
  9161. oldDelFromStorage.call(storage, el);
  9162. el && el.removeSelfFromZr(self);
  9163. };
  9164. storage.addToStorage = function (el) {
  9165. oldAddToStorage.call(storage, el);
  9166. el.addSelfToZr(self);
  9167. };
  9168. };
  9169. ZRender.prototype = {
  9170. constructor: ZRender,
  9171. /**
  9172. * 获取实例唯一标识
  9173. * @return {string}
  9174. */
  9175. getId: function () {
  9176. return this.id;
  9177. },
  9178. /**
  9179. * 添加元素
  9180. * @param {module:zrender/Element} el
  9181. */
  9182. add: function (el) {
  9183. this.storage.addRoot(el);
  9184. this._needsRefresh = true;
  9185. },
  9186. /**
  9187. * 删除元素
  9188. * @param {module:zrender/Element} el
  9189. */
  9190. remove: function (el) {
  9191. this.storage.delRoot(el);
  9192. this._needsRefresh = true;
  9193. },
  9194. /**
  9195. * Change configuration of layer
  9196. * @param {string} zLevel
  9197. * @param {Object} config
  9198. * @param {string} [config.clearColor=0] Clear color
  9199. * @param {string} [config.motionBlur=false] If enable motion blur
  9200. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9201. */
  9202. configLayer: function (zLevel, config) {
  9203. this.painter.configLayer(zLevel, config);
  9204. this._needsRefresh = true;
  9205. },
  9206. /**
  9207. * Repaint the canvas immediately
  9208. */
  9209. refreshImmediately: function () {
  9210. // var start = new Date();
  9211. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9212. // Or it will cause zrender refreshes again and again.
  9213. this._needsRefresh = false;
  9214. this.painter.refresh();
  9215. /**
  9216. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9217. */
  9218. this._needsRefresh = false;
  9219. // var end = new Date();
  9220. // var log = document.getElementById('log');
  9221. // if (log) {
  9222. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9223. // }
  9224. },
  9225. /**
  9226. * Mark and repaint the canvas in the next frame of browser
  9227. */
  9228. refresh: function() {
  9229. this._needsRefresh = true;
  9230. },
  9231. /**
  9232. * Perform all refresh
  9233. */
  9234. flush: function () {
  9235. if (this._needsRefresh) {
  9236. this.refreshImmediately();
  9237. }
  9238. if (this._needsRefreshHover) {
  9239. this.refreshHoverImmediately();
  9240. }
  9241. },
  9242. /**
  9243. * Add element to hover layer
  9244. * @param {module:zrender/Element} el
  9245. * @param {Object} style
  9246. */
  9247. addHover: function (el, style) {
  9248. if (this.painter.addHover) {
  9249. this.painter.addHover(el, style);
  9250. this.refreshHover();
  9251. }
  9252. },
  9253. /**
  9254. * Add element from hover layer
  9255. * @param {module:zrender/Element} el
  9256. */
  9257. removeHover: function (el) {
  9258. if (this.painter.removeHover) {
  9259. this.painter.removeHover(el);
  9260. this.refreshHover();
  9261. }
  9262. },
  9263. /**
  9264. * Clear all hover elements in hover layer
  9265. * @param {module:zrender/Element} el
  9266. */
  9267. clearHover: function () {
  9268. if (this.painter.clearHover) {
  9269. this.painter.clearHover();
  9270. this.refreshHover();
  9271. }
  9272. },
  9273. /**
  9274. * Refresh hover in next frame
  9275. */
  9276. refreshHover: function () {
  9277. this._needsRefreshHover = true;
  9278. },
  9279. /**
  9280. * Refresh hover immediately
  9281. */
  9282. refreshHoverImmediately: function () {
  9283. this._needsRefreshHover = false;
  9284. this.painter.refreshHover && this.painter.refreshHover();
  9285. },
  9286. /**
  9287. * Resize the canvas.
  9288. * Should be invoked when container size is changed
  9289. * @param {Object} [opts]
  9290. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9291. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9292. */
  9293. resize: function(opts) {
  9294. opts = opts || {};
  9295. this.painter.resize(opts.width, opts.height);
  9296. this.handler.resize();
  9297. },
  9298. /**
  9299. * Stop and clear all animation immediately
  9300. */
  9301. clearAnimation: function () {
  9302. this.animation.clear();
  9303. },
  9304. /**
  9305. * Get container width
  9306. */
  9307. getWidth: function() {
  9308. return this.painter.getWidth();
  9309. },
  9310. /**
  9311. * Get container height
  9312. */
  9313. getHeight: function() {
  9314. return this.painter.getHeight();
  9315. },
  9316. /**
  9317. * Export the canvas as Base64 URL
  9318. * @param {string} type
  9319. * @param {string} [backgroundColor='#fff']
  9320. * @return {string} Base64 URL
  9321. */
  9322. // toDataURL: function(type, backgroundColor) {
  9323. // return this.painter.getRenderedCanvas({
  9324. // backgroundColor: backgroundColor
  9325. // }).toDataURL(type);
  9326. // },
  9327. /**
  9328. * Converting a path to image.
  9329. * It has much better performance of drawing image rather than drawing a vector path.
  9330. * @param {module:zrender/graphic/Path} e
  9331. * @param {number} width
  9332. * @param {number} height
  9333. */
  9334. pathToImage: function(e, dpr) {
  9335. return this.painter.pathToImage(e, dpr);
  9336. },
  9337. /**
  9338. * Set default cursor
  9339. * @param {string} [cursorStyle='default'] 例如 crosshair
  9340. */
  9341. setCursorStyle: function (cursorStyle) {
  9342. this.handler.setCursorStyle(cursorStyle);
  9343. },
  9344. /**
  9345. * Find hovered element
  9346. * @param {number} x
  9347. * @param {number} y
  9348. * @return {Object} {target, topTarget}
  9349. */
  9350. findHover: function (x, y) {
  9351. return this.handler.findHover(x, y);
  9352. },
  9353. /**
  9354. * Bind event
  9355. *
  9356. * @param {string} eventName Event name
  9357. * @param {Function} eventHandler Handler function
  9358. * @param {Object} [context] Context object
  9359. */
  9360. on: function(eventName, eventHandler, context) {
  9361. this.handler.on(eventName, eventHandler, context);
  9362. },
  9363. /**
  9364. * Unbind event
  9365. * @param {string} eventName Event name
  9366. * @param {Function} [eventHandler] Handler function
  9367. */
  9368. off: function(eventName, eventHandler) {
  9369. this.handler.off(eventName, eventHandler);
  9370. },
  9371. /**
  9372. * Trigger event manually
  9373. *
  9374. * @param {string} eventName Event name
  9375. * @param {event=} event Event object
  9376. */
  9377. trigger: function (eventName, event) {
  9378. this.handler.trigger(eventName, event);
  9379. },
  9380. /**
  9381. * Clear all objects and the canvas.
  9382. */
  9383. clear: function () {
  9384. this.storage.delRoot();
  9385. this.painter.clear();
  9386. },
  9387. /**
  9388. * Dispose self.
  9389. */
  9390. dispose: function () {
  9391. this.animation.stop();
  9392. this.clear();
  9393. this.storage.dispose();
  9394. this.painter.dispose();
  9395. this.handler.dispose();
  9396. this.animation =
  9397. this.storage =
  9398. this.painter =
  9399. this.handler = null;
  9400. delInstance(this.id);
  9401. }
  9402. };
  9403. var zrender = (Object.freeze || Object)({
  9404. version: version$1,
  9405. init: init$1,
  9406. dispose: dispose$1,
  9407. getInstance: getInstance,
  9408. registerPainter: registerPainter
  9409. });
  9410. var each$2 = each$1;
  9411. var isObject$2 = isObject$1;
  9412. var isArray$1 = isArray;
  9413. /**
  9414. * name may be displayed on screen, so use '-'.
  9415. * But we should make sure it is not duplicated
  9416. * with user specified name, so use '\0';
  9417. */
  9418. var DEFAULT_COMPONENT_NAME = '\0-';
  9419. /**
  9420. * If value is not array, then translate it to array.
  9421. * @param {*} value
  9422. * @return {Array} [value] or value
  9423. */
  9424. function normalizeToArray(value) {
  9425. return value instanceof Array
  9426. ? value
  9427. : value == null
  9428. ? []
  9429. : [value];
  9430. }
  9431. /**
  9432. * Sync default option between normal and emphasis like `position` and `show`
  9433. * In case some one will write code like
  9434. * label: {
  9435. * show: false,
  9436. * position: 'outside',
  9437. * fontSize: 18
  9438. * },
  9439. * emphasis: {
  9440. * label: { show: true }
  9441. * }
  9442. * @param {Object} opt
  9443. * @param {string} key
  9444. * @param {Array.<string>} subOpts
  9445. */
  9446. function defaultEmphasis(opt, key, subOpts) {
  9447. if (opt) {
  9448. opt[key] = opt[key] || {};
  9449. opt.emphasis = opt.emphasis || {};
  9450. opt.emphasis[key] = opt.emphasis[key] || {};
  9451. // Default emphasis option from normal
  9452. for (var i = 0, len = subOpts.length; i < len; i++) {
  9453. var subOptName = subOpts[i];
  9454. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9455. && opt[key].hasOwnProperty(subOptName)
  9456. ) {
  9457. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9458. }
  9459. }
  9460. }
  9461. }
  9462. var TEXT_STYLE_OPTIONS = [
  9463. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9464. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9465. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9466. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9467. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9468. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9469. ];
  9470. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9471. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9472. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9473. // // FIXME: deprecated, check and remove it.
  9474. // 'textStyle'
  9475. // ]);
  9476. /**
  9477. * The method do not ensure performance.
  9478. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9479. * This helper method retieves value from data.
  9480. * @param {string|number|Date|Array|Object} dataItem
  9481. * @return {number|string|Date|Array.<number|string|Date>}
  9482. */
  9483. function getDataItemValue(dataItem) {
  9484. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9485. ? dataItem.value : dataItem;
  9486. }
  9487. /**
  9488. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9489. * This helper method determine if dataItem has extra option besides value
  9490. * @param {string|number|Date|Array|Object} dataItem
  9491. */
  9492. function isDataItemOption(dataItem) {
  9493. return isObject$2(dataItem)
  9494. && !(dataItem instanceof Array);
  9495. // // markLine data can be array
  9496. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9497. }
  9498. /**
  9499. * Mapping to exists for merge.
  9500. *
  9501. * @public
  9502. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9503. * @param {Object|Array.<Object>} newCptOptions
  9504. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9505. * index of which is the same as exists.
  9506. */
  9507. function mappingToExists(exists, newCptOptions) {
  9508. // Mapping by the order by original option (but not order of
  9509. // new option) in merge mode. Because we should ensure
  9510. // some specified index (like xAxisIndex) is consistent with
  9511. // original option, which is easy to understand, espatially in
  9512. // media query. And in most case, merge option is used to
  9513. // update partial option but not be expected to change order.
  9514. newCptOptions = (newCptOptions || []).slice();
  9515. var result = map(exists || [], function (obj, index) {
  9516. return {exist: obj};
  9517. });
  9518. // Mapping by id or name if specified.
  9519. each$2(newCptOptions, function (cptOption, index) {
  9520. if (!isObject$2(cptOption)) {
  9521. return;
  9522. }
  9523. // id has highest priority.
  9524. for (var i = 0; i < result.length; i++) {
  9525. if (!result[i].option // Consider name: two map to one.
  9526. && cptOption.id != null
  9527. && result[i].exist.id === cptOption.id + ''
  9528. ) {
  9529. result[i].option = cptOption;
  9530. newCptOptions[index] = null;
  9531. return;
  9532. }
  9533. }
  9534. for (var i = 0; i < result.length; i++) {
  9535. var exist = result[i].exist;
  9536. if (!result[i].option // Consider name: two map to one.
  9537. // Can not match when both ids exist but different.
  9538. && (exist.id == null || cptOption.id == null)
  9539. && cptOption.name != null
  9540. && !isIdInner(cptOption)
  9541. && !isIdInner(exist)
  9542. && exist.name === cptOption.name + ''
  9543. ) {
  9544. result[i].option = cptOption;
  9545. newCptOptions[index] = null;
  9546. return;
  9547. }
  9548. }
  9549. });
  9550. // Otherwise mapping by index.
  9551. each$2(newCptOptions, function (cptOption, index) {
  9552. if (!isObject$2(cptOption)) {
  9553. return;
  9554. }
  9555. var i = 0;
  9556. for (; i < result.length; i++) {
  9557. var exist = result[i].exist;
  9558. if (!result[i].option
  9559. // Existing model that already has id should be able to
  9560. // mapped to (because after mapping performed model may
  9561. // be assigned with a id, whish should not affect next
  9562. // mapping), except those has inner id.
  9563. && !isIdInner(exist)
  9564. // Caution:
  9565. // Do not overwrite id. But name can be overwritten,
  9566. // because axis use name as 'show label text'.
  9567. // 'exist' always has id and name and we dont
  9568. // need to check it.
  9569. && cptOption.id == null
  9570. ) {
  9571. result[i].option = cptOption;
  9572. break;
  9573. }
  9574. }
  9575. if (i >= result.length) {
  9576. result.push({option: cptOption});
  9577. }
  9578. });
  9579. return result;
  9580. }
  9581. /**
  9582. * Make id and name for mapping result (result of mappingToExists)
  9583. * into `keyInfo` field.
  9584. *
  9585. * @public
  9586. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9587. * which order is the same as exists.
  9588. * @return {Array.<Object>} The input.
  9589. */
  9590. function makeIdAndName(mapResult) {
  9591. // We use this id to hash component models and view instances
  9592. // in echarts. id can be specified by user, or auto generated.
  9593. // The id generation rule ensures new view instance are able
  9594. // to mapped to old instance when setOption are called in
  9595. // no-merge mode. So we generate model id by name and plus
  9596. // type in view id.
  9597. // name can be duplicated among components, which is convenient
  9598. // to specify multi components (like series) by one name.
  9599. // Ensure that each id is distinct.
  9600. var idMap = createHashMap();
  9601. each$2(mapResult, function (item, index) {
  9602. var existCpt = item.exist;
  9603. existCpt && idMap.set(existCpt.id, item);
  9604. });
  9605. each$2(mapResult, function (item, index) {
  9606. var opt = item.option;
  9607. assert$1(
  9608. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9609. 'id duplicates: ' + (opt && opt.id)
  9610. );
  9611. opt && opt.id != null && idMap.set(opt.id, item);
  9612. !item.keyInfo && (item.keyInfo = {});
  9613. });
  9614. // Make name and id.
  9615. each$2(mapResult, function (item, index) {
  9616. var existCpt = item.exist;
  9617. var opt = item.option;
  9618. var keyInfo = item.keyInfo;
  9619. if (!isObject$2(opt)) {
  9620. return;
  9621. }
  9622. // name can be overwitten. Consider case: axis.name = '20km'.
  9623. // But id generated by name will not be changed, which affect
  9624. // only in that case: setOption with 'not merge mode' and view
  9625. // instance will be recreated, which can be accepted.
  9626. keyInfo.name = opt.name != null
  9627. ? opt.name + ''
  9628. : existCpt
  9629. ? existCpt.name
  9630. : DEFAULT_COMPONENT_NAME;
  9631. if (existCpt) {
  9632. keyInfo.id = existCpt.id;
  9633. }
  9634. else if (opt.id != null) {
  9635. keyInfo.id = opt.id + '';
  9636. }
  9637. else {
  9638. // Consider this situatoin:
  9639. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9640. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9641. // Series with the same name between optionA and optionB
  9642. // should be mapped.
  9643. var idNum = 0;
  9644. do {
  9645. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9646. }
  9647. while (idMap.get(keyInfo.id));
  9648. }
  9649. idMap.set(keyInfo.id, item);
  9650. });
  9651. }
  9652. /**
  9653. * @public
  9654. * @param {Object} cptOption
  9655. * @return {boolean}
  9656. */
  9657. function isIdInner(cptOption) {
  9658. return isObject$2(cptOption)
  9659. && cptOption.id
  9660. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9661. }
  9662. /**
  9663. * A helper for removing duplicate items between batchA and batchB,
  9664. * and in themselves, and categorize by series.
  9665. *
  9666. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9667. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9668. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9669. */
  9670. /**
  9671. * @param {module:echarts/data/List} data
  9672. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9673. * each of which can be Array or primary type.
  9674. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9675. */
  9676. function queryDataIndex(data, payload) {
  9677. if (payload.dataIndexInside != null) {
  9678. return payload.dataIndexInside;
  9679. }
  9680. else if (payload.dataIndex != null) {
  9681. return isArray(payload.dataIndex)
  9682. ? map(payload.dataIndex, function (value) {
  9683. return data.indexOfRawIndex(value);
  9684. })
  9685. : data.indexOfRawIndex(payload.dataIndex);
  9686. }
  9687. else if (payload.name != null) {
  9688. return isArray(payload.name)
  9689. ? map(payload.name, function (value) {
  9690. return data.indexOfName(value);
  9691. })
  9692. : data.indexOfName(payload.name);
  9693. }
  9694. }
  9695. /**
  9696. * Enable property storage to any host object.
  9697. * Notice: Serialization is not supported.
  9698. *
  9699. * For example:
  9700. * var inner = zrUitl.makeInner();
  9701. *
  9702. * function some1(hostObj) {
  9703. * inner(hostObj).someProperty = 1212;
  9704. * ...
  9705. * }
  9706. * function some2() {
  9707. * var fields = inner(this);
  9708. * fields.someProperty1 = 1212;
  9709. * fields.someProperty2 = 'xx';
  9710. * ...
  9711. * }
  9712. *
  9713. * @return {Function}
  9714. */
  9715. function makeInner() {
  9716. // Consider different scope by es module import.
  9717. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9718. return function (hostObj) {
  9719. return hostObj[key] || (hostObj[key] = {});
  9720. };
  9721. }
  9722. var innerUniqueIndex = 0;
  9723. /**
  9724. * @param {module:echarts/model/Global} ecModel
  9725. * @param {string|Object} finder
  9726. * If string, e.g., 'geo', means {geoIndex: 0}.
  9727. * If Object, could contain some of these properties below:
  9728. * {
  9729. * seriesIndex, seriesId, seriesName,
  9730. * geoIndex, geoId, geoName,
  9731. * bmapIndex, bmapId, bmapName,
  9732. * xAxisIndex, xAxisId, xAxisName,
  9733. * yAxisIndex, yAxisId, yAxisName,
  9734. * gridIndex, gridId, gridName,
  9735. * ... (can be extended)
  9736. * }
  9737. * Each properties can be number|string|Array.<number>|Array.<string>
  9738. * For example, a finder could be
  9739. * {
  9740. * seriesIndex: 3,
  9741. * geoId: ['aa', 'cc'],
  9742. * gridName: ['xx', 'rr']
  9743. * }
  9744. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9745. * If nothing or null/undefined specified, return nothing.
  9746. * @param {Object} [opt]
  9747. * @param {string} [opt.defaultMainType]
  9748. * @param {Array.<string>} [opt.includeMainTypes]
  9749. * @return {Object} result like:
  9750. * {
  9751. * seriesModels: [seriesModel1, seriesModel2],
  9752. * seriesModel: seriesModel1, // The first model
  9753. * geoModels: [geoModel1, geoModel2],
  9754. * geoModel: geoModel1, // The first model
  9755. * ...
  9756. * }
  9757. */
  9758. function parseFinder(ecModel, finder, opt) {
  9759. if (isString(finder)) {
  9760. var obj = {};
  9761. obj[finder + 'Index'] = 0;
  9762. finder = obj;
  9763. }
  9764. var defaultMainType = opt && opt.defaultMainType;
  9765. if (defaultMainType
  9766. && !has(finder, defaultMainType + 'Index')
  9767. && !has(finder, defaultMainType + 'Id')
  9768. && !has(finder, defaultMainType + 'Name')
  9769. ) {
  9770. finder[defaultMainType + 'Index'] = 0;
  9771. }
  9772. var result = {};
  9773. each$2(finder, function (value, key) {
  9774. var value = finder[key];
  9775. // Exclude 'dataIndex' and other illgal keys.
  9776. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9777. result[key] = value;
  9778. return;
  9779. }
  9780. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9781. var mainType = parsedKey[1];
  9782. var queryType = (parsedKey[2] || '').toLowerCase();
  9783. if (!mainType
  9784. || !queryType
  9785. || value == null
  9786. || (queryType === 'index' && value === 'none')
  9787. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9788. ) {
  9789. return;
  9790. }
  9791. var queryParam = {mainType: mainType};
  9792. if (queryType !== 'index' || value !== 'all') {
  9793. queryParam[queryType] = value;
  9794. }
  9795. var models = ecModel.queryComponents(queryParam);
  9796. result[mainType + 'Models'] = models;
  9797. result[mainType + 'Model'] = models[0];
  9798. });
  9799. return result;
  9800. }
  9801. function has(obj, prop) {
  9802. return obj && obj.hasOwnProperty(prop);
  9803. }
  9804. function setAttribute(dom, key, value) {
  9805. dom.setAttribute
  9806. ? dom.setAttribute(key, value)
  9807. : (dom[key] = value);
  9808. }
  9809. function getAttribute(dom, key) {
  9810. return dom.getAttribute
  9811. ? dom.getAttribute(key)
  9812. : dom[key];
  9813. }
  9814. var TYPE_DELIMITER = '.';
  9815. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9816. /**
  9817. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9818. * @public
  9819. */
  9820. function parseClassType$1(componentType) {
  9821. var ret = {main: '', sub: ''};
  9822. if (componentType) {
  9823. componentType = componentType.split(TYPE_DELIMITER);
  9824. ret.main = componentType[0] || '';
  9825. ret.sub = componentType[1] || '';
  9826. }
  9827. return ret;
  9828. }
  9829. /**
  9830. * @public
  9831. */
  9832. function checkClassType(componentType) {
  9833. assert$1(
  9834. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9835. 'componentType "' + componentType + '" illegal'
  9836. );
  9837. }
  9838. /**
  9839. * @public
  9840. */
  9841. function enableClassExtend(RootClass, mandatoryMethods) {
  9842. RootClass.$constructor = RootClass;
  9843. RootClass.extend = function (proto) {
  9844. if (__DEV__) {
  9845. each$1(mandatoryMethods, function (method) {
  9846. if (!proto[method]) {
  9847. console.warn(
  9848. 'Method `' + method + '` should be implemented'
  9849. + (proto.type ? ' in ' + proto.type : '') + '.'
  9850. );
  9851. }
  9852. });
  9853. }
  9854. var superClass = this;
  9855. var ExtendedClass = function () {
  9856. if (!proto.$constructor) {
  9857. superClass.apply(this, arguments);
  9858. }
  9859. else {
  9860. proto.$constructor.apply(this, arguments);
  9861. }
  9862. };
  9863. extend(ExtendedClass.prototype, proto);
  9864. ExtendedClass.extend = this.extend;
  9865. ExtendedClass.superCall = superCall;
  9866. ExtendedClass.superApply = superApply;
  9867. inherits(ExtendedClass, this);
  9868. ExtendedClass.superClass = superClass;
  9869. return ExtendedClass;
  9870. };
  9871. }
  9872. var classBase = 0;
  9873. /**
  9874. * Can not use instanceof, consider different scope by
  9875. * cross domain or es module import in ec extensions.
  9876. * Mount a method "isInstance()" to Clz.
  9877. */
  9878. function enableClassCheck(Clz) {
  9879. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  9880. Clz.prototype[classAttr] = true;
  9881. if (__DEV__) {
  9882. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  9883. }
  9884. Clz.isInstance = function (obj) {
  9885. return !!(obj && obj[classAttr]);
  9886. };
  9887. }
  9888. // superCall should have class info, which can not be fetch from 'this'.
  9889. // Consider this case:
  9890. // class A has method f,
  9891. // class B inherits class A, overrides method f, f call superApply('f'),
  9892. // class C inherits class B, do not overrides method f,
  9893. // then when method of class C is called, dead loop occured.
  9894. function superCall(context, methodName) {
  9895. var args = slice(arguments, 2);
  9896. return this.superClass.prototype[methodName].apply(context, args);
  9897. }
  9898. function superApply(context, methodName, args) {
  9899. return this.superClass.prototype[methodName].apply(context, args);
  9900. }
  9901. /**
  9902. * @param {Object} entity
  9903. * @param {Object} options
  9904. * @param {boolean} [options.registerWhenExtend]
  9905. * @public
  9906. */
  9907. function enableClassManagement(entity, options) {
  9908. options = options || {};
  9909. /**
  9910. * Component model classes
  9911. * key: componentType,
  9912. * value:
  9913. * componentClass, when componentType is 'xxx'
  9914. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  9915. * @type {Object}
  9916. */
  9917. var storage = {};
  9918. entity.registerClass = function (Clazz, componentType) {
  9919. if (componentType) {
  9920. checkClassType(componentType);
  9921. componentType = parseClassType$1(componentType);
  9922. if (!componentType.sub) {
  9923. if (__DEV__) {
  9924. if (storage[componentType.main]) {
  9925. console.warn(componentType.main + ' exists.');
  9926. }
  9927. }
  9928. storage[componentType.main] = Clazz;
  9929. }
  9930. else if (componentType.sub !== IS_CONTAINER) {
  9931. var container = makeContainer(componentType);
  9932. container[componentType.sub] = Clazz;
  9933. }
  9934. }
  9935. return Clazz;
  9936. };
  9937. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  9938. var Clazz = storage[componentMainType];
  9939. if (Clazz && Clazz[IS_CONTAINER]) {
  9940. Clazz = subType ? Clazz[subType] : null;
  9941. }
  9942. if (throwWhenNotFound && !Clazz) {
  9943. throw new Error(
  9944. !subType
  9945. ? componentMainType + '.' + 'type should be specified.'
  9946. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  9947. );
  9948. }
  9949. return Clazz;
  9950. };
  9951. entity.getClassesByMainType = function (componentType) {
  9952. componentType = parseClassType$1(componentType);
  9953. var result = [];
  9954. var obj = storage[componentType.main];
  9955. if (obj && obj[IS_CONTAINER]) {
  9956. each$1(obj, function (o, type) {
  9957. type !== IS_CONTAINER && result.push(o);
  9958. });
  9959. }
  9960. else {
  9961. result.push(obj);
  9962. }
  9963. return result;
  9964. };
  9965. entity.hasClass = function (componentType) {
  9966. // Just consider componentType.main.
  9967. componentType = parseClassType$1(componentType);
  9968. return !!storage[componentType.main];
  9969. };
  9970. /**
  9971. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  9972. */
  9973. entity.getAllClassMainTypes = function () {
  9974. var types = [];
  9975. each$1(storage, function (obj, type) {
  9976. types.push(type);
  9977. });
  9978. return types;
  9979. };
  9980. /**
  9981. * If a main type is container and has sub types
  9982. * @param {string} mainType
  9983. * @return {boolean}
  9984. */
  9985. entity.hasSubTypes = function (componentType) {
  9986. componentType = parseClassType$1(componentType);
  9987. var obj = storage[componentType.main];
  9988. return obj && obj[IS_CONTAINER];
  9989. };
  9990. entity.parseClassType = parseClassType$1;
  9991. function makeContainer(componentType) {
  9992. var container = storage[componentType.main];
  9993. if (!container || !container[IS_CONTAINER]) {
  9994. container = storage[componentType.main] = {};
  9995. container[IS_CONTAINER] = true;
  9996. }
  9997. return container;
  9998. }
  9999. if (options.registerWhenExtend) {
  10000. var originalExtend = entity.extend;
  10001. if (originalExtend) {
  10002. entity.extend = function (proto) {
  10003. var ExtendedClass = originalExtend.call(this, proto);
  10004. return entity.registerClass(ExtendedClass, proto.type);
  10005. };
  10006. }
  10007. }
  10008. return entity;
  10009. }
  10010. /**
  10011. * @param {string|Array.<string>} properties
  10012. */
  10013. // TODO Parse shadow style
  10014. // TODO Only shallow path support
  10015. var makeStyleMapper = function (properties) {
  10016. // Normalize
  10017. for (var i = 0; i < properties.length; i++) {
  10018. if (!properties[i][1]) {
  10019. properties[i][1] = properties[i][0];
  10020. }
  10021. }
  10022. return function (model, excludes, includes) {
  10023. var style = {};
  10024. for (var i = 0; i < properties.length; i++) {
  10025. var propName = properties[i][1];
  10026. if ((excludes && indexOf(excludes, propName) >= 0)
  10027. || (includes && indexOf(includes, propName) < 0)
  10028. ) {
  10029. continue;
  10030. }
  10031. var val = model.getShallow(propName);
  10032. if (val != null) {
  10033. style[properties[i][0]] = val;
  10034. }
  10035. }
  10036. return style;
  10037. };
  10038. };
  10039. var getLineStyle = makeStyleMapper(
  10040. [
  10041. ['lineWidth', 'width'],
  10042. ['stroke', 'color'],
  10043. ['opacity'],
  10044. ['shadowBlur'],
  10045. ['shadowOffsetX'],
  10046. ['shadowOffsetY'],
  10047. ['shadowColor']
  10048. ]
  10049. );
  10050. var lineStyleMixin = {
  10051. getLineStyle: function (excludes) {
  10052. var style = getLineStyle(this, excludes);
  10053. var lineDash = this.getLineDash(style.lineWidth);
  10054. lineDash && (style.lineDash = lineDash);
  10055. return style;
  10056. },
  10057. getLineDash: function (lineWidth) {
  10058. if (lineWidth == null) {
  10059. lineWidth = 1;
  10060. }
  10061. var lineType = this.get('type');
  10062. var dotSize = Math.max(lineWidth, 2);
  10063. var dashSize = lineWidth * 4;
  10064. return (lineType === 'solid' || lineType == null) ? null
  10065. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10066. }
  10067. };
  10068. var getAreaStyle = makeStyleMapper(
  10069. [
  10070. ['fill', 'color'],
  10071. ['shadowBlur'],
  10072. ['shadowOffsetX'],
  10073. ['shadowOffsetY'],
  10074. ['opacity'],
  10075. ['shadowColor']
  10076. ]
  10077. );
  10078. var areaStyleMixin = {
  10079. getAreaStyle: function (excludes, includes) {
  10080. return getAreaStyle(this, excludes, includes);
  10081. }
  10082. };
  10083. /**
  10084. * 曲线辅助模块
  10085. * @module zrender/core/curve
  10086. * @author pissang(https://www.github.com/pissang)
  10087. */
  10088. var mathPow = Math.pow;
  10089. var mathSqrt$2 = Math.sqrt;
  10090. var EPSILON$1 = 1e-8;
  10091. var EPSILON_NUMERIC = 1e-4;
  10092. var THREE_SQRT = mathSqrt$2(3);
  10093. var ONE_THIRD = 1 / 3;
  10094. // 临时变量
  10095. var _v0 = create();
  10096. var _v1 = create();
  10097. var _v2 = create();
  10098. function isAroundZero(val) {
  10099. return val > -EPSILON$1 && val < EPSILON$1;
  10100. }
  10101. function isNotAroundZero$1(val) {
  10102. return val > EPSILON$1 || val < -EPSILON$1;
  10103. }
  10104. /**
  10105. * 计算三次贝塞尔值
  10106. * @memberOf module:zrender/core/curve
  10107. * @param {number} p0
  10108. * @param {number} p1
  10109. * @param {number} p2
  10110. * @param {number} p3
  10111. * @param {number} t
  10112. * @return {number}
  10113. */
  10114. function cubicAt(p0, p1, p2, p3, t) {
  10115. var onet = 1 - t;
  10116. return onet * onet * (onet * p0 + 3 * t * p1)
  10117. + t * t * (t * p3 + 3 * onet * p2);
  10118. }
  10119. /**
  10120. * 计算三次贝塞尔导数值
  10121. * @memberOf module:zrender/core/curve
  10122. * @param {number} p0
  10123. * @param {number} p1
  10124. * @param {number} p2
  10125. * @param {number} p3
  10126. * @param {number} t
  10127. * @return {number}
  10128. */
  10129. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10130. var onet = 1 - t;
  10131. return 3 * (
  10132. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10133. + (p3 - p2) * t * t
  10134. );
  10135. }
  10136. /**
  10137. * 计算三次贝塞尔方程根,使用盛金公式
  10138. * @memberOf module:zrender/core/curve
  10139. * @param {number} p0
  10140. * @param {number} p1
  10141. * @param {number} p2
  10142. * @param {number} p3
  10143. * @param {number} val
  10144. * @param {Array.<number>} roots
  10145. * @return {number} 有效根数目
  10146. */
  10147. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10148. // Evaluate roots of cubic functions
  10149. var a = p3 + 3 * (p1 - p2) - p0;
  10150. var b = 3 * (p2 - p1 * 2 + p0);
  10151. var c = 3 * (p1 - p0);
  10152. var d = p0 - val;
  10153. var A = b * b - 3 * a * c;
  10154. var B = b * c - 9 * a * d;
  10155. var C = c * c - 3 * b * d;
  10156. var n = 0;
  10157. if (isAroundZero(A) && isAroundZero(B)) {
  10158. if (isAroundZero(b)) {
  10159. roots[0] = 0;
  10160. }
  10161. else {
  10162. var t1 = -c / b; //t1, t2, t3, b is not zero
  10163. if (t1 >= 0 && t1 <= 1) {
  10164. roots[n++] = t1;
  10165. }
  10166. }
  10167. }
  10168. else {
  10169. var disc = B * B - 4 * A * C;
  10170. if (isAroundZero(disc)) {
  10171. var K = B / A;
  10172. var t1 = -b / a + K; // t1, a is not zero
  10173. var t2 = -K / 2; // t2, t3
  10174. if (t1 >= 0 && t1 <= 1) {
  10175. roots[n++] = t1;
  10176. }
  10177. if (t2 >= 0 && t2 <= 1) {
  10178. roots[n++] = t2;
  10179. }
  10180. }
  10181. else if (disc > 0) {
  10182. var discSqrt = mathSqrt$2(disc);
  10183. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10184. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10185. if (Y1 < 0) {
  10186. Y1 = -mathPow(-Y1, ONE_THIRD);
  10187. }
  10188. else {
  10189. Y1 = mathPow(Y1, ONE_THIRD);
  10190. }
  10191. if (Y2 < 0) {
  10192. Y2 = -mathPow(-Y2, ONE_THIRD);
  10193. }
  10194. else {
  10195. Y2 = mathPow(Y2, ONE_THIRD);
  10196. }
  10197. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10198. if (t1 >= 0 && t1 <= 1) {
  10199. roots[n++] = t1;
  10200. }
  10201. }
  10202. else {
  10203. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10204. var theta = Math.acos(T) / 3;
  10205. var ASqrt = mathSqrt$2(A);
  10206. var tmp = Math.cos(theta);
  10207. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10208. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10209. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10210. if (t1 >= 0 && t1 <= 1) {
  10211. roots[n++] = t1;
  10212. }
  10213. if (t2 >= 0 && t2 <= 1) {
  10214. roots[n++] = t2;
  10215. }
  10216. if (t3 >= 0 && t3 <= 1) {
  10217. roots[n++] = t3;
  10218. }
  10219. }
  10220. }
  10221. return n;
  10222. }
  10223. /**
  10224. * 计算三次贝塞尔方程极限值的位置
  10225. * @memberOf module:zrender/core/curve
  10226. * @param {number} p0
  10227. * @param {number} p1
  10228. * @param {number} p2
  10229. * @param {number} p3
  10230. * @param {Array.<number>} extrema
  10231. * @return {number} 有效数目
  10232. */
  10233. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10234. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10235. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10236. var c = 3 * p1 - 3 * p0;
  10237. var n = 0;
  10238. if (isAroundZero(a)) {
  10239. if (isNotAroundZero$1(b)) {
  10240. var t1 = -c / b;
  10241. if (t1 >= 0 && t1 <=1) {
  10242. extrema[n++] = t1;
  10243. }
  10244. }
  10245. }
  10246. else {
  10247. var disc = b * b - 4 * a * c;
  10248. if (isAroundZero(disc)) {
  10249. extrema[0] = -b / (2 * a);
  10250. }
  10251. else if (disc > 0) {
  10252. var discSqrt = mathSqrt$2(disc);
  10253. var t1 = (-b + discSqrt) / (2 * a);
  10254. var t2 = (-b - discSqrt) / (2 * a);
  10255. if (t1 >= 0 && t1 <= 1) {
  10256. extrema[n++] = t1;
  10257. }
  10258. if (t2 >= 0 && t2 <= 1) {
  10259. extrema[n++] = t2;
  10260. }
  10261. }
  10262. }
  10263. return n;
  10264. }
  10265. /**
  10266. * 细分三次贝塞尔曲线
  10267. * @memberOf module:zrender/core/curve
  10268. * @param {number} p0
  10269. * @param {number} p1
  10270. * @param {number} p2
  10271. * @param {number} p3
  10272. * @param {number} t
  10273. * @param {Array.<number>} out
  10274. */
  10275. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10276. var p01 = (p1 - p0) * t + p0;
  10277. var p12 = (p2 - p1) * t + p1;
  10278. var p23 = (p3 - p2) * t + p2;
  10279. var p012 = (p12 - p01) * t + p01;
  10280. var p123 = (p23 - p12) * t + p12;
  10281. var p0123 = (p123 - p012) * t + p012;
  10282. // Seg0
  10283. out[0] = p0;
  10284. out[1] = p01;
  10285. out[2] = p012;
  10286. out[3] = p0123;
  10287. // Seg1
  10288. out[4] = p0123;
  10289. out[5] = p123;
  10290. out[6] = p23;
  10291. out[7] = p3;
  10292. }
  10293. /**
  10294. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10295. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10296. * @param {number} x0
  10297. * @param {number} y0
  10298. * @param {number} x1
  10299. * @param {number} y1
  10300. * @param {number} x2
  10301. * @param {number} y2
  10302. * @param {number} x3
  10303. * @param {number} y3
  10304. * @param {number} x
  10305. * @param {number} y
  10306. * @param {Array.<number>} [out] 投射点
  10307. * @return {number}
  10308. */
  10309. function cubicProjectPoint(
  10310. x0, y0, x1, y1, x2, y2, x3, y3,
  10311. x, y, out
  10312. ) {
  10313. // http://pomax.github.io/bezierinfo/#projections
  10314. var t;
  10315. var interval = 0.005;
  10316. var d = Infinity;
  10317. var prev;
  10318. var next;
  10319. var d1;
  10320. var d2;
  10321. _v0[0] = x;
  10322. _v0[1] = y;
  10323. // 先粗略估计一下可能的最小距离的 t 值
  10324. // PENDING
  10325. for (var _t = 0; _t < 1; _t += 0.05) {
  10326. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10327. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10328. d1 = distSquare(_v0, _v1);
  10329. if (d1 < d) {
  10330. t = _t;
  10331. d = d1;
  10332. }
  10333. }
  10334. d = Infinity;
  10335. // At most 32 iteration
  10336. for (var i = 0; i < 32; i++) {
  10337. if (interval < EPSILON_NUMERIC) {
  10338. break;
  10339. }
  10340. prev = t - interval;
  10341. next = t + interval;
  10342. // t - interval
  10343. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10344. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10345. d1 = distSquare(_v1, _v0);
  10346. if (prev >= 0 && d1 < d) {
  10347. t = prev;
  10348. d = d1;
  10349. }
  10350. else {
  10351. // t + interval
  10352. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10353. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10354. d2 = distSquare(_v2, _v0);
  10355. if (next <= 1 && d2 < d) {
  10356. t = next;
  10357. d = d2;
  10358. }
  10359. else {
  10360. interval *= 0.5;
  10361. }
  10362. }
  10363. }
  10364. // t
  10365. if (out) {
  10366. out[0] = cubicAt(x0, x1, x2, x3, t);
  10367. out[1] = cubicAt(y0, y1, y2, y3, t);
  10368. }
  10369. // console.log(interval, i);
  10370. return mathSqrt$2(d);
  10371. }
  10372. /**
  10373. * 计算二次方贝塞尔值
  10374. * @param {number} p0
  10375. * @param {number} p1
  10376. * @param {number} p2
  10377. * @param {number} t
  10378. * @return {number}
  10379. */
  10380. function quadraticAt(p0, p1, p2, t) {
  10381. var onet = 1 - t;
  10382. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10383. }
  10384. /**
  10385. * 计算二次方贝塞尔导数值
  10386. * @param {number} p0
  10387. * @param {number} p1
  10388. * @param {number} p2
  10389. * @param {number} t
  10390. * @return {number}
  10391. */
  10392. function quadraticDerivativeAt(p0, p1, p2, t) {
  10393. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10394. }
  10395. /**
  10396. * 计算二次方贝塞尔方程根
  10397. * @param {number} p0
  10398. * @param {number} p1
  10399. * @param {number} p2
  10400. * @param {number} t
  10401. * @param {Array.<number>} roots
  10402. * @return {number} 有效根数目
  10403. */
  10404. function quadraticRootAt(p0, p1, p2, val, roots) {
  10405. var a = p0 - 2 * p1 + p2;
  10406. var b = 2 * (p1 - p0);
  10407. var c = p0 - val;
  10408. var n = 0;
  10409. if (isAroundZero(a)) {
  10410. if (isNotAroundZero$1(b)) {
  10411. var t1 = -c / b;
  10412. if (t1 >= 0 && t1 <= 1) {
  10413. roots[n++] = t1;
  10414. }
  10415. }
  10416. }
  10417. else {
  10418. var disc = b * b - 4 * a * c;
  10419. if (isAroundZero(disc)) {
  10420. var t1 = -b / (2 * a);
  10421. if (t1 >= 0 && t1 <= 1) {
  10422. roots[n++] = t1;
  10423. }
  10424. }
  10425. else if (disc > 0) {
  10426. var discSqrt = mathSqrt$2(disc);
  10427. var t1 = (-b + discSqrt) / (2 * a);
  10428. var t2 = (-b - discSqrt) / (2 * a);
  10429. if (t1 >= 0 && t1 <= 1) {
  10430. roots[n++] = t1;
  10431. }
  10432. if (t2 >= 0 && t2 <= 1) {
  10433. roots[n++] = t2;
  10434. }
  10435. }
  10436. }
  10437. return n;
  10438. }
  10439. /**
  10440. * 计算二次贝塞尔方程极限值
  10441. * @memberOf module:zrender/core/curve
  10442. * @param {number} p0
  10443. * @param {number} p1
  10444. * @param {number} p2
  10445. * @return {number}
  10446. */
  10447. function quadraticExtremum(p0, p1, p2) {
  10448. var divider = p0 + p2 - 2 * p1;
  10449. if (divider === 0) {
  10450. // p1 is center of p0 and p2
  10451. return 0.5;
  10452. }
  10453. else {
  10454. return (p0 - p1) / divider;
  10455. }
  10456. }
  10457. /**
  10458. * 细分二次贝塞尔曲线
  10459. * @memberOf module:zrender/core/curve
  10460. * @param {number} p0
  10461. * @param {number} p1
  10462. * @param {number} p2
  10463. * @param {number} t
  10464. * @param {Array.<number>} out
  10465. */
  10466. function quadraticSubdivide(p0, p1, p2, t, out) {
  10467. var p01 = (p1 - p0) * t + p0;
  10468. var p12 = (p2 - p1) * t + p1;
  10469. var p012 = (p12 - p01) * t + p01;
  10470. // Seg0
  10471. out[0] = p0;
  10472. out[1] = p01;
  10473. out[2] = p012;
  10474. // Seg1
  10475. out[3] = p012;
  10476. out[4] = p12;
  10477. out[5] = p2;
  10478. }
  10479. /**
  10480. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10481. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10482. * @param {number} x0
  10483. * @param {number} y0
  10484. * @param {number} x1
  10485. * @param {number} y1
  10486. * @param {number} x2
  10487. * @param {number} y2
  10488. * @param {number} x
  10489. * @param {number} y
  10490. * @param {Array.<number>} out 投射点
  10491. * @return {number}
  10492. */
  10493. function quadraticProjectPoint(
  10494. x0, y0, x1, y1, x2, y2,
  10495. x, y, out
  10496. ) {
  10497. // http://pomax.github.io/bezierinfo/#projections
  10498. var t;
  10499. var interval = 0.005;
  10500. var d = Infinity;
  10501. _v0[0] = x;
  10502. _v0[1] = y;
  10503. // 先粗略估计一下可能的最小距离的 t 值
  10504. // PENDING
  10505. for (var _t = 0; _t < 1; _t += 0.05) {
  10506. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10507. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10508. var d1 = distSquare(_v0, _v1);
  10509. if (d1 < d) {
  10510. t = _t;
  10511. d = d1;
  10512. }
  10513. }
  10514. d = Infinity;
  10515. // At most 32 iteration
  10516. for (var i = 0; i < 32; i++) {
  10517. if (interval < EPSILON_NUMERIC) {
  10518. break;
  10519. }
  10520. var prev = t - interval;
  10521. var next = t + interval;
  10522. // t - interval
  10523. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10524. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10525. var d1 = distSquare(_v1, _v0);
  10526. if (prev >= 0 && d1 < d) {
  10527. t = prev;
  10528. d = d1;
  10529. }
  10530. else {
  10531. // t + interval
  10532. _v2[0] = quadraticAt(x0, x1, x2, next);
  10533. _v2[1] = quadraticAt(y0, y1, y2, next);
  10534. var d2 = distSquare(_v2, _v0);
  10535. if (next <= 1 && d2 < d) {
  10536. t = next;
  10537. d = d2;
  10538. }
  10539. else {
  10540. interval *= 0.5;
  10541. }
  10542. }
  10543. }
  10544. // t
  10545. if (out) {
  10546. out[0] = quadraticAt(x0, x1, x2, t);
  10547. out[1] = quadraticAt(y0, y1, y2, t);
  10548. }
  10549. // console.log(interval, i);
  10550. return mathSqrt$2(d);
  10551. }
  10552. /**
  10553. * @author Yi Shen(https://github.com/pissang)
  10554. */
  10555. var mathMin$3 = Math.min;
  10556. var mathMax$3 = Math.max;
  10557. var mathSin$2 = Math.sin;
  10558. var mathCos$2 = Math.cos;
  10559. var PI2 = Math.PI * 2;
  10560. var start = create();
  10561. var end = create();
  10562. var extremity = create();
  10563. /**
  10564. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10565. * @module zrender/core/bbox
  10566. * @param {Array<Object>} points 顶点数组
  10567. * @param {number} min
  10568. * @param {number} max
  10569. */
  10570. function fromPoints(points, min$$1, max$$1) {
  10571. if (points.length === 0) {
  10572. return;
  10573. }
  10574. var p = points[0];
  10575. var left = p[0];
  10576. var right = p[0];
  10577. var top = p[1];
  10578. var bottom = p[1];
  10579. var i;
  10580. for (i = 1; i < points.length; i++) {
  10581. p = points[i];
  10582. left = mathMin$3(left, p[0]);
  10583. right = mathMax$3(right, p[0]);
  10584. top = mathMin$3(top, p[1]);
  10585. bottom = mathMax$3(bottom, p[1]);
  10586. }
  10587. min$$1[0] = left;
  10588. min$$1[1] = top;
  10589. max$$1[0] = right;
  10590. max$$1[1] = bottom;
  10591. }
  10592. /**
  10593. * @memberOf module:zrender/core/bbox
  10594. * @param {number} x0
  10595. * @param {number} y0
  10596. * @param {number} x1
  10597. * @param {number} y1
  10598. * @param {Array.<number>} min
  10599. * @param {Array.<number>} max
  10600. */
  10601. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10602. min$$1[0] = mathMin$3(x0, x1);
  10603. min$$1[1] = mathMin$3(y0, y1);
  10604. max$$1[0] = mathMax$3(x0, x1);
  10605. max$$1[1] = mathMax$3(y0, y1);
  10606. }
  10607. var xDim = [];
  10608. var yDim = [];
  10609. /**
  10610. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10611. * @memberOf module:zrender/core/bbox
  10612. * @param {number} x0
  10613. * @param {number} y0
  10614. * @param {number} x1
  10615. * @param {number} y1
  10616. * @param {number} x2
  10617. * @param {number} y2
  10618. * @param {number} x3
  10619. * @param {number} y3
  10620. * @param {Array.<number>} min
  10621. * @param {Array.<number>} max
  10622. */
  10623. function fromCubic(
  10624. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10625. ) {
  10626. var cubicExtrema$$1 = cubicExtrema;
  10627. var cubicAt$$1 = cubicAt;
  10628. var i;
  10629. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10630. min$$1[0] = Infinity;
  10631. min$$1[1] = Infinity;
  10632. max$$1[0] = -Infinity;
  10633. max$$1[1] = -Infinity;
  10634. for (i = 0; i < n; i++) {
  10635. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10636. min$$1[0] = mathMin$3(x, min$$1[0]);
  10637. max$$1[0] = mathMax$3(x, max$$1[0]);
  10638. }
  10639. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10640. for (i = 0; i < n; i++) {
  10641. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10642. min$$1[1] = mathMin$3(y, min$$1[1]);
  10643. max$$1[1] = mathMax$3(y, max$$1[1]);
  10644. }
  10645. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10646. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10647. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10648. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10649. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10650. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10651. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10652. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10653. }
  10654. /**
  10655. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10656. * @memberOf module:zrender/core/bbox
  10657. * @param {number} x0
  10658. * @param {number} y0
  10659. * @param {number} x1
  10660. * @param {number} y1
  10661. * @param {number} x2
  10662. * @param {number} y2
  10663. * @param {Array.<number>} min
  10664. * @param {Array.<number>} max
  10665. */
  10666. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10667. var quadraticExtremum$$1 = quadraticExtremum;
  10668. var quadraticAt$$1 = quadraticAt;
  10669. // Find extremities, where derivative in x dim or y dim is zero
  10670. var tx =
  10671. mathMax$3(
  10672. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10673. );
  10674. var ty =
  10675. mathMax$3(
  10676. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10677. );
  10678. var x = quadraticAt$$1(x0, x1, x2, tx);
  10679. var y = quadraticAt$$1(y0, y1, y2, ty);
  10680. min$$1[0] = mathMin$3(x0, x2, x);
  10681. min$$1[1] = mathMin$3(y0, y2, y);
  10682. max$$1[0] = mathMax$3(x0, x2, x);
  10683. max$$1[1] = mathMax$3(y0, y2, y);
  10684. }
  10685. /**
  10686. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10687. * @method
  10688. * @memberOf module:zrender/core/bbox
  10689. * @param {number} x
  10690. * @param {number} y
  10691. * @param {number} rx
  10692. * @param {number} ry
  10693. * @param {number} startAngle
  10694. * @param {number} endAngle
  10695. * @param {number} anticlockwise
  10696. * @param {Array.<number>} min
  10697. * @param {Array.<number>} max
  10698. */
  10699. function fromArc(
  10700. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10701. ) {
  10702. var vec2Min = min;
  10703. var vec2Max = max;
  10704. var diff = Math.abs(startAngle - endAngle);
  10705. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10706. // Is a circle
  10707. min$$1[0] = x - rx;
  10708. min$$1[1] = y - ry;
  10709. max$$1[0] = x + rx;
  10710. max$$1[1] = y + ry;
  10711. return;
  10712. }
  10713. start[0] = mathCos$2(startAngle) * rx + x;
  10714. start[1] = mathSin$2(startAngle) * ry + y;
  10715. end[0] = mathCos$2(endAngle) * rx + x;
  10716. end[1] = mathSin$2(endAngle) * ry + y;
  10717. vec2Min(min$$1, start, end);
  10718. vec2Max(max$$1, start, end);
  10719. // Thresh to [0, Math.PI * 2]
  10720. startAngle = startAngle % (PI2);
  10721. if (startAngle < 0) {
  10722. startAngle = startAngle + PI2;
  10723. }
  10724. endAngle = endAngle % (PI2);
  10725. if (endAngle < 0) {
  10726. endAngle = endAngle + PI2;
  10727. }
  10728. if (startAngle > endAngle && !anticlockwise) {
  10729. endAngle += PI2;
  10730. }
  10731. else if (startAngle < endAngle && anticlockwise) {
  10732. startAngle += PI2;
  10733. }
  10734. if (anticlockwise) {
  10735. var tmp = endAngle;
  10736. endAngle = startAngle;
  10737. startAngle = tmp;
  10738. }
  10739. // var number = 0;
  10740. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10741. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10742. if (angle > startAngle) {
  10743. extremity[0] = mathCos$2(angle) * rx + x;
  10744. extremity[1] = mathSin$2(angle) * ry + y;
  10745. vec2Min(min$$1, extremity, min$$1);
  10746. vec2Max(max$$1, extremity, max$$1);
  10747. }
  10748. }
  10749. }
  10750. /**
  10751. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10752. * 可以用于 isInsidePath 判断以及获取boundingRect
  10753. *
  10754. * @module zrender/core/PathProxy
  10755. * @author Yi Shen (http://www.github.com/pissang)
  10756. */
  10757. // TODO getTotalLength, getPointAtLength
  10758. var CMD = {
  10759. M: 1,
  10760. L: 2,
  10761. C: 3,
  10762. Q: 4,
  10763. A: 5,
  10764. Z: 6,
  10765. // Rect
  10766. R: 7
  10767. };
  10768. // var CMD_MEM_SIZE = {
  10769. // M: 3,
  10770. // L: 3,
  10771. // C: 7,
  10772. // Q: 5,
  10773. // A: 9,
  10774. // R: 5,
  10775. // Z: 1
  10776. // };
  10777. var min$1 = [];
  10778. var max$1 = [];
  10779. var min2 = [];
  10780. var max2 = [];
  10781. var mathMin$2 = Math.min;
  10782. var mathMax$2 = Math.max;
  10783. var mathCos$1 = Math.cos;
  10784. var mathSin$1 = Math.sin;
  10785. var mathSqrt$1 = Math.sqrt;
  10786. var mathAbs = Math.abs;
  10787. var hasTypedArray = typeof Float32Array != 'undefined';
  10788. /**
  10789. * @alias module:zrender/core/PathProxy
  10790. * @constructor
  10791. */
  10792. var PathProxy = function (notSaveData) {
  10793. this._saveData = !(notSaveData || false);
  10794. if (this._saveData) {
  10795. /**
  10796. * Path data. Stored as flat array
  10797. * @type {Array.<Object>}
  10798. */
  10799. this.data = [];
  10800. }
  10801. this._ctx = null;
  10802. };
  10803. /**
  10804. * 快速计算Path包围盒(并不是最小包围盒)
  10805. * @return {Object}
  10806. */
  10807. PathProxy.prototype = {
  10808. constructor: PathProxy,
  10809. _xi: 0,
  10810. _yi: 0,
  10811. _x0: 0,
  10812. _y0: 0,
  10813. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10814. _ux: 0,
  10815. _uy: 0,
  10816. _len: 0,
  10817. _lineDash: null,
  10818. _dashOffset: 0,
  10819. _dashIdx: 0,
  10820. _dashSum: 0,
  10821. /**
  10822. * @readOnly
  10823. */
  10824. setScale: function (sx, sy) {
  10825. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10826. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10827. },
  10828. getContext: function () {
  10829. return this._ctx;
  10830. },
  10831. /**
  10832. * @param {CanvasRenderingContext2D} ctx
  10833. * @return {module:zrender/core/PathProxy}
  10834. */
  10835. beginPath: function (ctx) {
  10836. this._ctx = ctx;
  10837. ctx && ctx.beginPath();
  10838. ctx && (this.dpr = ctx.dpr);
  10839. // Reset
  10840. if (this._saveData) {
  10841. this._len = 0;
  10842. }
  10843. if (this._lineDash) {
  10844. this._lineDash = null;
  10845. this._dashOffset = 0;
  10846. }
  10847. return this;
  10848. },
  10849. /**
  10850. * @param {number} x
  10851. * @param {number} y
  10852. * @return {module:zrender/core/PathProxy}
  10853. */
  10854. moveTo: function (x, y) {
  10855. this.addData(CMD.M, x, y);
  10856. this._ctx && this._ctx.moveTo(x, y);
  10857. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10858. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10859. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10860. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10861. this._x0 = x;
  10862. this._y0 = y;
  10863. this._xi = x;
  10864. this._yi = y;
  10865. return this;
  10866. },
  10867. /**
  10868. * @param {number} x
  10869. * @param {number} y
  10870. * @return {module:zrender/core/PathProxy}
  10871. */
  10872. lineTo: function (x, y) {
  10873. var exceedUnit = mathAbs(x - this._xi) > this._ux
  10874. || mathAbs(y - this._yi) > this._uy
  10875. // Force draw the first segment
  10876. || this._len < 5;
  10877. this.addData(CMD.L, x, y);
  10878. if (this._ctx && exceedUnit) {
  10879. this._needsDash() ? this._dashedLineTo(x, y)
  10880. : this._ctx.lineTo(x, y);
  10881. }
  10882. if (exceedUnit) {
  10883. this._xi = x;
  10884. this._yi = y;
  10885. }
  10886. return this;
  10887. },
  10888. /**
  10889. * @param {number} x1
  10890. * @param {number} y1
  10891. * @param {number} x2
  10892. * @param {number} y2
  10893. * @param {number} x3
  10894. * @param {number} y3
  10895. * @return {module:zrender/core/PathProxy}
  10896. */
  10897. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  10898. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  10899. if (this._ctx) {
  10900. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  10901. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10902. }
  10903. this._xi = x3;
  10904. this._yi = y3;
  10905. return this;
  10906. },
  10907. /**
  10908. * @param {number} x1
  10909. * @param {number} y1
  10910. * @param {number} x2
  10911. * @param {number} y2
  10912. * @return {module:zrender/core/PathProxy}
  10913. */
  10914. quadraticCurveTo: function (x1, y1, x2, y2) {
  10915. this.addData(CMD.Q, x1, y1, x2, y2);
  10916. if (this._ctx) {
  10917. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  10918. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  10919. }
  10920. this._xi = x2;
  10921. this._yi = y2;
  10922. return this;
  10923. },
  10924. /**
  10925. * @param {number} cx
  10926. * @param {number} cy
  10927. * @param {number} r
  10928. * @param {number} startAngle
  10929. * @param {number} endAngle
  10930. * @param {boolean} anticlockwise
  10931. * @return {module:zrender/core/PathProxy}
  10932. */
  10933. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  10934. this.addData(
  10935. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  10936. );
  10937. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10938. this._xi = mathCos$1(endAngle) * r + cx;
  10939. this._yi = mathSin$1(endAngle) * r + cx;
  10940. return this;
  10941. },
  10942. // TODO
  10943. arcTo: function (x1, y1, x2, y2, radius) {
  10944. if (this._ctx) {
  10945. this._ctx.arcTo(x1, y1, x2, y2, radius);
  10946. }
  10947. return this;
  10948. },
  10949. // TODO
  10950. rect: function (x, y, w, h) {
  10951. this._ctx && this._ctx.rect(x, y, w, h);
  10952. this.addData(CMD.R, x, y, w, h);
  10953. return this;
  10954. },
  10955. /**
  10956. * @return {module:zrender/core/PathProxy}
  10957. */
  10958. closePath: function () {
  10959. this.addData(CMD.Z);
  10960. var ctx = this._ctx;
  10961. var x0 = this._x0;
  10962. var y0 = this._y0;
  10963. if (ctx) {
  10964. this._needsDash() && this._dashedLineTo(x0, y0);
  10965. ctx.closePath();
  10966. }
  10967. this._xi = x0;
  10968. this._yi = y0;
  10969. return this;
  10970. },
  10971. /**
  10972. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  10973. * stroke 同样
  10974. * @param {CanvasRenderingContext2D} ctx
  10975. * @return {module:zrender/core/PathProxy}
  10976. */
  10977. fill: function (ctx) {
  10978. ctx && ctx.fill();
  10979. this.toStatic();
  10980. },
  10981. /**
  10982. * @param {CanvasRenderingContext2D} ctx
  10983. * @return {module:zrender/core/PathProxy}
  10984. */
  10985. stroke: function (ctx) {
  10986. ctx && ctx.stroke();
  10987. this.toStatic();
  10988. },
  10989. /**
  10990. * 必须在其它绘制命令前调用
  10991. * Must be invoked before all other path drawing methods
  10992. * @return {module:zrender/core/PathProxy}
  10993. */
  10994. setLineDash: function (lineDash) {
  10995. if (lineDash instanceof Array) {
  10996. this._lineDash = lineDash;
  10997. this._dashIdx = 0;
  10998. var lineDashSum = 0;
  10999. for (var i = 0; i < lineDash.length; i++) {
  11000. lineDashSum += lineDash[i];
  11001. }
  11002. this._dashSum = lineDashSum;
  11003. }
  11004. return this;
  11005. },
  11006. /**
  11007. * 必须在其它绘制命令前调用
  11008. * Must be invoked before all other path drawing methods
  11009. * @return {module:zrender/core/PathProxy}
  11010. */
  11011. setLineDashOffset: function (offset) {
  11012. this._dashOffset = offset;
  11013. return this;
  11014. },
  11015. /**
  11016. *
  11017. * @return {boolean}
  11018. */
  11019. len: function () {
  11020. return this._len;
  11021. },
  11022. /**
  11023. * 直接设置 Path 数据
  11024. */
  11025. setData: function (data) {
  11026. var len$$1 = data.length;
  11027. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11028. this.data = new Float32Array(len$$1);
  11029. }
  11030. for (var i = 0; i < len$$1; i++) {
  11031. this.data[i] = data[i];
  11032. }
  11033. this._len = len$$1;
  11034. },
  11035. /**
  11036. * 添加子路径
  11037. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11038. */
  11039. appendPath: function (path) {
  11040. if (!(path instanceof Array)) {
  11041. path = [path];
  11042. }
  11043. var len$$1 = path.length;
  11044. var appendSize = 0;
  11045. var offset = this._len;
  11046. for (var i = 0; i < len$$1; i++) {
  11047. appendSize += path[i].len();
  11048. }
  11049. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11050. this.data = new Float32Array(offset + appendSize);
  11051. }
  11052. for (var i = 0; i < len$$1; i++) {
  11053. var appendPathData = path[i].data;
  11054. for (var k = 0; k < appendPathData.length; k++) {
  11055. this.data[offset++] = appendPathData[k];
  11056. }
  11057. }
  11058. this._len = offset;
  11059. },
  11060. /**
  11061. * 填充 Path 数据。
  11062. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11063. */
  11064. addData: function (cmd) {
  11065. if (!this._saveData) {
  11066. return;
  11067. }
  11068. var data = this.data;
  11069. if (this._len + arguments.length > data.length) {
  11070. // 因为之前的数组已经转换成静态的 Float32Array
  11071. // 所以不够用时需要扩展一个新的动态数组
  11072. this._expandData();
  11073. data = this.data;
  11074. }
  11075. for (var i = 0; i < arguments.length; i++) {
  11076. data[this._len++] = arguments[i];
  11077. }
  11078. this._prevCmd = cmd;
  11079. },
  11080. _expandData: function () {
  11081. // Only if data is Float32Array
  11082. if (!(this.data instanceof Array)) {
  11083. var newData = [];
  11084. for (var i = 0; i < this._len; i++) {
  11085. newData[i] = this.data[i];
  11086. }
  11087. this.data = newData;
  11088. }
  11089. },
  11090. /**
  11091. * If needs js implemented dashed line
  11092. * @return {boolean}
  11093. * @private
  11094. */
  11095. _needsDash: function () {
  11096. return this._lineDash;
  11097. },
  11098. _dashedLineTo: function (x1, y1) {
  11099. var dashSum = this._dashSum;
  11100. var offset = this._dashOffset;
  11101. var lineDash = this._lineDash;
  11102. var ctx = this._ctx;
  11103. var x0 = this._xi;
  11104. var y0 = this._yi;
  11105. var dx = x1 - x0;
  11106. var dy = y1 - y0;
  11107. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11108. var x = x0;
  11109. var y = y0;
  11110. var dash;
  11111. var nDash = lineDash.length;
  11112. var idx;
  11113. dx /= dist$$1;
  11114. dy /= dist$$1;
  11115. if (offset < 0) {
  11116. // Convert to positive offset
  11117. offset = dashSum + offset;
  11118. }
  11119. offset %= dashSum;
  11120. x -= offset * dx;
  11121. y -= offset * dy;
  11122. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11123. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11124. idx = this._dashIdx;
  11125. dash = lineDash[idx];
  11126. x += dx * dash;
  11127. y += dy * dash;
  11128. this._dashIdx = (idx + 1) % nDash;
  11129. // Skip positive offset
  11130. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11131. continue;
  11132. }
  11133. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11134. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11135. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11136. );
  11137. }
  11138. // Offset for next lineTo
  11139. dx = x - x1;
  11140. dy = y - y1;
  11141. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11142. },
  11143. // Not accurate dashed line to
  11144. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11145. var dashSum = this._dashSum;
  11146. var offset = this._dashOffset;
  11147. var lineDash = this._lineDash;
  11148. var ctx = this._ctx;
  11149. var x0 = this._xi;
  11150. var y0 = this._yi;
  11151. var t;
  11152. var dx;
  11153. var dy;
  11154. var cubicAt$$1 = cubicAt;
  11155. var bezierLen = 0;
  11156. var idx = this._dashIdx;
  11157. var nDash = lineDash.length;
  11158. var x;
  11159. var y;
  11160. var tmpLen = 0;
  11161. if (offset < 0) {
  11162. // Convert to positive offset
  11163. offset = dashSum + offset;
  11164. }
  11165. offset %= dashSum;
  11166. // Bezier approx length
  11167. for (t = 0; t < 1; t += 0.1) {
  11168. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11169. - cubicAt$$1(x0, x1, x2, x3, t);
  11170. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11171. - cubicAt$$1(y0, y1, y2, y3, t);
  11172. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11173. }
  11174. // Find idx after add offset
  11175. for (; idx < nDash; idx++) {
  11176. tmpLen += lineDash[idx];
  11177. if (tmpLen > offset) {
  11178. break;
  11179. }
  11180. }
  11181. t = (tmpLen - offset) / bezierLen;
  11182. while (t <= 1) {
  11183. x = cubicAt$$1(x0, x1, x2, x3, t);
  11184. y = cubicAt$$1(y0, y1, y2, y3, t);
  11185. // Use line to approximate dashed bezier
  11186. // Bad result if dash is long
  11187. idx % 2 ? ctx.moveTo(x, y)
  11188. : ctx.lineTo(x, y);
  11189. t += lineDash[idx] / bezierLen;
  11190. idx = (idx + 1) % nDash;
  11191. }
  11192. // Finish the last segment and calculate the new offset
  11193. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11194. dx = x3 - x;
  11195. dy = y3 - y;
  11196. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11197. },
  11198. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11199. // Convert quadratic to cubic using degree elevation
  11200. var x3 = x2;
  11201. var y3 = y2;
  11202. x2 = (x2 + 2 * x1) / 3;
  11203. y2 = (y2 + 2 * y1) / 3;
  11204. x1 = (this._xi + 2 * x1) / 3;
  11205. y1 = (this._yi + 2 * y1) / 3;
  11206. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11207. },
  11208. /**
  11209. * 转成静态的 Float32Array 减少堆内存占用
  11210. * Convert dynamic array to static Float32Array
  11211. */
  11212. toStatic: function () {
  11213. var data = this.data;
  11214. if (data instanceof Array) {
  11215. data.length = this._len;
  11216. if (hasTypedArray) {
  11217. this.data = new Float32Array(data);
  11218. }
  11219. }
  11220. },
  11221. /**
  11222. * @return {module:zrender/core/BoundingRect}
  11223. */
  11224. getBoundingRect: function () {
  11225. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11226. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11227. var data = this.data;
  11228. var xi = 0;
  11229. var yi = 0;
  11230. var x0 = 0;
  11231. var y0 = 0;
  11232. for (var i = 0; i < data.length;) {
  11233. var cmd = data[i++];
  11234. if (i == 1) {
  11235. // 如果第一个命令是 L, C, Q
  11236. // 则 previous point 同绘制命令的第一个 point
  11237. //
  11238. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11239. xi = data[i];
  11240. yi = data[i + 1];
  11241. x0 = xi;
  11242. y0 = yi;
  11243. }
  11244. switch (cmd) {
  11245. case CMD.M:
  11246. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11247. // 在 closePath 的时候使用
  11248. x0 = data[i++];
  11249. y0 = data[i++];
  11250. xi = x0;
  11251. yi = y0;
  11252. min2[0] = x0;
  11253. min2[1] = y0;
  11254. max2[0] = x0;
  11255. max2[1] = y0;
  11256. break;
  11257. case CMD.L:
  11258. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11259. xi = data[i++];
  11260. yi = data[i++];
  11261. break;
  11262. case CMD.C:
  11263. fromCubic(
  11264. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11265. min2, max2
  11266. );
  11267. xi = data[i++];
  11268. yi = data[i++];
  11269. break;
  11270. case CMD.Q:
  11271. fromQuadratic(
  11272. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11273. min2, max2
  11274. );
  11275. xi = data[i++];
  11276. yi = data[i++];
  11277. break;
  11278. case CMD.A:
  11279. // TODO Arc 判断的开销比较大
  11280. var cx = data[i++];
  11281. var cy = data[i++];
  11282. var rx = data[i++];
  11283. var ry = data[i++];
  11284. var startAngle = data[i++];
  11285. var endAngle = data[i++] + startAngle;
  11286. // TODO Arc 旋转
  11287. var psi = data[i++];
  11288. var anticlockwise = 1 - data[i++];
  11289. if (i == 1) {
  11290. // 直接使用 arc 命令
  11291. // 第一个命令起点还未定义
  11292. x0 = mathCos$1(startAngle) * rx + cx;
  11293. y0 = mathSin$1(startAngle) * ry + cy;
  11294. }
  11295. fromArc(
  11296. cx, cy, rx, ry, startAngle, endAngle,
  11297. anticlockwise, min2, max2
  11298. );
  11299. xi = mathCos$1(endAngle) * rx + cx;
  11300. yi = mathSin$1(endAngle) * ry + cy;
  11301. break;
  11302. case CMD.R:
  11303. x0 = xi = data[i++];
  11304. y0 = yi = data[i++];
  11305. var width = data[i++];
  11306. var height = data[i++];
  11307. // Use fromLine
  11308. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11309. break;
  11310. case CMD.Z:
  11311. xi = x0;
  11312. yi = y0;
  11313. break;
  11314. }
  11315. // Union
  11316. min(min$1, min$1, min2);
  11317. max(max$1, max$1, max2);
  11318. }
  11319. // No data
  11320. if (i === 0) {
  11321. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11322. }
  11323. return new BoundingRect(
  11324. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11325. );
  11326. },
  11327. /**
  11328. * Rebuild path from current data
  11329. * Rebuild path will not consider javascript implemented line dash.
  11330. * @param {CanvasRenderingContext2D} ctx
  11331. */
  11332. rebuildPath: function (ctx) {
  11333. var d = this.data;
  11334. var x0, y0;
  11335. var xi, yi;
  11336. var x, y;
  11337. var ux = this._ux;
  11338. var uy = this._uy;
  11339. var len$$1 = this._len;
  11340. for (var i = 0; i < len$$1;) {
  11341. var cmd = d[i++];
  11342. if (i == 1) {
  11343. // 如果第一个命令是 L, C, Q
  11344. // 则 previous point 同绘制命令的第一个 point
  11345. //
  11346. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11347. xi = d[i];
  11348. yi = d[i + 1];
  11349. x0 = xi;
  11350. y0 = yi;
  11351. }
  11352. switch (cmd) {
  11353. case CMD.M:
  11354. x0 = xi = d[i++];
  11355. y0 = yi = d[i++];
  11356. ctx.moveTo(xi, yi);
  11357. break;
  11358. case CMD.L:
  11359. x = d[i++];
  11360. y = d[i++];
  11361. // Not draw too small seg between
  11362. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11363. ctx.lineTo(x, y);
  11364. xi = x;
  11365. yi = y;
  11366. }
  11367. break;
  11368. case CMD.C:
  11369. ctx.bezierCurveTo(
  11370. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11371. );
  11372. xi = d[i - 2];
  11373. yi = d[i - 1];
  11374. break;
  11375. case CMD.Q:
  11376. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11377. xi = d[i - 2];
  11378. yi = d[i - 1];
  11379. break;
  11380. case CMD.A:
  11381. var cx = d[i++];
  11382. var cy = d[i++];
  11383. var rx = d[i++];
  11384. var ry = d[i++];
  11385. var theta = d[i++];
  11386. var dTheta = d[i++];
  11387. var psi = d[i++];
  11388. var fs = d[i++];
  11389. var r = (rx > ry) ? rx : ry;
  11390. var scaleX = (rx > ry) ? 1 : rx / ry;
  11391. var scaleY = (rx > ry) ? ry / rx : 1;
  11392. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11393. var endAngle = theta + dTheta;
  11394. if (isEllipse) {
  11395. ctx.translate(cx, cy);
  11396. ctx.rotate(psi);
  11397. ctx.scale(scaleX, scaleY);
  11398. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11399. ctx.scale(1 / scaleX, 1 / scaleY);
  11400. ctx.rotate(-psi);
  11401. ctx.translate(-cx, -cy);
  11402. }
  11403. else {
  11404. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11405. }
  11406. if (i == 1) {
  11407. // 直接使用 arc 命令
  11408. // 第一个命令起点还未定义
  11409. x0 = mathCos$1(theta) * rx + cx;
  11410. y0 = mathSin$1(theta) * ry + cy;
  11411. }
  11412. xi = mathCos$1(endAngle) * rx + cx;
  11413. yi = mathSin$1(endAngle) * ry + cy;
  11414. break;
  11415. case CMD.R:
  11416. x0 = xi = d[i];
  11417. y0 = yi = d[i + 1];
  11418. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11419. break;
  11420. case CMD.Z:
  11421. ctx.closePath();
  11422. xi = x0;
  11423. yi = y0;
  11424. }
  11425. }
  11426. }
  11427. };
  11428. PathProxy.CMD = CMD;
  11429. /**
  11430. * 线段包含判断
  11431. * @param {number} x0
  11432. * @param {number} y0
  11433. * @param {number} x1
  11434. * @param {number} y1
  11435. * @param {number} lineWidth
  11436. * @param {number} x
  11437. * @param {number} y
  11438. * @return {boolean}
  11439. */
  11440. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11441. if (lineWidth === 0) {
  11442. return false;
  11443. }
  11444. var _l = lineWidth;
  11445. var _a = 0;
  11446. var _b = x0;
  11447. // Quick reject
  11448. if (
  11449. (y > y0 + _l && y > y1 + _l)
  11450. || (y < y0 - _l && y < y1 - _l)
  11451. || (x > x0 + _l && x > x1 + _l)
  11452. || (x < x0 - _l && x < x1 - _l)
  11453. ) {
  11454. return false;
  11455. }
  11456. if (x0 !== x1) {
  11457. _a = (y0 - y1) / (x0 - x1);
  11458. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11459. }
  11460. else {
  11461. return Math.abs(x - x0) <= _l / 2;
  11462. }
  11463. var tmp = _a * x - y + _b;
  11464. var _s = tmp * tmp / (_a * _a + 1);
  11465. return _s <= _l / 2 * _l / 2;
  11466. }
  11467. /**
  11468. * 三次贝塞尔曲线描边包含判断
  11469. * @param {number} x0
  11470. * @param {number} y0
  11471. * @param {number} x1
  11472. * @param {number} y1
  11473. * @param {number} x2
  11474. * @param {number} y2
  11475. * @param {number} x3
  11476. * @param {number} y3
  11477. * @param {number} lineWidth
  11478. * @param {number} x
  11479. * @param {number} y
  11480. * @return {boolean}
  11481. */
  11482. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11483. if (lineWidth === 0) {
  11484. return false;
  11485. }
  11486. var _l = lineWidth;
  11487. // Quick reject
  11488. if (
  11489. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11490. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11491. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11492. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11493. ) {
  11494. return false;
  11495. }
  11496. var d = cubicProjectPoint(
  11497. x0, y0, x1, y1, x2, y2, x3, y3,
  11498. x, y, null
  11499. );
  11500. return d <= _l / 2;
  11501. }
  11502. /**
  11503. * 二次贝塞尔曲线描边包含判断
  11504. * @param {number} x0
  11505. * @param {number} y0
  11506. * @param {number} x1
  11507. * @param {number} y1
  11508. * @param {number} x2
  11509. * @param {number} y2
  11510. * @param {number} lineWidth
  11511. * @param {number} x
  11512. * @param {number} y
  11513. * @return {boolean}
  11514. */
  11515. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11516. if (lineWidth === 0) {
  11517. return false;
  11518. }
  11519. var _l = lineWidth;
  11520. // Quick reject
  11521. if (
  11522. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11523. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11524. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11525. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11526. ) {
  11527. return false;
  11528. }
  11529. var d = quadraticProjectPoint(
  11530. x0, y0, x1, y1, x2, y2,
  11531. x, y, null
  11532. );
  11533. return d <= _l / 2;
  11534. }
  11535. var PI2$3 = Math.PI * 2;
  11536. function normalizeRadian(angle) {
  11537. angle %= PI2$3;
  11538. if (angle < 0) {
  11539. angle += PI2$3;
  11540. }
  11541. return angle;
  11542. }
  11543. var PI2$2 = Math.PI * 2;
  11544. /**
  11545. * 圆弧描边包含判断
  11546. * @param {number} cx
  11547. * @param {number} cy
  11548. * @param {number} r
  11549. * @param {number} startAngle
  11550. * @param {number} endAngle
  11551. * @param {boolean} anticlockwise
  11552. * @param {number} lineWidth
  11553. * @param {number} x
  11554. * @param {number} y
  11555. * @return {Boolean}
  11556. */
  11557. function containStroke$4(
  11558. cx, cy, r, startAngle, endAngle, anticlockwise,
  11559. lineWidth, x, y
  11560. ) {
  11561. if (lineWidth === 0) {
  11562. return false;
  11563. }
  11564. var _l = lineWidth;
  11565. x -= cx;
  11566. y -= cy;
  11567. var d = Math.sqrt(x * x + y * y);
  11568. if ((d - _l > r) || (d + _l < r)) {
  11569. return false;
  11570. }
  11571. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11572. // Is a circle
  11573. return true;
  11574. }
  11575. if (anticlockwise) {
  11576. var tmp = startAngle;
  11577. startAngle = normalizeRadian(endAngle);
  11578. endAngle = normalizeRadian(tmp);
  11579. } else {
  11580. startAngle = normalizeRadian(startAngle);
  11581. endAngle = normalizeRadian(endAngle);
  11582. }
  11583. if (startAngle > endAngle) {
  11584. endAngle += PI2$2;
  11585. }
  11586. var angle = Math.atan2(y, x);
  11587. if (angle < 0) {
  11588. angle += PI2$2;
  11589. }
  11590. return (angle >= startAngle && angle <= endAngle)
  11591. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11592. }
  11593. function windingLine(x0, y0, x1, y1, x, y) {
  11594. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11595. return 0;
  11596. }
  11597. // Ignore horizontal line
  11598. if (y1 === y0) {
  11599. return 0;
  11600. }
  11601. var dir = y1 < y0 ? 1 : -1;
  11602. var t = (y - y0) / (y1 - y0);
  11603. // Avoid winding error when intersection point is the connect point of two line of polygon
  11604. if (t === 1 || t === 0) {
  11605. dir = y1 < y0 ? 0.5 : -0.5;
  11606. }
  11607. var x_ = t * (x1 - x0) + x0;
  11608. return x_ > x ? dir : 0;
  11609. }
  11610. var CMD$1 = PathProxy.CMD;
  11611. var PI2$1 = Math.PI * 2;
  11612. var EPSILON$2 = 1e-4;
  11613. function isAroundEqual(a, b) {
  11614. return Math.abs(a - b) < EPSILON$2;
  11615. }
  11616. // 临时数组
  11617. var roots = [-1, -1, -1];
  11618. var extrema = [-1, -1];
  11619. function swapExtrema() {
  11620. var tmp = extrema[0];
  11621. extrema[0] = extrema[1];
  11622. extrema[1] = tmp;
  11623. }
  11624. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11625. // Quick reject
  11626. if (
  11627. (y > y0 && y > y1 && y > y2 && y > y3)
  11628. || (y < y0 && y < y1 && y < y2 && y < y3)
  11629. ) {
  11630. return 0;
  11631. }
  11632. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11633. if (nRoots === 0) {
  11634. return 0;
  11635. }
  11636. else {
  11637. var w = 0;
  11638. var nExtrema = -1;
  11639. var y0_, y1_;
  11640. for (var i = 0; i < nRoots; i++) {
  11641. var t = roots[i];
  11642. // Avoid winding error when intersection point is the connect point of two line of polygon
  11643. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11644. var x_ = cubicAt(x0, x1, x2, x3, t);
  11645. if (x_ < x) { // Quick reject
  11646. continue;
  11647. }
  11648. if (nExtrema < 0) {
  11649. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11650. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11651. swapExtrema();
  11652. }
  11653. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11654. if (nExtrema > 1) {
  11655. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11656. }
  11657. }
  11658. if (nExtrema == 2) {
  11659. // 分成三段单调函数
  11660. if (t < extrema[0]) {
  11661. w += y0_ < y0 ? unit : -unit;
  11662. }
  11663. else if (t < extrema[1]) {
  11664. w += y1_ < y0_ ? unit : -unit;
  11665. }
  11666. else {
  11667. w += y3 < y1_ ? unit : -unit;
  11668. }
  11669. }
  11670. else {
  11671. // 分成两段单调函数
  11672. if (t < extrema[0]) {
  11673. w += y0_ < y0 ? unit : -unit;
  11674. }
  11675. else {
  11676. w += y3 < y0_ ? unit : -unit;
  11677. }
  11678. }
  11679. }
  11680. return w;
  11681. }
  11682. }
  11683. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11684. // Quick reject
  11685. if (
  11686. (y > y0 && y > y1 && y > y2)
  11687. || (y < y0 && y < y1 && y < y2)
  11688. ) {
  11689. return 0;
  11690. }
  11691. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11692. if (nRoots === 0) {
  11693. return 0;
  11694. }
  11695. else {
  11696. var t = quadraticExtremum(y0, y1, y2);
  11697. if (t >= 0 && t <= 1) {
  11698. var w = 0;
  11699. var y_ = quadraticAt(y0, y1, y2, t);
  11700. for (var i = 0; i < nRoots; i++) {
  11701. // Remove one endpoint.
  11702. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11703. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11704. if (x_ < x) { // Quick reject
  11705. continue;
  11706. }
  11707. if (roots[i] < t) {
  11708. w += y_ < y0 ? unit : -unit;
  11709. }
  11710. else {
  11711. w += y2 < y_ ? unit : -unit;
  11712. }
  11713. }
  11714. return w;
  11715. }
  11716. else {
  11717. // Remove one endpoint.
  11718. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11719. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11720. if (x_ < x) { // Quick reject
  11721. return 0;
  11722. }
  11723. return y2 < y0 ? unit : -unit;
  11724. }
  11725. }
  11726. }
  11727. // TODO
  11728. // Arc 旋转
  11729. function windingArc(
  11730. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11731. ) {
  11732. y -= cy;
  11733. if (y > r || y < -r) {
  11734. return 0;
  11735. }
  11736. var tmp = Math.sqrt(r * r - y * y);
  11737. roots[0] = -tmp;
  11738. roots[1] = tmp;
  11739. var diff = Math.abs(startAngle - endAngle);
  11740. if (diff < 1e-4) {
  11741. return 0;
  11742. }
  11743. if (diff % PI2$1 < 1e-4) {
  11744. // Is a circle
  11745. startAngle = 0;
  11746. endAngle = PI2$1;
  11747. var dir = anticlockwise ? 1 : -1;
  11748. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11749. return dir;
  11750. } else {
  11751. return 0;
  11752. }
  11753. }
  11754. if (anticlockwise) {
  11755. var tmp = startAngle;
  11756. startAngle = normalizeRadian(endAngle);
  11757. endAngle = normalizeRadian(tmp);
  11758. }
  11759. else {
  11760. startAngle = normalizeRadian(startAngle);
  11761. endAngle = normalizeRadian(endAngle);
  11762. }
  11763. if (startAngle > endAngle) {
  11764. endAngle += PI2$1;
  11765. }
  11766. var w = 0;
  11767. for (var i = 0; i < 2; i++) {
  11768. var x_ = roots[i];
  11769. if (x_ + cx > x) {
  11770. var angle = Math.atan2(y, x_);
  11771. var dir = anticlockwise ? 1 : -1;
  11772. if (angle < 0) {
  11773. angle = PI2$1 + angle;
  11774. }
  11775. if (
  11776. (angle >= startAngle && angle <= endAngle)
  11777. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11778. ) {
  11779. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11780. dir = -dir;
  11781. }
  11782. w += dir;
  11783. }
  11784. }
  11785. }
  11786. return w;
  11787. }
  11788. function containPath(data, lineWidth, isStroke, x, y) {
  11789. var w = 0;
  11790. var xi = 0;
  11791. var yi = 0;
  11792. var x0 = 0;
  11793. var y0 = 0;
  11794. for (var i = 0; i < data.length;) {
  11795. var cmd = data[i++];
  11796. // Begin a new subpath
  11797. if (cmd === CMD$1.M && i > 1) {
  11798. // Close previous subpath
  11799. if (!isStroke) {
  11800. w += windingLine(xi, yi, x0, y0, x, y);
  11801. }
  11802. // 如果被任何一个 subpath 包含
  11803. // if (w !== 0) {
  11804. // return true;
  11805. // }
  11806. }
  11807. if (i == 1) {
  11808. // 如果第一个命令是 L, C, Q
  11809. // 则 previous point 同绘制命令的第一个 point
  11810. //
  11811. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11812. xi = data[i];
  11813. yi = data[i + 1];
  11814. x0 = xi;
  11815. y0 = yi;
  11816. }
  11817. switch (cmd) {
  11818. case CMD$1.M:
  11819. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11820. // 在 closePath 的时候使用
  11821. x0 = data[i++];
  11822. y0 = data[i++];
  11823. xi = x0;
  11824. yi = y0;
  11825. break;
  11826. case CMD$1.L:
  11827. if (isStroke) {
  11828. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11829. return true;
  11830. }
  11831. }
  11832. else {
  11833. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11834. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11835. }
  11836. xi = data[i++];
  11837. yi = data[i++];
  11838. break;
  11839. case CMD$1.C:
  11840. if (isStroke) {
  11841. if (containStroke$2(xi, yi,
  11842. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11843. lineWidth, x, y
  11844. )) {
  11845. return true;
  11846. }
  11847. }
  11848. else {
  11849. w += windingCubic(
  11850. xi, yi,
  11851. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11852. x, y
  11853. ) || 0;
  11854. }
  11855. xi = data[i++];
  11856. yi = data[i++];
  11857. break;
  11858. case CMD$1.Q:
  11859. if (isStroke) {
  11860. if (containStroke$3(xi, yi,
  11861. data[i++], data[i++], data[i], data[i + 1],
  11862. lineWidth, x, y
  11863. )) {
  11864. return true;
  11865. }
  11866. }
  11867. else {
  11868. w += windingQuadratic(
  11869. xi, yi,
  11870. data[i++], data[i++], data[i], data[i + 1],
  11871. x, y
  11872. ) || 0;
  11873. }
  11874. xi = data[i++];
  11875. yi = data[i++];
  11876. break;
  11877. case CMD$1.A:
  11878. // TODO Arc 判断的开销比较大
  11879. var cx = data[i++];
  11880. var cy = data[i++];
  11881. var rx = data[i++];
  11882. var ry = data[i++];
  11883. var theta = data[i++];
  11884. var dTheta = data[i++];
  11885. // TODO Arc 旋转
  11886. var psi = data[i++];
  11887. var anticlockwise = 1 - data[i++];
  11888. var x1 = Math.cos(theta) * rx + cx;
  11889. var y1 = Math.sin(theta) * ry + cy;
  11890. // 不是直接使用 arc 命令
  11891. if (i > 1) {
  11892. w += windingLine(xi, yi, x1, y1, x, y);
  11893. }
  11894. else {
  11895. // 第一个命令起点还未定义
  11896. x0 = x1;
  11897. y0 = y1;
  11898. }
  11899. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  11900. var _x = (x - cx) * ry / rx + cx;
  11901. if (isStroke) {
  11902. if (containStroke$4(
  11903. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11904. lineWidth, _x, y
  11905. )) {
  11906. return true;
  11907. }
  11908. }
  11909. else {
  11910. w += windingArc(
  11911. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11912. _x, y
  11913. );
  11914. }
  11915. xi = Math.cos(theta + dTheta) * rx + cx;
  11916. yi = Math.sin(theta + dTheta) * ry + cy;
  11917. break;
  11918. case CMD$1.R:
  11919. x0 = xi = data[i++];
  11920. y0 = yi = data[i++];
  11921. var width = data[i++];
  11922. var height = data[i++];
  11923. var x1 = x0 + width;
  11924. var y1 = y0 + height;
  11925. if (isStroke) {
  11926. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  11927. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  11928. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  11929. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  11930. ) {
  11931. return true;
  11932. }
  11933. }
  11934. else {
  11935. // FIXME Clockwise ?
  11936. w += windingLine(x1, y0, x1, y1, x, y);
  11937. w += windingLine(x0, y1, x0, y0, x, y);
  11938. }
  11939. break;
  11940. case CMD$1.Z:
  11941. if (isStroke) {
  11942. if (containStroke$1(
  11943. xi, yi, x0, y0, lineWidth, x, y
  11944. )) {
  11945. return true;
  11946. }
  11947. }
  11948. else {
  11949. // Close a subpath
  11950. w += windingLine(xi, yi, x0, y0, x, y);
  11951. // 如果被任何一个 subpath 包含
  11952. // FIXME subpaths may overlap
  11953. // if (w !== 0) {
  11954. // return true;
  11955. // }
  11956. }
  11957. xi = x0;
  11958. yi = y0;
  11959. break;
  11960. }
  11961. }
  11962. if (!isStroke && !isAroundEqual(yi, y0)) {
  11963. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  11964. }
  11965. return w !== 0;
  11966. }
  11967. function contain(pathData, x, y) {
  11968. return containPath(pathData, 0, false, x, y);
  11969. }
  11970. function containStroke(pathData, lineWidth, x, y) {
  11971. return containPath(pathData, lineWidth, true, x, y);
  11972. }
  11973. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  11974. var abs = Math.abs;
  11975. var pathProxyForDraw = new PathProxy(true);
  11976. /**
  11977. * @alias module:zrender/graphic/Path
  11978. * @extends module:zrender/graphic/Displayable
  11979. * @constructor
  11980. * @param {Object} opts
  11981. */
  11982. function Path(opts) {
  11983. Displayable.call(this, opts);
  11984. /**
  11985. * @type {module:zrender/core/PathProxy}
  11986. * @readOnly
  11987. */
  11988. this.path = null;
  11989. }
  11990. Path.prototype = {
  11991. constructor: Path,
  11992. type: 'path',
  11993. __dirtyPath: true,
  11994. strokeContainThreshold: 5,
  11995. brush: function (ctx, prevEl) {
  11996. var style = this.style;
  11997. var path = this.path || pathProxyForDraw;
  11998. var hasStroke = style.hasStroke();
  11999. var hasFill = style.hasFill();
  12000. var fill = style.fill;
  12001. var stroke = style.stroke;
  12002. var hasFillGradient = hasFill && !!(fill.colorStops);
  12003. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12004. var hasFillPattern = hasFill && !!(fill.image);
  12005. var hasStrokePattern = hasStroke && !!(stroke.image);
  12006. style.bind(ctx, this, prevEl);
  12007. this.setTransform(ctx);
  12008. if (this.__dirty) {
  12009. var rect;
  12010. // Update gradient because bounding rect may changed
  12011. if (hasFillGradient) {
  12012. rect = rect || this.getBoundingRect();
  12013. this._fillGradient = style.getGradient(ctx, fill, rect);
  12014. }
  12015. if (hasStrokeGradient) {
  12016. rect = rect || this.getBoundingRect();
  12017. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12018. }
  12019. }
  12020. // Use the gradient or pattern
  12021. if (hasFillGradient) {
  12022. // PENDING If may have affect the state
  12023. ctx.fillStyle = this._fillGradient;
  12024. }
  12025. else if (hasFillPattern) {
  12026. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12027. }
  12028. if (hasStrokeGradient) {
  12029. ctx.strokeStyle = this._strokeGradient;
  12030. }
  12031. else if (hasStrokePattern) {
  12032. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12033. }
  12034. var lineDash = style.lineDash;
  12035. var lineDashOffset = style.lineDashOffset;
  12036. var ctxLineDash = !!ctx.setLineDash;
  12037. // Update path sx, sy
  12038. var scale = this.getGlobalScale();
  12039. path.setScale(scale[0], scale[1]);
  12040. // Proxy context
  12041. // Rebuild path in following 2 cases
  12042. // 1. Path is dirty
  12043. // 2. Path needs javascript implemented lineDash stroking.
  12044. // In this case, lineDash information will not be saved in PathProxy
  12045. if (this.__dirtyPath
  12046. || (lineDash && !ctxLineDash && hasStroke)
  12047. ) {
  12048. path.beginPath(ctx);
  12049. // Setting line dash before build path
  12050. if (lineDash && !ctxLineDash) {
  12051. path.setLineDash(lineDash);
  12052. path.setLineDashOffset(lineDashOffset);
  12053. }
  12054. this.buildPath(path, this.shape, false);
  12055. // Clear path dirty flag
  12056. if (this.path) {
  12057. this.__dirtyPath = false;
  12058. }
  12059. }
  12060. else {
  12061. // Replay path building
  12062. ctx.beginPath();
  12063. this.path.rebuildPath(ctx);
  12064. }
  12065. hasFill && path.fill(ctx);
  12066. if (lineDash && ctxLineDash) {
  12067. ctx.setLineDash(lineDash);
  12068. ctx.lineDashOffset = lineDashOffset;
  12069. }
  12070. hasStroke && path.stroke(ctx);
  12071. if (lineDash && ctxLineDash) {
  12072. // PENDING
  12073. // Remove lineDash
  12074. ctx.setLineDash([]);
  12075. }
  12076. // Draw rect text
  12077. if (style.text != null) {
  12078. // Only restore transform when needs draw text.
  12079. this.restoreTransform(ctx);
  12080. this.drawRectText(ctx, this.getBoundingRect());
  12081. }
  12082. },
  12083. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12084. // Like in circle
  12085. buildPath: function (ctx, shapeCfg, inBundle) {},
  12086. createPathProxy: function () {
  12087. this.path = new PathProxy();
  12088. },
  12089. getBoundingRect: function () {
  12090. var rect = this._rect;
  12091. var style = this.style;
  12092. var needsUpdateRect = !rect;
  12093. if (needsUpdateRect) {
  12094. var path = this.path;
  12095. if (!path) {
  12096. // Create path on demand.
  12097. path = this.path = new PathProxy();
  12098. }
  12099. if (this.__dirtyPath) {
  12100. path.beginPath();
  12101. this.buildPath(path, this.shape, false);
  12102. }
  12103. rect = path.getBoundingRect();
  12104. }
  12105. this._rect = rect;
  12106. if (style.hasStroke()) {
  12107. // Needs update rect with stroke lineWidth when
  12108. // 1. Element changes scale or lineWidth
  12109. // 2. Shape is changed
  12110. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12111. if (this.__dirty || needsUpdateRect) {
  12112. rectWithStroke.copy(rect);
  12113. // FIXME Must after updateTransform
  12114. var w = style.lineWidth;
  12115. // PENDING, Min line width is needed when line is horizontal or vertical
  12116. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12117. // Only add extra hover lineWidth when there are no fill
  12118. if (!style.hasFill()) {
  12119. w = Math.max(w, this.strokeContainThreshold || 4);
  12120. }
  12121. // Consider line width
  12122. // Line scale can't be 0;
  12123. if (lineScale > 1e-10) {
  12124. rectWithStroke.width += w / lineScale;
  12125. rectWithStroke.height += w / lineScale;
  12126. rectWithStroke.x -= w / lineScale / 2;
  12127. rectWithStroke.y -= w / lineScale / 2;
  12128. }
  12129. }
  12130. // Return rect with stroke
  12131. return rectWithStroke;
  12132. }
  12133. return rect;
  12134. },
  12135. contain: function (x, y) {
  12136. var localPos = this.transformCoordToLocal(x, y);
  12137. var rect = this.getBoundingRect();
  12138. var style = this.style;
  12139. x = localPos[0];
  12140. y = localPos[1];
  12141. if (rect.contain(x, y)) {
  12142. var pathData = this.path.data;
  12143. if (style.hasStroke()) {
  12144. var lineWidth = style.lineWidth;
  12145. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12146. // Line scale can't be 0;
  12147. if (lineScale > 1e-10) {
  12148. // Only add extra hover lineWidth when there are no fill
  12149. if (!style.hasFill()) {
  12150. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12151. }
  12152. if (containStroke(
  12153. pathData, lineWidth / lineScale, x, y
  12154. )) {
  12155. return true;
  12156. }
  12157. }
  12158. }
  12159. if (style.hasFill()) {
  12160. return contain(pathData, x, y);
  12161. }
  12162. }
  12163. return false;
  12164. },
  12165. /**
  12166. * @param {boolean} dirtyPath
  12167. */
  12168. dirty: function (dirtyPath) {
  12169. if (dirtyPath == null) {
  12170. dirtyPath = true;
  12171. }
  12172. // Only mark dirty, not mark clean
  12173. if (dirtyPath) {
  12174. this.__dirtyPath = dirtyPath;
  12175. this._rect = null;
  12176. }
  12177. this.__dirty = true;
  12178. this.__zr && this.__zr.refresh();
  12179. // Used as a clipping path
  12180. if (this.__clipTarget) {
  12181. this.__clipTarget.dirty();
  12182. }
  12183. },
  12184. /**
  12185. * Alias for animate('shape')
  12186. * @param {boolean} loop
  12187. */
  12188. animateShape: function (loop) {
  12189. return this.animate('shape', loop);
  12190. },
  12191. // Overwrite attrKV
  12192. attrKV: function (key, value) {
  12193. // FIXME
  12194. if (key === 'shape') {
  12195. this.setShape(value);
  12196. this.__dirtyPath = true;
  12197. this._rect = null;
  12198. }
  12199. else {
  12200. Displayable.prototype.attrKV.call(this, key, value);
  12201. }
  12202. },
  12203. /**
  12204. * @param {Object|string} key
  12205. * @param {*} value
  12206. */
  12207. setShape: function (key, value) {
  12208. var shape = this.shape;
  12209. // Path from string may not have shape
  12210. if (shape) {
  12211. if (isObject$1(key)) {
  12212. for (var name in key) {
  12213. if (key.hasOwnProperty(name)) {
  12214. shape[name] = key[name];
  12215. }
  12216. }
  12217. }
  12218. else {
  12219. shape[key] = value;
  12220. }
  12221. this.dirty(true);
  12222. }
  12223. return this;
  12224. },
  12225. getLineScale: function () {
  12226. var m = this.transform;
  12227. // Get the line scale.
  12228. // Determinant of `m` means how much the area is enlarged by the
  12229. // transformation. So its square root can be used as a scale factor
  12230. // for width.
  12231. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12232. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12233. : 1;
  12234. }
  12235. };
  12236. /**
  12237. * 扩展一个 Path element, 比如星形,圆等。
  12238. * Extend a path element
  12239. * @param {Object} props
  12240. * @param {string} props.type Path type
  12241. * @param {Function} props.init Initialize
  12242. * @param {Function} props.buildPath Overwrite buildPath method
  12243. * @param {Object} [props.style] Extended default style config
  12244. * @param {Object} [props.shape] Extended default shape config
  12245. */
  12246. Path.extend = function (defaults$$1) {
  12247. var Sub = function (opts) {
  12248. Path.call(this, opts);
  12249. if (defaults$$1.style) {
  12250. // Extend default style
  12251. this.style.extendFrom(defaults$$1.style, false);
  12252. }
  12253. // Extend default shape
  12254. var defaultShape = defaults$$1.shape;
  12255. if (defaultShape) {
  12256. this.shape = this.shape || {};
  12257. var thisShape = this.shape;
  12258. for (var name in defaultShape) {
  12259. if (
  12260. ! thisShape.hasOwnProperty(name)
  12261. && defaultShape.hasOwnProperty(name)
  12262. ) {
  12263. thisShape[name] = defaultShape[name];
  12264. }
  12265. }
  12266. }
  12267. defaults$$1.init && defaults$$1.init.call(this, opts);
  12268. };
  12269. inherits(Sub, Path);
  12270. // FIXME 不能 extend position, rotation 等引用对象
  12271. for (var name in defaults$$1) {
  12272. // Extending prototype values and methods
  12273. if (name !== 'style' && name !== 'shape') {
  12274. Sub.prototype[name] = defaults$$1[name];
  12275. }
  12276. }
  12277. return Sub;
  12278. };
  12279. inherits(Path, Displayable);
  12280. var CMD$2 = PathProxy.CMD;
  12281. var points = [[], [], []];
  12282. var mathSqrt$3 = Math.sqrt;
  12283. var mathAtan2 = Math.atan2;
  12284. var transformPath = function (path, m) {
  12285. var data = path.data;
  12286. var cmd;
  12287. var nPoint;
  12288. var i;
  12289. var j;
  12290. var k;
  12291. var p;
  12292. var M = CMD$2.M;
  12293. var C = CMD$2.C;
  12294. var L = CMD$2.L;
  12295. var R = CMD$2.R;
  12296. var A = CMD$2.A;
  12297. var Q = CMD$2.Q;
  12298. for (i = 0, j = 0; i < data.length;) {
  12299. cmd = data[i++];
  12300. j = i;
  12301. nPoint = 0;
  12302. switch (cmd) {
  12303. case M:
  12304. nPoint = 1;
  12305. break;
  12306. case L:
  12307. nPoint = 1;
  12308. break;
  12309. case C:
  12310. nPoint = 3;
  12311. break;
  12312. case Q:
  12313. nPoint = 2;
  12314. break;
  12315. case A:
  12316. var x = m[4];
  12317. var y = m[5];
  12318. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12319. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12320. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12321. // cx
  12322. data[i] *= sx;
  12323. data[i++] += x;
  12324. // cy
  12325. data[i] *= sy;
  12326. data[i++] += y;
  12327. // Scale rx and ry
  12328. // FIXME Assume psi is 0 here
  12329. data[i++] *= sx;
  12330. data[i++] *= sy;
  12331. // Start angle
  12332. data[i++] += angle;
  12333. // end angle
  12334. data[i++] += angle;
  12335. // FIXME psi
  12336. i += 2;
  12337. j = i;
  12338. break;
  12339. case R:
  12340. // x0, y0
  12341. p[0] = data[i++];
  12342. p[1] = data[i++];
  12343. applyTransform(p, p, m);
  12344. data[j++] = p[0];
  12345. data[j++] = p[1];
  12346. // x1, y1
  12347. p[0] += data[i++];
  12348. p[1] += data[i++];
  12349. applyTransform(p, p, m);
  12350. data[j++] = p[0];
  12351. data[j++] = p[1];
  12352. }
  12353. for (k = 0; k < nPoint; k++) {
  12354. var p = points[k];
  12355. p[0] = data[i++];
  12356. p[1] = data[i++];
  12357. applyTransform(p, p, m);
  12358. // Write back
  12359. data[j++] = p[0];
  12360. data[j++] = p[1];
  12361. }
  12362. }
  12363. };
  12364. // command chars
  12365. var cc = [
  12366. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12367. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12368. ];
  12369. var mathSqrt = Math.sqrt;
  12370. var mathSin = Math.sin;
  12371. var mathCos = Math.cos;
  12372. var PI = Math.PI;
  12373. var vMag = function(v) {
  12374. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12375. };
  12376. var vRatio = function(u, v) {
  12377. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12378. };
  12379. var vAngle = function(u, v) {
  12380. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12381. * Math.acos(vRatio(u, v));
  12382. };
  12383. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12384. var psi = psiDeg * (PI / 180.0);
  12385. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12386. + mathSin(psi) * (y1 - y2) / 2.0;
  12387. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12388. + mathCos(psi) * (y1 - y2) / 2.0;
  12389. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12390. if (lambda > 1) {
  12391. rx *= mathSqrt(lambda);
  12392. ry *= mathSqrt(lambda);
  12393. }
  12394. var f = (fa === fs ? -1 : 1)
  12395. * mathSqrt((((rx * rx) * (ry * ry))
  12396. - ((rx * rx) * (yp * yp))
  12397. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12398. + (ry * ry) * (xp * xp))
  12399. ) || 0;
  12400. var cxp = f * rx * yp / ry;
  12401. var cyp = f * -ry * xp / rx;
  12402. var cx = (x1 + x2) / 2.0
  12403. + mathCos(psi) * cxp
  12404. - mathSin(psi) * cyp;
  12405. var cy = (y1 + y2) / 2.0
  12406. + mathSin(psi) * cxp
  12407. + mathCos(psi) * cyp;
  12408. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12409. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12410. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12411. var dTheta = vAngle(u, v);
  12412. if (vRatio(u, v) <= -1) {
  12413. dTheta = PI;
  12414. }
  12415. if (vRatio(u, v) >= 1) {
  12416. dTheta = 0;
  12417. }
  12418. if (fs === 0 && dTheta > 0) {
  12419. dTheta = dTheta - 2 * PI;
  12420. }
  12421. if (fs === 1 && dTheta < 0) {
  12422. dTheta = dTheta + 2 * PI;
  12423. }
  12424. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12425. }
  12426. function createPathProxyFromString(data) {
  12427. if (!data) {
  12428. return [];
  12429. }
  12430. // command string
  12431. var cs = data.replace(/-/g, ' -')
  12432. .replace(/ /g, ' ')
  12433. .replace(/ /g, ',')
  12434. .replace(/,,/g, ',');
  12435. var n;
  12436. // create pipes so that we can split the data
  12437. for (n = 0; n < cc.length; n++) {
  12438. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12439. }
  12440. // create array
  12441. var arr = cs.split('|');
  12442. // init context point
  12443. var cpx = 0;
  12444. var cpy = 0;
  12445. var path = new PathProxy();
  12446. var CMD = PathProxy.CMD;
  12447. var prevCmd;
  12448. for (n = 1; n < arr.length; n++) {
  12449. var str = arr[n];
  12450. var c = str.charAt(0);
  12451. var off = 0;
  12452. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12453. var cmd;
  12454. if (p.length > 0 && p[0] === '') {
  12455. p.shift();
  12456. }
  12457. for (var i = 0; i < p.length; i++) {
  12458. p[i] = parseFloat(p[i]);
  12459. }
  12460. while (off < p.length && !isNaN(p[off])) {
  12461. if (isNaN(p[0])) {
  12462. break;
  12463. }
  12464. var ctlPtx;
  12465. var ctlPty;
  12466. var rx;
  12467. var ry;
  12468. var psi;
  12469. var fa;
  12470. var fs;
  12471. var x1 = cpx;
  12472. var y1 = cpy;
  12473. // convert l, H, h, V, and v to L
  12474. switch (c) {
  12475. case 'l':
  12476. cpx += p[off++];
  12477. cpy += p[off++];
  12478. cmd = CMD.L;
  12479. path.addData(cmd, cpx, cpy);
  12480. break;
  12481. case 'L':
  12482. cpx = p[off++];
  12483. cpy = p[off++];
  12484. cmd = CMD.L;
  12485. path.addData(cmd, cpx, cpy);
  12486. break;
  12487. case 'm':
  12488. cpx += p[off++];
  12489. cpy += p[off++];
  12490. cmd = CMD.M;
  12491. path.addData(cmd, cpx, cpy);
  12492. c = 'l';
  12493. break;
  12494. case 'M':
  12495. cpx = p[off++];
  12496. cpy = p[off++];
  12497. cmd = CMD.M;
  12498. path.addData(cmd, cpx, cpy);
  12499. c = 'L';
  12500. break;
  12501. case 'h':
  12502. cpx += p[off++];
  12503. cmd = CMD.L;
  12504. path.addData(cmd, cpx, cpy);
  12505. break;
  12506. case 'H':
  12507. cpx = p[off++];
  12508. cmd = CMD.L;
  12509. path.addData(cmd, cpx, cpy);
  12510. break;
  12511. case 'v':
  12512. cpy += p[off++];
  12513. cmd = CMD.L;
  12514. path.addData(cmd, cpx, cpy);
  12515. break;
  12516. case 'V':
  12517. cpy = p[off++];
  12518. cmd = CMD.L;
  12519. path.addData(cmd, cpx, cpy);
  12520. break;
  12521. case 'C':
  12522. cmd = CMD.C;
  12523. path.addData(
  12524. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12525. );
  12526. cpx = p[off - 2];
  12527. cpy = p[off - 1];
  12528. break;
  12529. case 'c':
  12530. cmd = CMD.C;
  12531. path.addData(
  12532. cmd,
  12533. p[off++] + cpx, p[off++] + cpy,
  12534. p[off++] + cpx, p[off++] + cpy,
  12535. p[off++] + cpx, p[off++] + cpy
  12536. );
  12537. cpx += p[off - 2];
  12538. cpy += p[off - 1];
  12539. break;
  12540. case 'S':
  12541. ctlPtx = cpx;
  12542. ctlPty = cpy;
  12543. var len = path.len();
  12544. var pathData = path.data;
  12545. if (prevCmd === CMD.C) {
  12546. ctlPtx += cpx - pathData[len - 4];
  12547. ctlPty += cpy - pathData[len - 3];
  12548. }
  12549. cmd = CMD.C;
  12550. x1 = p[off++];
  12551. y1 = p[off++];
  12552. cpx = p[off++];
  12553. cpy = p[off++];
  12554. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12555. break;
  12556. case 's':
  12557. ctlPtx = cpx;
  12558. ctlPty = cpy;
  12559. var len = path.len();
  12560. var pathData = path.data;
  12561. if (prevCmd === CMD.C) {
  12562. ctlPtx += cpx - pathData[len - 4];
  12563. ctlPty += cpy - pathData[len - 3];
  12564. }
  12565. cmd = CMD.C;
  12566. x1 = cpx + p[off++];
  12567. y1 = cpy + p[off++];
  12568. cpx += p[off++];
  12569. cpy += p[off++];
  12570. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12571. break;
  12572. case 'Q':
  12573. x1 = p[off++];
  12574. y1 = p[off++];
  12575. cpx = p[off++];
  12576. cpy = p[off++];
  12577. cmd = CMD.Q;
  12578. path.addData(cmd, x1, y1, cpx, cpy);
  12579. break;
  12580. case 'q':
  12581. x1 = p[off++] + cpx;
  12582. y1 = p[off++] + cpy;
  12583. cpx += p[off++];
  12584. cpy += p[off++];
  12585. cmd = CMD.Q;
  12586. path.addData(cmd, x1, y1, cpx, cpy);
  12587. break;
  12588. case 'T':
  12589. ctlPtx = cpx;
  12590. ctlPty = cpy;
  12591. var len = path.len();
  12592. var pathData = path.data;
  12593. if (prevCmd === CMD.Q) {
  12594. ctlPtx += cpx - pathData[len - 4];
  12595. ctlPty += cpy - pathData[len - 3];
  12596. }
  12597. cpx = p[off++];
  12598. cpy = p[off++];
  12599. cmd = CMD.Q;
  12600. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12601. break;
  12602. case 't':
  12603. ctlPtx = cpx;
  12604. ctlPty = cpy;
  12605. var len = path.len();
  12606. var pathData = path.data;
  12607. if (prevCmd === CMD.Q) {
  12608. ctlPtx += cpx - pathData[len - 4];
  12609. ctlPty += cpy - pathData[len - 3];
  12610. }
  12611. cpx += p[off++];
  12612. cpy += p[off++];
  12613. cmd = CMD.Q;
  12614. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12615. break;
  12616. case 'A':
  12617. rx = p[off++];
  12618. ry = p[off++];
  12619. psi = p[off++];
  12620. fa = p[off++];
  12621. fs = p[off++];
  12622. x1 = cpx, y1 = cpy;
  12623. cpx = p[off++];
  12624. cpy = p[off++];
  12625. cmd = CMD.A;
  12626. processArc(
  12627. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12628. );
  12629. break;
  12630. case 'a':
  12631. rx = p[off++];
  12632. ry = p[off++];
  12633. psi = p[off++];
  12634. fa = p[off++];
  12635. fs = p[off++];
  12636. x1 = cpx, y1 = cpy;
  12637. cpx += p[off++];
  12638. cpy += p[off++];
  12639. cmd = CMD.A;
  12640. processArc(
  12641. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12642. );
  12643. break;
  12644. }
  12645. }
  12646. if (c === 'z' || c === 'Z') {
  12647. cmd = CMD.Z;
  12648. path.addData(cmd);
  12649. }
  12650. prevCmd = cmd;
  12651. }
  12652. path.toStatic();
  12653. return path;
  12654. }
  12655. // TODO Optimize double memory cost problem
  12656. function createPathOptions(str, opts) {
  12657. var pathProxy = createPathProxyFromString(str);
  12658. opts = opts || {};
  12659. opts.buildPath = function (path) {
  12660. if (path.setData) {
  12661. path.setData(pathProxy.data);
  12662. // Svg and vml renderer don't have context
  12663. var ctx = path.getContext();
  12664. if (ctx) {
  12665. path.rebuildPath(ctx);
  12666. }
  12667. }
  12668. else {
  12669. var ctx = path;
  12670. pathProxy.rebuildPath(ctx);
  12671. }
  12672. };
  12673. opts.applyTransform = function (m) {
  12674. transformPath(pathProxy, m);
  12675. this.dirty(true);
  12676. };
  12677. return opts;
  12678. }
  12679. /**
  12680. * Create a Path object from path string data
  12681. * http://www.w3.org/TR/SVG/paths.html#PathData
  12682. * @param {Object} opts Other options
  12683. */
  12684. function createFromString(str, opts) {
  12685. return new Path(createPathOptions(str, opts));
  12686. }
  12687. /**
  12688. * Create a Path class from path string data
  12689. * @param {string} str
  12690. * @param {Object} opts Other options
  12691. */
  12692. function extendFromString(str, opts) {
  12693. return Path.extend(createPathOptions(str, opts));
  12694. }
  12695. /**
  12696. * Merge multiple paths
  12697. */
  12698. // TODO Apply transform
  12699. // TODO stroke dash
  12700. // TODO Optimize double memory cost problem
  12701. function mergePath$1(pathEls, opts) {
  12702. var pathList = [];
  12703. var len = pathEls.length;
  12704. for (var i = 0; i < len; i++) {
  12705. var pathEl = pathEls[i];
  12706. if (!pathEl.path) {
  12707. pathEl.createPathProxy();
  12708. }
  12709. if (pathEl.__dirtyPath) {
  12710. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12711. }
  12712. pathList.push(pathEl.path);
  12713. }
  12714. var pathBundle = new Path(opts);
  12715. // Need path proxy.
  12716. pathBundle.createPathProxy();
  12717. pathBundle.buildPath = function (path) {
  12718. path.appendPath(pathList);
  12719. // Svg and vml renderer don't have context
  12720. var ctx = path.getContext();
  12721. if (ctx) {
  12722. path.rebuildPath(ctx);
  12723. }
  12724. };
  12725. return pathBundle;
  12726. }
  12727. /**
  12728. * @alias zrender/graphic/Text
  12729. * @extends module:zrender/graphic/Displayable
  12730. * @constructor
  12731. * @param {Object} opts
  12732. */
  12733. var Text = function (opts) { // jshint ignore:line
  12734. Displayable.call(this, opts);
  12735. };
  12736. Text.prototype = {
  12737. constructor: Text,
  12738. type: 'text',
  12739. brush: function (ctx, prevEl) {
  12740. var style = this.style;
  12741. // Optimize, avoid normalize every time.
  12742. this.__dirty && normalizeTextStyle(style, true);
  12743. // Use props with prefix 'text'.
  12744. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12745. style.shadowOffsetX = style.shadowOffsetY = null;
  12746. var text = style.text;
  12747. // Convert to string
  12748. text != null && (text += '');
  12749. // Always bind style
  12750. style.bind(ctx, this, prevEl);
  12751. if (!needDrawText(text, style)) {
  12752. return;
  12753. }
  12754. this.setTransform(ctx);
  12755. renderText(this, ctx, text, style);
  12756. this.restoreTransform(ctx);
  12757. },
  12758. getBoundingRect: function () {
  12759. var style = this.style;
  12760. // Optimize, avoid normalize every time.
  12761. this.__dirty && normalizeTextStyle(style, true);
  12762. if (!this._rect) {
  12763. var text = style.text;
  12764. text != null ? (text += '') : (text = '');
  12765. var rect = getBoundingRect(
  12766. style.text + '',
  12767. style.font,
  12768. style.textAlign,
  12769. style.textVerticalAlign,
  12770. style.textPadding,
  12771. style.rich
  12772. );
  12773. rect.x += style.x || 0;
  12774. rect.y += style.y || 0;
  12775. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12776. var w = style.textStrokeWidth;
  12777. rect.x -= w / 2;
  12778. rect.y -= w / 2;
  12779. rect.width += w;
  12780. rect.height += w;
  12781. }
  12782. this._rect = rect;
  12783. }
  12784. return this._rect;
  12785. }
  12786. };
  12787. inherits(Text, Displayable);
  12788. /**
  12789. * 圆形
  12790. * @module zrender/shape/Circle
  12791. */
  12792. var Circle = Path.extend({
  12793. type: 'circle',
  12794. shape: {
  12795. cx: 0,
  12796. cy: 0,
  12797. r: 0
  12798. },
  12799. buildPath : function (ctx, shape, inBundle) {
  12800. // Better stroking in ShapeBundle
  12801. // Always do it may have performence issue ( fill may be 2x more cost)
  12802. if (inBundle) {
  12803. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12804. }
  12805. // else {
  12806. // if (ctx.allocate && !ctx.data.length) {
  12807. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12808. // }
  12809. // }
  12810. // Better stroking in ShapeBundle
  12811. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12812. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12813. }
  12814. });
  12815. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12816. // where exception "unexpected call to method or property access"
  12817. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12818. // whose area size is zero is drawn and ctx.clip() is called and
  12819. // shadowBlur is set. See #4572, #3112, #5777.
  12820. // (e.g.,
  12821. // ctx.moveTo(10, 10);
  12822. // ctx.lineTo(20, 10);
  12823. // ctx.closePath();
  12824. // ctx.clip();
  12825. // ctx.shadowBlur = 10;
  12826. // ...
  12827. // ctx.fill();
  12828. // )
  12829. var shadowTemp = [
  12830. ['shadowBlur', 0],
  12831. ['shadowColor', '#000'],
  12832. ['shadowOffsetX', 0],
  12833. ['shadowOffsetY', 0]
  12834. ];
  12835. var fixClipWithShadow = function (orignalBrush) {
  12836. // version string can be: '11.0'
  12837. return (env$1.browser.ie && env$1.browser.version >= 11)
  12838. ? function () {
  12839. var clipPaths = this.__clipPaths;
  12840. var style = this.style;
  12841. var modified;
  12842. if (clipPaths) {
  12843. for (var i = 0; i < clipPaths.length; i++) {
  12844. var clipPath = clipPaths[i];
  12845. var shape = clipPath && clipPath.shape;
  12846. var type = clipPath && clipPath.type;
  12847. if (shape && (
  12848. (type === 'sector' && shape.startAngle === shape.endAngle)
  12849. || (type === 'rect' && (!shape.width || !shape.height))
  12850. )) {
  12851. for (var j = 0; j < shadowTemp.length; j++) {
  12852. // It is save to put shadowTemp static, because shadowTemp
  12853. // will be all modified each item brush called.
  12854. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12855. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12856. }
  12857. modified = true;
  12858. break;
  12859. }
  12860. }
  12861. }
  12862. orignalBrush.apply(this, arguments);
  12863. if (modified) {
  12864. for (var j = 0; j < shadowTemp.length; j++) {
  12865. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12866. }
  12867. }
  12868. }
  12869. : orignalBrush;
  12870. };
  12871. /**
  12872. * 扇形
  12873. * @module zrender/graphic/shape/Sector
  12874. */
  12875. var Sector = Path.extend({
  12876. type: 'sector',
  12877. shape: {
  12878. cx: 0,
  12879. cy: 0,
  12880. r0: 0,
  12881. r: 0,
  12882. startAngle: 0,
  12883. endAngle: Math.PI * 2,
  12884. clockwise: true
  12885. },
  12886. brush: fixClipWithShadow(Path.prototype.brush),
  12887. buildPath: function (ctx, shape) {
  12888. var x = shape.cx;
  12889. var y = shape.cy;
  12890. var r0 = Math.max(shape.r0 || 0, 0);
  12891. var r = Math.max(shape.r, 0);
  12892. var startAngle = shape.startAngle;
  12893. var endAngle = shape.endAngle;
  12894. var clockwise = shape.clockwise;
  12895. var unitX = Math.cos(startAngle);
  12896. var unitY = Math.sin(startAngle);
  12897. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  12898. ctx.lineTo(unitX * r + x, unitY * r + y);
  12899. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  12900. ctx.lineTo(
  12901. Math.cos(endAngle) * r0 + x,
  12902. Math.sin(endAngle) * r0 + y
  12903. );
  12904. if (r0 !== 0) {
  12905. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  12906. }
  12907. ctx.closePath();
  12908. }
  12909. });
  12910. /**
  12911. * 圆环
  12912. * @module zrender/graphic/shape/Ring
  12913. */
  12914. var Ring = Path.extend({
  12915. type: 'ring',
  12916. shape: {
  12917. cx: 0,
  12918. cy: 0,
  12919. r: 0,
  12920. r0: 0
  12921. },
  12922. buildPath: function (ctx, shape) {
  12923. var x = shape.cx;
  12924. var y = shape.cy;
  12925. var PI2 = Math.PI * 2;
  12926. ctx.moveTo(x + shape.r, y);
  12927. ctx.arc(x, y, shape.r, 0, PI2, false);
  12928. ctx.moveTo(x + shape.r0, y);
  12929. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12930. }
  12931. });
  12932. /**
  12933. * Catmull-Rom spline 插值折线
  12934. * @module zrender/shape/util/smoothSpline
  12935. * @author pissang (https://www.github.com/pissang)
  12936. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  12937. * errorrik (errorrik@gmail.com)
  12938. */
  12939. /**
  12940. * @inner
  12941. */
  12942. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12943. var v0 = (p2 - p0) * 0.5;
  12944. var v1 = (p3 - p1) * 0.5;
  12945. return (2 * (p1 - p2) + v0 + v1) * t3
  12946. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12947. + v0 * t + p1;
  12948. }
  12949. /**
  12950. * @alias module:zrender/shape/util/smoothSpline
  12951. * @param {Array} points 线段顶点数组
  12952. * @param {boolean} isLoop
  12953. * @return {Array}
  12954. */
  12955. var smoothSpline = function (points, isLoop) {
  12956. var len$$1 = points.length;
  12957. var ret = [];
  12958. var distance$$1 = 0;
  12959. for (var i = 1; i < len$$1; i++) {
  12960. distance$$1 += distance(points[i - 1], points[i]);
  12961. }
  12962. var segs = distance$$1 / 2;
  12963. segs = segs < len$$1 ? len$$1 : segs;
  12964. for (var i = 0; i < segs; i++) {
  12965. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  12966. var idx = Math.floor(pos);
  12967. var w = pos - idx;
  12968. var p0;
  12969. var p1 = points[idx % len$$1];
  12970. var p2;
  12971. var p3;
  12972. if (!isLoop) {
  12973. p0 = points[idx === 0 ? idx : idx - 1];
  12974. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  12975. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  12976. }
  12977. else {
  12978. p0 = points[(idx - 1 + len$$1) % len$$1];
  12979. p2 = points[(idx + 1) % len$$1];
  12980. p3 = points[(idx + 2) % len$$1];
  12981. }
  12982. var w2 = w * w;
  12983. var w3 = w * w2;
  12984. ret.push([
  12985. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  12986. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  12987. ]);
  12988. }
  12989. return ret;
  12990. };
  12991. /**
  12992. * 贝塞尔平滑曲线
  12993. * @module zrender/shape/util/smoothBezier
  12994. * @author pissang (https://www.github.com/pissang)
  12995. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  12996. * errorrik (errorrik@gmail.com)
  12997. */
  12998. /**
  12999. * 贝塞尔平滑曲线
  13000. * @alias module:zrender/shape/util/smoothBezier
  13001. * @param {Array} points 线段顶点数组
  13002. * @param {number} smooth 平滑等级, 0-1
  13003. * @param {boolean} isLoop
  13004. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13005. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13006. * 整个折线的包围盒做一个并集用来约束控制点。
  13007. * @param {Array} 计算出来的控制点数组
  13008. */
  13009. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13010. var cps = [];
  13011. var v = [];
  13012. var v1 = [];
  13013. var v2 = [];
  13014. var prevPoint;
  13015. var nextPoint;
  13016. var min$$1, max$$1;
  13017. if (constraint) {
  13018. min$$1 = [Infinity, Infinity];
  13019. max$$1 = [-Infinity, -Infinity];
  13020. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13021. min(min$$1, min$$1, points[i]);
  13022. max(max$$1, max$$1, points[i]);
  13023. }
  13024. // 与指定的包围盒做并集
  13025. min(min$$1, min$$1, constraint[0]);
  13026. max(max$$1, max$$1, constraint[1]);
  13027. }
  13028. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13029. var point = points[i];
  13030. if (isLoop) {
  13031. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13032. nextPoint = points[(i + 1) % len$$1];
  13033. }
  13034. else {
  13035. if (i === 0 || i === len$$1 - 1) {
  13036. cps.push(clone$1(points[i]));
  13037. continue;
  13038. }
  13039. else {
  13040. prevPoint = points[i - 1];
  13041. nextPoint = points[i + 1];
  13042. }
  13043. }
  13044. sub(v, nextPoint, prevPoint);
  13045. // use degree to scale the handle length
  13046. scale(v, v, smooth);
  13047. var d0 = distance(point, prevPoint);
  13048. var d1 = distance(point, nextPoint);
  13049. var sum = d0 + d1;
  13050. if (sum !== 0) {
  13051. d0 /= sum;
  13052. d1 /= sum;
  13053. }
  13054. scale(v1, v, -d0);
  13055. scale(v2, v, d1);
  13056. var cp0 = add([], point, v1);
  13057. var cp1 = add([], point, v2);
  13058. if (constraint) {
  13059. max(cp0, cp0, min$$1);
  13060. min(cp0, cp0, max$$1);
  13061. max(cp1, cp1, min$$1);
  13062. min(cp1, cp1, max$$1);
  13063. }
  13064. cps.push(cp0);
  13065. cps.push(cp1);
  13066. }
  13067. if (isLoop) {
  13068. cps.push(cps.shift());
  13069. }
  13070. return cps;
  13071. };
  13072. function buildPath$1(ctx, shape, closePath) {
  13073. var points = shape.points;
  13074. var smooth = shape.smooth;
  13075. if (points && points.length >= 2) {
  13076. if (smooth && smooth !== 'spline') {
  13077. var controlPoints = smoothBezier(
  13078. points, smooth, closePath, shape.smoothConstraint
  13079. );
  13080. ctx.moveTo(points[0][0], points[0][1]);
  13081. var len = points.length;
  13082. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13083. var cp1 = controlPoints[i * 2];
  13084. var cp2 = controlPoints[i * 2 + 1];
  13085. var p = points[(i + 1) % len];
  13086. ctx.bezierCurveTo(
  13087. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13088. );
  13089. }
  13090. }
  13091. else {
  13092. if (smooth === 'spline') {
  13093. points = smoothSpline(points, closePath);
  13094. }
  13095. ctx.moveTo(points[0][0], points[0][1]);
  13096. for (var i = 1, l = points.length; i < l; i++) {
  13097. ctx.lineTo(points[i][0], points[i][1]);
  13098. }
  13099. }
  13100. closePath && ctx.closePath();
  13101. }
  13102. }
  13103. /**
  13104. * 多边形
  13105. * @module zrender/shape/Polygon
  13106. */
  13107. var Polygon = Path.extend({
  13108. type: 'polygon',
  13109. shape: {
  13110. points: null,
  13111. smooth: false,
  13112. smoothConstraint: null
  13113. },
  13114. buildPath: function (ctx, shape) {
  13115. buildPath$1(ctx, shape, true);
  13116. }
  13117. });
  13118. /**
  13119. * @module zrender/graphic/shape/Polyline
  13120. */
  13121. var Polyline = Path.extend({
  13122. type: 'polyline',
  13123. shape: {
  13124. points: null,
  13125. smooth: false,
  13126. smoothConstraint: null
  13127. },
  13128. style: {
  13129. stroke: '#000',
  13130. fill: null
  13131. },
  13132. buildPath: function (ctx, shape) {
  13133. buildPath$1(ctx, shape, false);
  13134. }
  13135. });
  13136. /**
  13137. * 矩形
  13138. * @module zrender/graphic/shape/Rect
  13139. */
  13140. var Rect = Path.extend({
  13141. type: 'rect',
  13142. shape: {
  13143. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13144. // r缩写为1 相当于 [1, 1, 1, 1]
  13145. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13146. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13147. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13148. r: 0,
  13149. x: 0,
  13150. y: 0,
  13151. width: 0,
  13152. height: 0
  13153. },
  13154. buildPath: function (ctx, shape) {
  13155. var x = shape.x;
  13156. var y = shape.y;
  13157. var width = shape.width;
  13158. var height = shape.height;
  13159. if (!shape.r) {
  13160. ctx.rect(x, y, width, height);
  13161. }
  13162. else {
  13163. buildPath(ctx, shape);
  13164. }
  13165. ctx.closePath();
  13166. return;
  13167. }
  13168. });
  13169. /**
  13170. * 直线
  13171. * @module zrender/graphic/shape/Line
  13172. */
  13173. var Line = Path.extend({
  13174. type: 'line',
  13175. shape: {
  13176. // Start point
  13177. x1: 0,
  13178. y1: 0,
  13179. // End point
  13180. x2: 0,
  13181. y2: 0,
  13182. percent: 1
  13183. },
  13184. style: {
  13185. stroke: '#000',
  13186. fill: null
  13187. },
  13188. buildPath: function (ctx, shape) {
  13189. var x1 = shape.x1;
  13190. var y1 = shape.y1;
  13191. var x2 = shape.x2;
  13192. var y2 = shape.y2;
  13193. var percent = shape.percent;
  13194. if (percent === 0) {
  13195. return;
  13196. }
  13197. ctx.moveTo(x1, y1);
  13198. if (percent < 1) {
  13199. x2 = x1 * (1 - percent) + x2 * percent;
  13200. y2 = y1 * (1 - percent) + y2 * percent;
  13201. }
  13202. ctx.lineTo(x2, y2);
  13203. },
  13204. /**
  13205. * Get point at percent
  13206. * @param {number} percent
  13207. * @return {Array.<number>}
  13208. */
  13209. pointAt: function (p) {
  13210. var shape = this.shape;
  13211. return [
  13212. shape.x1 * (1 - p) + shape.x2 * p,
  13213. shape.y1 * (1 - p) + shape.y2 * p
  13214. ];
  13215. }
  13216. });
  13217. /**
  13218. * 贝塞尔曲线
  13219. * @module zrender/shape/BezierCurve
  13220. */
  13221. var out = [];
  13222. function someVectorAt(shape, t, isTangent) {
  13223. var cpx2 = shape.cpx2;
  13224. var cpy2 = shape.cpy2;
  13225. if (cpx2 === null || cpy2 === null) {
  13226. return [
  13227. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13228. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13229. ];
  13230. }
  13231. else {
  13232. return [
  13233. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13234. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13235. ];
  13236. }
  13237. }
  13238. var BezierCurve = Path.extend({
  13239. type: 'bezier-curve',
  13240. shape: {
  13241. x1: 0,
  13242. y1: 0,
  13243. x2: 0,
  13244. y2: 0,
  13245. cpx1: 0,
  13246. cpy1: 0,
  13247. // cpx2: 0,
  13248. // cpy2: 0
  13249. // Curve show percent, for animating
  13250. percent: 1
  13251. },
  13252. style: {
  13253. stroke: '#000',
  13254. fill: null
  13255. },
  13256. buildPath: function (ctx, shape) {
  13257. var x1 = shape.x1;
  13258. var y1 = shape.y1;
  13259. var x2 = shape.x2;
  13260. var y2 = shape.y2;
  13261. var cpx1 = shape.cpx1;
  13262. var cpy1 = shape.cpy1;
  13263. var cpx2 = shape.cpx2;
  13264. var cpy2 = shape.cpy2;
  13265. var percent = shape.percent;
  13266. if (percent === 0) {
  13267. return;
  13268. }
  13269. ctx.moveTo(x1, y1);
  13270. if (cpx2 == null || cpy2 == null) {
  13271. if (percent < 1) {
  13272. quadraticSubdivide(
  13273. x1, cpx1, x2, percent, out
  13274. );
  13275. cpx1 = out[1];
  13276. x2 = out[2];
  13277. quadraticSubdivide(
  13278. y1, cpy1, y2, percent, out
  13279. );
  13280. cpy1 = out[1];
  13281. y2 = out[2];
  13282. }
  13283. ctx.quadraticCurveTo(
  13284. cpx1, cpy1,
  13285. x2, y2
  13286. );
  13287. }
  13288. else {
  13289. if (percent < 1) {
  13290. cubicSubdivide(
  13291. x1, cpx1, cpx2, x2, percent, out
  13292. );
  13293. cpx1 = out[1];
  13294. cpx2 = out[2];
  13295. x2 = out[3];
  13296. cubicSubdivide(
  13297. y1, cpy1, cpy2, y2, percent, out
  13298. );
  13299. cpy1 = out[1];
  13300. cpy2 = out[2];
  13301. y2 = out[3];
  13302. }
  13303. ctx.bezierCurveTo(
  13304. cpx1, cpy1,
  13305. cpx2, cpy2,
  13306. x2, y2
  13307. );
  13308. }
  13309. },
  13310. /**
  13311. * Get point at percent
  13312. * @param {number} t
  13313. * @return {Array.<number>}
  13314. */
  13315. pointAt: function (t) {
  13316. return someVectorAt(this.shape, t, false);
  13317. },
  13318. /**
  13319. * Get tangent at percent
  13320. * @param {number} t
  13321. * @return {Array.<number>}
  13322. */
  13323. tangentAt: function (t) {
  13324. var p = someVectorAt(this.shape, t, true);
  13325. return normalize(p, p);
  13326. }
  13327. });
  13328. /**
  13329. * 圆弧
  13330. * @module zrender/graphic/shape/Arc
  13331. */
  13332. var Arc = Path.extend({
  13333. type: 'arc',
  13334. shape: {
  13335. cx: 0,
  13336. cy: 0,
  13337. r: 0,
  13338. startAngle: 0,
  13339. endAngle: Math.PI * 2,
  13340. clockwise: true
  13341. },
  13342. style: {
  13343. stroke: '#000',
  13344. fill: null
  13345. },
  13346. buildPath: function (ctx, shape) {
  13347. var x = shape.cx;
  13348. var y = shape.cy;
  13349. var r = Math.max(shape.r, 0);
  13350. var startAngle = shape.startAngle;
  13351. var endAngle = shape.endAngle;
  13352. var clockwise = shape.clockwise;
  13353. var unitX = Math.cos(startAngle);
  13354. var unitY = Math.sin(startAngle);
  13355. ctx.moveTo(unitX * r + x, unitY * r + y);
  13356. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13357. }
  13358. });
  13359. // CompoundPath to improve performance
  13360. var CompoundPath = Path.extend({
  13361. type: 'compound',
  13362. shape: {
  13363. paths: null
  13364. },
  13365. _updatePathDirty: function () {
  13366. var dirtyPath = this.__dirtyPath;
  13367. var paths = this.shape.paths;
  13368. for (var i = 0; i < paths.length; i++) {
  13369. // Mark as dirty if any subpath is dirty
  13370. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13371. }
  13372. this.__dirtyPath = dirtyPath;
  13373. this.__dirty = this.__dirty || dirtyPath;
  13374. },
  13375. beforeBrush: function () {
  13376. this._updatePathDirty();
  13377. var paths = this.shape.paths || [];
  13378. var scale = this.getGlobalScale();
  13379. // Update path scale
  13380. for (var i = 0; i < paths.length; i++) {
  13381. if (!paths[i].path) {
  13382. paths[i].createPathProxy();
  13383. }
  13384. paths[i].path.setScale(scale[0], scale[1]);
  13385. }
  13386. },
  13387. buildPath: function (ctx, shape) {
  13388. var paths = shape.paths || [];
  13389. for (var i = 0; i < paths.length; i++) {
  13390. paths[i].buildPath(ctx, paths[i].shape, true);
  13391. }
  13392. },
  13393. afterBrush: function () {
  13394. var paths = this.shape.paths || [];
  13395. for (var i = 0; i < paths.length; i++) {
  13396. paths[i].__dirtyPath = false;
  13397. }
  13398. },
  13399. getBoundingRect: function () {
  13400. this._updatePathDirty();
  13401. return Path.prototype.getBoundingRect.call(this);
  13402. }
  13403. });
  13404. /**
  13405. * @param {Array.<Object>} colorStops
  13406. */
  13407. var Gradient = function (colorStops) {
  13408. this.colorStops = colorStops || [];
  13409. };
  13410. Gradient.prototype = {
  13411. constructor: Gradient,
  13412. addColorStop: function (offset, color) {
  13413. this.colorStops.push({
  13414. offset: offset,
  13415. color: color
  13416. });
  13417. }
  13418. };
  13419. /**
  13420. * x, y, x2, y2 are all percent from 0 to 1
  13421. * @param {number} [x=0]
  13422. * @param {number} [y=0]
  13423. * @param {number} [x2=1]
  13424. * @param {number} [y2=0]
  13425. * @param {Array.<Object>} colorStops
  13426. * @param {boolean} [globalCoord=false]
  13427. */
  13428. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13429. // Should do nothing more in this constructor. Because gradient can be
  13430. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13431. // this constructor will not be called.
  13432. this.x = x == null ? 0 : x;
  13433. this.y = y == null ? 0 : y;
  13434. this.x2 = x2 == null ? 1 : x2;
  13435. this.y2 = y2 == null ? 0 : y2;
  13436. // Can be cloned
  13437. this.type = 'linear';
  13438. // If use global coord
  13439. this.global = globalCoord || false;
  13440. Gradient.call(this, colorStops);
  13441. };
  13442. LinearGradient.prototype = {
  13443. constructor: LinearGradient
  13444. };
  13445. inherits(LinearGradient, Gradient);
  13446. /**
  13447. * x, y, r are all percent from 0 to 1
  13448. * @param {number} [x=0.5]
  13449. * @param {number} [y=0.5]
  13450. * @param {number} [r=0.5]
  13451. * @param {Array.<Object>} [colorStops]
  13452. * @param {boolean} [globalCoord=false]
  13453. */
  13454. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13455. // Should do nothing more in this constructor. Because gradient can be
  13456. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13457. // this constructor will not be called.
  13458. this.x = x == null ? 0.5 : x;
  13459. this.y = y == null ? 0.5 : y;
  13460. this.r = r == null ? 0.5 : r;
  13461. // Can be cloned
  13462. this.type = 'radial';
  13463. // If use global coord
  13464. this.global = globalCoord || false;
  13465. Gradient.call(this, colorStops);
  13466. };
  13467. RadialGradient.prototype = {
  13468. constructor: RadialGradient
  13469. };
  13470. inherits(RadialGradient, Gradient);
  13471. /**
  13472. * Displayable for incremental rendering. It will be rendered in a separate layer
  13473. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13474. * addDisplayables will render the added displayables incremetally.
  13475. *
  13476. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13477. */
  13478. // TODO Style override ?
  13479. function IncrementalDisplayble(opts) {
  13480. Displayable.call(this, opts);
  13481. this._displayables = [];
  13482. this._temporaryDisplayables = [];
  13483. this._cursor = 0;
  13484. this.notClear = true;
  13485. }
  13486. IncrementalDisplayble.prototype.incremental = true;
  13487. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13488. this._displayables = [];
  13489. this._temporaryDisplayables = [];
  13490. this._cursor = 0;
  13491. this.dirty();
  13492. this.notClear = false;
  13493. };
  13494. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13495. if (notPersistent) {
  13496. this._temporaryDisplayables.push(displayable);
  13497. }
  13498. else {
  13499. this._displayables.push(displayable);
  13500. }
  13501. this.dirty();
  13502. };
  13503. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13504. notPersistent = notPersistent || false;
  13505. for (var i = 0; i < displayables.length; i++) {
  13506. this.addDisplayable(displayables[i], notPersistent);
  13507. }
  13508. };
  13509. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13510. for (var i = this._cursor; i < this._displayables.length; i++) {
  13511. cb && cb(this._displayables[i]);
  13512. }
  13513. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13514. cb && cb(this._temporaryDisplayables[i]);
  13515. }
  13516. };
  13517. IncrementalDisplayble.prototype.update = function () {
  13518. this.updateTransform();
  13519. for (var i = this._cursor; i < this._displayables.length; i++) {
  13520. var displayable = this._displayables[i];
  13521. // PENDING
  13522. displayable.parent = this;
  13523. displayable.update();
  13524. displayable.parent = null;
  13525. }
  13526. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13527. var displayable = this._temporaryDisplayables[i];
  13528. // PENDING
  13529. displayable.parent = this;
  13530. displayable.update();
  13531. displayable.parent = null;
  13532. }
  13533. };
  13534. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13535. // Render persistant displayables.
  13536. for (var i = this._cursor; i < this._displayables.length; i++) {
  13537. var displayable = this._temporaryDisplayables[i];
  13538. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13539. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13540. displayable.afterBrush && displayable.afterBrush(ctx);
  13541. }
  13542. this._cursor = i;
  13543. // Render temporary displayables.
  13544. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13545. var displayable = this._temporaryDisplayables[i];
  13546. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13547. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13548. displayable.afterBrush && displayable.afterBrush(ctx);
  13549. }
  13550. this._temporaryDisplayables = [];
  13551. this.notClear = true;
  13552. };
  13553. var m = [];
  13554. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13555. if (!this._rect) {
  13556. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13557. for (var i = 0; i < this._displayables.length; i++) {
  13558. var displayable = this._displayables[i];
  13559. var childRect = displayable.getBoundingRect().clone();
  13560. if (displayable.needLocalTransform()) {
  13561. childRect.applyTransform(displayable.getLocalTransform(m));
  13562. }
  13563. rect.union(childRect);
  13564. }
  13565. this._rect = rect;
  13566. }
  13567. return this._rect;
  13568. };
  13569. IncrementalDisplayble.prototype.contain = function (x, y) {
  13570. var localPos = this.transformCoordToLocal(x, y);
  13571. var rect = this.getBoundingRect();
  13572. if (rect.contain(localPos[0], localPos[1])) {
  13573. for (var i = 0; i < this._displayables.length; i++) {
  13574. var displayable = this._displayables[i];
  13575. if (displayable.contain(x, y)) {
  13576. return true;
  13577. }
  13578. }
  13579. }
  13580. return false;
  13581. };
  13582. inherits(IncrementalDisplayble, Displayable);
  13583. var round = Math.round;
  13584. var mathMax$1 = Math.max;
  13585. var mathMin$1 = Math.min;
  13586. var EMPTY_OBJ = {};
  13587. /**
  13588. * Extend shape with parameters
  13589. */
  13590. function extendShape(opts) {
  13591. return Path.extend(opts);
  13592. }
  13593. /**
  13594. * Extend path
  13595. */
  13596. function extendPath(pathData, opts) {
  13597. return extendFromString(pathData, opts);
  13598. }
  13599. /**
  13600. * Create a path element from path data string
  13601. * @param {string} pathData
  13602. * @param {Object} opts
  13603. * @param {module:zrender/core/BoundingRect} rect
  13604. * @param {string} [layout=cover] 'center' or 'cover'
  13605. */
  13606. function makePath(pathData, opts, rect, layout) {
  13607. var path = createFromString(pathData, opts);
  13608. var boundingRect = path.getBoundingRect();
  13609. if (rect) {
  13610. if (layout === 'center') {
  13611. rect = centerGraphic(rect, boundingRect);
  13612. }
  13613. resizePath(path, rect);
  13614. }
  13615. return path;
  13616. }
  13617. /**
  13618. * Create a image element from image url
  13619. * @param {string} imageUrl image url
  13620. * @param {Object} opts options
  13621. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13622. * @param {string} [layout=cover] 'center' or 'cover'
  13623. */
  13624. function makeImage(imageUrl, rect, layout) {
  13625. var path = new ZImage({
  13626. style: {
  13627. image: imageUrl,
  13628. x: rect.x,
  13629. y: rect.y,
  13630. width: rect.width,
  13631. height: rect.height
  13632. },
  13633. onload: function (img) {
  13634. if (layout === 'center') {
  13635. var boundingRect = {
  13636. width: img.width,
  13637. height: img.height
  13638. };
  13639. path.setStyle(centerGraphic(rect, boundingRect));
  13640. }
  13641. }
  13642. });
  13643. return path;
  13644. }
  13645. /**
  13646. * Get position of centered element in bounding box.
  13647. *
  13648. * @param {Object} rect element local bounding box
  13649. * @param {Object} boundingRect constraint bounding box
  13650. * @return {Object} element position containing x, y, width, and height
  13651. */
  13652. function centerGraphic(rect, boundingRect) {
  13653. // Set rect to center, keep width / height ratio.
  13654. var aspect = boundingRect.width / boundingRect.height;
  13655. var width = rect.height * aspect;
  13656. var height;
  13657. if (width <= rect.width) {
  13658. height = rect.height;
  13659. }
  13660. else {
  13661. width = rect.width;
  13662. height = width / aspect;
  13663. }
  13664. var cx = rect.x + rect.width / 2;
  13665. var cy = rect.y + rect.height / 2;
  13666. return {
  13667. x: cx - width / 2,
  13668. y: cy - height / 2,
  13669. width: width,
  13670. height: height
  13671. };
  13672. }
  13673. var mergePath = mergePath$1;
  13674. /**
  13675. * Resize a path to fit the rect
  13676. * @param {module:zrender/graphic/Path} path
  13677. * @param {Object} rect
  13678. */
  13679. function resizePath(path, rect) {
  13680. if (!path.applyTransform) {
  13681. return;
  13682. }
  13683. var pathRect = path.getBoundingRect();
  13684. var m = pathRect.calculateTransform(rect);
  13685. path.applyTransform(m);
  13686. }
  13687. /**
  13688. * Sub pixel optimize line for canvas
  13689. *
  13690. * @param {Object} param
  13691. * @param {Object} [param.shape]
  13692. * @param {number} [param.shape.x1]
  13693. * @param {number} [param.shape.y1]
  13694. * @param {number} [param.shape.x2]
  13695. * @param {number} [param.shape.y2]
  13696. * @param {Object} [param.style]
  13697. * @param {number} [param.style.lineWidth]
  13698. * @return {Object} Modified param
  13699. */
  13700. function subPixelOptimizeLine(param) {
  13701. var shape = param.shape;
  13702. var lineWidth = param.style.lineWidth;
  13703. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13704. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13705. }
  13706. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13707. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13708. }
  13709. return param;
  13710. }
  13711. /**
  13712. * Sub pixel optimize rect for canvas
  13713. *
  13714. * @param {Object} param
  13715. * @param {Object} [param.shape]
  13716. * @param {number} [param.shape.x]
  13717. * @param {number} [param.shape.y]
  13718. * @param {number} [param.shape.width]
  13719. * @param {number} [param.shape.height]
  13720. * @param {Object} [param.style]
  13721. * @param {number} [param.style.lineWidth]
  13722. * @return {Object} Modified param
  13723. */
  13724. function subPixelOptimizeRect(param) {
  13725. var shape = param.shape;
  13726. var lineWidth = param.style.lineWidth;
  13727. var originX = shape.x;
  13728. var originY = shape.y;
  13729. var originWidth = shape.width;
  13730. var originHeight = shape.height;
  13731. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13732. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13733. shape.width = Math.max(
  13734. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13735. originWidth === 0 ? 0 : 1
  13736. );
  13737. shape.height = Math.max(
  13738. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13739. originHeight === 0 ? 0 : 1
  13740. );
  13741. return param;
  13742. }
  13743. /**
  13744. * Sub pixel optimize for canvas
  13745. *
  13746. * @param {number} position Coordinate, such as x, y
  13747. * @param {number} lineWidth Should be nonnegative integer.
  13748. * @param {boolean=} positiveOrNegative Default false (negative).
  13749. * @return {number} Optimized position.
  13750. */
  13751. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13752. // Assure that (position + lineWidth / 2) is near integer edge,
  13753. // otherwise line will be fuzzy in canvas.
  13754. var doubledPosition = round(position * 2);
  13755. return (doubledPosition + round(lineWidth)) % 2 === 0
  13756. ? doubledPosition / 2
  13757. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13758. }
  13759. function hasFillOrStroke(fillOrStroke) {
  13760. return fillOrStroke != null && fillOrStroke != 'none';
  13761. }
  13762. function liftColor(color) {
  13763. return typeof color === 'string' ? lift(color, -0.1) : color;
  13764. }
  13765. /**
  13766. * @private
  13767. */
  13768. function cacheElementStl(el) {
  13769. if (el.__hoverStlDirty) {
  13770. var stroke = el.style.stroke;
  13771. var fill = el.style.fill;
  13772. // Create hoverStyle on mouseover
  13773. var hoverStyle = el.__hoverStl;
  13774. hoverStyle.fill = hoverStyle.fill
  13775. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13776. hoverStyle.stroke = hoverStyle.stroke
  13777. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13778. var normalStyle = {};
  13779. for (var name in hoverStyle) {
  13780. // See comment in `doSingleEnterHover`.
  13781. if (hoverStyle[name] != null) {
  13782. normalStyle[name] = el.style[name];
  13783. }
  13784. }
  13785. el.__normalStl = normalStyle;
  13786. el.__hoverStlDirty = false;
  13787. }
  13788. }
  13789. /**
  13790. * @private
  13791. */
  13792. function doSingleEnterHover(el) {
  13793. if (el.__isHover) {
  13794. return;
  13795. }
  13796. cacheElementStl(el);
  13797. if (el.useHoverLayer) {
  13798. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13799. }
  13800. else {
  13801. var style = el.style;
  13802. var insideRollbackOpt = style.insideRollbackOpt;
  13803. // Consider case: only `position: 'top'` is set on emphasis, then text
  13804. // color should be returned to `autoColor`, rather than remain '#fff'.
  13805. // So we should rollback then apply again after style merging.
  13806. insideRollbackOpt && rollbackInsideStyle(style);
  13807. // styles can be:
  13808. // {
  13809. // label: {
  13810. // show: false,
  13811. // position: 'outside',
  13812. // fontSize: 18
  13813. // },
  13814. // emphasis: {
  13815. // label: {
  13816. // show: true
  13817. // }
  13818. // }
  13819. // },
  13820. // where properties of `emphasis` may not appear in `normal`. We previously use
  13821. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13822. // But consider rich text and setOption in merge mode, it is impossible to cover
  13823. // all properties in merge. So we use merge mode when setting style here, where
  13824. // only properties that is not `null/undefined` can be set. The disadventage:
  13825. // null/undefined can not be used to remove style any more in `emphasis`.
  13826. style.extendFrom(el.__hoverStl);
  13827. // Do not save `insideRollback`.
  13828. if (insideRollbackOpt) {
  13829. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13830. // textFill may be rollbacked to null.
  13831. if (style.textFill == null) {
  13832. style.textFill = insideRollbackOpt.autoColor;
  13833. }
  13834. }
  13835. el.dirty(false);
  13836. el.z2 += 1;
  13837. }
  13838. el.__isHover = true;
  13839. }
  13840. /**
  13841. * @inner
  13842. */
  13843. function doSingleLeaveHover(el) {
  13844. if (!el.__isHover) {
  13845. return;
  13846. }
  13847. var normalStl = el.__normalStl;
  13848. if (el.useHoverLayer) {
  13849. el.__zr && el.__zr.removeHover(el);
  13850. }
  13851. else {
  13852. // Consider null/undefined value, should use
  13853. // `setStyle` but not `extendFrom(stl, true)`.
  13854. normalStl && el.setStyle(normalStl);
  13855. el.z2 -= 1;
  13856. }
  13857. el.__isHover = false;
  13858. }
  13859. /**
  13860. * @inner
  13861. */
  13862. function doEnterHover(el) {
  13863. el.type === 'group'
  13864. ? el.traverse(function (child) {
  13865. if (child.type !== 'group') {
  13866. doSingleEnterHover(child);
  13867. }
  13868. })
  13869. : doSingleEnterHover(el);
  13870. }
  13871. function doLeaveHover(el) {
  13872. el.type === 'group'
  13873. ? el.traverse(function (child) {
  13874. if (child.type !== 'group') {
  13875. doSingleLeaveHover(child);
  13876. }
  13877. })
  13878. : doSingleLeaveHover(el);
  13879. }
  13880. /**
  13881. * @inner
  13882. */
  13883. function setElementHoverStl(el, hoverStl) {
  13884. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13885. // Often used when item group has a label element and it's hoverStyle is different
  13886. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13887. el.__hoverStlDirty = true;
  13888. if (el.__isHover) {
  13889. cacheElementStl(el);
  13890. }
  13891. }
  13892. /**
  13893. * @inner
  13894. */
  13895. function onElementMouseOver(e) {
  13896. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13897. return;
  13898. }
  13899. // Only if element is not in emphasis status
  13900. !this.__isEmphasis && doEnterHover(this);
  13901. }
  13902. /**
  13903. * @inner
  13904. */
  13905. function onElementMouseOut(e) {
  13906. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13907. return;
  13908. }
  13909. // Only if element is not in emphasis status
  13910. !this.__isEmphasis && doLeaveHover(this);
  13911. }
  13912. /**
  13913. * @inner
  13914. */
  13915. function enterEmphasis() {
  13916. this.__isEmphasis = true;
  13917. doEnterHover(this);
  13918. }
  13919. /**
  13920. * @inner
  13921. */
  13922. function leaveEmphasis() {
  13923. this.__isEmphasis = false;
  13924. doLeaveHover(this);
  13925. }
  13926. /**
  13927. * Set hover style of element.
  13928. * This method can be called repeatly without side-effects.
  13929. * @param {module:zrender/Element} el
  13930. * @param {Object} [hoverStyle]
  13931. * @param {Object} [opt]
  13932. * @param {boolean} [opt.hoverSilentOnTouch=false]
  13933. * In touch device, mouseover event will be trigger on touchstart event
  13934. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  13935. * conviniently use hoverStyle when tap on touch screen without additional
  13936. * code for compatibility.
  13937. * But if the chart/component has select feature, which usually also use
  13938. * hoverStyle, there might be conflict between 'select-highlight' and
  13939. * 'hover-highlight' especially when roam is enabled (see geo for example).
  13940. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  13941. * on touch device.
  13942. */
  13943. function setHoverStyle(el, hoverStyle, opt) {
  13944. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  13945. el.type === 'group'
  13946. ? el.traverse(function (child) {
  13947. if (child.type !== 'group') {
  13948. setElementHoverStl(child, hoverStyle);
  13949. }
  13950. })
  13951. : setElementHoverStl(el, hoverStyle);
  13952. // Duplicated function will be auto-ignored, see Eventful.js.
  13953. el.on('mouseover', onElementMouseOver)
  13954. .on('mouseout', onElementMouseOut);
  13955. // Emphasis, normal can be triggered manually
  13956. el.on('emphasis', enterEmphasis)
  13957. .on('normal', leaveEmphasis);
  13958. }
  13959. /**
  13960. * @param {Object|module:zrender/graphic/Style} normalStyle
  13961. * @param {Object} emphasisStyle
  13962. * @param {module:echarts/model/Model} normalModel
  13963. * @param {module:echarts/model/Model} emphasisModel
  13964. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  13965. * @param {string|Function} [opt.defaultText]
  13966. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  13967. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13968. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  13969. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13970. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  13971. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13972. * @param {Object} [normalSpecified]
  13973. * @param {Object} [emphasisSpecified]
  13974. */
  13975. function setLabelStyle(
  13976. normalStyle, emphasisStyle,
  13977. normalModel, emphasisModel,
  13978. opt,
  13979. normalSpecified, emphasisSpecified
  13980. ) {
  13981. opt = opt || EMPTY_OBJ;
  13982. var labelFetcher = opt.labelFetcher;
  13983. var labelDataIndex = opt.labelDataIndex;
  13984. var labelDimIndex = opt.labelDimIndex;
  13985. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  13986. // is not supported util someone requests.
  13987. var showNormal = normalModel.getShallow('show');
  13988. var showEmphasis = emphasisModel.getShallow('show');
  13989. // Consider performance, only fetch label when necessary.
  13990. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  13991. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  13992. var baseText;
  13993. if (showNormal || showEmphasis) {
  13994. if (labelFetcher) {
  13995. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  13996. }
  13997. if (baseText == null) {
  13998. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  13999. }
  14000. }
  14001. var normalStyleText = showNormal ? baseText : null;
  14002. var emphasisStyleText = showEmphasis
  14003. ? retrieve2(
  14004. labelFetcher
  14005. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14006. : null,
  14007. baseText
  14008. )
  14009. : null;
  14010. // Optimize: If style.text is null, text will not be drawn.
  14011. if (normalStyleText != null || emphasisStyleText != null) {
  14012. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14013. // values have to be set on `normalStyle`.
  14014. // If we set default values on `emphasisStyle`, consider case:
  14015. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14016. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14017. // Then the 'red' will not work on emphasis.
  14018. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14019. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14020. }
  14021. normalStyle.text = normalStyleText;
  14022. emphasisStyle.text = emphasisStyleText;
  14023. }
  14024. /**
  14025. * Set basic textStyle properties.
  14026. * @param {Object|module:zrender/graphic/Style} textStyle
  14027. * @param {module:echarts/model/Model} model
  14028. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14029. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14030. * @param {boolean} [isEmphasis]
  14031. */
  14032. function setTextStyle(
  14033. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14034. ) {
  14035. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14036. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14037. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14038. return textStyle;
  14039. }
  14040. /**
  14041. * Set text option in the style.
  14042. * @deprecated
  14043. * @param {Object} textStyle
  14044. * @param {module:echarts/model/Model} labelModel
  14045. * @param {string|boolean} defaultColor Default text color.
  14046. * If set as false, it will be processed as a emphasis style.
  14047. */
  14048. function setText(textStyle, labelModel, defaultColor) {
  14049. var opt = {isRectText: true};
  14050. var isEmphasis;
  14051. if (defaultColor === false) {
  14052. isEmphasis = true;
  14053. }
  14054. else {
  14055. // Support setting color as 'auto' to get visual color.
  14056. opt.autoColor = defaultColor;
  14057. }
  14058. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14059. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14060. }
  14061. /**
  14062. * {
  14063. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14064. * isRectText: boolean,
  14065. * autoColor: string, specify a color when color is 'auto',
  14066. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14067. * If autoColor specified, it is used as default textFill.
  14068. * useInsideStyle:
  14069. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14070. * if `textFill` is not specified.
  14071. * `false`: Do not use inside style.
  14072. * `null/undefined`: use inside style if `isRectText` is true and
  14073. * `textFill` is not specified and textPosition contains `'inside'`.
  14074. * forceRich: boolean
  14075. * }
  14076. */
  14077. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14078. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14079. opt = opt || EMPTY_OBJ;
  14080. if (opt.isRectText) {
  14081. var textPosition = textStyleModel.getShallow('position')
  14082. || (isEmphasis ? null : 'inside');
  14083. // 'outside' is not a valid zr textPostion value, but used
  14084. // in bar series, and magric type should be considered.
  14085. textPosition === 'outside' && (textPosition = 'top');
  14086. textStyle.textPosition = textPosition;
  14087. textStyle.textOffset = textStyleModel.getShallow('offset');
  14088. var labelRotate = textStyleModel.getShallow('rotate');
  14089. labelRotate != null && (labelRotate *= Math.PI / 180);
  14090. textStyle.textRotation = labelRotate;
  14091. textStyle.textDistance = retrieve2(
  14092. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14093. );
  14094. }
  14095. var ecModel = textStyleModel.ecModel;
  14096. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14097. // Consider case:
  14098. // {
  14099. // data: [{
  14100. // value: 12,
  14101. // label: {
  14102. // rich: {
  14103. // // no 'a' here but using parent 'a'.
  14104. // }
  14105. // }
  14106. // }],
  14107. // rich: {
  14108. // a: { ... }
  14109. // }
  14110. // }
  14111. var richItemNames = getRichItemNames(textStyleModel);
  14112. var richResult;
  14113. if (richItemNames) {
  14114. richResult = {};
  14115. for (var name in richItemNames) {
  14116. if (richItemNames.hasOwnProperty(name)) {
  14117. // Cascade is supported in rich.
  14118. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14119. // In rich, never `disableBox`.
  14120. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14121. }
  14122. }
  14123. }
  14124. textStyle.rich = richResult;
  14125. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14126. if (opt.forceRich && !opt.textStyle) {
  14127. opt.textStyle = {};
  14128. }
  14129. return textStyle;
  14130. }
  14131. // Consider case:
  14132. // {
  14133. // data: [{
  14134. // value: 12,
  14135. // label: {
  14136. // rich: {
  14137. // // no 'a' here but using parent 'a'.
  14138. // }
  14139. // }
  14140. // }],
  14141. // rich: {
  14142. // a: { ... }
  14143. // }
  14144. // }
  14145. function getRichItemNames(textStyleModel) {
  14146. // Use object to remove duplicated names.
  14147. var richItemNameMap;
  14148. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14149. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14150. if (rich) {
  14151. richItemNameMap = richItemNameMap || {};
  14152. for (var name in rich) {
  14153. if (rich.hasOwnProperty(name)) {
  14154. richItemNameMap[name] = 1;
  14155. }
  14156. }
  14157. }
  14158. textStyleModel = textStyleModel.parentModel;
  14159. }
  14160. return richItemNameMap;
  14161. }
  14162. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14163. // In merge mode, default value should not be given.
  14164. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14165. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14166. || globalTextStyle.color;
  14167. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14168. || globalTextStyle.textBorderColor;
  14169. textStyle.textStrokeWidth = retrieve2(
  14170. textStyleModel.getShallow('textBorderWidth'),
  14171. globalTextStyle.textBorderWidth
  14172. );
  14173. if (!isEmphasis) {
  14174. if (isBlock) {
  14175. // Always set `insideRollback`, for clearing previous.
  14176. var originalTextPosition = textStyle.textPosition;
  14177. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14178. // Save original textPosition, because style.textPosition will be repalced by
  14179. // real location (like [10, 30]) in zrender.
  14180. textStyle.insideOriginalTextPosition = originalTextPosition;
  14181. textStyle.insideRollbackOpt = opt;
  14182. }
  14183. // Set default finally.
  14184. if (textStyle.textFill == null) {
  14185. textStyle.textFill = opt.autoColor;
  14186. }
  14187. }
  14188. // Do not use `getFont` here, because merge should be supported, where
  14189. // part of these properties may be changed in emphasis style, and the
  14190. // others should remain their original value got from normal style.
  14191. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14192. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14193. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14194. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14195. textStyle.textAlign = textStyleModel.getShallow('align');
  14196. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14197. || textStyleModel.getShallow('baseline');
  14198. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14199. textStyle.textWidth = textStyleModel.getShallow('width');
  14200. textStyle.textHeight = textStyleModel.getShallow('height');
  14201. textStyle.textTag = textStyleModel.getShallow('tag');
  14202. if (!isBlock || !opt.disableBox) {
  14203. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14204. textStyle.textPadding = textStyleModel.getShallow('padding');
  14205. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14206. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14207. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14208. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14209. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14210. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14211. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14212. }
  14213. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14214. || globalTextStyle.textShadowColor;
  14215. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14216. || globalTextStyle.textShadowBlur;
  14217. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14218. || globalTextStyle.textShadowOffsetX;
  14219. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14220. || globalTextStyle.textShadowOffsetY;
  14221. }
  14222. function getAutoColor(color, opt) {
  14223. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14224. }
  14225. function applyInsideStyle(textStyle, textPosition, opt) {
  14226. var useInsideStyle = opt.useInsideStyle;
  14227. var insideRollback;
  14228. if (textStyle.textFill == null
  14229. && useInsideStyle !== false
  14230. && (useInsideStyle === true
  14231. || (opt.isRectText
  14232. && textPosition
  14233. // textPosition can be [10, 30]
  14234. && typeof textPosition === 'string'
  14235. && textPosition.indexOf('inside') >= 0
  14236. )
  14237. )
  14238. ) {
  14239. insideRollback = {
  14240. textFill: null,
  14241. textStroke: textStyle.textStroke,
  14242. textStrokeWidth: textStyle.textStrokeWidth
  14243. };
  14244. textStyle.textFill = '#fff';
  14245. // Consider text with #fff overflow its container.
  14246. if (textStyle.textStroke == null) {
  14247. textStyle.textStroke = opt.autoColor;
  14248. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14249. }
  14250. }
  14251. return insideRollback;
  14252. }
  14253. function rollbackInsideStyle(style) {
  14254. var insideRollback = style.insideRollback;
  14255. if (insideRollback) {
  14256. style.textFill = insideRollback.textFill;
  14257. style.textStroke = insideRollback.textStroke;
  14258. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14259. }
  14260. }
  14261. function getFont(opt, ecModel) {
  14262. // ecModel or default text style model.
  14263. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14264. return trim([
  14265. // FIXME in node-canvas fontWeight is before fontStyle
  14266. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14267. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14268. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14269. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14270. ].join(' '));
  14271. }
  14272. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14273. if (typeof dataIndex === 'function') {
  14274. cb = dataIndex;
  14275. dataIndex = null;
  14276. }
  14277. // Do not check 'animation' property directly here. Consider this case:
  14278. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14279. // but its parent model (`seriesModel`) does.
  14280. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14281. if (animationEnabled) {
  14282. var postfix = isUpdate ? 'Update' : '';
  14283. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14284. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14285. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14286. if (typeof animationDelay === 'function') {
  14287. animationDelay = animationDelay(
  14288. dataIndex,
  14289. animatableModel.getAnimationDelayParams
  14290. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14291. : null
  14292. );
  14293. }
  14294. if (typeof duration === 'function') {
  14295. duration = duration(dataIndex);
  14296. }
  14297. duration > 0
  14298. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14299. : (el.stopAnimation(), el.attr(props), cb && cb());
  14300. }
  14301. else {
  14302. el.stopAnimation();
  14303. el.attr(props);
  14304. cb && cb();
  14305. }
  14306. }
  14307. /**
  14308. * Update graphic element properties with or without animation according to the
  14309. * configuration in series.
  14310. *
  14311. * Caution: this method will stop previous animation.
  14312. * So if do not use this method to one element twice before
  14313. * animation starts, unless you know what you are doing.
  14314. *
  14315. * @param {module:zrender/Element} el
  14316. * @param {Object} props
  14317. * @param {module:echarts/model/Model} [animatableModel]
  14318. * @param {number} [dataIndex]
  14319. * @param {Function} [cb]
  14320. * @example
  14321. * graphic.updateProps(el, {
  14322. * position: [100, 100]
  14323. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14324. * // Or
  14325. * graphic.updateProps(el, {
  14326. * position: [100, 100]
  14327. * }, seriesModel, function () { console.log('Animation done!'); });
  14328. */
  14329. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14330. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14331. }
  14332. /**
  14333. * Init graphic element properties with or without animation according to the
  14334. * configuration in series.
  14335. *
  14336. * Caution: this method will stop previous animation.
  14337. * So if do not use this method to one element twice before
  14338. * animation starts, unless you know what you are doing.
  14339. *
  14340. * @param {module:zrender/Element} el
  14341. * @param {Object} props
  14342. * @param {module:echarts/model/Model} [animatableModel]
  14343. * @param {number} [dataIndex]
  14344. * @param {Function} cb
  14345. */
  14346. function initProps(el, props, animatableModel, dataIndex, cb) {
  14347. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14348. }
  14349. /**
  14350. * Get transform matrix of target (param target),
  14351. * in coordinate of its ancestor (param ancestor)
  14352. *
  14353. * @param {module:zrender/mixin/Transformable} target
  14354. * @param {module:zrender/mixin/Transformable} [ancestor]
  14355. */
  14356. function getTransform(target, ancestor) {
  14357. var mat = identity([]);
  14358. while (target && target !== ancestor) {
  14359. mul$1(mat, target.getLocalTransform(), mat);
  14360. target = target.parent;
  14361. }
  14362. return mat;
  14363. }
  14364. /**
  14365. * Apply transform to an vertex.
  14366. * @param {Array.<number>} target [x, y]
  14367. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14368. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14369. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14370. * @param {boolean=} invert Whether use invert matrix.
  14371. * @return {Array.<number>} [x, y]
  14372. */
  14373. function applyTransform$1(target, transform, invert$$1) {
  14374. if (transform && !isArrayLike(transform)) {
  14375. transform = Transformable.getLocalTransform(transform);
  14376. }
  14377. if (invert$$1) {
  14378. transform = invert([], transform);
  14379. }
  14380. return applyTransform([], target, transform);
  14381. }
  14382. /**
  14383. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14384. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14385. * @param {boolean=} invert Whether use invert matrix.
  14386. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14387. */
  14388. function transformDirection(direction, transform, invert$$1) {
  14389. // Pick a base, ensure that transform result will not be (0, 0).
  14390. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14391. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14392. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14393. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14394. var vertex = [
  14395. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14396. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14397. ];
  14398. vertex = applyTransform$1(vertex, transform, invert$$1);
  14399. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14400. ? (vertex[0] > 0 ? 'right' : 'left')
  14401. : (vertex[1] > 0 ? 'bottom' : 'top');
  14402. }
  14403. /**
  14404. * Apply group transition animation from g1 to g2.
  14405. * If no animatableModel, no animation.
  14406. */
  14407. function groupTransition(g1, g2, animatableModel, cb) {
  14408. if (!g1 || !g2) {
  14409. return;
  14410. }
  14411. function getElMap(g) {
  14412. var elMap = {};
  14413. g.traverse(function (el) {
  14414. if (!el.isGroup && el.anid) {
  14415. elMap[el.anid] = el;
  14416. }
  14417. });
  14418. return elMap;
  14419. }
  14420. function getAnimatableProps(el) {
  14421. var obj = {
  14422. position: clone$1(el.position),
  14423. rotation: el.rotation
  14424. };
  14425. if (el.shape) {
  14426. obj.shape = extend({}, el.shape);
  14427. }
  14428. return obj;
  14429. }
  14430. var elMap1 = getElMap(g1);
  14431. g2.traverse(function (el) {
  14432. if (!el.isGroup && el.anid) {
  14433. var oldEl = elMap1[el.anid];
  14434. if (oldEl) {
  14435. var newProp = getAnimatableProps(el);
  14436. el.attr(getAnimatableProps(oldEl));
  14437. updateProps(el, newProp, animatableModel, el.dataIndex);
  14438. }
  14439. // else {
  14440. // if (el.previousProps) {
  14441. // graphic.updateProps
  14442. // }
  14443. // }
  14444. }
  14445. });
  14446. }
  14447. /**
  14448. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14449. * @param {Object} rect {x, y, width, height}
  14450. * @return {Array.<Array.<number>>} A new clipped points.
  14451. */
  14452. function clipPointsByRect(points, rect) {
  14453. return map(points, function (point) {
  14454. var x = point[0];
  14455. x = mathMax$1(x, rect.x);
  14456. x = mathMin$1(x, rect.x + rect.width);
  14457. var y = point[1];
  14458. y = mathMax$1(y, rect.y);
  14459. y = mathMin$1(y, rect.y + rect.height);
  14460. return [x, y];
  14461. });
  14462. }
  14463. /**
  14464. * @param {Object} targetRect {x, y, width, height}
  14465. * @param {Object} rect {x, y, width, height}
  14466. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14467. */
  14468. function clipRectByRect(targetRect, rect) {
  14469. var x = mathMax$1(targetRect.x, rect.x);
  14470. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14471. var y = mathMax$1(targetRect.y, rect.y);
  14472. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14473. if (x2 >= x && y2 >= y) {
  14474. return {
  14475. x: x,
  14476. y: y,
  14477. width: x2 - x,
  14478. height: y2 - y
  14479. };
  14480. }
  14481. }
  14482. /**
  14483. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14484. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14485. * @param {Object} [rect] {x, y, width, height}
  14486. * @return {module:zrender/Element} Icon path or image element.
  14487. */
  14488. function createIcon(iconStr, opt, rect) {
  14489. opt = extend({rectHover: true}, opt);
  14490. var style = opt.style = {strokeNoScale: true};
  14491. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14492. if (iconStr) {
  14493. return iconStr.indexOf('image://') === 0
  14494. ? (
  14495. style.image = iconStr.slice(8),
  14496. defaults(style, rect),
  14497. new ZImage(opt)
  14498. )
  14499. : (
  14500. makePath(
  14501. iconStr.replace('path://', ''),
  14502. opt,
  14503. rect,
  14504. 'center'
  14505. )
  14506. );
  14507. }
  14508. }
  14509. var graphic = (Object.freeze || Object)({
  14510. extendShape: extendShape,
  14511. extendPath: extendPath,
  14512. makePath: makePath,
  14513. makeImage: makeImage,
  14514. mergePath: mergePath,
  14515. resizePath: resizePath,
  14516. subPixelOptimizeLine: subPixelOptimizeLine,
  14517. subPixelOptimizeRect: subPixelOptimizeRect,
  14518. subPixelOptimize: subPixelOptimize,
  14519. setHoverStyle: setHoverStyle,
  14520. setLabelStyle: setLabelStyle,
  14521. setTextStyle: setTextStyle,
  14522. setText: setText,
  14523. getFont: getFont,
  14524. updateProps: updateProps,
  14525. initProps: initProps,
  14526. getTransform: getTransform,
  14527. applyTransform: applyTransform$1,
  14528. transformDirection: transformDirection,
  14529. groupTransition: groupTransition,
  14530. clipPointsByRect: clipPointsByRect,
  14531. clipRectByRect: clipRectByRect,
  14532. createIcon: createIcon,
  14533. Group: Group,
  14534. Image: ZImage,
  14535. Text: Text,
  14536. Circle: Circle,
  14537. Sector: Sector,
  14538. Ring: Ring,
  14539. Polygon: Polygon,
  14540. Polyline: Polyline,
  14541. Rect: Rect,
  14542. Line: Line,
  14543. BezierCurve: BezierCurve,
  14544. Arc: Arc,
  14545. IncrementalDisplayable: IncrementalDisplayble,
  14546. CompoundPath: CompoundPath,
  14547. LinearGradient: LinearGradient,
  14548. RadialGradient: RadialGradient,
  14549. BoundingRect: BoundingRect
  14550. });
  14551. var PATH_COLOR = ['textStyle', 'color'];
  14552. var textStyleMixin = {
  14553. /**
  14554. * Get color property or get color from option.textStyle.color
  14555. * @param {boolean} [isEmphasis]
  14556. * @return {string}
  14557. */
  14558. getTextColor: function (isEmphasis) {
  14559. var ecModel = this.ecModel;
  14560. return this.getShallow('color')
  14561. || (
  14562. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14563. );
  14564. },
  14565. /**
  14566. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14567. * @return {string}
  14568. */
  14569. getFont: function () {
  14570. return getFont({
  14571. fontStyle: this.getShallow('fontStyle'),
  14572. fontWeight: this.getShallow('fontWeight'),
  14573. fontSize: this.getShallow('fontSize'),
  14574. fontFamily: this.getShallow('fontFamily')
  14575. }, this.ecModel);
  14576. },
  14577. getTextRect: function (text) {
  14578. return getBoundingRect(
  14579. text,
  14580. this.getFont(),
  14581. this.getShallow('align'),
  14582. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14583. this.getShallow('padding'),
  14584. this.getShallow('rich'),
  14585. this.getShallow('truncateText')
  14586. );
  14587. }
  14588. };
  14589. var getItemStyle = makeStyleMapper(
  14590. [
  14591. ['fill', 'color'],
  14592. ['stroke', 'borderColor'],
  14593. ['lineWidth', 'borderWidth'],
  14594. ['opacity'],
  14595. ['shadowBlur'],
  14596. ['shadowOffsetX'],
  14597. ['shadowOffsetY'],
  14598. ['shadowColor'],
  14599. ['textPosition'],
  14600. ['textAlign']
  14601. ]
  14602. );
  14603. var itemStyleMixin = {
  14604. getItemStyle: function (excludes, includes) {
  14605. var style = getItemStyle(this, excludes, includes);
  14606. var lineDash = this.getBorderLineDash();
  14607. lineDash && (style.lineDash = lineDash);
  14608. return style;
  14609. },
  14610. getBorderLineDash: function () {
  14611. var lineType = this.get('borderType');
  14612. return (lineType === 'solid' || lineType == null) ? null
  14613. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14614. }
  14615. };
  14616. /**
  14617. * @module echarts/model/Model
  14618. */
  14619. var mixin$1 = mixin;
  14620. var inner = makeInner();
  14621. /**
  14622. * @alias module:echarts/model/Model
  14623. * @constructor
  14624. * @param {Object} option
  14625. * @param {module:echarts/model/Model} [parentModel]
  14626. * @param {module:echarts/model/Global} [ecModel]
  14627. */
  14628. function Model(option, parentModel, ecModel) {
  14629. /**
  14630. * @type {module:echarts/model/Model}
  14631. * @readOnly
  14632. */
  14633. this.parentModel = parentModel;
  14634. /**
  14635. * @type {module:echarts/model/Global}
  14636. * @readOnly
  14637. */
  14638. this.ecModel = ecModel;
  14639. /**
  14640. * @type {Object}
  14641. * @protected
  14642. */
  14643. this.option = option;
  14644. // Simple optimization
  14645. // if (this.init) {
  14646. // if (arguments.length <= 4) {
  14647. // this.init(option, parentModel, ecModel, extraOpt);
  14648. // }
  14649. // else {
  14650. // this.init.apply(this, arguments);
  14651. // }
  14652. // }
  14653. }
  14654. Model.prototype = {
  14655. constructor: Model,
  14656. /**
  14657. * Model 的初始化函数
  14658. * @param {Object} option
  14659. */
  14660. init: null,
  14661. /**
  14662. * 从新的 Option merge
  14663. */
  14664. mergeOption: function (option) {
  14665. merge(this.option, option, true);
  14666. },
  14667. /**
  14668. * @param {string|Array.<string>} path
  14669. * @param {boolean} [ignoreParent=false]
  14670. * @return {*}
  14671. */
  14672. get: function (path, ignoreParent) {
  14673. if (path == null) {
  14674. return this.option;
  14675. }
  14676. return doGet(
  14677. this.option,
  14678. this.parsePath(path),
  14679. !ignoreParent && getParent(this, path)
  14680. );
  14681. },
  14682. /**
  14683. * @param {string} key
  14684. * @param {boolean} [ignoreParent=false]
  14685. * @return {*}
  14686. */
  14687. getShallow: function (key, ignoreParent) {
  14688. var option = this.option;
  14689. var val = option == null ? option : option[key];
  14690. var parentModel = !ignoreParent && getParent(this, key);
  14691. if (val == null && parentModel) {
  14692. val = parentModel.getShallow(key);
  14693. }
  14694. return val;
  14695. },
  14696. /**
  14697. * @param {string|Array.<string>} [path]
  14698. * @param {module:echarts/model/Model} [parentModel]
  14699. * @return {module:echarts/model/Model}
  14700. */
  14701. getModel: function (path, parentModel) {
  14702. var obj = path == null
  14703. ? this.option
  14704. : doGet(this.option, path = this.parsePath(path));
  14705. var thisParentModel;
  14706. parentModel = parentModel || (
  14707. (thisParentModel = getParent(this, path))
  14708. && thisParentModel.getModel(path)
  14709. );
  14710. return new Model(obj, parentModel, this.ecModel);
  14711. },
  14712. /**
  14713. * If model has option
  14714. */
  14715. isEmpty: function () {
  14716. return this.option == null;
  14717. },
  14718. restoreData: function () {},
  14719. // Pending
  14720. clone: function () {
  14721. var Ctor = this.constructor;
  14722. return new Ctor(clone(this.option));
  14723. },
  14724. setReadOnly: function (properties) {
  14725. // clazzUtil.setReadOnly(this, properties);
  14726. },
  14727. // If path is null/undefined, return null/undefined.
  14728. parsePath: function(path) {
  14729. if (typeof path === 'string') {
  14730. path = path.split('.');
  14731. }
  14732. return path;
  14733. },
  14734. /**
  14735. * @param {Function} getParentMethod
  14736. * param {Array.<string>|string} path
  14737. * return {module:echarts/model/Model}
  14738. */
  14739. customizeGetParent: function (getParentMethod) {
  14740. inner(this).getParent = getParentMethod;
  14741. },
  14742. isAnimationEnabled: function () {
  14743. if (!env$1.node) {
  14744. if (this.option.animation != null) {
  14745. return !!this.option.animation;
  14746. }
  14747. else if (this.parentModel) {
  14748. return this.parentModel.isAnimationEnabled();
  14749. }
  14750. }
  14751. }
  14752. };
  14753. function doGet(obj, pathArr, parentModel) {
  14754. for (var i = 0; i < pathArr.length; i++) {
  14755. // Ignore empty
  14756. if (!pathArr[i]) {
  14757. continue;
  14758. }
  14759. // obj could be number/string/... (like 0)
  14760. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14761. if (obj == null) {
  14762. break;
  14763. }
  14764. }
  14765. if (obj == null && parentModel) {
  14766. obj = parentModel.get(pathArr);
  14767. }
  14768. return obj;
  14769. }
  14770. // `path` can be null/undefined
  14771. function getParent(model, path) {
  14772. var getParentMethod = inner(model).getParent;
  14773. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14774. }
  14775. // Enable Model.extend.
  14776. enableClassExtend(Model);
  14777. enableClassCheck(Model);
  14778. mixin$1(Model, lineStyleMixin);
  14779. mixin$1(Model, areaStyleMixin);
  14780. mixin$1(Model, textStyleMixin);
  14781. mixin$1(Model, itemStyleMixin);
  14782. var base = 0;
  14783. /**
  14784. * @public
  14785. * @param {string} type
  14786. * @return {string}
  14787. */
  14788. function getUID(type) {
  14789. // Considering the case of crossing js context,
  14790. // use Math.random to make id as unique as possible.
  14791. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14792. }
  14793. /**
  14794. * @inner
  14795. */
  14796. function enableSubTypeDefaulter(entity) {
  14797. var subTypeDefaulters = {};
  14798. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14799. componentType = parseClassType$1(componentType);
  14800. subTypeDefaulters[componentType.main] = defaulter;
  14801. };
  14802. entity.determineSubType = function (componentType, option) {
  14803. var type = option.type;
  14804. if (!type) {
  14805. var componentTypeMain = parseClassType$1(componentType).main;
  14806. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14807. type = subTypeDefaulters[componentTypeMain](option);
  14808. }
  14809. }
  14810. return type;
  14811. };
  14812. return entity;
  14813. }
  14814. /**
  14815. * Topological travel on Activity Network (Activity On Vertices).
  14816. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14817. *
  14818. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14819. *
  14820. * If there is circle dependencey, Error will be thrown.
  14821. *
  14822. */
  14823. function enableTopologicalTravel(entity, dependencyGetter) {
  14824. /**
  14825. * @public
  14826. * @param {Array.<string>} targetNameList Target Component type list.
  14827. * Can be ['aa', 'bb', 'aa.xx']
  14828. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14829. * @param {Function} callback Params: componentType, dependencies.
  14830. * @param {Object} context Scope of callback.
  14831. */
  14832. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14833. if (!targetNameList.length) {
  14834. return;
  14835. }
  14836. var result = makeDepndencyGraph(fullNameList);
  14837. var graph = result.graph;
  14838. var stack = result.noEntryList;
  14839. var targetNameSet = {};
  14840. each$1(targetNameList, function (name) {
  14841. targetNameSet[name] = true;
  14842. });
  14843. while (stack.length) {
  14844. var currComponentType = stack.pop();
  14845. var currVertex = graph[currComponentType];
  14846. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14847. if (isInTargetNameSet) {
  14848. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14849. delete targetNameSet[currComponentType];
  14850. }
  14851. each$1(
  14852. currVertex.successor,
  14853. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14854. );
  14855. }
  14856. each$1(targetNameSet, function () {
  14857. throw new Error('Circle dependency may exists');
  14858. });
  14859. function removeEdge(succComponentType) {
  14860. graph[succComponentType].entryCount--;
  14861. if (graph[succComponentType].entryCount === 0) {
  14862. stack.push(succComponentType);
  14863. }
  14864. }
  14865. // Consider this case: legend depends on series, and we call
  14866. // chart.setOption({series: [...]}), where only series is in option.
  14867. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14868. // not be called, but only sereis.mergeOption is called. Thus legend
  14869. // have no chance to update its local record about series (like which
  14870. // name of series is available in legend).
  14871. function removeEdgeAndAdd(succComponentType) {
  14872. targetNameSet[succComponentType] = true;
  14873. removeEdge(succComponentType);
  14874. }
  14875. };
  14876. /**
  14877. * DepndencyGraph: {Object}
  14878. * key: conponentType,
  14879. * value: {
  14880. * successor: [conponentTypes...],
  14881. * originalDeps: [conponentTypes...],
  14882. * entryCount: {number}
  14883. * }
  14884. */
  14885. function makeDepndencyGraph(fullNameList) {
  14886. var graph = {};
  14887. var noEntryList = [];
  14888. each$1(fullNameList, function (name) {
  14889. var thisItem = createDependencyGraphItem(graph, name);
  14890. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14891. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14892. thisItem.entryCount = availableDeps.length;
  14893. if (thisItem.entryCount === 0) {
  14894. noEntryList.push(name);
  14895. }
  14896. each$1(availableDeps, function (dependentName) {
  14897. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14898. thisItem.predecessor.push(dependentName);
  14899. }
  14900. var thatItem = createDependencyGraphItem(graph, dependentName);
  14901. if (indexOf(thatItem.successor, dependentName) < 0) {
  14902. thatItem.successor.push(name);
  14903. }
  14904. });
  14905. });
  14906. return {graph: graph, noEntryList: noEntryList};
  14907. }
  14908. function createDependencyGraphItem(graph, name) {
  14909. if (!graph[name]) {
  14910. graph[name] = {predecessor: [], successor: []};
  14911. }
  14912. return graph[name];
  14913. }
  14914. function getAvailableDependencies(originalDeps, fullNameList) {
  14915. var availableDeps = [];
  14916. each$1(originalDeps, function (dep) {
  14917. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14918. });
  14919. return availableDeps;
  14920. }
  14921. }
  14922. var RADIAN_EPSILON = 1e-4;
  14923. function _trim(str) {
  14924. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  14925. }
  14926. /**
  14927. * Linear mapping a value from domain to range
  14928. * @memberOf module:echarts/util/number
  14929. * @param {(number|Array.<number>)} val
  14930. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  14931. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  14932. * @param {boolean} clamp
  14933. * @return {(number|Array.<number>}
  14934. */
  14935. function linearMap(val, domain, range, clamp) {
  14936. var subDomain = domain[1] - domain[0];
  14937. var subRange = range[1] - range[0];
  14938. if (subDomain === 0) {
  14939. return subRange === 0
  14940. ? range[0]
  14941. : (range[0] + range[1]) / 2;
  14942. }
  14943. // Avoid accuracy problem in edge, such as
  14944. // 146.39 - 62.83 === 83.55999999999999.
  14945. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  14946. // It is a little verbose for efficiency considering this method
  14947. // is a hotspot.
  14948. if (clamp) {
  14949. if (subDomain > 0) {
  14950. if (val <= domain[0]) {
  14951. return range[0];
  14952. }
  14953. else if (val >= domain[1]) {
  14954. return range[1];
  14955. }
  14956. }
  14957. else {
  14958. if (val >= domain[0]) {
  14959. return range[0];
  14960. }
  14961. else if (val <= domain[1]) {
  14962. return range[1];
  14963. }
  14964. }
  14965. }
  14966. else {
  14967. if (val === domain[0]) {
  14968. return range[0];
  14969. }
  14970. if (val === domain[1]) {
  14971. return range[1];
  14972. }
  14973. }
  14974. return (val - domain[0]) / subDomain * subRange + range[0];
  14975. }
  14976. /**
  14977. * Convert a percent string to absolute number.
  14978. * Returns NaN if percent is not a valid string or number
  14979. * @memberOf module:echarts/util/number
  14980. * @param {string|number} percent
  14981. * @param {number} all
  14982. * @return {number}
  14983. */
  14984. function parsePercent$1(percent, all) {
  14985. switch (percent) {
  14986. case 'center':
  14987. case 'middle':
  14988. percent = '50%';
  14989. break;
  14990. case 'left':
  14991. case 'top':
  14992. percent = '0%';
  14993. break;
  14994. case 'right':
  14995. case 'bottom':
  14996. percent = '100%';
  14997. break;
  14998. }
  14999. if (typeof percent === 'string') {
  15000. if (_trim(percent).match(/%$/)) {
  15001. return parseFloat(percent) / 100 * all;
  15002. }
  15003. return parseFloat(percent);
  15004. }
  15005. return percent == null ? NaN : +percent;
  15006. }
  15007. /**
  15008. * (1) Fix rounding error of float numbers.
  15009. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15010. *
  15011. * @param {number} x
  15012. * @param {number} [precision]
  15013. * @param {boolean} [returnStr]
  15014. * @return {number|string}
  15015. */
  15016. function round$1(x, precision, returnStr) {
  15017. if (precision == null) {
  15018. precision = 10;
  15019. }
  15020. // Avoid range error
  15021. precision = Math.min(Math.max(0, precision), 20);
  15022. x = (+x).toFixed(precision);
  15023. return returnStr ? x : +x;
  15024. }
  15025. function asc(arr) {
  15026. arr.sort(function (a, b) {
  15027. return a - b;
  15028. });
  15029. return arr;
  15030. }
  15031. /**
  15032. * Get precision
  15033. * @param {number} val
  15034. */
  15035. function getPrecision(val) {
  15036. val = +val;
  15037. if (isNaN(val)) {
  15038. return 0;
  15039. }
  15040. // It is much faster than methods converting number to string as follows
  15041. // var tmp = val.toString();
  15042. // return tmp.length - 1 - tmp.indexOf('.');
  15043. // especially when precision is low
  15044. var e = 1;
  15045. var count = 0;
  15046. while (Math.round(val * e) / e !== val) {
  15047. e *= 10;
  15048. count++;
  15049. }
  15050. return count;
  15051. }
  15052. /**
  15053. * @param {string|number} val
  15054. * @return {number}
  15055. */
  15056. function getPrecisionSafe(val) {
  15057. var str = val.toString();
  15058. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15059. var eIndex = str.indexOf('e');
  15060. if (eIndex > 0) {
  15061. var precision = +str.slice(eIndex + 1);
  15062. return precision < 0 ? -precision : 0;
  15063. }
  15064. else {
  15065. var dotIndex = str.indexOf('.');
  15066. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15067. }
  15068. }
  15069. /**
  15070. * Minimal dicernible data precisioin according to a single pixel.
  15071. *
  15072. * @param {Array.<number>} dataExtent
  15073. * @param {Array.<number>} pixelExtent
  15074. * @return {number} precision
  15075. */
  15076. function getPixelPrecision(dataExtent, pixelExtent) {
  15077. var log = Math.log;
  15078. var LN10 = Math.LN10;
  15079. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15080. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15081. // toFixed() digits argument must be between 0 and 20.
  15082. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15083. return !isFinite(precision) ? 20 : precision;
  15084. }
  15085. /**
  15086. * Get a data of given precision, assuring the sum of percentages
  15087. * in valueList is 1.
  15088. * The largest remainer method is used.
  15089. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15090. *
  15091. * @param {Array.<number>} valueList a list of all data
  15092. * @param {number} idx index of the data to be processed in valueList
  15093. * @param {number} precision integer number showing digits of precision
  15094. * @return {number} percent ranging from 0 to 100
  15095. */
  15096. function getPercentWithPrecision(valueList, idx, precision) {
  15097. if (!valueList[idx]) {
  15098. return 0;
  15099. }
  15100. var sum = reduce(valueList, function (acc, val) {
  15101. return acc + (isNaN(val) ? 0 : val);
  15102. }, 0);
  15103. if (sum === 0) {
  15104. return 0;
  15105. }
  15106. var digits = Math.pow(10, precision);
  15107. var votesPerQuota = map(valueList, function (val) {
  15108. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15109. });
  15110. var targetSeats = digits * 100;
  15111. var seats = map(votesPerQuota, function (votes) {
  15112. // Assign automatic seats.
  15113. return Math.floor(votes);
  15114. });
  15115. var currentSum = reduce(seats, function (acc, val) {
  15116. return acc + val;
  15117. }, 0);
  15118. var remainder = map(votesPerQuota, function (votes, idx) {
  15119. return votes - seats[idx];
  15120. });
  15121. // Has remainding votes.
  15122. while (currentSum < targetSeats) {
  15123. // Find next largest remainder.
  15124. var max = Number.NEGATIVE_INFINITY;
  15125. var maxId = null;
  15126. for (var i = 0, len = remainder.length; i < len; ++i) {
  15127. if (remainder[i] > max) {
  15128. max = remainder[i];
  15129. maxId = i;
  15130. }
  15131. }
  15132. // Add a vote to max remainder.
  15133. ++seats[maxId];
  15134. remainder[maxId] = 0;
  15135. ++currentSum;
  15136. }
  15137. return seats[idx] / digits;
  15138. }
  15139. // Number.MAX_SAFE_INTEGER, ie do not support.
  15140. var MAX_SAFE_INTEGER = 9007199254740991;
  15141. /**
  15142. * To 0 - 2 * PI, considering negative radian.
  15143. * @param {number} radian
  15144. * @return {number}
  15145. */
  15146. function remRadian(radian) {
  15147. var pi2 = Math.PI * 2;
  15148. return (radian % pi2 + pi2) % pi2;
  15149. }
  15150. /**
  15151. * @param {type} radian
  15152. * @return {boolean}
  15153. */
  15154. function isRadianAroundZero(val) {
  15155. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15156. }
  15157. 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
  15158. /**
  15159. * @param {string|Date|number} value These values can be accepted:
  15160. * + An instance of Date, represent a time in its own time zone.
  15161. * + Or string in a subset of ISO 8601, only including:
  15162. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15163. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15164. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15165. * all of which will be treated as local time if time zone is not specified
  15166. * (see <https://momentjs.com/>).
  15167. * + Or other string format, including (all of which will be treated as loacal time):
  15168. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15169. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15170. * + a timestamp, which represent a time in UTC.
  15171. * @return {Date} date
  15172. */
  15173. function parseDate(value) {
  15174. if (value instanceof Date) {
  15175. return value;
  15176. }
  15177. else if (typeof value === 'string') {
  15178. // Different browsers parse date in different way, so we parse it manually.
  15179. // Some other issues:
  15180. // new Date('1970-01-01') is UTC,
  15181. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15182. // See issue #3623
  15183. var match = TIME_REG.exec(value);
  15184. if (!match) {
  15185. // return Invalid Date.
  15186. return new Date(NaN);
  15187. }
  15188. // Use local time when no timezone offset specifed.
  15189. if (!match[8]) {
  15190. // match[n] can only be string or undefined.
  15191. // But take care of '12' + 1 => '121'.
  15192. return new Date(
  15193. +match[1],
  15194. +(match[2] || 1) - 1,
  15195. +match[3] || 1,
  15196. +match[4] || 0,
  15197. +(match[5] || 0),
  15198. +match[6] || 0,
  15199. +match[7] || 0
  15200. );
  15201. }
  15202. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15203. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15204. // For example, system timezone is set as "Time Zone: America/Toronto",
  15205. // then these code will get different result:
  15206. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15207. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15208. // So we should not use `new Date`, but use `Date.UTC`.
  15209. else {
  15210. var hour = +match[4] || 0;
  15211. if (match[8].toUpperCase() !== 'Z') {
  15212. hour -= match[8].slice(0, 3);
  15213. }
  15214. return new Date(Date.UTC(
  15215. +match[1],
  15216. +(match[2] || 1) - 1,
  15217. +match[3] || 1,
  15218. hour,
  15219. +(match[5] || 0),
  15220. +match[6] || 0,
  15221. +match[7] || 0
  15222. ));
  15223. }
  15224. }
  15225. else if (value == null) {
  15226. return new Date(NaN);
  15227. }
  15228. return new Date(Math.round(value));
  15229. }
  15230. /**
  15231. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15232. *
  15233. * @param {number} val
  15234. * @return {number}
  15235. */
  15236. function quantity(val) {
  15237. return Math.pow(10, quantityExponent(val));
  15238. }
  15239. function quantityExponent(val) {
  15240. return Math.floor(Math.log(val) / Math.LN10);
  15241. }
  15242. /**
  15243. * find a “nice” number approximately equal to x. Round the number if round = true,
  15244. * take ceiling if round = false. The primary observation is that the “nicest”
  15245. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15246. *
  15247. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15248. *
  15249. * @param {number} val Non-negative value.
  15250. * @param {boolean} round
  15251. * @return {number}
  15252. */
  15253. function nice(val, round) {
  15254. var exponent = quantityExponent(val);
  15255. var exp10 = Math.pow(10, exponent);
  15256. var f = val / exp10; // 1 <= f < 10
  15257. var nf;
  15258. if (round) {
  15259. if (f < 1.5) { nf = 1; }
  15260. else if (f < 2.5) { nf = 2; }
  15261. else if (f < 4) { nf = 3; }
  15262. else if (f < 7) { nf = 5; }
  15263. else { nf = 10; }
  15264. }
  15265. else {
  15266. if (f < 1) { nf = 1; }
  15267. else if (f < 2) { nf = 2; }
  15268. else if (f < 3) { nf = 3; }
  15269. else if (f < 5) { nf = 5; }
  15270. else { nf = 10; }
  15271. }
  15272. val = nf * exp10;
  15273. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15274. // 20 is the uppper bound of toFixed.
  15275. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15276. }
  15277. /**
  15278. * Order intervals asc, and split them when overlap.
  15279. * expect(numberUtil.reformIntervals([
  15280. * {interval: [18, 62], close: [1, 1]},
  15281. * {interval: [-Infinity, -70], close: [0, 0]},
  15282. * {interval: [-70, -26], close: [1, 1]},
  15283. * {interval: [-26, 18], close: [1, 1]},
  15284. * {interval: [62, 150], close: [1, 1]},
  15285. * {interval: [106, 150], close: [1, 1]},
  15286. * {interval: [150, Infinity], close: [0, 0]}
  15287. * ])).toEqual([
  15288. * {interval: [-Infinity, -70], close: [0, 0]},
  15289. * {interval: [-70, -26], close: [1, 1]},
  15290. * {interval: [-26, 18], close: [0, 1]},
  15291. * {interval: [18, 62], close: [0, 1]},
  15292. * {interval: [62, 150], close: [0, 1]},
  15293. * {interval: [150, Infinity], close: [0, 0]}
  15294. * ]);
  15295. * @param {Array.<Object>} list, where `close` mean open or close
  15296. * of the interval, and Infinity can be used.
  15297. * @return {Array.<Object>} The origin list, which has been reformed.
  15298. */
  15299. function reformIntervals(list) {
  15300. list.sort(function (a, b) {
  15301. return littleThan(a, b, 0) ? -1 : 1;
  15302. });
  15303. var curr = -Infinity;
  15304. var currClose = 1;
  15305. for (var i = 0; i < list.length;) {
  15306. var interval = list[i].interval;
  15307. var close = list[i].close;
  15308. for (var lg = 0; lg < 2; lg++) {
  15309. if (interval[lg] <= curr) {
  15310. interval[lg] = curr;
  15311. close[lg] = !lg ? 1 - currClose : 1;
  15312. }
  15313. curr = interval[lg];
  15314. currClose = close[lg];
  15315. }
  15316. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15317. list.splice(i, 1);
  15318. }
  15319. else {
  15320. i++;
  15321. }
  15322. }
  15323. return list;
  15324. function littleThan(a, b, lg) {
  15325. return a.interval[lg] < b.interval[lg]
  15326. || (
  15327. a.interval[lg] === b.interval[lg]
  15328. && (
  15329. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15330. || (!lg && littleThan(a, b, 1))
  15331. )
  15332. );
  15333. }
  15334. }
  15335. /**
  15336. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15337. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15338. * subtraction forces infinities to NaN
  15339. *
  15340. * @param {*} v
  15341. * @return {boolean}
  15342. */
  15343. function isNumeric(v) {
  15344. return v - parseFloat(v) >= 0;
  15345. }
  15346. var number = (Object.freeze || Object)({
  15347. linearMap: linearMap,
  15348. parsePercent: parsePercent$1,
  15349. round: round$1,
  15350. asc: asc,
  15351. getPrecision: getPrecision,
  15352. getPrecisionSafe: getPrecisionSafe,
  15353. getPixelPrecision: getPixelPrecision,
  15354. getPercentWithPrecision: getPercentWithPrecision,
  15355. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15356. remRadian: remRadian,
  15357. isRadianAroundZero: isRadianAroundZero,
  15358. parseDate: parseDate,
  15359. quantity: quantity,
  15360. nice: nice,
  15361. reformIntervals: reformIntervals,
  15362. isNumeric: isNumeric
  15363. });
  15364. /**
  15365. * 每三位默认加,格式化
  15366. * @param {string|number} x
  15367. * @return {string}
  15368. */
  15369. function addCommas(x) {
  15370. if (isNaN(x)) {
  15371. return '-';
  15372. }
  15373. x = (x + '').split('.');
  15374. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15375. + (x.length > 1 ? ('.' + x[1]) : '');
  15376. }
  15377. /**
  15378. * @param {string} str
  15379. * @param {boolean} [upperCaseFirst=false]
  15380. * @return {string} str
  15381. */
  15382. function toCamelCase(str, upperCaseFirst) {
  15383. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15384. return group1.toUpperCase();
  15385. });
  15386. if (upperCaseFirst && str) {
  15387. str = str.charAt(0).toUpperCase() + str.slice(1);
  15388. }
  15389. return str;
  15390. }
  15391. var normalizeCssArray$1 = normalizeCssArray;
  15392. function encodeHTML(source) {
  15393. return String(source)
  15394. .replace(/&/g, '&amp;')
  15395. .replace(/</g, '&lt;')
  15396. .replace(/>/g, '&gt;')
  15397. .replace(/"/g, '&quot;')
  15398. .replace(/'/g, '&#39;');
  15399. }
  15400. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15401. var wrapVar = function (varName, seriesIdx) {
  15402. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15403. };
  15404. /**
  15405. * Template formatter
  15406. * @param {string} tpl
  15407. * @param {Array.<Object>|Object} paramsList
  15408. * @param {boolean} [encode=false]
  15409. * @return {string}
  15410. */
  15411. function formatTpl(tpl, paramsList, encode) {
  15412. if (!isArray(paramsList)) {
  15413. paramsList = [paramsList];
  15414. }
  15415. var seriesLen = paramsList.length;
  15416. if (!seriesLen) {
  15417. return '';
  15418. }
  15419. var $vars = paramsList[0].$vars || [];
  15420. for (var i = 0; i < $vars.length; i++) {
  15421. var alias = TPL_VAR_ALIAS[i];
  15422. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15423. }
  15424. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15425. for (var k = 0; k < $vars.length; k++) {
  15426. var val = paramsList[seriesIdx][$vars[k]];
  15427. tpl = tpl.replace(
  15428. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15429. encode ? encodeHTML(val) : val
  15430. );
  15431. }
  15432. }
  15433. return tpl;
  15434. }
  15435. /**
  15436. * simple Template formatter
  15437. *
  15438. * @param {string} tpl
  15439. * @param {Object} param
  15440. * @param {boolean} [encode=false]
  15441. * @return {string}
  15442. */
  15443. function formatTplSimple(tpl, param, encode) {
  15444. each$1(param, function (value, key) {
  15445. tpl = tpl.replace(
  15446. '{' + key + '}',
  15447. encode ? encodeHTML(value) : value
  15448. );
  15449. });
  15450. return tpl;
  15451. }
  15452. /**
  15453. * @param {Object|string} [opt] If string, means color.
  15454. * @param {string} [opt.color]
  15455. * @param {string} [opt.extraCssText]
  15456. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15457. * @return {string}
  15458. */
  15459. function getTooltipMarker(opt, extraCssText) {
  15460. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15461. var color = opt.color;
  15462. var type = opt.type;
  15463. var extraCssText = opt.extraCssText;
  15464. if (!color) {
  15465. return '';
  15466. }
  15467. return type === 'subItem'
  15468. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15469. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15470. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15471. : '<span style="display:inline-block;margin-right:5px;'
  15472. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15473. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15474. }
  15475. /**
  15476. * @param {string} str
  15477. * @return {string}
  15478. * @inner
  15479. */
  15480. var s2d = function (str) {
  15481. return str < 10 ? ('0' + str) : str;
  15482. };
  15483. /**
  15484. * ISO Date format
  15485. * @param {string} tpl
  15486. * @param {number} value
  15487. * @param {boolean} [isUTC=false] Default in local time.
  15488. * see `module:echarts/scale/Time`
  15489. * and `module:echarts/util/number#parseDate`.
  15490. * @inner
  15491. */
  15492. function formatTime(tpl, value, isUTC) {
  15493. if (tpl === 'week'
  15494. || tpl === 'month'
  15495. || tpl === 'quarter'
  15496. || tpl === 'half-year'
  15497. || tpl === 'year'
  15498. ) {
  15499. tpl = 'MM-dd\nyyyy';
  15500. }
  15501. var date = parseDate(value);
  15502. var utc = isUTC ? 'UTC' : '';
  15503. var y = date['get' + utc + 'FullYear']();
  15504. var M = date['get' + utc + 'Month']() + 1;
  15505. var d = date['get' + utc + 'Date']();
  15506. var h = date['get' + utc + 'Hours']();
  15507. var m = date['get' + utc + 'Minutes']();
  15508. var s = date['get' + utc + 'Seconds']();
  15509. tpl = tpl.replace('MM', s2d(M))
  15510. .replace('M', M)
  15511. .replace('yyyy', y)
  15512. .replace('yy', y % 100)
  15513. .replace('dd', s2d(d))
  15514. .replace('d', d)
  15515. .replace('hh', s2d(h))
  15516. .replace('h', h)
  15517. .replace('mm', s2d(m))
  15518. .replace('m', m)
  15519. .replace('ss', s2d(s))
  15520. .replace('s', s);
  15521. return tpl;
  15522. }
  15523. /**
  15524. * Capital first
  15525. * @param {string} str
  15526. * @return {string}
  15527. */
  15528. function capitalFirst(str) {
  15529. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15530. }
  15531. var truncateText$1 = truncateText;
  15532. var getTextRect = getBoundingRect;
  15533. var format = (Object.freeze || Object)({
  15534. addCommas: addCommas,
  15535. toCamelCase: toCamelCase,
  15536. normalizeCssArray: normalizeCssArray$1,
  15537. encodeHTML: encodeHTML,
  15538. formatTpl: formatTpl,
  15539. formatTplSimple: formatTplSimple,
  15540. getTooltipMarker: getTooltipMarker,
  15541. formatTime: formatTime,
  15542. capitalFirst: capitalFirst,
  15543. truncateText: truncateText$1,
  15544. getTextRect: getTextRect
  15545. });
  15546. // Layout helpers for each component positioning
  15547. var each$3 = each$1;
  15548. /**
  15549. * @public
  15550. */
  15551. var LOCATION_PARAMS = [
  15552. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15553. ];
  15554. /**
  15555. * @public
  15556. */
  15557. var HV_NAMES = [
  15558. ['width', 'left', 'right'],
  15559. ['height', 'top', 'bottom']
  15560. ];
  15561. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15562. var x = 0;
  15563. var y = 0;
  15564. if (maxWidth == null) {
  15565. maxWidth = Infinity;
  15566. }
  15567. if (maxHeight == null) {
  15568. maxHeight = Infinity;
  15569. }
  15570. var currentLineMaxSize = 0;
  15571. group.eachChild(function (child, idx) {
  15572. var position = child.position;
  15573. var rect = child.getBoundingRect();
  15574. var nextChild = group.childAt(idx + 1);
  15575. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15576. var nextX;
  15577. var nextY;
  15578. if (orient === 'horizontal') {
  15579. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15580. nextX = x + moveX;
  15581. // Wrap when width exceeds maxWidth or meet a `newline` group
  15582. // FIXME compare before adding gap?
  15583. if (nextX > maxWidth || child.newline) {
  15584. x = 0;
  15585. nextX = moveX;
  15586. y += currentLineMaxSize + gap;
  15587. currentLineMaxSize = rect.height;
  15588. }
  15589. else {
  15590. // FIXME: consider rect.y is not `0`?
  15591. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15592. }
  15593. }
  15594. else {
  15595. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15596. nextY = y + moveY;
  15597. // Wrap when width exceeds maxHeight or meet a `newline` group
  15598. if (nextY > maxHeight || child.newline) {
  15599. x += currentLineMaxSize + gap;
  15600. y = 0;
  15601. nextY = moveY;
  15602. currentLineMaxSize = rect.width;
  15603. }
  15604. else {
  15605. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15606. }
  15607. }
  15608. if (child.newline) {
  15609. return;
  15610. }
  15611. position[0] = x;
  15612. position[1] = y;
  15613. orient === 'horizontal'
  15614. ? (x = nextX + gap)
  15615. : (y = nextY + gap);
  15616. });
  15617. }
  15618. /**
  15619. * VBox or HBox layouting
  15620. * @param {string} orient
  15621. * @param {module:zrender/container/Group} group
  15622. * @param {number} gap
  15623. * @param {number} [width=Infinity]
  15624. * @param {number} [height=Infinity]
  15625. */
  15626. var box = boxLayout;
  15627. /**
  15628. * VBox layouting
  15629. * @param {module:zrender/container/Group} group
  15630. * @param {number} gap
  15631. * @param {number} [width=Infinity]
  15632. * @param {number} [height=Infinity]
  15633. */
  15634. var vbox = curry(boxLayout, 'vertical');
  15635. /**
  15636. * HBox layouting
  15637. * @param {module:zrender/container/Group} group
  15638. * @param {number} gap
  15639. * @param {number} [width=Infinity]
  15640. * @param {number} [height=Infinity]
  15641. */
  15642. var hbox = curry(boxLayout, 'horizontal');
  15643. /**
  15644. * If x or x2 is not specified or 'center' 'left' 'right',
  15645. * the width would be as long as possible.
  15646. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15647. * the height would be as long as possible.
  15648. *
  15649. * @param {Object} positionInfo
  15650. * @param {number|string} [positionInfo.x]
  15651. * @param {number|string} [positionInfo.y]
  15652. * @param {number|string} [positionInfo.x2]
  15653. * @param {number|string} [positionInfo.y2]
  15654. * @param {Object} containerRect {width, height}
  15655. * @param {string|number} margin
  15656. * @return {Object} {width, height}
  15657. */
  15658. /**
  15659. * Parse position info.
  15660. *
  15661. * @param {Object} positionInfo
  15662. * @param {number|string} [positionInfo.left]
  15663. * @param {number|string} [positionInfo.top]
  15664. * @param {number|string} [positionInfo.right]
  15665. * @param {number|string} [positionInfo.bottom]
  15666. * @param {number|string} [positionInfo.width]
  15667. * @param {number|string} [positionInfo.height]
  15668. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15669. * @param {Object} containerRect
  15670. * @param {string|number} [margin]
  15671. *
  15672. * @return {module:zrender/core/BoundingRect}
  15673. */
  15674. function getLayoutRect(
  15675. positionInfo, containerRect, margin
  15676. ) {
  15677. margin = normalizeCssArray$1(margin || 0);
  15678. var containerWidth = containerRect.width;
  15679. var containerHeight = containerRect.height;
  15680. var left = parsePercent$1(positionInfo.left, containerWidth);
  15681. var top = parsePercent$1(positionInfo.top, containerHeight);
  15682. var right = parsePercent$1(positionInfo.right, containerWidth);
  15683. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15684. var width = parsePercent$1(positionInfo.width, containerWidth);
  15685. var height = parsePercent$1(positionInfo.height, containerHeight);
  15686. var verticalMargin = margin[2] + margin[0];
  15687. var horizontalMargin = margin[1] + margin[3];
  15688. var aspect = positionInfo.aspect;
  15689. // If width is not specified, calculate width from left and right
  15690. if (isNaN(width)) {
  15691. width = containerWidth - right - horizontalMargin - left;
  15692. }
  15693. if (isNaN(height)) {
  15694. height = containerHeight - bottom - verticalMargin - top;
  15695. }
  15696. if (aspect != null) {
  15697. // If width and height are not given
  15698. // 1. Graph should not exceeds the container
  15699. // 2. Aspect must be keeped
  15700. // 3. Graph should take the space as more as possible
  15701. // FIXME
  15702. // Margin is not considered, because there is no case that both
  15703. // using margin and aspect so far.
  15704. if (isNaN(width) && isNaN(height)) {
  15705. if (aspect > containerWidth / containerHeight) {
  15706. width = containerWidth * 0.8;
  15707. }
  15708. else {
  15709. height = containerHeight * 0.8;
  15710. }
  15711. }
  15712. // Calculate width or height with given aspect
  15713. if (isNaN(width)) {
  15714. width = aspect * height;
  15715. }
  15716. if (isNaN(height)) {
  15717. height = width / aspect;
  15718. }
  15719. }
  15720. // If left is not specified, calculate left from right and width
  15721. if (isNaN(left)) {
  15722. left = containerWidth - right - width - horizontalMargin;
  15723. }
  15724. if (isNaN(top)) {
  15725. top = containerHeight - bottom - height - verticalMargin;
  15726. }
  15727. // Align left and top
  15728. switch (positionInfo.left || positionInfo.right) {
  15729. case 'center':
  15730. left = containerWidth / 2 - width / 2 - margin[3];
  15731. break;
  15732. case 'right':
  15733. left = containerWidth - width - horizontalMargin;
  15734. break;
  15735. }
  15736. switch (positionInfo.top || positionInfo.bottom) {
  15737. case 'middle':
  15738. case 'center':
  15739. top = containerHeight / 2 - height / 2 - margin[0];
  15740. break;
  15741. case 'bottom':
  15742. top = containerHeight - height - verticalMargin;
  15743. break;
  15744. }
  15745. // If something is wrong and left, top, width, height are calculated as NaN
  15746. left = left || 0;
  15747. top = top || 0;
  15748. if (isNaN(width)) {
  15749. // Width may be NaN if only one value is given except width
  15750. width = containerWidth - horizontalMargin - left - (right || 0);
  15751. }
  15752. if (isNaN(height)) {
  15753. // Height may be NaN if only one value is given except height
  15754. height = containerHeight - verticalMargin - top - (bottom || 0);
  15755. }
  15756. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15757. rect.margin = margin;
  15758. return rect;
  15759. }
  15760. /**
  15761. * Position a zr element in viewport
  15762. * Group position is specified by either
  15763. * {left, top}, {right, bottom}
  15764. * If all properties exists, right and bottom will be igonred.
  15765. *
  15766. * Logic:
  15767. * 1. Scale (against origin point in parent coord)
  15768. * 2. Rotate (against origin point in parent coord)
  15769. * 3. Traslate (with el.position by this method)
  15770. * So this method only fixes the last step 'Traslate', which does not affect
  15771. * scaling and rotating.
  15772. *
  15773. * If be called repeatly with the same input el, the same result will be gotten.
  15774. *
  15775. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15776. * @param {Object} positionInfo
  15777. * @param {number|string} [positionInfo.left]
  15778. * @param {number|string} [positionInfo.top]
  15779. * @param {number|string} [positionInfo.right]
  15780. * @param {number|string} [positionInfo.bottom]
  15781. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15782. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15783. * @param {Object} containerRect
  15784. * @param {string|number} margin
  15785. * @param {Object} [opt]
  15786. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15787. * @param {Array.<number>} [opt.boundingMode='all']
  15788. * Specify how to calculate boundingRect when locating.
  15789. * 'all': Position the boundingRect that is transformed and uioned
  15790. * both itself and its descendants.
  15791. * This mode simplies confine the elements in the bounding
  15792. * of their container (e.g., using 'right: 0').
  15793. * 'raw': Position the boundingRect that is not transformed and only itself.
  15794. * This mode is useful when you want a element can overflow its
  15795. * container. (Consider a rotated circle needs to be located in a corner.)
  15796. * In this mode positionInfo.width/height can only be number.
  15797. */
  15798. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15799. var h = !opt || !opt.hv || opt.hv[0];
  15800. var v = !opt || !opt.hv || opt.hv[1];
  15801. var boundingMode = opt && opt.boundingMode || 'all';
  15802. if (!h && !v) {
  15803. return;
  15804. }
  15805. var rect;
  15806. if (boundingMode === 'raw') {
  15807. rect = el.type === 'group'
  15808. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15809. : el.getBoundingRect();
  15810. }
  15811. else {
  15812. rect = el.getBoundingRect();
  15813. if (el.needLocalTransform()) {
  15814. var transform = el.getLocalTransform();
  15815. // Notice: raw rect may be inner object of el,
  15816. // which should not be modified.
  15817. rect = rect.clone();
  15818. rect.applyTransform(transform);
  15819. }
  15820. }
  15821. // The real width and height can not be specified but calculated by the given el.
  15822. positionInfo = getLayoutRect(
  15823. defaults(
  15824. {width: rect.width, height: rect.height},
  15825. positionInfo
  15826. ),
  15827. containerRect,
  15828. margin
  15829. );
  15830. // Because 'tranlate' is the last step in transform
  15831. // (see zrender/core/Transformable#getLocalTransform),
  15832. // we can just only modify el.position to get final result.
  15833. var elPos = el.position;
  15834. var dx = h ? positionInfo.x - rect.x : 0;
  15835. var dy = v ? positionInfo.y - rect.y : 0;
  15836. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15837. }
  15838. /**
  15839. * @param {Object} option Contains some of the properties in HV_NAMES.
  15840. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15841. */
  15842. /**
  15843. * Consider Case:
  15844. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15845. * through setOption or media query, using normal zrUtil.merge will cause
  15846. * {right: 0} does not take effect.
  15847. *
  15848. * @example
  15849. * ComponentModel.extend({
  15850. * init: function () {
  15851. * ...
  15852. * var inputPositionParams = layout.getLayoutParams(option);
  15853. * this.mergeOption(inputPositionParams);
  15854. * },
  15855. * mergeOption: function (newOption) {
  15856. * newOption && zrUtil.merge(thisOption, newOption, true);
  15857. * layout.mergeLayoutParam(thisOption, newOption);
  15858. * }
  15859. * });
  15860. *
  15861. * @param {Object} targetOption
  15862. * @param {Object} newOption
  15863. * @param {Object|string} [opt]
  15864. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15865. * that width (or height) should not be calculated by left and right (or top and bottom).
  15866. */
  15867. function mergeLayoutParam(targetOption, newOption, opt) {
  15868. !isObject$1(opt) && (opt = {});
  15869. var ignoreSize = opt.ignoreSize;
  15870. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15871. var hResult = merge$$1(HV_NAMES[0], 0);
  15872. var vResult = merge$$1(HV_NAMES[1], 1);
  15873. copy(HV_NAMES[0], targetOption, hResult);
  15874. copy(HV_NAMES[1], targetOption, vResult);
  15875. function merge$$1(names, hvIdx) {
  15876. var newParams = {};
  15877. var newValueCount = 0;
  15878. var merged = {};
  15879. var mergedValueCount = 0;
  15880. var enoughParamNumber = 2;
  15881. each$3(names, function (name) {
  15882. merged[name] = targetOption[name];
  15883. });
  15884. each$3(names, function (name) {
  15885. // Consider case: newOption.width is null, which is
  15886. // set by user for removing width setting.
  15887. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15888. hasValue(newParams, name) && newValueCount++;
  15889. hasValue(merged, name) && mergedValueCount++;
  15890. });
  15891. if (ignoreSize[hvIdx]) {
  15892. // Only one of left/right is premitted to exist.
  15893. if (hasValue(newOption, names[1])) {
  15894. merged[names[2]] = null;
  15895. }
  15896. else if (hasValue(newOption, names[2])) {
  15897. merged[names[1]] = null;
  15898. }
  15899. return merged;
  15900. }
  15901. // Case: newOption: {width: ..., right: ...},
  15902. // or targetOption: {right: ...} and newOption: {width: ...},
  15903. // There is no conflict when merged only has params count
  15904. // little than enoughParamNumber.
  15905. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15906. return merged;
  15907. }
  15908. // Case: newOption: {width: ..., right: ...},
  15909. // Than we can make sure user only want those two, and ignore
  15910. // all origin params in targetOption.
  15911. else if (newValueCount >= enoughParamNumber) {
  15912. return newParams;
  15913. }
  15914. else {
  15915. // Chose another param from targetOption by priority.
  15916. for (var i = 0; i < names.length; i++) {
  15917. var name = names[i];
  15918. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  15919. newParams[name] = targetOption[name];
  15920. break;
  15921. }
  15922. }
  15923. return newParams;
  15924. }
  15925. }
  15926. function hasProp(obj, name) {
  15927. return obj.hasOwnProperty(name);
  15928. }
  15929. function hasValue(obj, name) {
  15930. return obj[name] != null && obj[name] !== 'auto';
  15931. }
  15932. function copy(names, target, source) {
  15933. each$3(names, function (name) {
  15934. target[name] = source[name];
  15935. });
  15936. }
  15937. }
  15938. /**
  15939. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15940. * @param {Object} source
  15941. * @return {Object} Result contains those props.
  15942. */
  15943. function getLayoutParams(source) {
  15944. return copyLayoutParams({}, source);
  15945. }
  15946. /**
  15947. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15948. * @param {Object} source
  15949. * @return {Object} Result contains those props.
  15950. */
  15951. function copyLayoutParams(target, source) {
  15952. source && target && each$3(LOCATION_PARAMS, function (name) {
  15953. source.hasOwnProperty(name) && (target[name] = source[name]);
  15954. });
  15955. return target;
  15956. }
  15957. var boxLayoutMixin = {
  15958. getBoxLayoutParams: function () {
  15959. return {
  15960. left: this.get('left'),
  15961. top: this.get('top'),
  15962. right: this.get('right'),
  15963. bottom: this.get('bottom'),
  15964. width: this.get('width'),
  15965. height: this.get('height')
  15966. };
  15967. }
  15968. };
  15969. /**
  15970. * Component model
  15971. *
  15972. * @module echarts/model/Component
  15973. */
  15974. var inner$1 = makeInner();
  15975. /**
  15976. * @alias module:echarts/model/Component
  15977. * @constructor
  15978. * @param {Object} option
  15979. * @param {module:echarts/model/Model} parentModel
  15980. * @param {module:echarts/model/Model} ecModel
  15981. */
  15982. var ComponentModel = Model.extend({
  15983. type: 'component',
  15984. /**
  15985. * @readOnly
  15986. * @type {string}
  15987. */
  15988. id: '',
  15989. /**
  15990. * Because simplified concept is probably better, series.name (or component.name)
  15991. * has been having too many resposibilities:
  15992. * (1) Generating id (which requires name in option should not be modified).
  15993. * (2) As an index to mapping series when merging option or calling API (a name
  15994. * can refer to more then one components, which is convinient is some case).
  15995. * (3) Display.
  15996. * @readOnly
  15997. */
  15998. name: '',
  15999. /**
  16000. * @readOnly
  16001. * @type {string}
  16002. */
  16003. mainType: '',
  16004. /**
  16005. * @readOnly
  16006. * @type {string}
  16007. */
  16008. subType: '',
  16009. /**
  16010. * @readOnly
  16011. * @type {number}
  16012. */
  16013. componentIndex: 0,
  16014. /**
  16015. * @type {Object}
  16016. * @protected
  16017. */
  16018. defaultOption: null,
  16019. /**
  16020. * @type {module:echarts/model/Global}
  16021. * @readOnly
  16022. */
  16023. ecModel: null,
  16024. /**
  16025. * key: componentType
  16026. * value: Component model list, can not be null.
  16027. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16028. * @readOnly
  16029. */
  16030. dependentModels: [],
  16031. /**
  16032. * @type {string}
  16033. * @readOnly
  16034. */
  16035. uid: null,
  16036. /**
  16037. * Support merge layout params.
  16038. * Only support 'box' now (left/right/top/bottom/width/height).
  16039. * @type {string|Object} Object can be {ignoreSize: true}
  16040. * @readOnly
  16041. */
  16042. layoutMode: null,
  16043. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16044. Model.call(this, option, parentModel, ecModel, extraOpt);
  16045. this.uid = getUID('ec_cpt_model');
  16046. },
  16047. init: function (option, parentModel, ecModel, extraOpt) {
  16048. this.mergeDefaultAndTheme(option, ecModel);
  16049. },
  16050. mergeDefaultAndTheme: function (option, ecModel) {
  16051. var layoutMode = this.layoutMode;
  16052. var inputPositionParams = layoutMode
  16053. ? getLayoutParams(option) : {};
  16054. var themeModel = ecModel.getTheme();
  16055. merge(option, themeModel.get(this.mainType));
  16056. merge(option, this.getDefaultOption());
  16057. if (layoutMode) {
  16058. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16059. }
  16060. },
  16061. mergeOption: function (option, extraOpt) {
  16062. merge(this.option, option, true);
  16063. var layoutMode = this.layoutMode;
  16064. if (layoutMode) {
  16065. mergeLayoutParam(this.option, option, layoutMode);
  16066. }
  16067. },
  16068. // Hooker after init or mergeOption
  16069. optionUpdated: function (newCptOption, isInit) {},
  16070. getDefaultOption: function () {
  16071. var fields = inner$1(this);
  16072. if (!fields.defaultOption) {
  16073. var optList = [];
  16074. var Class = this.constructor;
  16075. while (Class) {
  16076. var opt = Class.prototype.defaultOption;
  16077. opt && optList.push(opt);
  16078. Class = Class.superClass;
  16079. }
  16080. var defaultOption = {};
  16081. for (var i = optList.length - 1; i >= 0; i--) {
  16082. defaultOption = merge(defaultOption, optList[i], true);
  16083. }
  16084. fields.defaultOption = defaultOption;
  16085. }
  16086. return fields.defaultOption;
  16087. },
  16088. getReferringComponents: function (mainType) {
  16089. return this.ecModel.queryComponents({
  16090. mainType: mainType,
  16091. index: this.get(mainType + 'Index', true),
  16092. id: this.get(mainType + 'Id', true)
  16093. });
  16094. }
  16095. });
  16096. // Reset ComponentModel.extend, add preConstruct.
  16097. // clazzUtil.enableClassExtend(
  16098. // ComponentModel,
  16099. // function (option, parentModel, ecModel, extraOpt) {
  16100. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16101. // zrUtil.extend(this, extraOpt);
  16102. // this.uid = componentUtil.getUID('componentModel');
  16103. // // this.setReadOnly([
  16104. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16105. // // 'dependentModels', 'componentIndex'
  16106. // // ]);
  16107. // }
  16108. // );
  16109. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16110. enableClassManagement(
  16111. ComponentModel, {registerWhenExtend: true}
  16112. );
  16113. enableSubTypeDefaulter(ComponentModel);
  16114. // Add capability of ComponentModel.topologicalTravel.
  16115. enableTopologicalTravel(ComponentModel, getDependencies);
  16116. function getDependencies(componentType) {
  16117. var deps = [];
  16118. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16119. deps = deps.concat(Clazz.prototype.dependencies || []);
  16120. });
  16121. // Ensure main type.
  16122. deps = map(deps, function (type) {
  16123. return parseClassType$1(type).main;
  16124. });
  16125. // Hack dataset for convenience.
  16126. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16127. deps.unshift('dataset');
  16128. }
  16129. return deps;
  16130. }
  16131. mixin(ComponentModel, boxLayoutMixin);
  16132. var platform = '';
  16133. // Navigator not exists in node
  16134. if (typeof navigator !== 'undefined') {
  16135. platform = navigator.platform || '';
  16136. }
  16137. var globalDefault = {
  16138. // 全图默认背景
  16139. // backgroundColor: 'rgba(0,0,0,0)',
  16140. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16141. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16142. // 浅色
  16143. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16144. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16145. // 深色
  16146. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16147. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16148. // 默认需要 Grid 配置项
  16149. // grid: {},
  16150. // 主题,主题
  16151. textStyle: {
  16152. // color: '#000',
  16153. // decoration: 'none',
  16154. // PENDING
  16155. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16156. // fontFamily: 'Arial, Verdana, sans-serif',
  16157. fontSize: 12,
  16158. fontStyle: 'normal',
  16159. fontWeight: 'normal'
  16160. },
  16161. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16162. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16163. // Default is source-over
  16164. blendMode: null,
  16165. animation: 'auto',
  16166. animationDuration: 1000,
  16167. animationDurationUpdate: 300,
  16168. animationEasing: 'exponentialOut',
  16169. animationEasingUpdate: 'cubicOut',
  16170. animationThreshold: 2000,
  16171. // Configuration for progressive/incremental rendering
  16172. progressiveThreshold: 3000,
  16173. progressive: 400,
  16174. // Threshold of if use single hover layer to optimize.
  16175. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16176. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16177. // which is unexpected.
  16178. // see example <echarts/test/heatmap-large.html>.
  16179. hoverLayerThreshold: 3000,
  16180. // See: module:echarts/scale/Time
  16181. useUTC: false
  16182. };
  16183. var inner$2 = makeInner();
  16184. function getNearestColorPalette(colors, requestColorNum) {
  16185. var paletteNum = colors.length;
  16186. // TODO colors must be in order
  16187. for (var i = 0; i < paletteNum; i++) {
  16188. if (colors[i].length > requestColorNum) {
  16189. return colors[i];
  16190. }
  16191. }
  16192. return colors[paletteNum - 1];
  16193. }
  16194. var colorPaletteMixin = {
  16195. clearColorPalette: function () {
  16196. inner$2(this).colorIdx = 0;
  16197. inner$2(this).colorNameMap = {};
  16198. },
  16199. getColorFromPalette: function (name, scope, requestColorNum) {
  16200. scope = scope || this;
  16201. var scopeFields = inner$2(scope);
  16202. var colorIdx = scopeFields.colorIdx || 0;
  16203. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16204. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16205. if (colorNameMap.hasOwnProperty(name)) {
  16206. return colorNameMap[name];
  16207. }
  16208. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16209. var layeredColorPalette = this.get('colorLayer', true);
  16210. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16211. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16212. // In case can't find in layered color palette.
  16213. colorPalette = colorPalette || defaultColorPalette;
  16214. if (!colorPalette || !colorPalette.length) {
  16215. return;
  16216. }
  16217. var color = colorPalette[colorIdx];
  16218. if (name) {
  16219. colorNameMap[name] = color;
  16220. }
  16221. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16222. return color;
  16223. }
  16224. };
  16225. /**
  16226. * Helper for model references.
  16227. * There are many manners to refer axis/coordSys.
  16228. */
  16229. // TODO
  16230. // merge relevant logic to this file?
  16231. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16232. /**
  16233. * @return {Object} For example:
  16234. * {
  16235. * coordSysName: 'cartesian2d',
  16236. * coordSysDims: ['x', 'y', ...],
  16237. * axisMap: HashMap({
  16238. * x: xAxisModel,
  16239. * y: yAxisModel
  16240. * }),
  16241. * categoryAxisMap: HashMap({
  16242. * x: xAxisModel,
  16243. * y: undefined
  16244. * }),
  16245. * // It also indicate that whether there is category axis.
  16246. * firstCategoryDimIndex: 1,
  16247. * // To replace user specified encode.
  16248. * }
  16249. */
  16250. function getCoordSysDefineBySeries(seriesModel) {
  16251. var coordSysName = seriesModel.get('coordinateSystem');
  16252. var result = {
  16253. coordSysName: coordSysName,
  16254. coordSysDims: [],
  16255. axisMap: createHashMap(),
  16256. categoryAxisMap: createHashMap()
  16257. };
  16258. var fetch = fetchers[coordSysName];
  16259. if (fetch) {
  16260. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16261. return result;
  16262. }
  16263. }
  16264. var fetchers = {
  16265. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16266. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16267. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16268. if (__DEV__) {
  16269. if (!xAxisModel) {
  16270. throw new Error('xAxis "' + retrieve(
  16271. seriesModel.get('xAxisIndex'),
  16272. seriesModel.get('xAxisId'),
  16273. 0
  16274. ) + '" not found');
  16275. }
  16276. if (!yAxisModel) {
  16277. throw new Error('yAxis "' + retrieve(
  16278. seriesModel.get('xAxisIndex'),
  16279. seriesModel.get('yAxisId'),
  16280. 0
  16281. ) + '" not found');
  16282. }
  16283. }
  16284. result.coordSysDims = ['x', 'y'];
  16285. axisMap.set('x', xAxisModel);
  16286. axisMap.set('y', yAxisModel);
  16287. if (isCategory(xAxisModel)) {
  16288. categoryAxisMap.set('x', xAxisModel);
  16289. result.firstCategoryDimIndex = 0;
  16290. }
  16291. if (isCategory(yAxisModel)) {
  16292. categoryAxisMap.set('y', yAxisModel);
  16293. result.firstCategoryDimIndex = 1;
  16294. }
  16295. },
  16296. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16297. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16298. if (__DEV__) {
  16299. if (!singleAxisModel) {
  16300. throw new Error('singleAxis should be specified.');
  16301. }
  16302. }
  16303. result.coordSysDims = ['single'];
  16304. axisMap.set('single', singleAxisModel);
  16305. if (isCategory(singleAxisModel)) {
  16306. categoryAxisMap.set('single', singleAxisModel);
  16307. result.firstCategoryDimIndex = 0;
  16308. }
  16309. },
  16310. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16311. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16312. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16313. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16314. if (__DEV__) {
  16315. if (!angleAxisModel) {
  16316. throw new Error('angleAxis option not found');
  16317. }
  16318. if (!radiusAxisModel) {
  16319. throw new Error('radiusAxis option not found');
  16320. }
  16321. }
  16322. result.coordSysDims = ['radius', 'angle'];
  16323. axisMap.set('radius', radiusAxisModel);
  16324. axisMap.set('angle', angleAxisModel);
  16325. if (isCategory(radiusAxisModel)) {
  16326. categoryAxisMap.set('radius', radiusAxisModel);
  16327. result.firstCategoryDimIndex = 0;
  16328. }
  16329. if (isCategory(angleAxisModel)) {
  16330. categoryAxisMap.set('angle', angleAxisModel);
  16331. result.firstCategoryDimIndex = 1;
  16332. }
  16333. },
  16334. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16335. result.coordSysDims = ['lng', 'lat'];
  16336. },
  16337. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16338. var ecModel = seriesModel.ecModel;
  16339. var parallelModel = ecModel.getComponent(
  16340. 'parallel', seriesModel.get('parallelIndex')
  16341. );
  16342. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16343. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16344. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16345. var axisDim = coordSysDims[index];
  16346. axisMap.set(axisDim, axisModel);
  16347. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16348. categoryAxisMap.set(axisDim, axisModel);
  16349. result.firstCategoryDimIndex = index;
  16350. }
  16351. });
  16352. }
  16353. };
  16354. function isCategory(axisModel) {
  16355. return axisModel.get('type') === 'category';
  16356. }
  16357. // Avoid typo.
  16358. var SOURCE_FORMAT_ORIGINAL = 'original';
  16359. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16360. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16361. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16362. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16363. // ??? CHANGE A NAME
  16364. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16365. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16366. var SERIES_LAYOUT_BY_ROW = 'row';
  16367. /**
  16368. * [sourceFormat]
  16369. *
  16370. * + "original":
  16371. * This format is only used in series.data, where
  16372. * itemStyle can be specified in data item.
  16373. *
  16374. * + "arrayRows":
  16375. * [
  16376. * ['product', 'score', 'amount'],
  16377. * ['Matcha Latte', 89.3, 95.8],
  16378. * ['Milk Tea', 92.1, 89.4],
  16379. * ['Cheese Cocoa', 94.4, 91.2],
  16380. * ['Walnut Brownie', 85.4, 76.9]
  16381. * ]
  16382. *
  16383. * + "objectRows":
  16384. * [
  16385. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16386. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16387. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16388. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16389. * ]
  16390. *
  16391. * + "keyedColumns":
  16392. * {
  16393. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16394. * 'count': [823, 235, 1042, 988],
  16395. * 'score': [95.8, 81.4, 91.2, 76.9]
  16396. * }
  16397. *
  16398. * + "typedArray"
  16399. *
  16400. * + "unknown"
  16401. */
  16402. /**
  16403. * @constructor
  16404. * @param {Object} fields
  16405. * @param {string} fields.sourceFormat
  16406. * @param {Array|Object} fields.fromDataset
  16407. * @param {Array|Object} [fields.data]
  16408. * @param {string} [seriesLayoutBy='column']
  16409. * @param {Array.<Object|string>} [dimensionsDefine]
  16410. * @param {Objet|HashMap} [encodeDefine]
  16411. * @param {number} [startIndex=0]
  16412. * @param {number} [dimensionsDetectCount]
  16413. */
  16414. function Source(fields) {
  16415. /**
  16416. * @type {boolean}
  16417. */
  16418. this.fromDataset = fields.fromDataset;
  16419. /**
  16420. * Not null/undefined.
  16421. * @type {Array|Object}
  16422. */
  16423. this.data = fields.data || (
  16424. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16425. );
  16426. /**
  16427. * See also "detectSourceFormat".
  16428. * Not null/undefined.
  16429. * @type {string}
  16430. */
  16431. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16432. /**
  16433. * 'row' or 'column'
  16434. * Not null/undefined.
  16435. * @type {string} seriesLayoutBy
  16436. */
  16437. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16438. /**
  16439. * dimensions definition in option.
  16440. * can be null/undefined.
  16441. * @type {Array.<Object|string>}
  16442. */
  16443. this.dimensionsDefine = fields.dimensionsDefine;
  16444. /**
  16445. * encode definition in option.
  16446. * can be null/undefined.
  16447. * @type {Objet|HashMap}
  16448. */
  16449. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16450. /**
  16451. * Not null/undefined, uint.
  16452. * @type {number}
  16453. */
  16454. this.startIndex = fields.startIndex || 0;
  16455. /**
  16456. * Can be null/undefined (when unknown), uint.
  16457. * @type {number}
  16458. */
  16459. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16460. }
  16461. /**
  16462. * Wrap original series data for some compatibility cases.
  16463. */
  16464. Source.seriesDataToSource = function (data) {
  16465. return new Source({
  16466. data: data,
  16467. sourceFormat: isTypedArray(data)
  16468. ? SOURCE_FORMAT_TYPED_ARRAY
  16469. : SOURCE_FORMAT_ORIGINAL,
  16470. fromDataset: false
  16471. });
  16472. };
  16473. enableClassCheck(Source);
  16474. var inner$3 = makeInner();
  16475. /**
  16476. * @see {module:echarts/data/Source}
  16477. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  16478. * @return {string} sourceFormat
  16479. */
  16480. function detectSourceFormat(datasetModel) {
  16481. var data = datasetModel.option.source;
  16482. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  16483. if (isTypedArray(data)) {
  16484. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  16485. }
  16486. else if (isArray(data)) {
  16487. // FIXME Whether tolerate null in top level array?
  16488. for (var i = 0, len = data.length; i < len; i++) {
  16489. var item = data[i];
  16490. if (item == null) {
  16491. continue;
  16492. }
  16493. else if (isArray(item)) {
  16494. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  16495. break;
  16496. }
  16497. else if (isObject$1(item)) {
  16498. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  16499. break;
  16500. }
  16501. }
  16502. }
  16503. else if (isObject$1(data)) {
  16504. for (var key in data) {
  16505. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  16506. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  16507. break;
  16508. }
  16509. }
  16510. }
  16511. else if (data != null) {
  16512. throw new Error('Invalid data');
  16513. }
  16514. inner$3(datasetModel).sourceFormat = sourceFormat;
  16515. }
  16516. /**
  16517. * [Scenarios]:
  16518. * (1) Provide source data directly:
  16519. * series: {
  16520. * encode: {...},
  16521. * dimensions: [...]
  16522. * seriesLayoutBy: 'row',
  16523. * data: [[...]]
  16524. * }
  16525. * (2) Refer to datasetModel.
  16526. * series: [{
  16527. * encode: {...}
  16528. * // Ignore datasetIndex means `datasetIndex: 0`
  16529. * // and the dimensions defination in dataset is used
  16530. * }, {
  16531. * encode: {...},
  16532. * seriesLayoutBy: 'column',
  16533. * datasetIndex: 1
  16534. * }]
  16535. *
  16536. * Get data from series itself or datset.
  16537. * @return {module:echarts/data/Source} source
  16538. */
  16539. function getSource(seriesModel) {
  16540. return inner$3(seriesModel).source;
  16541. }
  16542. /**
  16543. * MUST be called before mergeOption of all series.
  16544. * @param {module:echarts/model/Global} ecModel
  16545. */
  16546. function resetSourceDefaulter(ecModel) {
  16547. // `datasetMap` is used to make default encode.
  16548. inner$3(ecModel).datasetMap = createHashMap();
  16549. }
  16550. /**
  16551. * [Caution]:
  16552. * MUST be called after series option merged and
  16553. * before "series.getInitailData()" called.
  16554. *
  16555. * [The rule of making default encode]:
  16556. * Category axis (if exists) alway map to the first dimension.
  16557. * Each other axis occupies a subsequent dimension.
  16558. *
  16559. * [Why make default encode]:
  16560. * Simplify the typing of encode in option, avoiding the case like that:
  16561. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16562. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16563. *
  16564. * @param {module:echarts/model/Series} seriesModel
  16565. */
  16566. function prepareSource(seriesModel) {
  16567. var seriesOption = seriesModel.option;
  16568. var data = seriesOption.data;
  16569. var sourceFormat = isTypedArray(data)
  16570. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16571. var fromDataset = false;
  16572. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16573. var sourceHeader = seriesOption.sourceHeader;
  16574. var dimensionsDefine = seriesOption.dimensions;
  16575. var datasetModel = getDatasetModel(seriesModel);
  16576. if (datasetModel) {
  16577. var datasetOption = datasetModel.option;
  16578. data = datasetOption.source;
  16579. sourceFormat = inner$3(datasetModel).sourceFormat;
  16580. fromDataset = true;
  16581. // These settings from series has higher priority.
  16582. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16583. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16584. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16585. }
  16586. var completeResult = completeBySourceData(
  16587. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16588. );
  16589. // Note: dataset option does not have `encode`.
  16590. var encodeDefine = seriesOption.encode;
  16591. if (!encodeDefine && datasetModel) {
  16592. encodeDefine = makeDefaultEncode(
  16593. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16594. );
  16595. }
  16596. inner$3(seriesModel).source = new Source({
  16597. data: data,
  16598. fromDataset: fromDataset,
  16599. seriesLayoutBy: seriesLayoutBy,
  16600. sourceFormat: sourceFormat,
  16601. dimensionsDefine: completeResult.dimensionsDefine,
  16602. startIndex: completeResult.startIndex,
  16603. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16604. encodeDefine: encodeDefine
  16605. });
  16606. }
  16607. // return {startIndex, dimensionsDefine, dimensionsCount}
  16608. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16609. if (!data) {
  16610. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16611. }
  16612. var dimensionsDetectCount;
  16613. var startIndex;
  16614. var findPotentialName;
  16615. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16616. // Rule: Most of the first line are string: it is header.
  16617. // Caution: consider a line with 5 string and 1 number,
  16618. // it still can not be sure it is a head, because the
  16619. // 5 string may be 5 values of category columns.
  16620. if (sourceHeader === 'auto' || sourceHeader == null) {
  16621. arrayRowsTravelFirst(function (val) {
  16622. // '-' is regarded as null/undefined.
  16623. if (val != null && val !== '-') {
  16624. if (isString(val)) {
  16625. startIndex == null && (startIndex = 1);
  16626. }
  16627. else {
  16628. startIndex = 0;
  16629. }
  16630. }
  16631. // 10 is an experience number, avoid long loop.
  16632. }, seriesLayoutBy, data, 10);
  16633. }
  16634. else {
  16635. startIndex = sourceHeader ? 1 : 0;
  16636. }
  16637. if (!dimensionsDefine && startIndex === 1) {
  16638. dimensionsDefine = [];
  16639. arrayRowsTravelFirst(function (val, index) {
  16640. dimensionsDefine[index] = val != null ? val : '';
  16641. }, seriesLayoutBy, data);
  16642. }
  16643. dimensionsDetectCount = dimensionsDefine
  16644. ? dimensionsDefine.length
  16645. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16646. ? data.length
  16647. : data[0]
  16648. ? data[0].length
  16649. : null;
  16650. }
  16651. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16652. if (!dimensionsDefine) {
  16653. dimensionsDefine = objectRowsCollectDimensions(data);
  16654. findPotentialName = true;
  16655. }
  16656. }
  16657. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16658. if (!dimensionsDefine) {
  16659. dimensionsDefine = [];
  16660. findPotentialName = true;
  16661. each$1(data, function (colArr, key) {
  16662. dimensionsDefine.push(key);
  16663. });
  16664. }
  16665. }
  16666. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16667. var value0 = getDataItemValue(data[0]);
  16668. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16669. }
  16670. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16671. if (__DEV__) {
  16672. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16673. }
  16674. }
  16675. var potentialNameDimIndex;
  16676. if (findPotentialName) {
  16677. each$1(dimensionsDefine, function (dim, idx) {
  16678. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16679. potentialNameDimIndex = idx;
  16680. }
  16681. });
  16682. }
  16683. return {
  16684. startIndex: startIndex,
  16685. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16686. dimensionsDetectCount: dimensionsDetectCount,
  16687. potentialNameDimIndex: potentialNameDimIndex
  16688. // TODO: potentialIdDimIdx
  16689. };
  16690. }
  16691. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16692. // which is reasonable. But dimension name is duplicated.
  16693. // Returns undefined or an array contains only object without null/undefiend or string.
  16694. function normalizeDimensionsDefine(dimensionsDefine) {
  16695. if (!dimensionsDefine) {
  16696. // The meaning of null/undefined is different from empty array.
  16697. return;
  16698. }
  16699. var nameMap = createHashMap();
  16700. return map(dimensionsDefine, function (item, index) {
  16701. item = extend({}, isObject$1(item) ? item : {name: item});
  16702. // User can set null in dimensions.
  16703. // We dont auto specify name, othewise a given name may
  16704. // cause it be refered unexpectedly.
  16705. if (item.name == null) {
  16706. return item;
  16707. }
  16708. // Also consider number form like 2012.
  16709. item.name += '';
  16710. // User may also specify displayName.
  16711. // displayName will always exists except user not
  16712. // specified or dim name is not specified or detected.
  16713. // (A auto generated dim name will not be used as
  16714. // displayName).
  16715. if (item.displayName == null) {
  16716. item.displayName = item.name;
  16717. }
  16718. var exist = nameMap.get(item.name);
  16719. if (!exist) {
  16720. nameMap.set(item.name, {count: 1});
  16721. }
  16722. else {
  16723. item.name += '-' + exist.count++;
  16724. }
  16725. return item;
  16726. });
  16727. }
  16728. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16729. maxLoop == null && (maxLoop = Infinity);
  16730. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16731. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16732. cb(data[i] ? data[i][0] : null, i);
  16733. }
  16734. }
  16735. else {
  16736. var value0 = data[0] || [];
  16737. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16738. cb(value0[i], i);
  16739. }
  16740. }
  16741. }
  16742. function objectRowsCollectDimensions(data) {
  16743. var firstIndex = 0;
  16744. var obj;
  16745. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16746. if (obj) {
  16747. var dimensions = [];
  16748. each$1(obj, function (value, key) {
  16749. dimensions.push(key);
  16750. });
  16751. return dimensions;
  16752. }
  16753. }
  16754. // ??? TODO merge to completedimensions, where also has
  16755. // default encode making logic. And the default rule
  16756. // should depends on series? consider 'map'.
  16757. function makeDefaultEncode(
  16758. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16759. ) {
  16760. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16761. var encode = {};
  16762. // var encodeTooltip = [];
  16763. // var encodeLabel = [];
  16764. var encodeItemName = [];
  16765. var encodeSeriesName = [];
  16766. var seriesType = seriesModel.subType;
  16767. // ??? TODO refactor: provide by series itself.
  16768. // Consider the case: 'map' series is based on geo coordSys,
  16769. // 'graph', 'heatmap' can be based on cartesian. But can not
  16770. // give default rule simply here.
  16771. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16772. var cSeriesMap = createHashMap([
  16773. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16774. ]);
  16775. // Usually in this case series will use the first data
  16776. // dimension as the "value" dimension, or other default
  16777. // processes respectively.
  16778. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16779. var ecModel = seriesModel.ecModel;
  16780. var datasetMap = inner$3(ecModel).datasetMap;
  16781. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16782. var datasetRecord = datasetMap.get(key)
  16783. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16784. // TODO
  16785. // Auto detect first time axis and do arrangement.
  16786. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16787. // In value way.
  16788. if (coordSysDefine.firstCategoryDimIndex == null) {
  16789. var dataDim = datasetRecord.valueWayDim++;
  16790. encode[coordDim] = dataDim;
  16791. // ??? TODO give a better default series name rule?
  16792. // especially when encode x y specified.
  16793. // consider: when mutiple series share one dimension
  16794. // category axis, series name should better use
  16795. // the other dimsion name. On the other hand, use
  16796. // both dimensions name.
  16797. encodeSeriesName.push(dataDim);
  16798. // encodeTooltip.push(dataDim);
  16799. // encodeLabel.push(dataDim);
  16800. }
  16801. // In category way, category axis.
  16802. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16803. encode[coordDim] = 0;
  16804. encodeItemName.push(0);
  16805. }
  16806. // In category way, non-category axis.
  16807. else {
  16808. var dataDim = datasetRecord.categoryWayDim++;
  16809. encode[coordDim] = dataDim;
  16810. // encodeTooltip.push(dataDim);
  16811. // encodeLabel.push(dataDim);
  16812. encodeSeriesName.push(dataDim);
  16813. }
  16814. });
  16815. }
  16816. // Do not make a complex rule! Hard to code maintain and not necessary.
  16817. // ??? TODO refactor: provide by series itself.
  16818. // [{name: ..., value: ...}, ...] like:
  16819. else if (nSeriesMap.get(seriesType) != null) {
  16820. // Find the first not ordinal. (5 is an experience value)
  16821. var firstNotOrdinal;
  16822. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16823. if (!doGuessOrdinal(
  16824. data, sourceFormat, seriesLayoutBy,
  16825. completeResult.dimensionsDefine, completeResult.startIndex, i
  16826. )) {
  16827. firstNotOrdinal = i;
  16828. }
  16829. }
  16830. if (firstNotOrdinal != null) {
  16831. encode.value = firstNotOrdinal;
  16832. var nameDimIndex = completeResult.potentialNameDimIndex
  16833. || Math.max(firstNotOrdinal - 1, 0);
  16834. // By default, label use itemName in charts.
  16835. // So we dont set encodeLabel here.
  16836. encodeSeriesName.push(nameDimIndex);
  16837. encodeItemName.push(nameDimIndex);
  16838. // encodeTooltip.push(firstNotOrdinal);
  16839. }
  16840. }
  16841. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16842. // encodeLabel.length && (encode.label = encodeLabel);
  16843. encodeItemName.length && (encode.itemName = encodeItemName);
  16844. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16845. return encode;
  16846. }
  16847. /**
  16848. * If return null/undefined, indicate that should not use datasetModel.
  16849. */
  16850. function getDatasetModel(seriesModel) {
  16851. var option = seriesModel.option;
  16852. // Caution: consider the scenario:
  16853. // A dataset is declared and a series is not expected to use the dataset,
  16854. // and at the beginning `setOption({series: { noData })` (just prepare other
  16855. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16856. // the user should set an empty array to avoid that dataset is used by default.
  16857. var thisData = option.data;
  16858. if (!thisData) {
  16859. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  16860. }
  16861. }
  16862. /**
  16863. * The rule should not be complex, otherwise user might not
  16864. * be able to known where the data is wrong.
  16865. * The code is ugly, but how to make it neat?
  16866. *
  16867. * @param {module:echars/data/Source} source
  16868. * @param {number} dimIndex
  16869. * @return {boolean} Whether ordinal.
  16870. */
  16871. function guessOrdinal(source, dimIndex) {
  16872. return doGuessOrdinal(
  16873. source.data,
  16874. source.sourceFormat,
  16875. source.seriesLayoutBy,
  16876. source.dimensionsDefine,
  16877. source.startIndex,
  16878. dimIndex
  16879. );
  16880. }
  16881. // dimIndex may be overflow source data.
  16882. function doGuessOrdinal(
  16883. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  16884. ) {
  16885. var result;
  16886. // Experience value.
  16887. var maxLoop = 5;
  16888. if (isTypedArray(data)) {
  16889. return false;
  16890. }
  16891. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16892. // always exists in source.
  16893. var dimName;
  16894. if (dimensionsDefine) {
  16895. dimName = dimensionsDefine[dimIndex];
  16896. dimName = isObject$1(dimName) ? dimName.name : dimName;
  16897. }
  16898. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16899. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16900. var sample = data[dimIndex];
  16901. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16902. if ((result = detectValue(sample[startIndex + i])) != null) {
  16903. return result;
  16904. }
  16905. }
  16906. }
  16907. else {
  16908. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16909. var row = data[startIndex + i];
  16910. if (row && (result = detectValue(row[dimIndex])) != null) {
  16911. return result;
  16912. }
  16913. }
  16914. }
  16915. }
  16916. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16917. if (!dimName) {
  16918. return;
  16919. }
  16920. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16921. var item = data[i];
  16922. if (item && (result = detectValue(item[dimName])) != null) {
  16923. return result;
  16924. }
  16925. }
  16926. }
  16927. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16928. if (!dimName) {
  16929. return;
  16930. }
  16931. var sample = data[dimName];
  16932. if (!sample || isTypedArray(sample)) {
  16933. return false;
  16934. }
  16935. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16936. if ((result = detectValue(sample[i])) != null) {
  16937. return result;
  16938. }
  16939. }
  16940. }
  16941. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16942. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16943. var item = data[i];
  16944. var val = getDataItemValue(item);
  16945. if (!isArray(val)) {
  16946. return false;
  16947. }
  16948. if ((result = detectValue(val[dimIndex])) != null) {
  16949. return result;
  16950. }
  16951. }
  16952. }
  16953. function detectValue(val) {
  16954. // Consider usage convenience, '1', '2' will be treated as "number".
  16955. // `isFinit('')` get `true`.
  16956. if (val != null && isFinite(val) && val !== '') {
  16957. return false;
  16958. }
  16959. else if (isString(val) && val !== '-') {
  16960. return true;
  16961. }
  16962. }
  16963. return false;
  16964. }
  16965. /**
  16966. * ECharts global model
  16967. *
  16968. * @module {echarts/model/Global}
  16969. */
  16970. /**
  16971. * Caution: If the mechanism should be changed some day, these cases
  16972. * should be considered:
  16973. *
  16974. * (1) In `merge option` mode, if using the same option to call `setOption`
  16975. * many times, the result should be the same (try our best to ensure that).
  16976. * (2) In `merge option` mode, if a component has no id/name specified, it
  16977. * will be merged by index, and the result sequence of the components is
  16978. * consistent to the original sequence.
  16979. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  16980. * `mergeOption` in module:echarts/model/OptionManager.
  16981. */
  16982. var OPTION_INNER_KEY = '\0_ec_inner';
  16983. /**
  16984. * @alias module:echarts/model/Global
  16985. *
  16986. * @param {Object} option
  16987. * @param {module:echarts/model/Model} parentModel
  16988. * @param {Object} theme
  16989. */
  16990. var GlobalModel = Model.extend({
  16991. constructor: GlobalModel,
  16992. init: function (option, parentModel, theme, optionManager) {
  16993. theme = theme || {};
  16994. this.option = null; // Mark as not initialized.
  16995. /**
  16996. * @type {module:echarts/model/Model}
  16997. * @private
  16998. */
  16999. this._theme = new Model(theme);
  17000. /**
  17001. * @type {module:echarts/model/OptionManager}
  17002. */
  17003. this._optionManager = optionManager;
  17004. },
  17005. setOption: function (option, optionPreprocessorFuncs) {
  17006. assert$1(
  17007. !(OPTION_INNER_KEY in option),
  17008. 'please use chart.getOption()'
  17009. );
  17010. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17011. this.resetOption(null);
  17012. },
  17013. /**
  17014. * @param {string} type null/undefined: reset all.
  17015. * 'recreate': force recreate all.
  17016. * 'timeline': only reset timeline option
  17017. * 'media': only reset media query option
  17018. * @return {boolean} Whether option changed.
  17019. */
  17020. resetOption: function (type) {
  17021. var optionChanged = false;
  17022. var optionManager = this._optionManager;
  17023. if (!type || type === 'recreate') {
  17024. var baseOption = optionManager.mountOption(type === 'recreate');
  17025. if (!this.option || type === 'recreate') {
  17026. initBase.call(this, baseOption);
  17027. }
  17028. else {
  17029. this.restoreData();
  17030. this.mergeOption(baseOption);
  17031. }
  17032. optionChanged = true;
  17033. }
  17034. if (type === 'timeline' || type === 'media') {
  17035. this.restoreData();
  17036. }
  17037. if (!type || type === 'recreate' || type === 'timeline') {
  17038. var timelineOption = optionManager.getTimelineOption(this);
  17039. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17040. }
  17041. if (!type || type === 'recreate' || type === 'media') {
  17042. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17043. if (mediaOptions.length) {
  17044. each$1(mediaOptions, function (mediaOption) {
  17045. this.mergeOption(mediaOption, optionChanged = true);
  17046. }, this);
  17047. }
  17048. }
  17049. return optionChanged;
  17050. },
  17051. /**
  17052. * @protected
  17053. */
  17054. mergeOption: function (newOption) {
  17055. var option = this.option;
  17056. var componentsMap = this._componentsMap;
  17057. var newCptTypes = [];
  17058. resetSourceDefaulter(this);
  17059. // If no component class, merge directly.
  17060. // For example: color, animaiton options, etc.
  17061. each$1(newOption, function (componentOption, mainType) {
  17062. if (componentOption == null) {
  17063. return;
  17064. }
  17065. if (!ComponentModel.hasClass(mainType)) {
  17066. // globalSettingTask.dirty();
  17067. option[mainType] = option[mainType] == null
  17068. ? clone(componentOption)
  17069. : merge(option[mainType], componentOption, true);
  17070. }
  17071. else if (mainType) {
  17072. newCptTypes.push(mainType);
  17073. }
  17074. });
  17075. ComponentModel.topologicalTravel(
  17076. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17077. );
  17078. function visitComponent(mainType, dependencies) {
  17079. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17080. var mapResult = mappingToExists(
  17081. componentsMap.get(mainType), newCptOptionList
  17082. );
  17083. makeIdAndName(mapResult);
  17084. // Set mainType and complete subType.
  17085. each$1(mapResult, function (item, index) {
  17086. var opt = item.option;
  17087. if (isObject$1(opt)) {
  17088. item.keyInfo.mainType = mainType;
  17089. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17090. }
  17091. });
  17092. var dependentModels = getComponentsByTypes(
  17093. componentsMap, dependencies
  17094. );
  17095. option[mainType] = [];
  17096. componentsMap.set(mainType, []);
  17097. each$1(mapResult, function (resultItem, index) {
  17098. var componentModel = resultItem.exist;
  17099. var newCptOption = resultItem.option;
  17100. assert$1(
  17101. isObject$1(newCptOption) || componentModel,
  17102. 'Empty component definition'
  17103. );
  17104. // Consider where is no new option and should be merged using {},
  17105. // see removeEdgeAndAdd in topologicalTravel and
  17106. // ComponentModel.getAllClassMainTypes.
  17107. if (!newCptOption) {
  17108. componentModel.mergeOption({}, this);
  17109. componentModel.optionUpdated({}, false);
  17110. }
  17111. else {
  17112. var ComponentModelClass = ComponentModel.getClass(
  17113. mainType, resultItem.keyInfo.subType, true
  17114. );
  17115. if (componentModel && componentModel instanceof ComponentModelClass) {
  17116. componentModel.name = resultItem.keyInfo.name;
  17117. // componentModel.settingTask && componentModel.settingTask.dirty();
  17118. componentModel.mergeOption(newCptOption, this);
  17119. componentModel.optionUpdated(newCptOption, false);
  17120. }
  17121. else {
  17122. // PENDING Global as parent ?
  17123. var extraOpt = extend(
  17124. {
  17125. dependentModels: dependentModels,
  17126. componentIndex: index
  17127. },
  17128. resultItem.keyInfo
  17129. );
  17130. componentModel = new ComponentModelClass(
  17131. newCptOption, this, this, extraOpt
  17132. );
  17133. extend(componentModel, extraOpt);
  17134. componentModel.init(newCptOption, this, this, extraOpt);
  17135. // Call optionUpdated after init.
  17136. // newCptOption has been used as componentModel.option
  17137. // and may be merged with theme and default, so pass null
  17138. // to avoid confusion.
  17139. componentModel.optionUpdated(null, true);
  17140. }
  17141. }
  17142. componentsMap.get(mainType)[index] = componentModel;
  17143. option[mainType][index] = componentModel.option;
  17144. }, this);
  17145. // Backup series for filtering.
  17146. if (mainType === 'series') {
  17147. createSeriesIndices(this, componentsMap.get('series'));
  17148. }
  17149. }
  17150. this._seriesIndicesMap = createHashMap(
  17151. this._seriesIndices = this._seriesIndices || []
  17152. );
  17153. },
  17154. /**
  17155. * Get option for output (cloned option and inner info removed)
  17156. * @public
  17157. * @return {Object}
  17158. */
  17159. getOption: function () {
  17160. var option = clone(this.option);
  17161. each$1(option, function (opts, mainType) {
  17162. if (ComponentModel.hasClass(mainType)) {
  17163. var opts = normalizeToArray(opts);
  17164. for (var i = opts.length - 1; i >= 0; i--) {
  17165. // Remove options with inner id.
  17166. if (isIdInner(opts[i])) {
  17167. opts.splice(i, 1);
  17168. }
  17169. }
  17170. option[mainType] = opts;
  17171. }
  17172. });
  17173. delete option[OPTION_INNER_KEY];
  17174. return option;
  17175. },
  17176. /**
  17177. * @return {module:echarts/model/Model}
  17178. */
  17179. getTheme: function () {
  17180. return this._theme;
  17181. },
  17182. /**
  17183. * @param {string} mainType
  17184. * @param {number} [idx=0]
  17185. * @return {module:echarts/model/Component}
  17186. */
  17187. getComponent: function (mainType, idx) {
  17188. var list = this._componentsMap.get(mainType);
  17189. if (list) {
  17190. return list[idx || 0];
  17191. }
  17192. },
  17193. /**
  17194. * If none of index and id and name used, return all components with mainType.
  17195. * @param {Object} condition
  17196. * @param {string} condition.mainType
  17197. * @param {string} [condition.subType] If ignore, only query by mainType
  17198. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17199. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17200. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17201. * @return {Array.<module:echarts/model/Component>}
  17202. */
  17203. queryComponents: function (condition) {
  17204. var mainType = condition.mainType;
  17205. if (!mainType) {
  17206. return [];
  17207. }
  17208. var index = condition.index;
  17209. var id = condition.id;
  17210. var name = condition.name;
  17211. var cpts = this._componentsMap.get(mainType);
  17212. if (!cpts || !cpts.length) {
  17213. return [];
  17214. }
  17215. var result;
  17216. if (index != null) {
  17217. if (!isArray(index)) {
  17218. index = [index];
  17219. }
  17220. result = filter(map(index, function (idx) {
  17221. return cpts[idx];
  17222. }), function (val) {
  17223. return !!val;
  17224. });
  17225. }
  17226. else if (id != null) {
  17227. var isIdArray = isArray(id);
  17228. result = filter(cpts, function (cpt) {
  17229. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17230. || (!isIdArray && cpt.id === id);
  17231. });
  17232. }
  17233. else if (name != null) {
  17234. var isNameArray = isArray(name);
  17235. result = filter(cpts, function (cpt) {
  17236. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17237. || (!isNameArray && cpt.name === name);
  17238. });
  17239. }
  17240. else {
  17241. // Return all components with mainType
  17242. result = cpts.slice();
  17243. }
  17244. return filterBySubType(result, condition);
  17245. },
  17246. /**
  17247. * The interface is different from queryComponents,
  17248. * which is convenient for inner usage.
  17249. *
  17250. * @usage
  17251. * var result = findComponents(
  17252. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17253. * );
  17254. * var result = findComponents(
  17255. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17256. * );
  17257. * var result = findComponents(
  17258. * {mainType: 'series'},
  17259. * function (model, index) {...}
  17260. * );
  17261. * // result like [component0, componnet1, ...]
  17262. *
  17263. * @param {Object} condition
  17264. * @param {string} condition.mainType Mandatory.
  17265. * @param {string} [condition.subType] Optional.
  17266. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17267. * where xxx is mainType.
  17268. * If query attribute is null/undefined or has no index/id/name,
  17269. * do not filtering by query conditions, which is convenient for
  17270. * no-payload situations or when target of action is global.
  17271. * @param {Function} [condition.filter] parameter: component, return boolean.
  17272. * @return {Array.<module:echarts/model/Component>}
  17273. */
  17274. findComponents: function (condition) {
  17275. var query = condition.query;
  17276. var mainType = condition.mainType;
  17277. var queryCond = getQueryCond(query);
  17278. var result = queryCond
  17279. ? this.queryComponents(queryCond)
  17280. : this._componentsMap.get(mainType);
  17281. return doFilter(filterBySubType(result, condition));
  17282. function getQueryCond(q) {
  17283. var indexAttr = mainType + 'Index';
  17284. var idAttr = mainType + 'Id';
  17285. var nameAttr = mainType + 'Name';
  17286. return q && (
  17287. q[indexAttr] != null
  17288. || q[idAttr] != null
  17289. || q[nameAttr] != null
  17290. )
  17291. ? {
  17292. mainType: mainType,
  17293. // subType will be filtered finally.
  17294. index: q[indexAttr],
  17295. id: q[idAttr],
  17296. name: q[nameAttr]
  17297. }
  17298. : null;
  17299. }
  17300. function doFilter(res) {
  17301. return condition.filter
  17302. ? filter(res, condition.filter)
  17303. : res;
  17304. }
  17305. },
  17306. /**
  17307. * @usage
  17308. * eachComponent('legend', function (legendModel, index) {
  17309. * ...
  17310. * });
  17311. * eachComponent(function (componentType, model, index) {
  17312. * // componentType does not include subType
  17313. * // (componentType is 'xxx' but not 'xxx.aa')
  17314. * });
  17315. * eachComponent(
  17316. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17317. * function (model, index) {...}
  17318. * );
  17319. * eachComponent(
  17320. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17321. * function (model, index) {...}
  17322. * );
  17323. *
  17324. * @param {string|Object=} mainType When mainType is object, the definition
  17325. * is the same as the method 'findComponents'.
  17326. * @param {Function} cb
  17327. * @param {*} context
  17328. */
  17329. eachComponent: function (mainType, cb, context) {
  17330. var componentsMap = this._componentsMap;
  17331. if (typeof mainType === 'function') {
  17332. context = cb;
  17333. cb = mainType;
  17334. componentsMap.each(function (components, componentType) {
  17335. each$1(components, function (component, index) {
  17336. cb.call(context, componentType, component, index);
  17337. });
  17338. });
  17339. }
  17340. else if (isString(mainType)) {
  17341. each$1(componentsMap.get(mainType), cb, context);
  17342. }
  17343. else if (isObject$1(mainType)) {
  17344. var queryResult = this.findComponents(mainType);
  17345. each$1(queryResult, cb, context);
  17346. }
  17347. },
  17348. /**
  17349. * @param {string} name
  17350. * @return {Array.<module:echarts/model/Series>}
  17351. */
  17352. getSeriesByName: function (name) {
  17353. var series = this._componentsMap.get('series');
  17354. return filter(series, function (oneSeries) {
  17355. return oneSeries.name === name;
  17356. });
  17357. },
  17358. /**
  17359. * @param {number} seriesIndex
  17360. * @return {module:echarts/model/Series}
  17361. */
  17362. getSeriesByIndex: function (seriesIndex) {
  17363. return this._componentsMap.get('series')[seriesIndex];
  17364. },
  17365. /**
  17366. * @param {string} subType
  17367. * @return {Array.<module:echarts/model/Series>}
  17368. */
  17369. getSeriesByType: function (subType) {
  17370. var series = this._componentsMap.get('series');
  17371. return filter(series, function (oneSeries) {
  17372. return oneSeries.subType === subType;
  17373. });
  17374. },
  17375. /**
  17376. * @return {Array.<module:echarts/model/Series>}
  17377. */
  17378. getSeries: function () {
  17379. return this._componentsMap.get('series').slice();
  17380. },
  17381. /**
  17382. * @return {number}
  17383. */
  17384. getSeriesCount: function () {
  17385. return this._componentsMap.get('series').length;
  17386. },
  17387. /**
  17388. * After filtering, series may be different
  17389. * frome raw series.
  17390. *
  17391. * @param {Function} cb
  17392. * @param {*} context
  17393. */
  17394. eachSeries: function (cb, context) {
  17395. assertSeriesInitialized(this);
  17396. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17397. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17398. cb.call(context, series, rawSeriesIndex);
  17399. }, this);
  17400. },
  17401. /**
  17402. * Iterate raw series before filtered.
  17403. *
  17404. * @param {Function} cb
  17405. * @param {*} context
  17406. */
  17407. eachRawSeries: function (cb, context) {
  17408. each$1(this._componentsMap.get('series'), cb, context);
  17409. },
  17410. /**
  17411. * After filtering, series may be different.
  17412. * frome raw series.
  17413. *
  17414. * @parma {string} subType
  17415. * @param {Function} cb
  17416. * @param {*} context
  17417. */
  17418. eachSeriesByType: function (subType, cb, context) {
  17419. assertSeriesInitialized(this);
  17420. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17421. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17422. if (series.subType === subType) {
  17423. cb.call(context, series, rawSeriesIndex);
  17424. }
  17425. }, this);
  17426. },
  17427. /**
  17428. * Iterate raw series before filtered of given type.
  17429. *
  17430. * @parma {string} subType
  17431. * @param {Function} cb
  17432. * @param {*} context
  17433. */
  17434. eachRawSeriesByType: function (subType, cb, context) {
  17435. return each$1(this.getSeriesByType(subType), cb, context);
  17436. },
  17437. /**
  17438. * @param {module:echarts/model/Series} seriesModel
  17439. */
  17440. isSeriesFiltered: function (seriesModel) {
  17441. assertSeriesInitialized(this);
  17442. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17443. },
  17444. /**
  17445. * @return {Array.<number>}
  17446. */
  17447. getCurrentSeriesIndices: function () {
  17448. return (this._seriesIndices || []).slice();
  17449. },
  17450. /**
  17451. * @param {Function} cb
  17452. * @param {*} context
  17453. */
  17454. filterSeries: function (cb, context) {
  17455. assertSeriesInitialized(this);
  17456. var filteredSeries = filter(
  17457. this._componentsMap.get('series'), cb, context
  17458. );
  17459. createSeriesIndices(this, filteredSeries);
  17460. },
  17461. restoreData: function (payload) {
  17462. var componentsMap = this._componentsMap;
  17463. createSeriesIndices(this, componentsMap.get('series'));
  17464. var componentTypes = [];
  17465. componentsMap.each(function (components, componentType) {
  17466. componentTypes.push(componentType);
  17467. });
  17468. ComponentModel.topologicalTravel(
  17469. componentTypes,
  17470. ComponentModel.getAllClassMainTypes(),
  17471. function (componentType, dependencies) {
  17472. each$1(componentsMap.get(componentType), function (component) {
  17473. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  17474. && component.restoreData();
  17475. });
  17476. }
  17477. );
  17478. }
  17479. });
  17480. function isNotTargetSeries(seriesModel, payload) {
  17481. if (payload) {
  17482. var index = payload.seiresIndex;
  17483. var id = payload.seriesId;
  17484. var name = payload.seriesName;
  17485. return (index != null && seriesModel.componentIndex !== index)
  17486. || (id != null && seriesModel.id !== id)
  17487. || (name != null && seriesModel.name !== name);
  17488. }
  17489. }
  17490. /**
  17491. * @inner
  17492. */
  17493. function mergeTheme(option, theme) {
  17494. each$1(theme, function (themeItem, name) {
  17495. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  17496. if (!ComponentModel.hasClass(name)) {
  17497. if (typeof themeItem === 'object') {
  17498. option[name] = !option[name]
  17499. ? clone(themeItem)
  17500. : merge(option[name], themeItem, false);
  17501. }
  17502. else {
  17503. if (option[name] == null) {
  17504. option[name] = themeItem;
  17505. }
  17506. }
  17507. }
  17508. });
  17509. }
  17510. function initBase(baseOption) {
  17511. baseOption = baseOption;
  17512. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17513. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17514. this.option = {};
  17515. this.option[OPTION_INNER_KEY] = 1;
  17516. /**
  17517. * Init with series: [], in case of calling findSeries method
  17518. * before series initialized.
  17519. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17520. * @private
  17521. */
  17522. this._componentsMap = createHashMap({series: []});
  17523. /**
  17524. * Mapping between filtered series list and raw series list.
  17525. * key: filtered series indices, value: raw series indices.
  17526. * @type {Array.<nubmer>}
  17527. * @private
  17528. */
  17529. this._seriesIndices;
  17530. this._seriesIndicesMap;
  17531. mergeTheme(baseOption, this._theme.option);
  17532. // TODO Needs clone when merging to the unexisted property
  17533. merge(baseOption, globalDefault, false);
  17534. this.mergeOption(baseOption);
  17535. }
  17536. /**
  17537. * @inner
  17538. * @param {Array.<string>|string} types model types
  17539. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17540. */
  17541. function getComponentsByTypes(componentsMap, types) {
  17542. if (!isArray(types)) {
  17543. types = types ? [types] : [];
  17544. }
  17545. var ret = {};
  17546. each$1(types, function (type) {
  17547. ret[type] = (componentsMap.get(type) || []).slice();
  17548. });
  17549. return ret;
  17550. }
  17551. /**
  17552. * @inner
  17553. */
  17554. function determineSubType(mainType, newCptOption, existComponent) {
  17555. var subType = newCptOption.type
  17556. ? newCptOption.type
  17557. : existComponent
  17558. ? existComponent.subType
  17559. // Use determineSubType only when there is no existComponent.
  17560. : ComponentModel.determineSubType(mainType, newCptOption);
  17561. // tooltip, markline, markpoint may always has no subType
  17562. return subType;
  17563. }
  17564. /**
  17565. * @inner
  17566. */
  17567. function createSeriesIndices(ecModel, seriesModels) {
  17568. ecModel._seriesIndicesMap = createHashMap(
  17569. ecModel._seriesIndices = map(seriesModels, function (series) {
  17570. return series.componentIndex;
  17571. }) || []
  17572. );
  17573. }
  17574. /**
  17575. * @inner
  17576. */
  17577. function filterBySubType(components, condition) {
  17578. // Using hasOwnProperty for restrict. Consider
  17579. // subType is undefined in user payload.
  17580. return condition.hasOwnProperty('subType')
  17581. ? filter(components, function (cpt) {
  17582. return cpt.subType === condition.subType;
  17583. })
  17584. : components;
  17585. }
  17586. /**
  17587. * @inner
  17588. */
  17589. function assertSeriesInitialized(ecModel) {
  17590. // Components that use _seriesIndices should depends on series component,
  17591. // which make sure that their initialization is after series.
  17592. if (__DEV__) {
  17593. if (!ecModel._seriesIndices) {
  17594. throw new Error('Option should contains series.');
  17595. }
  17596. }
  17597. }
  17598. mixin(GlobalModel, colorPaletteMixin);
  17599. var echartsAPIList = [
  17600. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17601. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17602. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17603. ];
  17604. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17605. function ExtensionAPI(chartInstance) {
  17606. each$1(echartsAPIList, function (name) {
  17607. this[name] = bind(chartInstance[name], chartInstance);
  17608. }, this);
  17609. }
  17610. var coordinateSystemCreators = {};
  17611. function CoordinateSystemManager() {
  17612. this._coordinateSystems = [];
  17613. }
  17614. CoordinateSystemManager.prototype = {
  17615. constructor: CoordinateSystemManager,
  17616. create: function (ecModel, api) {
  17617. var coordinateSystems = [];
  17618. each$1(coordinateSystemCreators, function (creater, type) {
  17619. var list = creater.create(ecModel, api);
  17620. coordinateSystems = coordinateSystems.concat(list || []);
  17621. });
  17622. this._coordinateSystems = coordinateSystems;
  17623. },
  17624. update: function (ecModel, api) {
  17625. each$1(this._coordinateSystems, function (coordSys) {
  17626. coordSys.update && coordSys.update(ecModel, api);
  17627. });
  17628. },
  17629. getCoordinateSystems: function () {
  17630. return this._coordinateSystems.slice();
  17631. }
  17632. };
  17633. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17634. coordinateSystemCreators[type] = coordinateSystemCreator;
  17635. };
  17636. CoordinateSystemManager.get = function (type) {
  17637. return coordinateSystemCreators[type];
  17638. };
  17639. /**
  17640. * ECharts option manager
  17641. *
  17642. * @module {echarts/model/OptionManager}
  17643. */
  17644. var each$4 = each$1;
  17645. var clone$3 = clone;
  17646. var map$1 = map;
  17647. var merge$1 = merge;
  17648. var QUERY_REG = /^(min|max)?(.+)$/;
  17649. /**
  17650. * TERM EXPLANATIONS:
  17651. *
  17652. * [option]:
  17653. *
  17654. * An object that contains definitions of components. For example:
  17655. * var option = {
  17656. * title: {...},
  17657. * legend: {...},
  17658. * visualMap: {...},
  17659. * series: [
  17660. * {data: [...]},
  17661. * {data: [...]},
  17662. * ...
  17663. * ]
  17664. * };
  17665. *
  17666. * [rawOption]:
  17667. *
  17668. * An object input to echarts.setOption. 'rawOption' may be an
  17669. * 'option', or may be an object contains multi-options. For example:
  17670. * var option = {
  17671. * baseOption: {
  17672. * title: {...},
  17673. * legend: {...},
  17674. * series: [
  17675. * {data: [...]},
  17676. * {data: [...]},
  17677. * ...
  17678. * ]
  17679. * },
  17680. * timeline: {...},
  17681. * options: [
  17682. * {title: {...}, series: {data: [...]}},
  17683. * {title: {...}, series: {data: [...]}},
  17684. * ...
  17685. * ],
  17686. * media: [
  17687. * {
  17688. * query: {maxWidth: 320},
  17689. * option: {series: {x: 20}, visualMap: {show: false}}
  17690. * },
  17691. * {
  17692. * query: {minWidth: 320, maxWidth: 720},
  17693. * option: {series: {x: 500}, visualMap: {show: true}}
  17694. * },
  17695. * {
  17696. * option: {series: {x: 1200}, visualMap: {show: true}}
  17697. * }
  17698. * ]
  17699. * };
  17700. *
  17701. * @alias module:echarts/model/OptionManager
  17702. * @param {module:echarts/ExtensionAPI} api
  17703. */
  17704. function OptionManager(api) {
  17705. /**
  17706. * @private
  17707. * @type {module:echarts/ExtensionAPI}
  17708. */
  17709. this._api = api;
  17710. /**
  17711. * @private
  17712. * @type {Array.<number>}
  17713. */
  17714. this._timelineOptions = [];
  17715. /**
  17716. * @private
  17717. * @type {Array.<Object>}
  17718. */
  17719. this._mediaList = [];
  17720. /**
  17721. * @private
  17722. * @type {Object}
  17723. */
  17724. this._mediaDefault;
  17725. /**
  17726. * -1, means default.
  17727. * empty means no media.
  17728. * @private
  17729. * @type {Array.<number>}
  17730. */
  17731. this._currentMediaIndices = [];
  17732. /**
  17733. * @private
  17734. * @type {Object}
  17735. */
  17736. this._optionBackup;
  17737. /**
  17738. * @private
  17739. * @type {Object}
  17740. */
  17741. this._newBaseOption;
  17742. }
  17743. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17744. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17745. // rawOption cloned and backuped when timeline changed, which does no
  17746. // good to performance. What's more, that both timeline and setOption
  17747. // method supply 'notMerge' brings complex and some problems.
  17748. // Consider this case:
  17749. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17750. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17751. OptionManager.prototype = {
  17752. constructor: OptionManager,
  17753. /**
  17754. * @public
  17755. * @param {Object} rawOption Raw option.
  17756. * @param {module:echarts/model/Global} ecModel
  17757. * @param {Array.<Function>} optionPreprocessorFuncs
  17758. * @return {Object} Init option
  17759. */
  17760. setOption: function (rawOption, optionPreprocessorFuncs) {
  17761. if (rawOption) {
  17762. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17763. each$1(normalizeToArray(rawOption.series), function (series) {
  17764. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17765. });
  17766. }
  17767. // Caution: some series modify option data, if do not clone,
  17768. // it should ensure that the repeat modify correctly
  17769. // (create a new object when modify itself).
  17770. rawOption = clone$3(rawOption, true);
  17771. // FIXME
  17772. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17773. var oldOptionBackup = this._optionBackup;
  17774. var newParsedOption = parseRawOption.call(
  17775. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17776. );
  17777. this._newBaseOption = newParsedOption.baseOption;
  17778. // For setOption at second time (using merge mode);
  17779. if (oldOptionBackup) {
  17780. // Only baseOption can be merged.
  17781. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17782. // For simplicity, timeline options and media options do not support merge,
  17783. // that is, if you `setOption` twice and both has timeline options, the latter
  17784. // timeline opitons will not be merged to the formers, but just substitude them.
  17785. if (newParsedOption.timelineOptions.length) {
  17786. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17787. }
  17788. if (newParsedOption.mediaList.length) {
  17789. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17790. }
  17791. if (newParsedOption.mediaDefault) {
  17792. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17793. }
  17794. }
  17795. else {
  17796. this._optionBackup = newParsedOption;
  17797. }
  17798. },
  17799. /**
  17800. * @param {boolean} isRecreate
  17801. * @return {Object}
  17802. */
  17803. mountOption: function (isRecreate) {
  17804. var optionBackup = this._optionBackup;
  17805. // TODO
  17806. // 如果没有reset功能则不clone。
  17807. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17808. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17809. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17810. this._currentMediaIndices = [];
  17811. return clone$3(isRecreate
  17812. // this._optionBackup.baseOption, which is created at the first `setOption`
  17813. // called, and is merged into every new option by inner method `mergeOption`
  17814. // each time `setOption` called, can be only used in `isRecreate`, because
  17815. // its reliability is under suspicion. In other cases option merge is
  17816. // performed by `model.mergeOption`.
  17817. ? optionBackup.baseOption : this._newBaseOption
  17818. );
  17819. },
  17820. /**
  17821. * @param {module:echarts/model/Global} ecModel
  17822. * @return {Object}
  17823. */
  17824. getTimelineOption: function (ecModel) {
  17825. var option;
  17826. var timelineOptions = this._timelineOptions;
  17827. if (timelineOptions.length) {
  17828. // getTimelineOption can only be called after ecModel inited,
  17829. // so we can get currentIndex from timelineModel.
  17830. var timelineModel = ecModel.getComponent('timeline');
  17831. if (timelineModel) {
  17832. option = clone$3(
  17833. timelineOptions[timelineModel.getCurrentIndex()],
  17834. true
  17835. );
  17836. }
  17837. }
  17838. return option;
  17839. },
  17840. /**
  17841. * @param {module:echarts/model/Global} ecModel
  17842. * @return {Array.<Object>}
  17843. */
  17844. getMediaOption: function (ecModel) {
  17845. var ecWidth = this._api.getWidth();
  17846. var ecHeight = this._api.getHeight();
  17847. var mediaList = this._mediaList;
  17848. var mediaDefault = this._mediaDefault;
  17849. var indices = [];
  17850. var result = [];
  17851. // No media defined.
  17852. if (!mediaList.length && !mediaDefault) {
  17853. return result;
  17854. }
  17855. // Multi media may be applied, the latter defined media has higher priority.
  17856. for (var i = 0, len = mediaList.length; i < len; i++) {
  17857. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17858. indices.push(i);
  17859. }
  17860. }
  17861. // FIXME
  17862. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17863. if (!indices.length && mediaDefault) {
  17864. indices = [-1];
  17865. }
  17866. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17867. result = map$1(indices, function (index) {
  17868. return clone$3(
  17869. index === -1 ? mediaDefault.option : mediaList[index].option
  17870. );
  17871. });
  17872. }
  17873. // Otherwise return nothing.
  17874. this._currentMediaIndices = indices;
  17875. return result;
  17876. }
  17877. };
  17878. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17879. var timelineOptions = [];
  17880. var mediaList = [];
  17881. var mediaDefault;
  17882. var baseOption;
  17883. // Compatible with ec2.
  17884. var timelineOpt = rawOption.timeline;
  17885. if (rawOption.baseOption) {
  17886. baseOption = rawOption.baseOption;
  17887. }
  17888. // For timeline
  17889. if (timelineOpt || rawOption.options) {
  17890. baseOption = baseOption || {};
  17891. timelineOptions = (rawOption.options || []).slice();
  17892. }
  17893. // For media query
  17894. if (rawOption.media) {
  17895. baseOption = baseOption || {};
  17896. var media = rawOption.media;
  17897. each$4(media, function (singleMedia) {
  17898. if (singleMedia && singleMedia.option) {
  17899. if (singleMedia.query) {
  17900. mediaList.push(singleMedia);
  17901. }
  17902. else if (!mediaDefault) {
  17903. // Use the first media default.
  17904. mediaDefault = singleMedia;
  17905. }
  17906. }
  17907. });
  17908. }
  17909. // For normal option
  17910. if (!baseOption) {
  17911. baseOption = rawOption;
  17912. }
  17913. // Set timelineOpt to baseOption in ec3,
  17914. // which is convenient for merge option.
  17915. if (!baseOption.timeline) {
  17916. baseOption.timeline = timelineOpt;
  17917. }
  17918. // Preprocess.
  17919. each$4([baseOption].concat(timelineOptions)
  17920. .concat(map(mediaList, function (media) {
  17921. return media.option;
  17922. })),
  17923. function (option) {
  17924. each$4(optionPreprocessorFuncs, function (preProcess) {
  17925. preProcess(option, isNew);
  17926. });
  17927. }
  17928. );
  17929. return {
  17930. baseOption: baseOption,
  17931. timelineOptions: timelineOptions,
  17932. mediaDefault: mediaDefault,
  17933. mediaList: mediaList
  17934. };
  17935. }
  17936. /**
  17937. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17938. * Support: width, height, aspectRatio
  17939. * Can use max or min as prefix.
  17940. */
  17941. function applyMediaQuery(query, ecWidth, ecHeight) {
  17942. var realMap = {
  17943. width: ecWidth,
  17944. height: ecHeight,
  17945. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17946. };
  17947. var applicatable = true;
  17948. each$1(query, function (value, attr) {
  17949. var matched = attr.match(QUERY_REG);
  17950. if (!matched || !matched[1] || !matched[2]) {
  17951. return;
  17952. }
  17953. var operator = matched[1];
  17954. var realAttr = matched[2].toLowerCase();
  17955. if (!compare(realMap[realAttr], value, operator)) {
  17956. applicatable = false;
  17957. }
  17958. });
  17959. return applicatable;
  17960. }
  17961. function compare(real, expect, operator) {
  17962. if (operator === 'min') {
  17963. return real >= expect;
  17964. }
  17965. else if (operator === 'max') {
  17966. return real <= expect;
  17967. }
  17968. else { // Equals
  17969. return real === expect;
  17970. }
  17971. }
  17972. function indicesEquals(indices1, indices2) {
  17973. // indices is always order by asc and has only finite number.
  17974. return indices1.join(',') === indices2.join(',');
  17975. }
  17976. /**
  17977. * Consider case:
  17978. * `chart.setOption(opt1);`
  17979. * Then user do some interaction like dataZoom, dataView changing.
  17980. * `chart.setOption(opt2);`
  17981. * Then user press 'reset button' in toolbox.
  17982. *
  17983. * After doing that all of the interaction effects should be reset, the
  17984. * chart should be the same as the result of invoke
  17985. * `chart.setOption(opt1); chart.setOption(opt2);`.
  17986. *
  17987. * Although it is not able ensure that
  17988. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  17989. * `chart.setOption(merge(opt1, opt2));` exactly,
  17990. * this might be the only simple way to implement that feature.
  17991. *
  17992. * MEMO: We've considered some other approaches:
  17993. * 1. Each model handle its self restoration but not uniform treatment.
  17994. * (Too complex in logic and error-prone)
  17995. * 2. Use a shadow ecModel. (Performace expensive)
  17996. */
  17997. function mergeOption(oldOption, newOption) {
  17998. newOption = newOption || {};
  17999. each$4(newOption, function (newCptOpt, mainType) {
  18000. if (newCptOpt == null) {
  18001. return;
  18002. }
  18003. var oldCptOpt = oldOption[mainType];
  18004. if (!ComponentModel.hasClass(mainType)) {
  18005. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18006. }
  18007. else {
  18008. newCptOpt = normalizeToArray(newCptOpt);
  18009. oldCptOpt = normalizeToArray(oldCptOpt);
  18010. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18011. oldOption[mainType] = map$1(mapResult, function (item) {
  18012. return (item.option && item.exist)
  18013. ? merge$1(item.exist, item.option, true)
  18014. : (item.exist || item.option);
  18015. });
  18016. }
  18017. });
  18018. }
  18019. var each$5 = each$1;
  18020. var isObject$3 = isObject$1;
  18021. var POSSIBLE_STYLES = [
  18022. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18023. 'chordStyle', 'label', 'labelLine'
  18024. ];
  18025. function compatEC2ItemStyle(opt) {
  18026. var itemStyleOpt = opt && opt.itemStyle;
  18027. if (!itemStyleOpt) {
  18028. return;
  18029. }
  18030. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18031. var styleName = POSSIBLE_STYLES[i];
  18032. var normalItemStyleOpt = itemStyleOpt.normal;
  18033. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18034. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18035. opt[styleName] = opt[styleName] || {};
  18036. if (!opt[styleName].normal) {
  18037. opt[styleName].normal = normalItemStyleOpt[styleName];
  18038. }
  18039. else {
  18040. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18041. }
  18042. normalItemStyleOpt[styleName] = null;
  18043. }
  18044. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18045. opt[styleName] = opt[styleName] || {};
  18046. if (!opt[styleName].emphasis) {
  18047. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18048. }
  18049. else {
  18050. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18051. }
  18052. emphasisItemStyleOpt[styleName] = null;
  18053. }
  18054. }
  18055. }
  18056. function convertNormalEmphasis(opt, optType, useExtend) {
  18057. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18058. var normalOpt = opt[optType].normal;
  18059. var emphasisOpt = opt[optType].emphasis;
  18060. if (normalOpt) {
  18061. // Timeline controlStyle has other properties besides normal and emphasis
  18062. if (useExtend) {
  18063. opt[optType].normal = opt[optType].emphasis = null;
  18064. defaults(opt[optType], normalOpt);
  18065. }
  18066. else {
  18067. opt[optType] = normalOpt;
  18068. }
  18069. }
  18070. if (emphasisOpt) {
  18071. opt.emphasis = opt.emphasis || {};
  18072. opt.emphasis[optType] = emphasisOpt;
  18073. }
  18074. }
  18075. }
  18076. function removeEC3NormalStatus(opt) {
  18077. convertNormalEmphasis(opt, 'itemStyle');
  18078. convertNormalEmphasis(opt, 'lineStyle');
  18079. convertNormalEmphasis(opt, 'areaStyle');
  18080. convertNormalEmphasis(opt, 'label');
  18081. convertNormalEmphasis(opt, 'labelLine');
  18082. // treemap
  18083. convertNormalEmphasis(opt, 'upperLabel');
  18084. // graph
  18085. convertNormalEmphasis(opt, 'edgeLabel');
  18086. }
  18087. function compatTextStyle(labelOpt) {
  18088. var textStyle = isObject$3(labelOpt) && labelOpt.textStyle;
  18089. if (textStyle) {
  18090. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18091. var propName = TEXT_STYLE_OPTIONS[i];
  18092. if (textStyle.hasOwnProperty(propName)) {
  18093. labelOpt[propName] = textStyle[propName];
  18094. }
  18095. }
  18096. }
  18097. }
  18098. function compatEC3CommonStyles(opt) {
  18099. if (opt) {
  18100. removeEC3NormalStatus(opt);
  18101. compatTextStyle(opt.label);
  18102. opt.emphasis && compatTextStyle(opt.emphasis.label);
  18103. }
  18104. }
  18105. function processSeries(seriesOpt) {
  18106. if (!isObject$3(seriesOpt)) {
  18107. return;
  18108. }
  18109. compatEC2ItemStyle(seriesOpt);
  18110. removeEC3NormalStatus(seriesOpt);
  18111. compatTextStyle(seriesOpt.label);
  18112. // treemap
  18113. compatTextStyle(seriesOpt.upperLabel);
  18114. // graph
  18115. compatTextStyle(seriesOpt.edgeLabel);
  18116. if (seriesOpt.emphasis) {
  18117. compatTextStyle(seriesOpt.emphasis.label);
  18118. // treemap
  18119. compatTextStyle(seriesOpt.emphasis.upperLabel);
  18120. // graph
  18121. compatTextStyle(seriesOpt.emphasis.edgeLabel);
  18122. }
  18123. var markPoint = seriesOpt.markPoint;
  18124. if (markPoint) {
  18125. compatEC2ItemStyle(markPoint);
  18126. compatEC3CommonStyles(markPoint);
  18127. }
  18128. var markLine = seriesOpt.markLine;
  18129. if (markLine) {
  18130. compatEC2ItemStyle(markLine);
  18131. compatEC3CommonStyles(markLine);
  18132. }
  18133. var markArea = seriesOpt.markArea;
  18134. if (markArea) {
  18135. compatEC3CommonStyles(markArea);
  18136. }
  18137. var data = seriesOpt.data;
  18138. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18139. // then the backward compat based on option type will not be performed.
  18140. if (seriesOpt.type === 'graph') {
  18141. data = data || seriesOpt.nodes;
  18142. var edgeData = seriesOpt.links || seriesOpt.edges;
  18143. if (edgeData && !isTypedArray(edgeData)) {
  18144. for (var i = 0; i < edgeData.length; i++) {
  18145. compatEC3CommonStyles(edgeData[i]);
  18146. }
  18147. }
  18148. each$1(seriesOpt.categories, function (opt) {
  18149. removeEC3NormalStatus(opt);
  18150. });
  18151. }
  18152. if (data && !isTypedArray(data)) {
  18153. for (var i = 0; i < data.length; i++) {
  18154. compatEC3CommonStyles(data[i]);
  18155. }
  18156. }
  18157. // mark point data
  18158. var markPoint = seriesOpt.markPoint;
  18159. if (markPoint && markPoint.data) {
  18160. var mpData = markPoint.data;
  18161. for (var i = 0; i < mpData.length; i++) {
  18162. compatEC3CommonStyles(mpData[i]);
  18163. }
  18164. }
  18165. // mark line data
  18166. var markLine = seriesOpt.markLine;
  18167. if (markLine && markLine.data) {
  18168. var mlData = markLine.data;
  18169. for (var i = 0; i < mlData.length; i++) {
  18170. if (isArray(mlData[i])) {
  18171. compatEC3CommonStyles(mlData[i][0]);
  18172. compatEC3CommonStyles(mlData[i][1]);
  18173. }
  18174. else {
  18175. compatEC3CommonStyles(mlData[i]);
  18176. }
  18177. }
  18178. }
  18179. // Series
  18180. if (seriesOpt.type === 'gauge') {
  18181. compatTextStyle(seriesOpt, 'axisLabel');
  18182. compatTextStyle(seriesOpt, 'title');
  18183. compatTextStyle(seriesOpt, 'detail');
  18184. }
  18185. else if (seriesOpt.type === 'treemap') {
  18186. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18187. each$1(seriesOpt.levels, function (opt) {
  18188. removeEC3NormalStatus(opt);
  18189. });
  18190. }
  18191. // sunburst starts from ec4, so it does not need to compat levels.
  18192. }
  18193. function toArr(o) {
  18194. return isArray(o) ? o : o ? [o] : [];
  18195. }
  18196. function toObj(o) {
  18197. return (isArray(o) ? o[0] : o) || {};
  18198. }
  18199. var compatStyle = function (option, isTheme) {
  18200. each$5(toArr(option.series), function (seriesOpt) {
  18201. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18202. });
  18203. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18204. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18205. each$5(
  18206. axes,
  18207. function (axisName) {
  18208. each$5(toArr(option[axisName]), function (axisOpt) {
  18209. if (axisOpt) {
  18210. compatTextStyle(axisOpt, 'axisLabel');
  18211. compatTextStyle(axisOpt.axisPointer, 'label');
  18212. }
  18213. });
  18214. }
  18215. );
  18216. each$5(toArr(option.parallel), function (parallelOpt) {
  18217. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18218. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18219. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18220. });
  18221. each$5(toArr(option.calendar), function (calendarOpt) {
  18222. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18223. compatTextStyle(calendarOpt, 'dayLabel');
  18224. compatTextStyle(calendarOpt, 'monthLabel');
  18225. compatTextStyle(calendarOpt, 'yearLabel');
  18226. });
  18227. // radar.name.textStyle
  18228. each$5(toArr(option.radar), function (radarOpt) {
  18229. compatTextStyle(radarOpt, 'name');
  18230. });
  18231. each$5(toArr(option.geo), function (geoOpt) {
  18232. if (isObject$3(geoOpt)) {
  18233. compatEC3CommonStyles(geoOpt);
  18234. each$5(toArr(geoOpt.regions), function (regionObj) {
  18235. compatEC3CommonStyles(regionObj);
  18236. });
  18237. }
  18238. });
  18239. each$5(toArr(option.timeline), function (timelineOpt) {
  18240. compatEC3CommonStyles(timelineOpt);
  18241. convertNormalEmphasis(timelineOpt, 'label');
  18242. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18243. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18244. convertNormalEmphasis(timelineOpt, 'checkpointStyle');
  18245. var data = timelineOpt.data;
  18246. isArray(data) && each$1(data, function (item) {
  18247. if (isObject$1(item)) {
  18248. convertNormalEmphasis(item, 'label');
  18249. convertNormalEmphasis(item, 'itemStyle');
  18250. }
  18251. });
  18252. });
  18253. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18254. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18255. each$5(toolboxOpt.feature, function (featureOpt) {
  18256. convertNormalEmphasis(featureOpt, 'iconStyle');
  18257. });
  18258. });
  18259. compatTextStyle(toObj(option.axisPointer), 'label');
  18260. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18261. };
  18262. // Compatitable with 2.0
  18263. function get(opt, path) {
  18264. path = path.split(',');
  18265. var obj = opt;
  18266. for (var i = 0; i < path.length; i++) {
  18267. obj = obj && obj[path[i]];
  18268. if (obj == null) {
  18269. break;
  18270. }
  18271. }
  18272. return obj;
  18273. }
  18274. function set$1(opt, path, val, overwrite) {
  18275. path = path.split(',');
  18276. var obj = opt;
  18277. var key;
  18278. for (var i = 0; i < path.length - 1; i++) {
  18279. key = path[i];
  18280. if (obj[key] == null) {
  18281. obj[key] = {};
  18282. }
  18283. obj = obj[key];
  18284. }
  18285. if (overwrite || obj[path[i]] == null) {
  18286. obj[path[i]] = val;
  18287. }
  18288. }
  18289. function compatLayoutProperties(option) {
  18290. each$1(LAYOUT_PROPERTIES, function (prop) {
  18291. if (prop[0] in option && !(prop[1] in option)) {
  18292. option[prop[1]] = option[prop[0]];
  18293. }
  18294. });
  18295. }
  18296. var LAYOUT_PROPERTIES = [
  18297. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18298. ];
  18299. var COMPATITABLE_COMPONENTS = [
  18300. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18301. ];
  18302. var backwardCompat = function (option, isTheme) {
  18303. compatStyle(option, isTheme);
  18304. // Make sure series array for model initialization.
  18305. option.series = normalizeToArray(option.series);
  18306. each$1(option.series, function (seriesOpt) {
  18307. if (!isObject$1(seriesOpt)) {
  18308. return;
  18309. }
  18310. var seriesType = seriesOpt.type;
  18311. if (seriesType === 'pie' || seriesType === 'gauge') {
  18312. if (seriesOpt.clockWise != null) {
  18313. seriesOpt.clockwise = seriesOpt.clockWise;
  18314. }
  18315. }
  18316. if (seriesType === 'gauge') {
  18317. var pointerColor = get(seriesOpt, 'pointer.color');
  18318. pointerColor != null
  18319. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18320. }
  18321. compatLayoutProperties(seriesOpt);
  18322. });
  18323. // dataRange has changed to visualMap
  18324. if (option.dataRange) {
  18325. option.visualMap = option.dataRange;
  18326. }
  18327. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18328. var options = option[componentName];
  18329. if (options) {
  18330. if (!isArray(options)) {
  18331. options = [options];
  18332. }
  18333. each$1(options, function (option) {
  18334. compatLayoutProperties(option);
  18335. });
  18336. }
  18337. });
  18338. };
  18339. // TODO
  18340. // ??? refactor? check the outer usage of data provider.
  18341. // merge with defaultDimValueGetter?
  18342. /**
  18343. * If normal array used, mutable chunk size is supported.
  18344. * If typed array used, chunk size must be fixed.
  18345. */
  18346. function DefaultDataProvider(source, dimSize) {
  18347. if (!Source.isInstance(source)) {
  18348. source = Source.seriesDataToSource(source);
  18349. }
  18350. this._source = source;
  18351. var data = this._data = source.data;
  18352. var sourceFormat = source.sourceFormat;
  18353. // Typed array. TODO IE10+?
  18354. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18355. if (__DEV__) {
  18356. if (dimSize == null) {
  18357. throw new Error('Typed array data must specify dimension size');
  18358. }
  18359. }
  18360. this._offset = 0;
  18361. this._dimSize = dimSize;
  18362. this._data = data;
  18363. }
  18364. var methods = providerMethods[
  18365. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  18366. ? sourceFormat + '_' + source.seriesLayoutBy
  18367. : sourceFormat
  18368. ];
  18369. if (__DEV__) {
  18370. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18371. }
  18372. extend(this, methods);
  18373. }
  18374. var providerProto = DefaultDataProvider.prototype;
  18375. // If data is pure without style configuration
  18376. providerProto.pure = false;
  18377. // If data is persistent and will not be released after use.
  18378. providerProto.persistent = true;
  18379. // ???! FIXME legacy data provider do not has method getSource
  18380. providerProto.getSource = function () {
  18381. return this._source;
  18382. };
  18383. var providerMethods = {
  18384. 'arrayRows_column': {
  18385. pure: true,
  18386. count: function () {
  18387. return Math.max(0, this._data.length - this._source.startIndex);
  18388. },
  18389. getItem: function (idx) {
  18390. return this._data[idx + this._source.startIndex];
  18391. },
  18392. appendData: appendDataSimply
  18393. },
  18394. 'arrayRows_row': {
  18395. pure: true,
  18396. count: function () {
  18397. var row = this._data[0];
  18398. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  18399. },
  18400. getItem: function (idx) {
  18401. idx += this._source.startIndex;
  18402. var item = [];
  18403. var data = this._data;
  18404. for (var i = 0; i < data.length; i++) {
  18405. var row = data[i];
  18406. item.push(row ? row[idx] : null);
  18407. }
  18408. return item;
  18409. },
  18410. appendData: function () {
  18411. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18412. }
  18413. },
  18414. 'objectRows': {
  18415. pure: true,
  18416. count: countSimply,
  18417. getItem: getItemSimply,
  18418. appendData: appendDataSimply
  18419. },
  18420. 'keyedColumns': {
  18421. pure: true,
  18422. count: function () {
  18423. var dimName = this._source.dimensionsDefine[0].name;
  18424. var col = this._data[dimName];
  18425. return col ? col.length : 0;
  18426. },
  18427. getItem: function (idx) {
  18428. var item = [];
  18429. var dims = this._source.dimensionsDefine;
  18430. for (var i = 0; i < dims.length; i++) {
  18431. var col = this._data[dims[i].name];
  18432. item.push(col ? col[idx] : null);
  18433. }
  18434. return item;
  18435. },
  18436. appendData: function (newData) {
  18437. var data = this._data;
  18438. each$1(newData, function (newCol, key) {
  18439. var oldCol = data[key] || (data[key] = []);
  18440. for (var i = 0; i < (newCol || []).length; i++) {
  18441. oldCol.push(newCol[i]);
  18442. }
  18443. });
  18444. }
  18445. },
  18446. 'original': {
  18447. count: countSimply,
  18448. getItem: getItemSimply,
  18449. appendData: appendDataSimply
  18450. },
  18451. 'typedArray': {
  18452. persistent: false,
  18453. pure: true,
  18454. count: function () {
  18455. return this._data ? (this._data.length / this._dimSize) : 0;
  18456. },
  18457. getItem: function (idx) {
  18458. idx = idx - this._offset;
  18459. var item = [];
  18460. var offset = this._dimSize * idx;
  18461. for (var i = 0; i < this._dimSize; i++) {
  18462. item[i] = this._data[offset + i];
  18463. }
  18464. return item;
  18465. },
  18466. appendData: function (newData) {
  18467. if (__DEV__) {
  18468. assert$1(
  18469. isTypedArray(newData),
  18470. 'Added data must be TypedArray if data in initialization is TypedArray'
  18471. );
  18472. }
  18473. this._data = newData;
  18474. },
  18475. // Clean self if data is already used.
  18476. clean: function () {
  18477. // PENDING
  18478. this._offset += this.count();
  18479. this._data = null;
  18480. }
  18481. }
  18482. };
  18483. function countSimply() {
  18484. return this._data.length;
  18485. }
  18486. function getItemSimply(idx) {
  18487. return this._data[idx];
  18488. }
  18489. function appendDataSimply(newData) {
  18490. for (var i = 0; i < newData.length; i++) {
  18491. this._data.push(newData[i]);
  18492. }
  18493. }
  18494. var rawValueGetters = {
  18495. arrayRows: getRawValueSimply,
  18496. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  18497. return dimIndex != null ? dataItem[dimName] : dataItem;
  18498. },
  18499. keyedColumns: getRawValueSimply,
  18500. original: function (dataItem, dataIndex, dimIndex, dimName) {
  18501. // FIXME
  18502. // In some case (markpoint in geo (geo-map.html)), dataItem
  18503. // is {coord: [...]}
  18504. var value = getDataItemValue(dataItem);
  18505. return (dimIndex == null || !(value instanceof Array))
  18506. ? value
  18507. : value[dimIndex];
  18508. },
  18509. typedArray: getRawValueSimply
  18510. };
  18511. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18512. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18513. }
  18514. var defaultDimValueGetters = {
  18515. arrayRows: getDimValueSimply,
  18516. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18517. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18518. },
  18519. keyedColumns: getDimValueSimply,
  18520. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18521. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18522. // If dataItem is an plain object with no value field, the var `value`
  18523. // will be assigned with the object, but it will be tread correctly
  18524. // in the `convertDataValue`.
  18525. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18526. // If any dataItem is like { value: 10 }
  18527. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18528. this.hasItemOption = true;
  18529. }
  18530. return converDataValue(
  18531. (value instanceof Array)
  18532. ? value[dimIndex]
  18533. // If value is a single number or something else not array.
  18534. : value,
  18535. this._dimensionInfos[dimName]
  18536. );
  18537. },
  18538. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18539. return dataItem[dimIndex];
  18540. }
  18541. };
  18542. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18543. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18544. }
  18545. /**
  18546. * This helper method convert value in data.
  18547. * @param {string|number|Date} value
  18548. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18549. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18550. */
  18551. function converDataValue(value, dimInfo) {
  18552. // Performance sensitive.
  18553. var dimType = dimInfo && dimInfo.type;
  18554. if (dimType === 'ordinal') {
  18555. // If given value is a category string
  18556. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18557. return ordinalMeta
  18558. ? ordinalMeta.parseAndCollect(value)
  18559. : value;
  18560. }
  18561. if (dimType === 'time'
  18562. // spead up when using timestamp
  18563. && typeof value !== 'number'
  18564. && value != null
  18565. && value !== '-'
  18566. ) {
  18567. value = +parseDate(value);
  18568. }
  18569. // dimType defaults 'number'.
  18570. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18571. // parse to NaN.
  18572. return (value == null || value === '')
  18573. ? NaN
  18574. // If string (like '-'), using '+' parse to NaN
  18575. // If object, also parse to NaN
  18576. : +value;
  18577. }
  18578. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18579. // Consider persistent.
  18580. // Caution: why use raw value to display on label or tooltip?
  18581. // A reason is to avoid format. For example time value we do not know
  18582. // how to format is expected. More over, if stack is used, calculated
  18583. // value may be 0.91000000001, which have brings trouble to display.
  18584. // TODO: consider how to treat null/undefined/NaN when display?
  18585. /**
  18586. * @param {module:echarts/data/List} data
  18587. * @param {number} dataIndex
  18588. * @param {string|number} [dim] dimName or dimIndex
  18589. * @return {Array.<number>|string|number} can be null/undefined.
  18590. */
  18591. function retrieveRawValue(data, dataIndex, dim) {
  18592. if (!data) {
  18593. return;
  18594. }
  18595. // Consider data may be not persistent.
  18596. var dataItem = data.getRawDataItem(dataIndex);
  18597. if (dataItem == null) {
  18598. return;
  18599. }
  18600. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18601. var dimName;
  18602. var dimIndex;
  18603. var dimInfo = data.getDimensionInfo(dim);
  18604. if (dimInfo) {
  18605. dimName = dimInfo.name;
  18606. dimIndex = dimInfo.index;
  18607. }
  18608. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18609. }
  18610. /**
  18611. * Compatible with some cases (in pie, map) like:
  18612. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18613. * where only sourceFormat is 'original' and 'objectRows' supported.
  18614. *
  18615. * ??? TODO
  18616. * Supported detail options in data item when using 'arrayRows'.
  18617. *
  18618. * @param {module:echarts/data/List} data
  18619. * @param {number} dataIndex
  18620. * @param {string} attr like 'selected'
  18621. */
  18622. function retrieveRawAttr(data, dataIndex, attr) {
  18623. if (!data) {
  18624. return;
  18625. }
  18626. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18627. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18628. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18629. ) {
  18630. return;
  18631. }
  18632. var dataItem = data.getRawDataItem(dataIndex);
  18633. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18634. dataItem = null;
  18635. }
  18636. if (dataItem) {
  18637. return dataItem[attr];
  18638. }
  18639. }
  18640. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18641. // PENDING A little ugly
  18642. var dataFormatMixin = {
  18643. /**
  18644. * Get params for formatter
  18645. * @param {number} dataIndex
  18646. * @param {string} [dataType]
  18647. * @return {Object}
  18648. */
  18649. getDataParams: function (dataIndex, dataType) {
  18650. var data = this.getData(dataType);
  18651. var rawValue = this.getRawValue(dataIndex, dataType);
  18652. var rawDataIndex = data.getRawIndex(dataIndex);
  18653. var name = data.getName(dataIndex, true);
  18654. var itemOpt = data.getRawDataItem(dataIndex);
  18655. var color = data.getItemVisual(dataIndex, 'color');
  18656. return {
  18657. componentType: this.mainType,
  18658. componentSubType: this.subType,
  18659. seriesType: this.mainType === 'series' ? this.subType : null,
  18660. seriesIndex: this.seriesIndex,
  18661. seriesId: this.id,
  18662. seriesName: this.name,
  18663. name: name,
  18664. dataIndex: rawDataIndex,
  18665. data: itemOpt,
  18666. dataType: dataType,
  18667. value: rawValue,
  18668. color: color,
  18669. marker: getTooltipMarker(color),
  18670. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18671. $vars: ['seriesName', 'name', 'value']
  18672. };
  18673. },
  18674. /**
  18675. * Format label
  18676. * @param {number} dataIndex
  18677. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18678. * @param {string} [dataType]
  18679. * @param {number} [dimIndex]
  18680. * @param {string} [labelProp='label']
  18681. * @return {string} If not formatter, return null/undefined
  18682. */
  18683. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18684. status = status || 'normal';
  18685. var data = this.getData(dataType);
  18686. var itemModel = data.getItemModel(dataIndex);
  18687. var params = this.getDataParams(dataIndex, dataType);
  18688. if (dimIndex != null && (params.value instanceof Array)) {
  18689. params.value = params.value[dimIndex];
  18690. }
  18691. var formatter = itemModel.get(
  18692. status === 'normal'
  18693. ? [labelProp || 'label', 'formatter']
  18694. : [status, labelProp || 'label', 'formatter']
  18695. );
  18696. if (typeof formatter === 'function') {
  18697. params.status = status;
  18698. return formatter(params);
  18699. }
  18700. else if (typeof formatter === 'string') {
  18701. var str = formatTpl(formatter, params);
  18702. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18703. // Do not support '}' in dim name util have to.
  18704. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18705. var len = dim.length;
  18706. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18707. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18708. }
  18709. return retrieveRawValue(data, dataIndex, dim);
  18710. });
  18711. }
  18712. },
  18713. /**
  18714. * Get raw value in option
  18715. * @param {number} idx
  18716. * @param {string} [dataType]
  18717. * @return {Array|number|string}
  18718. */
  18719. getRawValue: function (idx, dataType) {
  18720. return retrieveRawValue(this.getData(dataType), idx);
  18721. },
  18722. /**
  18723. * Should be implemented.
  18724. * @param {number} dataIndex
  18725. * @param {boolean} [multipleSeries=false]
  18726. * @param {number} [dataType]
  18727. * @return {string} tooltip string
  18728. */
  18729. formatTooltip: function () {
  18730. // Empty function
  18731. }
  18732. };
  18733. /**
  18734. * @param {Object} define
  18735. * @return See the return of `createTask`.
  18736. */
  18737. function createTask(define) {
  18738. return new Task(define);
  18739. }
  18740. /**
  18741. * @constructor
  18742. * @param {Object} define
  18743. * @param {Function} define.reset Custom reset
  18744. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18745. * @param {Function} [define.count] count is used to determin data task.
  18746. * @param {Function} [define.onDirty] count is used to determin data task.
  18747. */
  18748. function Task(define) {
  18749. define = define || {};
  18750. this._reset = define.reset;
  18751. this._plan = define.plan;
  18752. this._count = define.count;
  18753. this._onDirty = define.onDirty;
  18754. this._dirty = true;
  18755. // Context must be specified implicitly, to
  18756. // avoid miss update context when model changed.
  18757. this.context;
  18758. }
  18759. var taskProto = Task.prototype;
  18760. /**
  18761. * @param {Object} performArgs
  18762. * @param {number} [performArgs.step] Specified step.
  18763. * @param {number} [performArgs.skip] Skip customer perform call.
  18764. */
  18765. taskProto.perform = function (performArgs) {
  18766. var upTask = this._upstream;
  18767. var skip = performArgs && performArgs.skip;
  18768. // TODO some refactor.
  18769. // Pull data. Must pull data each time, because context.data
  18770. // may be updated by Series.setData.
  18771. if (this._dirty && upTask) {
  18772. var context = this.context;
  18773. context.data = context.outputData = upTask.context.outputData;
  18774. }
  18775. if (this.__pipeline) {
  18776. this.__pipeline.currentTask = this;
  18777. }
  18778. var planResult;
  18779. if (this._plan && !skip) {
  18780. planResult = this._plan(this.context);
  18781. }
  18782. if (this._dirty || planResult === 'reset') {
  18783. this._dirty = false;
  18784. reset(this, skip);
  18785. }
  18786. var step = performArgs && performArgs.step;
  18787. if (upTask) {
  18788. if (__DEV__) {
  18789. assert$1(upTask._outputDueEnd != null);
  18790. }
  18791. // ??? FIXME move to schedueler?
  18792. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  18793. this._dueEnd = upTask._outputDueEnd;
  18794. }
  18795. // DataTask or overallTask
  18796. else {
  18797. if (__DEV__) {
  18798. assert$1(!this._progress || this._count);
  18799. }
  18800. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18801. }
  18802. // Note: Stubs, that its host overall task let it has progress, has progress.
  18803. // If no progress, pass index from upstream to downstream each time plan called.
  18804. if (this._progress) {
  18805. var start = this._dueIndex;
  18806. var end = Math.min(
  18807. step != null ? this._dueIndex + step : Infinity,
  18808. this._dueEnd
  18809. );
  18810. !skip && start < end && (
  18811. this._progress({start: start, end: end}, this.context)
  18812. );
  18813. this._dueIndex = end;
  18814. // If no `outputDueEnd`, assume that output data and
  18815. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18816. var outputDueEnd = this._settedOutputEnd != null
  18817. ? this._settedOutputEnd : end;
  18818. if (__DEV__) {
  18819. // ??? Can not rollback.
  18820. assert$1(outputDueEnd >= this._outputDueEnd);
  18821. }
  18822. this._outputDueEnd = outputDueEnd;
  18823. }
  18824. else {
  18825. // (1) Some overall task has no progress.
  18826. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18827. // This should always be performed so it can be passed to downstream.
  18828. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  18829. ? this._settedOutputEnd : this._dueEnd;
  18830. }
  18831. return this.unfinished();
  18832. };
  18833. taskProto.dirty = function () {
  18834. this._dirty = true;
  18835. this._onDirty && this._onDirty(this.context);
  18836. };
  18837. /**
  18838. * @param {Object} [params]
  18839. */
  18840. function reset(taskIns, skip) {
  18841. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  18842. taskIns._settedOutputEnd = null;
  18843. taskIns._progress = !skip && taskIns._reset && taskIns._reset(
  18844. taskIns.context
  18845. );
  18846. var downstream = taskIns._downstream;
  18847. downstream && downstream.dirty();
  18848. }
  18849. /**
  18850. * @return {boolean}
  18851. */
  18852. taskProto.unfinished = function () {
  18853. return this._progress && this._dueIndex < this._dueEnd;
  18854. };
  18855. /**
  18856. * @param {Object} downTask The downstream task.
  18857. * @return {Object} The downstream task.
  18858. */
  18859. taskProto.pipe = function (downTask) {
  18860. if (__DEV__) {
  18861. assert$1(downTask && !downTask._disposed && downTask !== this);
  18862. }
  18863. // If already downstream, do not dirty downTask.
  18864. if (this._downstream !== downTask || this._dirty) {
  18865. this._downstream = downTask;
  18866. downTask._upstream = this;
  18867. downTask.dirty();
  18868. }
  18869. };
  18870. taskProto.dispose = function () {
  18871. if (this._disposed) {
  18872. return;
  18873. }
  18874. this._upstream && (this._upstream._downstream = null);
  18875. this._downstream && (this._downstream._upstream = null);
  18876. this._dirty = false;
  18877. this._disposed = true;
  18878. };
  18879. taskProto.getUpstream = function () {
  18880. return this._upstream;
  18881. };
  18882. taskProto.getDownstream = function () {
  18883. return this._downstream;
  18884. };
  18885. taskProto.setOutputEnd = function (end) {
  18886. // ??? FIXME: check
  18887. // This only happend in dataTask, dataZoom, map, currently.
  18888. // where dataZoom do not set end each time, but only set
  18889. // when reset. So we should record the setted end, in case
  18890. // that the stub of dataZoom perform again and earse the
  18891. // setted end by upstream.
  18892. this._outputDueEnd = this._settedOutputEnd = end;
  18893. // this._outputDueEnd = end;
  18894. };
  18895. var inner$4 = makeInner();
  18896. var SeriesModel = ComponentModel.extend({
  18897. type: 'series.__base__',
  18898. /**
  18899. * @readOnly
  18900. */
  18901. seriesIndex: 0,
  18902. // coodinateSystem will be injected in the echarts/CoordinateSystem
  18903. coordinateSystem: null,
  18904. /**
  18905. * @type {Object}
  18906. * @protected
  18907. */
  18908. defaultOption: null,
  18909. /**
  18910. * Data provided for legend
  18911. * @type {Function}
  18912. */
  18913. // PENDING
  18914. legendDataProvider: null,
  18915. /**
  18916. * Access path of color for visual
  18917. */
  18918. visualColorAccessPath: 'itemStyle.color',
  18919. /**
  18920. * Support merge layout params.
  18921. * Only support 'box' now (left/right/top/bottom/width/height).
  18922. * @type {string|Object} Object can be {ignoreSize: true}
  18923. * @readOnly
  18924. */
  18925. layoutMode: null,
  18926. init: function (option, parentModel, ecModel, extraOpt) {
  18927. /**
  18928. * @type {number}
  18929. * @readOnly
  18930. */
  18931. this.seriesIndex = this.componentIndex;
  18932. this.dataTask = createTask({
  18933. count: dataTaskCount,
  18934. reset: dataTaskReset
  18935. });
  18936. this.dataTask.context = {model: this};
  18937. this.mergeDefaultAndTheme(option, ecModel);
  18938. prepareSource(this);
  18939. var data = this.getInitialData(option, ecModel);
  18940. wrapData(data, this);
  18941. this.dataTask.context.data = data;
  18942. if (__DEV__) {
  18943. assert$1(data, 'getInitialData returned invalid data.');
  18944. }
  18945. /**
  18946. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  18947. * @private
  18948. */
  18949. inner$4(this).dataBeforeProcessed = data;
  18950. // If we reverse the order (make data firstly, and then make
  18951. // dataBeforeProcessed by cloneShallow), cloneShallow will
  18952. // cause data.graph.data !== data when using
  18953. // module:echarts/data/Graph or module:echarts/data/Tree.
  18954. // See module:echarts/data/helper/linkList
  18955. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  18956. // init or merge stage, because the data can be restored. So we do not `restoreData`
  18957. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  18958. // Call `seriesModel.getRawData()` instead.
  18959. // this.restoreData();
  18960. autoSeriesName(this);
  18961. },
  18962. /**
  18963. * Util for merge default and theme to option
  18964. * @param {Object} option
  18965. * @param {module:echarts/model/Global} ecModel
  18966. */
  18967. mergeDefaultAndTheme: function (option, ecModel) {
  18968. var layoutMode = this.layoutMode;
  18969. var inputPositionParams = layoutMode
  18970. ? getLayoutParams(option) : {};
  18971. // Backward compat: using subType on theme.
  18972. // But if name duplicate between series subType
  18973. // (for example: parallel) add component mainType,
  18974. // add suffix 'Series'.
  18975. var themeSubType = this.subType;
  18976. if (ComponentModel.hasClass(themeSubType)) {
  18977. themeSubType += 'Series';
  18978. }
  18979. merge(
  18980. option,
  18981. ecModel.getTheme().get(this.subType)
  18982. );
  18983. merge(option, this.getDefaultOption());
  18984. // Default label emphasis `show`
  18985. defaultEmphasis(option, 'label', ['show']);
  18986. this.fillDataTextStyle(option.data);
  18987. if (layoutMode) {
  18988. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18989. }
  18990. },
  18991. mergeOption: function (newSeriesOption, ecModel) {
  18992. // this.settingTask.dirty();
  18993. newSeriesOption = merge(this.option, newSeriesOption, true);
  18994. this.fillDataTextStyle(newSeriesOption.data);
  18995. var layoutMode = this.layoutMode;
  18996. if (layoutMode) {
  18997. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  18998. }
  18999. prepareSource(this);
  19000. var data = this.getInitialData(newSeriesOption, ecModel);
  19001. wrapData(data, this);
  19002. this.dataTask.dirty();
  19003. this.dataTask.context.data = data;
  19004. inner$4(this).dataBeforeProcessed = data;
  19005. autoSeriesName(this);
  19006. },
  19007. fillDataTextStyle: function (data) {
  19008. // Default data label emphasis `show`
  19009. // FIXME Tree structure data ?
  19010. // FIXME Performance ?
  19011. if (data) {
  19012. var props = ['show'];
  19013. for (var i = 0; i < data.length; i++) {
  19014. if (data[i] && data[i].label) {
  19015. defaultEmphasis(data[i], 'label', props);
  19016. }
  19017. }
  19018. }
  19019. },
  19020. /**
  19021. * Init a data structure from data related option in series
  19022. * Must be overwritten
  19023. */
  19024. getInitialData: function () {},
  19025. /**
  19026. * Append data to list
  19027. * @param {Object} params
  19028. * @param {Array|TypedArray} params.data
  19029. */
  19030. appendData: function (params) {
  19031. // FIXME ???
  19032. // (1) If data from dataset, forbidden append.
  19033. // (2) support append data of dataset.
  19034. var data = this.getRawData();
  19035. data.appendData(params.data);
  19036. },
  19037. /**
  19038. * Consider some method like `filter`, `map` need make new data,
  19039. * We should make sure that `seriesModel.getData()` get correct
  19040. * data in the stream procedure. So we fetch data from upstream
  19041. * each time `task.perform` called.
  19042. * @param {string} [dataType]
  19043. * @return {module:echarts/data/List}
  19044. */
  19045. getData: function (dataType) {
  19046. var task = getCurrentTask(this);
  19047. if (task) {
  19048. var data = task.context.data;
  19049. return dataType == null ? data : data.getLinkedData(dataType);
  19050. }
  19051. else {
  19052. // When series is not alive (that may happen when click toolbox
  19053. // restore or setOption with not merge mode), series data may
  19054. // be still need to judge animation or something when graphic
  19055. // elements want to know whether fade out.
  19056. return inner$4(this).data;
  19057. }
  19058. },
  19059. /**
  19060. * @param {module:echarts/data/List} data
  19061. */
  19062. setData: function (data) {
  19063. var task = getCurrentTask(this);
  19064. if (task) {
  19065. var context = task.context;
  19066. // Consider case: filter, data sample.
  19067. if (context.data !== data && task.isOverallFilter) {
  19068. task.setOutputEnd(data.count());
  19069. }
  19070. context.outputData = data;
  19071. // Caution: setData should update context.data,
  19072. // Because getData may be called multiply in a
  19073. // single stage and expect to get the data just
  19074. // set. (For example, AxisProxy, x y both call
  19075. // getData and setDate sequentially).
  19076. // So the context.data should be fetched from
  19077. // upstream each time when a stage starts to be
  19078. // performed.
  19079. if (task !== this.dataTask) {
  19080. context.data = data;
  19081. }
  19082. }
  19083. inner$4(this).data = data;
  19084. },
  19085. /**
  19086. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19087. * @return {module:echarts/data/Source} source
  19088. */
  19089. getSource: function () {
  19090. return getSource(this);
  19091. },
  19092. /**
  19093. * Get data before processed
  19094. * @return {module:echarts/data/List}
  19095. */
  19096. getRawData: function () {
  19097. return inner$4(this).dataBeforeProcessed;
  19098. },
  19099. /**
  19100. * Get base axis if has coordinate system and has axis.
  19101. * By default use coordSys.getBaseAxis();
  19102. * Can be overrided for some chart.
  19103. * @return {type} description
  19104. */
  19105. getBaseAxis: function () {
  19106. var coordSys = this.coordinateSystem;
  19107. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19108. },
  19109. // FIXME
  19110. /**
  19111. * Default tooltip formatter
  19112. *
  19113. * @param {number} dataIndex
  19114. * @param {boolean} [multipleSeries=false]
  19115. * @param {number} [dataType]
  19116. */
  19117. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  19118. function formatArrayValue(value) {
  19119. // ??? TODO refactor these logic.
  19120. // check: category-no-encode-has-axis-data in dataset.html
  19121. var vertially = reduce(value, function (vertially, val, idx) {
  19122. var dimItem = data.getDimensionInfo(idx);
  19123. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19124. }, 0);
  19125. var result = [];
  19126. tooltipDims.length
  19127. ? each$1(tooltipDims, function (dim) {
  19128. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19129. })
  19130. // By default, all dims is used on tooltip.
  19131. : each$1(value, setEachItem);
  19132. function setEachItem(val, dim) {
  19133. var dimInfo = data.getDimensionInfo(dim);
  19134. // If `dimInfo.tooltip` is not set, show tooltip.
  19135. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19136. return;
  19137. }
  19138. var dimType = dimInfo.type;
  19139. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  19140. var valStr = (vertially
  19141. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  19142. : ''
  19143. )
  19144. // FIXME should not format time for raw data?
  19145. + encodeHTML(dimType === 'ordinal'
  19146. ? val + ''
  19147. : dimType === 'time'
  19148. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  19149. : addCommas(val)
  19150. );
  19151. valStr && result.push(valStr);
  19152. }
  19153. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  19154. }
  19155. function formatSingleValue(val) {
  19156. return encodeHTML(addCommas(val));
  19157. }
  19158. var data = this.getData();
  19159. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19160. var tooltipDimLen = tooltipDims.length;
  19161. var value = this.getRawValue(dataIndex);
  19162. var isValueArr = isArray(value);
  19163. var color = data.getItemVisual(dataIndex, 'color');
  19164. if (isObject$1(color) && color.colorStops) {
  19165. color = (color.colorStops[0] || {}).color;
  19166. }
  19167. color = color || 'transparent';
  19168. // Complicated rule for pretty tooltip.
  19169. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  19170. ? formatArrayValue(value)
  19171. : tooltipDimLen
  19172. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  19173. : formatSingleValue(isValueArr ? value[0] : value);
  19174. var colorEl = getTooltipMarker(color);
  19175. var name = data.getName(dataIndex);
  19176. var seriesName = this.name;
  19177. if (seriesName === DEFAULT_COMPONENT_NAME) {
  19178. // Not show '-'
  19179. seriesName = '';
  19180. }
  19181. seriesName = seriesName
  19182. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  19183. : '';
  19184. return !multipleSeries
  19185. ? seriesName + colorEl
  19186. + (name
  19187. ? encodeHTML(name) + ': ' + formattedValue
  19188. : formattedValue
  19189. )
  19190. : colorEl + seriesName + formattedValue;
  19191. },
  19192. /**
  19193. * @return {boolean}
  19194. */
  19195. isAnimationEnabled: function () {
  19196. if (env$1.node) {
  19197. return false;
  19198. }
  19199. var animationEnabled = this.getShallow('animation');
  19200. if (animationEnabled) {
  19201. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19202. animationEnabled = false;
  19203. }
  19204. }
  19205. return animationEnabled;
  19206. },
  19207. restoreData: function () {
  19208. this.dataTask.dirty();
  19209. },
  19210. getColorFromPalette: function (name, scope, requestColorNum) {
  19211. var ecModel = this.ecModel;
  19212. // PENDING
  19213. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19214. if (!color) {
  19215. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19216. }
  19217. return color;
  19218. },
  19219. /**
  19220. * Use `data.mapDimension(coordDim, true)` instead.
  19221. * @deprecated
  19222. */
  19223. coordDimToDataDim: function (coordDim) {
  19224. return this.getRawData().mapDimension(coordDim, true);
  19225. },
  19226. /**
  19227. * Get progressive rendering count each step
  19228. * @return {number}
  19229. */
  19230. getProgressive: function () {
  19231. return this.get('progressive');
  19232. },
  19233. /**
  19234. * Get progressive rendering count each step
  19235. * @return {number}
  19236. */
  19237. getProgressiveThreshold: function () {
  19238. return this.get('progressiveThreshold');
  19239. },
  19240. /**
  19241. * Get data indices for show tooltip content. See tooltip.
  19242. * @abstract
  19243. * @param {Array.<string>|string} dim
  19244. * @param {Array.<number>} value
  19245. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  19246. * @return {Object} {dataIndices, nestestValue}.
  19247. */
  19248. getAxisTooltipData: null,
  19249. /**
  19250. * See tooltip.
  19251. * @abstract
  19252. * @param {number} dataIndex
  19253. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  19254. */
  19255. getTooltipPosition: null,
  19256. /**
  19257. * @see {module:echarts/stream/Scheduler}
  19258. */
  19259. pipeTask: null,
  19260. /**
  19261. * Convinient for override in extended class.
  19262. * @protected
  19263. * @type {Function}
  19264. */
  19265. preventIncremental: null,
  19266. /**
  19267. * @public
  19268. * @readOnly
  19269. * @type {Object}
  19270. */
  19271. pipelineContext: null
  19272. });
  19273. mixin(SeriesModel, dataFormatMixin);
  19274. mixin(SeriesModel, colorPaletteMixin);
  19275. /**
  19276. * MUST be called after `prepareSource` called
  19277. * Here we need to make auto series, especially for auto legend. But we
  19278. * do not modify series.name in option to avoid side effects.
  19279. */
  19280. function autoSeriesName(seriesModel) {
  19281. // User specified name has higher priority, otherwise it may cause
  19282. // series can not be queried unexpectedly.
  19283. var name = seriesModel.name;
  19284. if (DEFAULT_COMPONENT_NAME === name) {
  19285. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19286. }
  19287. }
  19288. function getSeriesAutoName(seriesModel) {
  19289. var data = seriesModel.getRawData();
  19290. var dataDims = data.mapDimension('seriesName', true);
  19291. var nameArr = [];
  19292. each$1(dataDims, function (dataDim) {
  19293. var dimInfo = data.getDimensionInfo(dataDim);
  19294. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19295. });
  19296. return nameArr.join(' ');
  19297. }
  19298. function dataTaskCount(context) {
  19299. return context.model.getRawData().count();
  19300. }
  19301. function dataTaskReset(context) {
  19302. var seriesModel = context.model;
  19303. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19304. return dataTaskProgress;
  19305. }
  19306. function dataTaskProgress(param, context) {
  19307. // Avoid repead cloneShallow when data just created in reset.
  19308. if (param.end > context.outputData.count()) {
  19309. context.model.getRawData().cloneShallow(context.outputData);
  19310. }
  19311. }
  19312. // TODO refactor
  19313. function wrapData(data, seriesModel) {
  19314. each$1(data.CHANGABLE_METHODS, function (methodName) {
  19315. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  19316. });
  19317. }
  19318. function onDataSelfChange(seriesModel) {
  19319. var task = getCurrentTask(seriesModel);
  19320. if (task) {
  19321. // Consider case: filter, selectRange
  19322. task.setOutputEnd(this.count());
  19323. }
  19324. }
  19325. function getCurrentTask(seriesModel) {
  19326. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19327. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19328. if (pipeline) {
  19329. // When pipline finished, the currrentTask keep the last
  19330. // task (renderTask).
  19331. var task = pipeline.currentTask;
  19332. if (task) {
  19333. var agentStubMap = task.agentStubMap;
  19334. if (agentStubMap) {
  19335. task = agentStubMap.get(seriesModel.uid);
  19336. }
  19337. }
  19338. return task;
  19339. }
  19340. }
  19341. var Component$1 = function () {
  19342. /**
  19343. * @type {module:zrender/container/Group}
  19344. * @readOnly
  19345. */
  19346. this.group = new Group();
  19347. /**
  19348. * @type {string}
  19349. * @readOnly
  19350. */
  19351. this.uid = getUID('viewComponent');
  19352. };
  19353. Component$1.prototype = {
  19354. constructor: Component$1,
  19355. init: function (ecModel, api) {},
  19356. render: function (componentModel, ecModel, api, payload) {},
  19357. dispose: function () {}
  19358. };
  19359. var componentProto = Component$1.prototype;
  19360. componentProto.updateView
  19361. = componentProto.updateLayout
  19362. = componentProto.updateVisual
  19363. = function (seriesModel, ecModel, api, payload) {
  19364. // Do nothing;
  19365. };
  19366. // Enable Component.extend.
  19367. enableClassExtend(Component$1);
  19368. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19369. enableClassManagement(Component$1, {registerWhenExtend: true});
  19370. /**
  19371. * @return {string} If large mode changed, return string 'reset';
  19372. */
  19373. var createRenderPlanner = function () {
  19374. var inner = makeInner();
  19375. return function (seriesModel) {
  19376. var fields = inner(seriesModel);
  19377. var pipelineContext = seriesModel.pipelineContext;
  19378. var originalLarge = fields.large;
  19379. var originalIncremental = fields.incrementalRender;
  19380. var large = fields.large = pipelineContext.large;
  19381. var incremental = fields.incrementalRender = pipelineContext.incrementalRender;
  19382. return ((originalLarge ^ large) || (originalIncremental ^ incremental)) && 'reset';
  19383. };
  19384. };
  19385. var inner$5 = makeInner();
  19386. var renderPlanner = createRenderPlanner();
  19387. function Chart() {
  19388. /**
  19389. * @type {module:zrender/container/Group}
  19390. * @readOnly
  19391. */
  19392. this.group = new Group();
  19393. /**
  19394. * @type {string}
  19395. * @readOnly
  19396. */
  19397. this.uid = getUID('viewChart');
  19398. this.renderTask = createTask({
  19399. plan: renderTaskPlan,
  19400. reset: renderTaskReset
  19401. });
  19402. this.renderTask.context = {view: this};
  19403. }
  19404. Chart.prototype = {
  19405. type: 'chart',
  19406. /**
  19407. * Init the chart.
  19408. * @param {module:echarts/model/Global} ecModel
  19409. * @param {module:echarts/ExtensionAPI} api
  19410. */
  19411. init: function (ecModel, api) {},
  19412. /**
  19413. * Render the chart.
  19414. * @param {module:echarts/model/Series} seriesModel
  19415. * @param {module:echarts/model/Global} ecModel
  19416. * @param {module:echarts/ExtensionAPI} api
  19417. * @param {Object} payload
  19418. */
  19419. render: function (seriesModel, ecModel, api, payload) {},
  19420. /**
  19421. * Highlight series or specified data item.
  19422. * @param {module:echarts/model/Series} seriesModel
  19423. * @param {module:echarts/model/Global} ecModel
  19424. * @param {module:echarts/ExtensionAPI} api
  19425. * @param {Object} payload
  19426. */
  19427. highlight: function (seriesModel, ecModel, api, payload) {
  19428. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  19429. },
  19430. /**
  19431. * Downplay series or specified data item.
  19432. * @param {module:echarts/model/Series} seriesModel
  19433. * @param {module:echarts/model/Global} ecModel
  19434. * @param {module:echarts/ExtensionAPI} api
  19435. * @param {Object} payload
  19436. */
  19437. downplay: function (seriesModel, ecModel, api, payload) {
  19438. toggleHighlight(seriesModel.getData(), payload, 'normal');
  19439. },
  19440. /**
  19441. * Remove self.
  19442. * @param {module:echarts/model/Global} ecModel
  19443. * @param {module:echarts/ExtensionAPI} api
  19444. */
  19445. remove: function (ecModel, api) {
  19446. this.group.removeAll();
  19447. },
  19448. /**
  19449. * Dispose self.
  19450. * @param {module:echarts/model/Global} ecModel
  19451. * @param {module:echarts/ExtensionAPI} api
  19452. */
  19453. dispose: function () {},
  19454. /**
  19455. * Rendering preparation in progressive mode.
  19456. * @param {module:echarts/model/Series} seriesModel
  19457. * @param {module:echarts/model/Global} ecModel
  19458. * @param {module:echarts/ExtensionAPI} api
  19459. * @param {Object} payload
  19460. */
  19461. incrementalPrepareRender: null,
  19462. /**
  19463. * Render in progressive mode.
  19464. * @param {module:echarts/model/Series} seriesModel
  19465. * @param {module:echarts/model/Global} ecModel
  19466. * @param {module:echarts/ExtensionAPI} api
  19467. * @param {Object} payload
  19468. */
  19469. incrementalRender: null,
  19470. /**
  19471. * Update transform directly.
  19472. * @param {module:echarts/model/Series} seriesModel
  19473. * @param {module:echarts/model/Global} ecModel
  19474. * @param {module:echarts/ExtensionAPI} api
  19475. * @param {Object} payload
  19476. * @return {Object} {update: true}
  19477. */
  19478. updateTransform: null
  19479. /**
  19480. * The view contains the given point.
  19481. * @interface
  19482. * @param {Array.<number>} point
  19483. * @return {boolean}
  19484. */
  19485. // containPoint: function () {}
  19486. };
  19487. var chartProto = Chart.prototype;
  19488. chartProto.updateView
  19489. = chartProto.updateLayout
  19490. = chartProto.updateVisual
  19491. = function (seriesModel, ecModel, api, payload) {
  19492. this.render(seriesModel, ecModel, api, payload);
  19493. };
  19494. /**
  19495. * Set state of single element
  19496. * @param {module:zrender/Element} el
  19497. * @param {string} state
  19498. */
  19499. function elSetState(el, state) {
  19500. if (el) {
  19501. el.trigger(state);
  19502. if (el.type === 'group') {
  19503. for (var i = 0; i < el.childCount(); i++) {
  19504. elSetState(el.childAt(i), state);
  19505. }
  19506. }
  19507. }
  19508. }
  19509. /**
  19510. * @param {module:echarts/data/List} data
  19511. * @param {Object} payload
  19512. * @param {string} state 'normal'|'emphasis'
  19513. */
  19514. function toggleHighlight(data, payload, state) {
  19515. var dataIndex = queryDataIndex(data, payload);
  19516. if (dataIndex != null) {
  19517. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19518. elSetState(data.getItemGraphicEl(dataIdx), state);
  19519. });
  19520. }
  19521. else {
  19522. data.eachItemGraphicEl(function (el) {
  19523. elSetState(el, state);
  19524. });
  19525. }
  19526. }
  19527. // Enable Chart.extend.
  19528. enableClassExtend(Chart, ['dispose']);
  19529. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19530. enableClassManagement(Chart, {registerWhenExtend: true});
  19531. Chart.markUpdateMethod = function (payload, methodName) {
  19532. inner$5(payload).updateMethod = methodName;
  19533. };
  19534. function renderTaskPlan(context) {
  19535. return renderPlanner(context.model);
  19536. }
  19537. function renderTaskReset(context) {
  19538. var seriesModel = context.model;
  19539. var ecModel = context.ecModel;
  19540. var api = context.api;
  19541. var payload = context.payload;
  19542. // ???! remove updateView updateVisual
  19543. var incremental = seriesModel.pipelineContext.incrementalRender;
  19544. var view = context.view;
  19545. var updateMethod = payload && inner$5(payload).updateMethod;
  19546. var methodName = (incremental && view.incrementalPrepareRender)
  19547. ? 'incrementalPrepareRender'
  19548. : (updateMethod && view[updateMethod])
  19549. ? updateMethod
  19550. : 'render';
  19551. view[methodName](seriesModel, ecModel, api, payload);
  19552. return incremental ? renderTaskProgress : null;
  19553. }
  19554. function renderTaskProgress(params, context) {
  19555. context.view.incrementalRender(
  19556. params, context.model, context.ecModel, context.api, context.payload
  19557. );
  19558. }
  19559. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  19560. var RATE = '\0__throttleRate';
  19561. var THROTTLE_TYPE = '\0__throttleType';
  19562. /**
  19563. * @public
  19564. * @param {(Function)} fn
  19565. * @param {number} [delay=0] Unit: ms.
  19566. * @param {boolean} [debounce=false]
  19567. * true: If call interval less than `delay`, only the last call works.
  19568. * false: If call interval less than `delay, call works on fixed rate.
  19569. * @return {(Function)} throttled fn.
  19570. */
  19571. function throttle(fn, delay, debounce) {
  19572. var currCall;
  19573. var lastCall = 0;
  19574. var lastExec = 0;
  19575. var timer = null;
  19576. var diff;
  19577. var scope;
  19578. var args;
  19579. var debounceNextCall;
  19580. delay = delay || 0;
  19581. function exec() {
  19582. lastExec = (new Date()).getTime();
  19583. timer = null;
  19584. fn.apply(scope, args || []);
  19585. }
  19586. var cb = function () {
  19587. currCall = (new Date()).getTime();
  19588. scope = this;
  19589. args = arguments;
  19590. var thisDelay = debounceNextCall || delay;
  19591. var thisDebounce = debounceNextCall || debounce;
  19592. debounceNextCall = null;
  19593. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19594. clearTimeout(timer);
  19595. if (thisDebounce) {
  19596. timer = setTimeout(exec, thisDelay);
  19597. }
  19598. else {
  19599. if (diff >= 0) {
  19600. exec();
  19601. }
  19602. else {
  19603. timer = setTimeout(exec, -diff);
  19604. }
  19605. }
  19606. lastCall = currCall;
  19607. };
  19608. /**
  19609. * Clear throttle.
  19610. * @public
  19611. */
  19612. cb.clear = function () {
  19613. if (timer) {
  19614. clearTimeout(timer);
  19615. timer = null;
  19616. }
  19617. };
  19618. /**
  19619. * Enable debounce once.
  19620. */
  19621. cb.debounceNextCall = function (debounceDelay) {
  19622. debounceNextCall = debounceDelay;
  19623. };
  19624. return cb;
  19625. }
  19626. /**
  19627. * Create throttle method or update throttle rate.
  19628. *
  19629. * @example
  19630. * ComponentView.prototype.render = function () {
  19631. * ...
  19632. * throttle.createOrUpdate(
  19633. * this,
  19634. * '_dispatchAction',
  19635. * this.model.get('throttle'),
  19636. * 'fixRate'
  19637. * );
  19638. * };
  19639. * ComponentView.prototype.remove = function () {
  19640. * throttle.clear(this, '_dispatchAction');
  19641. * };
  19642. * ComponentView.prototype.dispose = function () {
  19643. * throttle.clear(this, '_dispatchAction');
  19644. * };
  19645. *
  19646. * @public
  19647. * @param {Object} obj
  19648. * @param {string} fnAttr
  19649. * @param {number} [rate]
  19650. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19651. * @return {Function} throttled function.
  19652. */
  19653. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  19654. var fn = obj[fnAttr];
  19655. if (!fn) {
  19656. return;
  19657. }
  19658. var originFn = fn[ORIGIN_METHOD] || fn;
  19659. var lastThrottleType = fn[THROTTLE_TYPE];
  19660. var lastRate = fn[RATE];
  19661. if (lastRate !== rate || lastThrottleType !== throttleType) {
  19662. if (rate == null || !throttleType) {
  19663. return (obj[fnAttr] = originFn);
  19664. }
  19665. fn = obj[fnAttr] = throttle(
  19666. originFn, rate, throttleType === 'debounce'
  19667. );
  19668. fn[ORIGIN_METHOD] = originFn;
  19669. fn[THROTTLE_TYPE] = throttleType;
  19670. fn[RATE] = rate;
  19671. }
  19672. return fn;
  19673. }
  19674. /**
  19675. * Clear throttle. Example see throttle.createOrUpdate.
  19676. *
  19677. * @public
  19678. * @param {Object} obj
  19679. * @param {string} fnAttr
  19680. */
  19681. function clear(obj, fnAttr) {
  19682. var fn = obj[fnAttr];
  19683. if (fn && fn[ORIGIN_METHOD]) {
  19684. obj[fnAttr] = fn[ORIGIN_METHOD];
  19685. }
  19686. }
  19687. var seriesColor = {
  19688. createOnAllSeries: true,
  19689. performRawSeries: true,
  19690. reset: function (seriesModel, ecModel) {
  19691. var data = seriesModel.getData();
  19692. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  19693. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  19694. || seriesModel.getColorFromPalette(
  19695. // TODO series count changed.
  19696. seriesModel.get('name'), null, ecModel.getSeriesCount()
  19697. ); // Default color
  19698. // FIXME Set color function or use the platte color
  19699. data.setVisual('color', color);
  19700. // Only visible series has each data be visual encoded
  19701. if (!ecModel.isSeriesFiltered(seriesModel)) {
  19702. if (typeof color === 'function' && !(color instanceof Gradient)) {
  19703. data.each(function (idx) {
  19704. data.setItemVisual(
  19705. idx, 'color', color(seriesModel.getDataParams(idx))
  19706. );
  19707. });
  19708. }
  19709. // itemStyle in each data item
  19710. var dataEach = function (data, idx) {
  19711. var itemModel = data.getItemModel(idx);
  19712. var color = itemModel.get(colorAccessPath, true);
  19713. if (color != null) {
  19714. data.setItemVisual(idx, 'color', color);
  19715. }
  19716. };
  19717. return { dataEach: data.hasItemOption ? dataEach : null };
  19718. }
  19719. }
  19720. };
  19721. var lang = {
  19722. toolbox: {
  19723. brush: {
  19724. title: {
  19725. rect: '矩形选择',
  19726. polygon: '圈选',
  19727. lineX: '横向选择',
  19728. lineY: '纵向选择',
  19729. keep: '保持选择',
  19730. clear: '清除选择'
  19731. }
  19732. },
  19733. dataView: {
  19734. title: '数据视图',
  19735. lang: ['数据视图', '关闭', '刷新']
  19736. },
  19737. dataZoom: {
  19738. title: {
  19739. zoom: '区域缩放',
  19740. back: '区域缩放还原'
  19741. }
  19742. },
  19743. magicType: {
  19744. title: {
  19745. line: '切换为折线图',
  19746. bar: '切换为柱状图',
  19747. stack: '切换为堆叠',
  19748. tiled: '切换为平铺'
  19749. }
  19750. },
  19751. restore: {
  19752. title: '还原'
  19753. },
  19754. saveAsImage: {
  19755. title: '保存为图片',
  19756. lang: ['右键另存为图片']
  19757. }
  19758. },
  19759. series: {
  19760. typeNames: {
  19761. pie: '饼图',
  19762. bar: '柱状图',
  19763. line: '折线图',
  19764. scatter: '散点图',
  19765. effectScatter: '涟漪散点图',
  19766. radar: '雷达图',
  19767. tree: '树图',
  19768. treemap: '矩形树图',
  19769. boxplot: '箱型图',
  19770. candlestick: 'K线图',
  19771. k: 'K线图',
  19772. heatmap: '热力图',
  19773. map: '地图',
  19774. parallel: '平行坐标图',
  19775. lines: '线图',
  19776. graph: '关系图',
  19777. sankey: '桑基图',
  19778. funnel: '漏斗图',
  19779. gauge: '仪表盘图',
  19780. pictorialBar: '象形柱图',
  19781. themeRiver: '主题河流图',
  19782. sunburst: '旭日图'
  19783. }
  19784. },
  19785. aria: {
  19786. general: {
  19787. withTitle: '这是一个关于“{title}”的图表。',
  19788. withoutTitle: '这是一个图表,'
  19789. },
  19790. series: {
  19791. single: {
  19792. prefix: '',
  19793. withName: '图表类型是{seriesType},表示{seriesName}。',
  19794. withoutName: '图表类型是{seriesType}。'
  19795. },
  19796. multiple: {
  19797. prefix: '它由{seriesCount}个图表系列组成。',
  19798. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  19799. withoutName: '第{seriesId}个系列是一个{seriesType},',
  19800. separator: {
  19801. middle: ';',
  19802. end: '。'
  19803. }
  19804. }
  19805. },
  19806. data: {
  19807. allData: '其数据是——',
  19808. partialData: '其中,前{displayCnt}项是——',
  19809. withName: '{name}的数据是{value}',
  19810. withoutName: '{value}',
  19811. separator: {
  19812. middle: ',',
  19813. end: ''
  19814. }
  19815. }
  19816. }
  19817. };
  19818. var aria = function (dom, ecModel) {
  19819. var ariaModel = ecModel.getModel('aria');
  19820. if (!ariaModel.get('show')) {
  19821. return;
  19822. }
  19823. else if (ariaModel.get('description')) {
  19824. dom.setAttribute('aria-label', ariaModel.get('description'));
  19825. return;
  19826. }
  19827. var seriesCnt = 0;
  19828. ecModel.eachSeries(function (seriesModel, idx) {
  19829. ++seriesCnt;
  19830. }, this);
  19831. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  19832. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  19833. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  19834. var ariaLabel;
  19835. if (seriesCnt < 1) {
  19836. // No series, no aria label
  19837. return;
  19838. }
  19839. else {
  19840. var title = getTitle();
  19841. if (title) {
  19842. ariaLabel = replace(getConfig('general.withTitle'), {
  19843. title: title
  19844. });
  19845. }
  19846. else {
  19847. ariaLabel = getConfig('general.withoutTitle');
  19848. }
  19849. var seriesLabels = [];
  19850. var prefix = seriesCnt > 1
  19851. ? 'series.multiple.prefix'
  19852. : 'series.single.prefix';
  19853. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  19854. ecModel.eachSeries(function (seriesModel, idx) {
  19855. if (idx < displaySeriesCnt) {
  19856. var seriesLabel;
  19857. var seriesName = seriesModel.get('name');
  19858. var seriesTpl = 'series.'
  19859. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  19860. seriesLabel = getConfig(seriesName
  19861. ? seriesTpl + 'withName'
  19862. : seriesTpl + 'withoutName');
  19863. seriesLabel = replace(seriesLabel, {
  19864. seriesId: seriesModel.seriesIndex,
  19865. seriesName: seriesModel.get('name'),
  19866. seriesType: getSeriesTypeName(seriesModel.subType)
  19867. });
  19868. var data = seriesModel.getData();
  19869. window.data = data;
  19870. if (data.count() > maxDataCnt) {
  19871. // Show part of data
  19872. seriesLabel += replace(getConfig('data.partialData'), {
  19873. displayCnt: maxDataCnt
  19874. });
  19875. }
  19876. else {
  19877. seriesLabel += getConfig('data.allData');
  19878. }
  19879. var dataLabels = [];
  19880. for (var i = 0; i < data.count(); i++) {
  19881. if (i < maxDataCnt) {
  19882. var name = data.getName(i);
  19883. var value = retrieveRawValue(data, i);
  19884. dataLabels.push(
  19885. replace(
  19886. name
  19887. ? getConfig('data.withName')
  19888. : getConfig('data.withoutName'),
  19889. {
  19890. name: name,
  19891. value: value
  19892. }
  19893. )
  19894. );
  19895. }
  19896. }
  19897. seriesLabel += dataLabels
  19898. .join(getConfig('data.separator.middle'))
  19899. + getConfig('data.separator.end');
  19900. seriesLabels.push(seriesLabel);
  19901. }
  19902. });
  19903. ariaLabel += seriesLabels
  19904. .join(getConfig('series.multiple.separator.middle'))
  19905. + getConfig('series.multiple.separator.end');
  19906. dom.setAttribute('aria-label', ariaLabel);
  19907. }
  19908. function replace(str, keyValues) {
  19909. if (typeof str !== 'string') {
  19910. return str;
  19911. }
  19912. var result = str;
  19913. each$1(keyValues, function (value, key) {
  19914. result = result.replace(
  19915. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  19916. value
  19917. );
  19918. });
  19919. return result;
  19920. }
  19921. function getConfig(path) {
  19922. var userConfig = ariaModel.get(path);
  19923. if (userConfig == null) {
  19924. var pathArr = path.split('.');
  19925. var result = lang.aria;
  19926. for (var i = 0; i < pathArr.length; ++i) {
  19927. result = result[pathArr[i]];
  19928. }
  19929. return result;
  19930. }
  19931. else {
  19932. return userConfig;
  19933. }
  19934. }
  19935. function getTitle() {
  19936. var title = ecModel.getModel('title').option;
  19937. if (title && title.length) {
  19938. title = title[0];
  19939. }
  19940. return title && title.text;
  19941. }
  19942. function getSeriesTypeName(type) {
  19943. return lang.series.typeNames[type] || '自定义图';
  19944. }
  19945. };
  19946. var PI$1 = Math.PI;
  19947. /**
  19948. * @param {module:echarts/ExtensionAPI} api
  19949. * @param {Object} [opts]
  19950. * @param {string} [opts.text]
  19951. * @param {string} [opts.color]
  19952. * @param {string} [opts.textColor]
  19953. * @return {module:zrender/Element}
  19954. */
  19955. var loadingDefault = function (api, opts) {
  19956. opts = opts || {};
  19957. defaults(opts, {
  19958. text: 'loading',
  19959. color: '#c23531',
  19960. textColor: '#000',
  19961. maskColor: 'rgba(255, 255, 255, 0.8)',
  19962. zlevel: 0
  19963. });
  19964. var mask = new Rect({
  19965. style: {
  19966. fill: opts.maskColor
  19967. },
  19968. zlevel: opts.zlevel,
  19969. z: 10000
  19970. });
  19971. var arc = new Arc({
  19972. shape: {
  19973. startAngle: -PI$1 / 2,
  19974. endAngle: -PI$1 / 2 + 0.1,
  19975. r: 10
  19976. },
  19977. style: {
  19978. stroke: opts.color,
  19979. lineCap: 'round',
  19980. lineWidth: 5
  19981. },
  19982. zlevel: opts.zlevel,
  19983. z: 10001
  19984. });
  19985. var labelRect = new Rect({
  19986. style: {
  19987. fill: 'none',
  19988. text: opts.text,
  19989. textPosition: 'right',
  19990. textDistance: 10,
  19991. textFill: opts.textColor
  19992. },
  19993. zlevel: opts.zlevel,
  19994. z: 10001
  19995. });
  19996. arc.animateShape(true)
  19997. .when(1000, {
  19998. endAngle: PI$1 * 3 / 2
  19999. })
  20000. .start('circularInOut');
  20001. arc.animateShape(true)
  20002. .when(1000, {
  20003. startAngle: PI$1 * 3 / 2
  20004. })
  20005. .delay(300)
  20006. .start('circularInOut');
  20007. var group = new Group();
  20008. group.add(arc);
  20009. group.add(labelRect);
  20010. group.add(mask);
  20011. // Inject resize
  20012. group.resize = function () {
  20013. var cx = api.getWidth() / 2;
  20014. var cy = api.getHeight() / 2;
  20015. arc.setShape({
  20016. cx: cx,
  20017. cy: cy
  20018. });
  20019. var r = arc.shape.r;
  20020. labelRect.setShape({
  20021. x: cx - r,
  20022. y: cy - r,
  20023. width: r * 2,
  20024. height: r * 2
  20025. });
  20026. mask.setShape({
  20027. x: 0,
  20028. y: 0,
  20029. width: api.getWidth(),
  20030. height: api.getHeight()
  20031. });
  20032. };
  20033. group.resize();
  20034. return group;
  20035. };
  20036. /**
  20037. * @module echarts/stream/Scheduler
  20038. */
  20039. /**
  20040. * @constructor
  20041. */
  20042. function Scheduler(ecInstance, api) {
  20043. // this._pipelineMap = createHashMap();
  20044. this.ecInstance = ecInstance;
  20045. this.api = api;
  20046. this.unfinished;
  20047. /**
  20048. * @private
  20049. * @type {
  20050. * [handlerUID: string]: {
  20051. * seriesTaskMap?: {
  20052. * [seriesUID: string]: Task
  20053. * },
  20054. * overallTask?: Task
  20055. * }
  20056. * }
  20057. */
  20058. this._stageTaskMap = createHashMap();
  20059. }
  20060. var proto = Scheduler.prototype;
  20061. // If seriesModel provided, incremental threshold is check by series data.
  20062. proto.getPerformArgs = function (task, isBlock) {
  20063. // For overall task
  20064. if (!task.__pipeline) {
  20065. return;
  20066. }
  20067. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20068. var pCtx = pipeline.context;
  20069. var incremental = !isBlock
  20070. && pipeline.progressiveEnabled
  20071. && (!pCtx || pCtx.incrementalRender)
  20072. && task.__idxInPipeline > pipeline.bockIndex;
  20073. return {step: incremental ? pipeline.step : null};
  20074. };
  20075. proto.getPipeline = function (pipelineId) {
  20076. return this._pipelineMap.get(pipelineId);
  20077. };
  20078. /**
  20079. * Current, progressive rendering starts from visual and layout.
  20080. * Always detect render mode in the same stage, avoiding that incorrect
  20081. * detection caused by data filtering.
  20082. * Caution:
  20083. * `updateStreamModes` use `seriesModel.getData()`.
  20084. */
  20085. proto.updateStreamModes = function (seriesModel, view) {
  20086. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20087. var data = seriesModel.getData();
  20088. var dataLen = data.count();
  20089. var incrementalRender = pipeline.progressiveEnabled
  20090. && view.incrementalPrepareRender
  20091. && dataLen >= pipeline.threshold;
  20092. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20093. seriesModel.pipelineContext = pipeline.context = {
  20094. incrementalRender: incrementalRender,
  20095. large: large
  20096. };
  20097. };
  20098. proto.restorePipelines = function (ecModel) {
  20099. var scheduler = this;
  20100. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20101. ecModel.eachSeries(function (seriesModel) {
  20102. var progressive = seriesModel.getProgressive();
  20103. var pipelineId = seriesModel.uid;
  20104. pipelineMap.set(pipelineId, {
  20105. id: pipelineId,
  20106. head: null,
  20107. tail: null,
  20108. threshold: seriesModel.getProgressiveThreshold(),
  20109. progressiveEnabled: progressive
  20110. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20111. bockIndex: -1,
  20112. step: progressive || 700, // ??? Temporarily number
  20113. count: 0
  20114. });
  20115. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20116. });
  20117. };
  20118. proto.prepareStageTasks = function (stageHandlers, useClearVisual) {
  20119. var stageTaskMap = this._stageTaskMap;
  20120. var ecModel = this.ecInstance.getModel();
  20121. var api = this.api;
  20122. each$1(stageHandlers, function (handler) {
  20123. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20124. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20125. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20126. }, this);
  20127. };
  20128. proto.prepareView = function (view, model, ecModel, api) {
  20129. var renderTask = view.renderTask;
  20130. var context = renderTask.context;
  20131. context.model = model;
  20132. context.ecModel = ecModel;
  20133. context.api = api;
  20134. renderTask.__block = !view.incrementalPrepareRender;
  20135. pipe(this, model, renderTask);
  20136. };
  20137. proto.performDataProcessorTasks = function (stageHandlers, ecModel, payload) {
  20138. // If we do not use `block` here, it should be considered when to update modes.
  20139. performStageTasks(this, stageHandlers, ecModel, payload, {block: true});
  20140. };
  20141. // opt
  20142. // opt.visualType: 'visual' or 'layout'
  20143. // opt.setDirty
  20144. proto.performVisualTasks = function (stageHandlers, ecModel, payload, opt) {
  20145. performStageTasks(this, stageHandlers, ecModel, payload, opt);
  20146. };
  20147. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20148. opt = opt || {};
  20149. var unfinished;
  20150. each$1(stageHandlers, function (stageHandler, idx) {
  20151. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20152. return;
  20153. }
  20154. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20155. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20156. var overallTask = stageHandlerRecord.overallTask;
  20157. if (overallTask) {
  20158. var overallNeedDirty;
  20159. var agentStubMap = overallTask.agentStubMap;
  20160. agentStubMap.each(function (stub) {
  20161. if (needSetDirty(opt, stub)) {
  20162. stub.dirty();
  20163. overallNeedDirty = true;
  20164. }
  20165. });
  20166. overallNeedDirty && overallTask.dirty();
  20167. updatePayload(overallTask, payload);
  20168. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20169. // Execute stubs firstly, which may set the overall task dirty,
  20170. // then execute the overall task. And stub will call seriesModel.setData,
  20171. // which ensures that in the overallTask seriesModel.getData() will not
  20172. // return incorrect data.
  20173. agentStubMap.each(function (stub) {
  20174. stub.perform(performArgs);
  20175. });
  20176. unfinished |= overallTask.perform(performArgs);
  20177. }
  20178. else if (seriesTaskMap) {
  20179. seriesTaskMap.each(function (task, pipelineId) {
  20180. if (needSetDirty(opt, task)) {
  20181. task.dirty();
  20182. }
  20183. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20184. performArgs.skip = !stageHandler.performRawSeries
  20185. && ecModel.isSeriesFiltered(task.context.model);
  20186. updatePayload(task, payload);
  20187. unfinished |= task.perform(performArgs);
  20188. });
  20189. }
  20190. });
  20191. function needSetDirty(opt, task) {
  20192. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20193. }
  20194. scheduler.unfinished |= unfinished;
  20195. }
  20196. proto.performSeriesTasks = function (ecModel) {
  20197. var unfinished;
  20198. ecModel.eachSeries(function (seriesModel) {
  20199. // Progress to the end for dataInit and dataRestore.
  20200. unfinished |= seriesModel.dataTask.perform();
  20201. });
  20202. this.unfinished |= unfinished;
  20203. };
  20204. proto.plan = function () {
  20205. // Travel pipelines, check block.
  20206. this._pipelineMap.each(function (pipeline) {
  20207. var task = pipeline.tail;
  20208. do {
  20209. if (task.__block) {
  20210. pipeline.bockIndex = task.__idxInPipeline;
  20211. break;
  20212. }
  20213. task = task.getUpstream();
  20214. }
  20215. while (task);
  20216. });
  20217. };
  20218. var updatePayload = proto.updatePayload = function (task, payload) {
  20219. payload !== 'remain' && (task.context.payload = payload);
  20220. };
  20221. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20222. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20223. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20224. var seriesType = stageHandler.seriesType;
  20225. var getTargetSeries = stageHandler.getTargetSeries;
  20226. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20227. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20228. // it works but it may cause other irrelevant charts blocked.
  20229. if (stageHandler.createOnAllSeries) {
  20230. ecModel.eachRawSeries(create);
  20231. }
  20232. else if (seriesType) {
  20233. ecModel.eachRawSeriesByType(seriesType, create);
  20234. }
  20235. else if (getTargetSeries) {
  20236. getTargetSeries(ecModel, api).each(create);
  20237. }
  20238. function create(seriesModel) {
  20239. var pipelineId = seriesModel.uid;
  20240. // Init tasks for each seriesModel only once.
  20241. // Reuse original task instance.
  20242. var task = seriesTaskMap.get(pipelineId)
  20243. || seriesTaskMap.set(pipelineId, createTask({
  20244. plan: seriesTaskPlan,
  20245. reset: seriesTaskReset,
  20246. count: seriesTaskCount
  20247. }));
  20248. task.context = {
  20249. model: seriesModel,
  20250. ecModel: ecModel,
  20251. api: api,
  20252. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20253. plan: stageHandler.plan,
  20254. reset: stageHandler.reset,
  20255. scheduler: scheduler
  20256. };
  20257. pipe(scheduler, seriesModel, task);
  20258. }
  20259. // Clear unused series tasks.
  20260. var pipelineMap = scheduler._pipelineMap;
  20261. seriesTaskMap.each(function (task, pipelineId) {
  20262. if (!pipelineMap.get(pipelineId)) {
  20263. task.dispose();
  20264. seriesTaskMap.removeKey(pipelineId);
  20265. }
  20266. });
  20267. }
  20268. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20269. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20270. // For overall task, the function only be called on reset stage.
  20271. || createTask({reset: overallTaskReset});
  20272. overallTask.context = {
  20273. ecModel: ecModel,
  20274. api: api,
  20275. overallReset: stageHandler.overallReset,
  20276. scheduler: scheduler
  20277. };
  20278. // Reuse orignal stubs.
  20279. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20280. var seriesType = stageHandler.seriesType;
  20281. var getTargetSeries = stageHandler.getTargetSeries;
  20282. var overallProgress = true;
  20283. var isOverallFilter = stageHandler.isOverallFilter;
  20284. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20285. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20286. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20287. // we set the pipeline block.
  20288. if (seriesType) {
  20289. ecModel.eachRawSeriesByType(seriesType, createStub);
  20290. }
  20291. else if (getTargetSeries) {
  20292. getTargetSeries(ecModel, api).each(createStub);
  20293. }
  20294. // Otherwise, (usually it is legancy case), the overall task will only be
  20295. // executed when upstream dirty. Otherwise the progressive rendering of all
  20296. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20297. // dirty info from upsteam.
  20298. else {
  20299. overallProgress = false;
  20300. each$1(ecModel.getSeries(), createStub);
  20301. }
  20302. function createStub(seriesModel) {
  20303. var pipelineId = seriesModel.uid;
  20304. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20305. {reset: stubReset, onDirty: stubOnDirty}
  20306. ));
  20307. stub.context = {
  20308. model: seriesModel,
  20309. overallProgress: overallProgress,
  20310. isOverallFilter: isOverallFilter
  20311. };
  20312. stub.agent = overallTask;
  20313. stub.__block = overallProgress;
  20314. pipe(scheduler, seriesModel, stub);
  20315. }
  20316. // Clear unused stubs.
  20317. var pipelineMap = scheduler._pipelineMap;
  20318. agentStubMap.each(function (stub, pipelineId) {
  20319. if (!pipelineMap.get(pipelineId)) {
  20320. stub.dispose();
  20321. agentStubMap.removeKey(pipelineId);
  20322. }
  20323. });
  20324. }
  20325. function overallTaskReset(context) {
  20326. context.overallReset(
  20327. context.ecModel, context.api, context.payload
  20328. );
  20329. }
  20330. function stubReset(context, upstreamContext) {
  20331. return context.overallProgress && stubProgress;
  20332. }
  20333. function stubProgress() {
  20334. this.agent.dirty();
  20335. this.getDownstream().dirty();
  20336. }
  20337. function stubOnDirty() {
  20338. this.agent && this.agent.dirty();
  20339. }
  20340. function seriesTaskPlan(context) {
  20341. return context.plan && context.plan(
  20342. context.model, context.ecModel, context.api, context.payload
  20343. );
  20344. }
  20345. function seriesTaskReset(context) {
  20346. if (context.useClearVisual) {
  20347. context.data.clearAllVisual();
  20348. }
  20349. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20350. context.model, context.ecModel, context.api, context.payload
  20351. ));
  20352. if (resetDefines.length) {
  20353. return seriesTaskProgress;
  20354. }
  20355. }
  20356. function seriesTaskProgress(params, context) {
  20357. var data = context.data;
  20358. var resetDefines = context.resetDefines;
  20359. for (var k = 0; k < resetDefines.length; k++) {
  20360. var resetDefine = resetDefines[k];
  20361. if (resetDefine && resetDefine.dataEach) {
  20362. for (var i = params.start; i < params.end; i++) {
  20363. resetDefine.dataEach(data, i);
  20364. }
  20365. }
  20366. else if (resetDefine && resetDefine.progress) {
  20367. resetDefine.progress(params, data);
  20368. }
  20369. }
  20370. }
  20371. function seriesTaskCount(context) {
  20372. return context.data.count();
  20373. }
  20374. function pipe(scheduler, seriesModel, task) {
  20375. var pipelineId = seriesModel.uid;
  20376. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20377. !pipeline.head && (pipeline.head = task);
  20378. pipeline.tail && pipeline.tail.pipe(task);
  20379. pipeline.tail = task;
  20380. task.__idxInPipeline = pipeline.count++;
  20381. task.__pipeline = pipeline;
  20382. }
  20383. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20384. if (isFunction$1(stageHandler)) {
  20385. stageHandler = {
  20386. overallReset: stageHandler,
  20387. seriesType: detectSeriseType(stageHandler)
  20388. };
  20389. }
  20390. stageHandler.uid = getUID('stageHandler');
  20391. visualType && (stageHandler.visualType = visualType);
  20392. return stageHandler;
  20393. };
  20394. /**
  20395. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20396. * To ensure that they can work normally, they should work in block mode, that is,
  20397. * they should not be started util the previous tasks finished. So they cause the
  20398. * progressive rendering disabled. We try to detect the series type, to narrow down
  20399. * the block range to only the series type they concern, but not all series.
  20400. */
  20401. function detectSeriseType(legacyFunc) {
  20402. seriesType = null;
  20403. try {
  20404. // Assume there is no async when calling `eachSeriesByType`.
  20405. legacyFunc(ecModelMock, apiMock);
  20406. }
  20407. catch (e) {
  20408. }
  20409. return seriesType;
  20410. }
  20411. var ecModelMock = {};
  20412. var apiMock = {};
  20413. var seriesType;
  20414. mockMethods(ecModelMock, GlobalModel);
  20415. mockMethods(apiMock, ExtensionAPI);
  20416. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20417. seriesType = type;
  20418. };
  20419. ecModelMock.eachComponent = function (cond) {
  20420. if (cond.mainType === 'series' && cond.subType) {
  20421. seriesType = cond.subType;
  20422. }
  20423. };
  20424. function mockMethods(target, Clz) {
  20425. for (var name in Clz.prototype) {
  20426. // Do not use hasOwnProperty
  20427. target[name] = noop;
  20428. }
  20429. }
  20430. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20431. var lightTheme = {
  20432. color: colorAll,
  20433. colorLayer: [
  20434. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20435. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20436. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20437. colorAll
  20438. ]
  20439. };
  20440. var contrastColor = '#eee';
  20441. var axisCommon = function () {
  20442. return {
  20443. axisLine: {
  20444. lineStyle: {
  20445. color: contrastColor
  20446. }
  20447. },
  20448. axisTick: {
  20449. lineStyle: {
  20450. color: contrastColor
  20451. }
  20452. },
  20453. axisLabel: {
  20454. textStyle: {
  20455. color: contrastColor
  20456. }
  20457. },
  20458. splitLine: {
  20459. lineStyle: {
  20460. type: 'dashed',
  20461. color: '#aaa'
  20462. }
  20463. },
  20464. splitArea: {
  20465. areaStyle: {
  20466. color: contrastColor
  20467. }
  20468. }
  20469. };
  20470. };
  20471. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20472. var theme = {
  20473. color: colorPalette,
  20474. backgroundColor: '#333',
  20475. tooltip: {
  20476. axisPointer: {
  20477. lineStyle: {
  20478. color: contrastColor
  20479. },
  20480. crossStyle: {
  20481. color: contrastColor
  20482. }
  20483. }
  20484. },
  20485. legend: {
  20486. textStyle: {
  20487. color: contrastColor
  20488. }
  20489. },
  20490. textStyle: {
  20491. color: contrastColor
  20492. },
  20493. title: {
  20494. textStyle: {
  20495. color: contrastColor
  20496. }
  20497. },
  20498. toolbox: {
  20499. iconStyle: {
  20500. normal: {
  20501. borderColor: contrastColor
  20502. }
  20503. }
  20504. },
  20505. dataZoom: {
  20506. textStyle: {
  20507. color: contrastColor
  20508. }
  20509. },
  20510. visualMap: {
  20511. textStyle: {
  20512. color: contrastColor
  20513. }
  20514. },
  20515. timeline: {
  20516. lineStyle: {
  20517. color: contrastColor
  20518. },
  20519. itemStyle: {
  20520. normal: {
  20521. color: colorPalette[1]
  20522. }
  20523. },
  20524. label: {
  20525. normal: {
  20526. textStyle: {
  20527. color: contrastColor
  20528. }
  20529. }
  20530. },
  20531. controlStyle: {
  20532. normal: {
  20533. color: contrastColor,
  20534. borderColor: contrastColor
  20535. }
  20536. }
  20537. },
  20538. timeAxis: axisCommon(),
  20539. logAxis: axisCommon(),
  20540. valueAxis: axisCommon(),
  20541. categoryAxis: axisCommon(),
  20542. line: {
  20543. symbol: 'circle'
  20544. },
  20545. graph: {
  20546. color: colorPalette
  20547. },
  20548. gauge: {
  20549. title: {
  20550. textStyle: {
  20551. color: contrastColor
  20552. }
  20553. }
  20554. },
  20555. candlestick: {
  20556. itemStyle: {
  20557. normal: {
  20558. color: '#FD1050',
  20559. color0: '#0CF49B',
  20560. borderColor: '#FD1050',
  20561. borderColor0: '#0CF49B'
  20562. }
  20563. }
  20564. }
  20565. };
  20566. theme.categoryAxis.splitLine.show = false;
  20567. /*!
  20568. * ECharts, a free, powerful charting and visualization library.
  20569. *
  20570. * Copyright (c) 2017, Baidu Inc.
  20571. * All rights reserved.
  20572. *
  20573. * LICENSE
  20574. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20575. */
  20576. var assert = assert$1;
  20577. var each = each$1;
  20578. var isFunction = isFunction$1;
  20579. var isObject = isObject$1;
  20580. var parseClassType = ComponentModel.parseClassType;
  20581. var version = '4.0.2';
  20582. var dependencies = {
  20583. zrender: '4.0.1'
  20584. };
  20585. var TEST_FRAME_REMAIN_TIME = 1;
  20586. var PRIORITY_PROCESSOR_FILTER = 1000;
  20587. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20588. var PRIORITY_VISUAL_LAYOUT = 1000;
  20589. var PRIORITY_VISUAL_GLOBAL = 2000;
  20590. var PRIORITY_VISUAL_CHART = 3000;
  20591. var PRIORITY_VISUAL_COMPONENT = 4000;
  20592. // FIXME
  20593. // necessary?
  20594. var PRIORITY_VISUAL_BRUSH = 5000;
  20595. var PRIORITY = {
  20596. PROCESSOR: {
  20597. FILTER: PRIORITY_PROCESSOR_FILTER,
  20598. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20599. },
  20600. VISUAL: {
  20601. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20602. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20603. CHART: PRIORITY_VISUAL_CHART,
  20604. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20605. BRUSH: PRIORITY_VISUAL_BRUSH
  20606. }
  20607. };
  20608. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20609. // where they must not be invoked nestedly, except the only case: invoke
  20610. // dispatchAction with updateMethod "none" in main process.
  20611. // This flag is used to carry out this rule.
  20612. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20613. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20614. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  20615. var OPTION_UPDATED = '__optionUpdated';
  20616. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20617. function createRegisterEventWithLowercaseName(method) {
  20618. return function (eventName, handler, context) {
  20619. // Event name is all lowercase
  20620. eventName = eventName && eventName.toLowerCase();
  20621. Eventful.prototype[method].call(this, eventName, handler, context);
  20622. };
  20623. }
  20624. /**
  20625. * @module echarts~MessageCenter
  20626. */
  20627. function MessageCenter() {
  20628. Eventful.call(this);
  20629. }
  20630. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20631. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20632. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20633. mixin(MessageCenter, Eventful);
  20634. /**
  20635. * @module echarts~ECharts
  20636. */
  20637. function ECharts(dom, theme$$1, opts) {
  20638. opts = opts || {};
  20639. // Get theme by name
  20640. if (typeof theme$$1 === 'string') {
  20641. theme$$1 = themeStorage[theme$$1];
  20642. }
  20643. /**
  20644. * @type {string}
  20645. */
  20646. this.id;
  20647. /**
  20648. * Group id
  20649. * @type {string}
  20650. */
  20651. this.group;
  20652. /**
  20653. * @type {HTMLElement}
  20654. * @private
  20655. */
  20656. this._dom = dom;
  20657. var defaultRenderer = 'canvas';
  20658. if (__DEV__) {
  20659. defaultRenderer = (
  20660. typeof window === 'undefined' ? global : window
  20661. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20662. }
  20663. /**
  20664. * @type {module:zrender/ZRender}
  20665. * @private
  20666. */
  20667. var zr = this._zr = init$1(dom, {
  20668. renderer: opts.renderer || defaultRenderer,
  20669. devicePixelRatio: opts.devicePixelRatio,
  20670. width: opts.width,
  20671. height: opts.height
  20672. });
  20673. /**
  20674. * Expect 60 pfs.
  20675. * @type {Function}
  20676. * @private
  20677. */
  20678. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20679. var theme$$1 = clone(theme$$1);
  20680. theme$$1 && backwardCompat(theme$$1, true);
  20681. /**
  20682. * @type {Object}
  20683. * @private
  20684. */
  20685. this._theme = theme$$1;
  20686. /**
  20687. * @type {Array.<module:echarts/view/Chart>}
  20688. * @private
  20689. */
  20690. this._chartsViews = [];
  20691. /**
  20692. * @type {Object.<string, module:echarts/view/Chart>}
  20693. * @private
  20694. */
  20695. this._chartsMap = {};
  20696. /**
  20697. * @type {Array.<module:echarts/view/Component>}
  20698. * @private
  20699. */
  20700. this._componentsViews = [];
  20701. /**
  20702. * @type {Object.<string, module:echarts/view/Component>}
  20703. * @private
  20704. */
  20705. this._componentsMap = {};
  20706. /**
  20707. * @type {module:echarts/CoordinateSystem}
  20708. * @private
  20709. */
  20710. this._coordSysMgr = new CoordinateSystemManager();
  20711. /**
  20712. * @type {module:echarts/ExtensionAPI}
  20713. * @private
  20714. */
  20715. var api = this._api = createExtensionAPI(this);
  20716. /**
  20717. * @type {module:echarts/stream/Scheduler}
  20718. */
  20719. this._scheduler = new Scheduler(this, api);
  20720. Eventful.call(this);
  20721. /**
  20722. * @type {module:echarts~MessageCenter}
  20723. * @private
  20724. */
  20725. this._messageCenter = new MessageCenter();
  20726. // this._scheduler = new Scheduler();
  20727. // Init mouse events
  20728. this._initEvents();
  20729. // In case some people write `window.onresize = chart.resize`
  20730. this.resize = bind(this.resize, this);
  20731. // Can't dispatch action during rendering procedure
  20732. this._pendingActions = [];
  20733. // Sort on demand
  20734. function prioritySortFunc(a, b) {
  20735. return a.__prio - b.__prio;
  20736. }
  20737. sort(visualFuncs, prioritySortFunc);
  20738. sort(dataProcessorFuncs, prioritySortFunc);
  20739. zr.animation.on('frame', this._onframe, this);
  20740. // ECharts instance can be used as value.
  20741. setAsPrimitive(this);
  20742. }
  20743. var echartsProto = ECharts.prototype;
  20744. echartsProto._onframe = function () {
  20745. if (this._disposed) {
  20746. return;
  20747. }
  20748. var scheduler = this._scheduler;
  20749. // Lazy update
  20750. if (this[OPTION_UPDATED]) {
  20751. var silent = this[OPTION_UPDATED].silent;
  20752. this[IN_MAIN_PROCESS] = true;
  20753. prepare(this);
  20754. updateMethods.update.call(this);
  20755. this[IN_MAIN_PROCESS] = false;
  20756. this[OPTION_UPDATED] = false;
  20757. flushPendingActions.call(this, silent);
  20758. triggerUpdatedEvent.call(this, silent);
  20759. }
  20760. // Avoid do both lazy update and progress in one frame.
  20761. else if (scheduler.unfinished) {
  20762. // Stream progress.
  20763. var remainTime = TEST_FRAME_REMAIN_TIME;
  20764. var ecModel = this._model;
  20765. var api = this._api;
  20766. scheduler.unfinished = false;
  20767. do {
  20768. var startTime = +new Date();
  20769. scheduler.performSeriesTasks(ecModel);
  20770. // Currently dataProcessorFuncs do not check threshold.
  20771. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel);
  20772. updateStreamModes(this, ecModel);
  20773. // Do not update coordinate system here. Because that coord system update in
  20774. // each frame is not a good user experience. So we follow the rule that
  20775. // the extent of the coordinate system is determin in the first frame (the
  20776. // frame is executed immedietely after task reset.
  20777. // this._coordSysMgr.update(ecModel, api);
  20778. // console.log('--- ec frame visual ---', remainTime);
  20779. scheduler.performVisualTasks(visualFuncs, ecModel);
  20780. renderSeries(this, this._model, api, 'remain');
  20781. remainTime -= (+new Date() - startTime);
  20782. }
  20783. while (remainTime > 0 && scheduler.unfinished);
  20784. if (!scheduler.unfinished) {
  20785. this._zr && this._zr.flush();
  20786. this.trigger('finished');
  20787. }
  20788. // Else, zr flushing be ensue within the same frame,
  20789. // because zr flushing is after onframe event.
  20790. }
  20791. };
  20792. /**
  20793. * @return {HTMLElement}
  20794. */
  20795. echartsProto.getDom = function () {
  20796. return this._dom;
  20797. };
  20798. /**
  20799. * @return {module:zrender~ZRender}
  20800. */
  20801. echartsProto.getZr = function () {
  20802. return this._zr;
  20803. };
  20804. /**
  20805. * Usage:
  20806. * chart.setOption(option, notMerge, lazyUpdate);
  20807. * chart.setOption(option, {
  20808. * notMerge: ...,
  20809. * lazyUpdate: ...,
  20810. * silent: ...
  20811. * });
  20812. *
  20813. * @param {Object} option
  20814. * @param {Object|boolean} [opts] opts or notMerge.
  20815. * @param {boolean} [opts.notMerge=false]
  20816. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  20817. */
  20818. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  20819. if (__DEV__) {
  20820. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  20821. }
  20822. var silent;
  20823. if (isObject(notMerge)) {
  20824. lazyUpdate = notMerge.lazyUpdate;
  20825. silent = notMerge.silent;
  20826. notMerge = notMerge.notMerge;
  20827. }
  20828. this[IN_MAIN_PROCESS] = true;
  20829. if (!this._model || notMerge) {
  20830. var optionManager = new OptionManager(this._api);
  20831. var theme$$1 = this._theme;
  20832. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  20833. ecModel.scheduler = this._scheduler;
  20834. ecModel.init(null, null, theme$$1, optionManager);
  20835. }
  20836. this._model.setOption(option, optionPreprocessorFuncs);
  20837. if (lazyUpdate) {
  20838. this[OPTION_UPDATED] = {silent: silent};
  20839. this[IN_MAIN_PROCESS] = false;
  20840. }
  20841. else {
  20842. prepare(this);
  20843. updateMethods.update.call(this);
  20844. // Ensure zr refresh sychronously, and then pixel in canvas can be
  20845. // fetched after `setOption`.
  20846. this._zr.flush();
  20847. this[OPTION_UPDATED] = false;
  20848. this[IN_MAIN_PROCESS] = false;
  20849. flushPendingActions.call(this, silent);
  20850. triggerUpdatedEvent.call(this, silent);
  20851. }
  20852. };
  20853. /**
  20854. * @DEPRECATED
  20855. */
  20856. echartsProto.setTheme = function () {
  20857. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  20858. };
  20859. /**
  20860. * @return {module:echarts/model/Global}
  20861. */
  20862. echartsProto.getModel = function () {
  20863. return this._model;
  20864. };
  20865. /**
  20866. * @return {Object}
  20867. */
  20868. echartsProto.getOption = function () {
  20869. return this._model && this._model.getOption();
  20870. };
  20871. /**
  20872. * @return {number}
  20873. */
  20874. echartsProto.getWidth = function () {
  20875. return this._zr.getWidth();
  20876. };
  20877. /**
  20878. * @return {number}
  20879. */
  20880. echartsProto.getHeight = function () {
  20881. return this._zr.getHeight();
  20882. };
  20883. /**
  20884. * @return {number}
  20885. */
  20886. echartsProto.getDevicePixelRatio = function () {
  20887. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  20888. };
  20889. /**
  20890. * Get canvas which has all thing rendered
  20891. * @param {Object} opts
  20892. * @param {string} [opts.backgroundColor]
  20893. * @return {string}
  20894. */
  20895. echartsProto.getRenderedCanvas = function (opts) {
  20896. if (!env$1.canvasSupported) {
  20897. return;
  20898. }
  20899. opts = opts || {};
  20900. opts.pixelRatio = opts.pixelRatio || 1;
  20901. opts.backgroundColor = opts.backgroundColor
  20902. || this._model.get('backgroundColor');
  20903. var zr = this._zr;
  20904. var list = zr.storage.getDisplayList();
  20905. // Stop animations
  20906. each$1(list, function (el) {
  20907. el.stopAnimation(true);
  20908. });
  20909. return zr.painter.getRenderedCanvas(opts);
  20910. };
  20911. /**
  20912. * Get svg data url
  20913. * @return {string}
  20914. */
  20915. echartsProto.getSvgDataUrl = function () {
  20916. if (!env$1.svgSupported) {
  20917. return;
  20918. }
  20919. var zr = this._zr;
  20920. var list = zr.storage.getDisplayList();
  20921. // Stop animations
  20922. each$1(list, function (el) {
  20923. el.stopAnimation(true);
  20924. });
  20925. return zr.painter.pathToSvg();
  20926. };
  20927. /**
  20928. * @return {string}
  20929. * @param {Object} opts
  20930. * @param {string} [opts.type='png']
  20931. * @param {string} [opts.pixelRatio=1]
  20932. * @param {string} [opts.backgroundColor]
  20933. * @param {string} [opts.excludeComponents]
  20934. */
  20935. echartsProto.getDataURL = function (opts) {
  20936. opts = opts || {};
  20937. var excludeComponents = opts.excludeComponents;
  20938. var ecModel = this._model;
  20939. var excludesComponentViews = [];
  20940. var self = this;
  20941. each(excludeComponents, function (componentType) {
  20942. ecModel.eachComponent({
  20943. mainType: componentType
  20944. }, function (component) {
  20945. var view = self._componentsMap[component.__viewId];
  20946. if (!view.group.ignore) {
  20947. excludesComponentViews.push(view);
  20948. view.group.ignore = true;
  20949. }
  20950. });
  20951. });
  20952. var url = this._zr.painter.getType() === 'svg'
  20953. ? this.getSvgDataUrl()
  20954. : this.getRenderedCanvas(opts).toDataURL(
  20955. 'image/' + (opts && opts.type || 'png')
  20956. );
  20957. each(excludesComponentViews, function (view) {
  20958. view.group.ignore = false;
  20959. });
  20960. return url;
  20961. };
  20962. /**
  20963. * @return {string}
  20964. * @param {Object} opts
  20965. * @param {string} [opts.type='png']
  20966. * @param {string} [opts.pixelRatio=1]
  20967. * @param {string} [opts.backgroundColor]
  20968. */
  20969. echartsProto.getConnectedDataURL = function (opts) {
  20970. if (!env$1.canvasSupported) {
  20971. return;
  20972. }
  20973. var groupId = this.group;
  20974. var mathMin = Math.min;
  20975. var mathMax = Math.max;
  20976. var MAX_NUMBER = Infinity;
  20977. if (connectedGroups[groupId]) {
  20978. var left = MAX_NUMBER;
  20979. var top = MAX_NUMBER;
  20980. var right = -MAX_NUMBER;
  20981. var bottom = -MAX_NUMBER;
  20982. var canvasList = [];
  20983. var dpr = (opts && opts.pixelRatio) || 1;
  20984. each$1(instances, function (chart, id) {
  20985. if (chart.group === groupId) {
  20986. var canvas = chart.getRenderedCanvas(
  20987. clone(opts)
  20988. );
  20989. var boundingRect = chart.getDom().getBoundingClientRect();
  20990. left = mathMin(boundingRect.left, left);
  20991. top = mathMin(boundingRect.top, top);
  20992. right = mathMax(boundingRect.right, right);
  20993. bottom = mathMax(boundingRect.bottom, bottom);
  20994. canvasList.push({
  20995. dom: canvas,
  20996. left: boundingRect.left,
  20997. top: boundingRect.top
  20998. });
  20999. }
  21000. });
  21001. left *= dpr;
  21002. top *= dpr;
  21003. right *= dpr;
  21004. bottom *= dpr;
  21005. var width = right - left;
  21006. var height = bottom - top;
  21007. var targetCanvas = createCanvas();
  21008. targetCanvas.width = width;
  21009. targetCanvas.height = height;
  21010. var zr = init$1(targetCanvas);
  21011. each(canvasList, function (item) {
  21012. var img = new ZImage({
  21013. style: {
  21014. x: item.left * dpr - left,
  21015. y: item.top * dpr - top,
  21016. image: item.dom
  21017. }
  21018. });
  21019. zr.add(img);
  21020. });
  21021. zr.refreshImmediately();
  21022. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21023. }
  21024. else {
  21025. return this.getDataURL(opts);
  21026. }
  21027. };
  21028. /**
  21029. * Convert from logical coordinate system to pixel coordinate system.
  21030. * See CoordinateSystem#convertToPixel.
  21031. * @param {string|Object} finder
  21032. * If string, e.g., 'geo', means {geoIndex: 0}.
  21033. * If Object, could contain some of these properties below:
  21034. * {
  21035. * seriesIndex / seriesId / seriesName,
  21036. * geoIndex / geoId, geoName,
  21037. * bmapIndex / bmapId / bmapName,
  21038. * xAxisIndex / xAxisId / xAxisName,
  21039. * yAxisIndex / yAxisId / yAxisName,
  21040. * gridIndex / gridId / gridName,
  21041. * ... (can be extended)
  21042. * }
  21043. * @param {Array|number} value
  21044. * @return {Array|number} result
  21045. */
  21046. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21047. /**
  21048. * Convert from pixel coordinate system to logical coordinate system.
  21049. * See CoordinateSystem#convertFromPixel.
  21050. * @param {string|Object} finder
  21051. * If string, e.g., 'geo', means {geoIndex: 0}.
  21052. * If Object, could contain some of these properties below:
  21053. * {
  21054. * seriesIndex / seriesId / seriesName,
  21055. * geoIndex / geoId / geoName,
  21056. * bmapIndex / bmapId / bmapName,
  21057. * xAxisIndex / xAxisId / xAxisName,
  21058. * yAxisIndex / yAxisId / yAxisName
  21059. * gridIndex / gridId / gridName,
  21060. * ... (can be extended)
  21061. * }
  21062. * @param {Array|number} value
  21063. * @return {Array|number} result
  21064. */
  21065. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21066. function doConvertPixel(methodName, finder, value) {
  21067. var ecModel = this._model;
  21068. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21069. var result;
  21070. finder = parseFinder(ecModel, finder);
  21071. for (var i = 0; i < coordSysList.length; i++) {
  21072. var coordSys = coordSysList[i];
  21073. if (coordSys[methodName]
  21074. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21075. ) {
  21076. return result;
  21077. }
  21078. }
  21079. if (__DEV__) {
  21080. console.warn(
  21081. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21082. );
  21083. }
  21084. }
  21085. /**
  21086. * Is the specified coordinate systems or components contain the given pixel point.
  21087. * @param {string|Object} finder
  21088. * If string, e.g., 'geo', means {geoIndex: 0}.
  21089. * If Object, could contain some of these properties below:
  21090. * {
  21091. * seriesIndex / seriesId / seriesName,
  21092. * geoIndex / geoId / geoName,
  21093. * bmapIndex / bmapId / bmapName,
  21094. * xAxisIndex / xAxisId / xAxisName,
  21095. * yAxisIndex / yAxisId / yAxisName,
  21096. * gridIndex / gridId / gridName,
  21097. * ... (can be extended)
  21098. * }
  21099. * @param {Array|number} value
  21100. * @return {boolean} result
  21101. */
  21102. echartsProto.containPixel = function (finder, value) {
  21103. var ecModel = this._model;
  21104. var result;
  21105. finder = parseFinder(ecModel, finder);
  21106. each$1(finder, function (models, key) {
  21107. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21108. var coordSys = model.coordinateSystem;
  21109. if (coordSys && coordSys.containPoint) {
  21110. result |= !!coordSys.containPoint(value);
  21111. }
  21112. else if (key === 'seriesModels') {
  21113. var view = this._chartsMap[model.__viewId];
  21114. if (view && view.containPoint) {
  21115. result |= view.containPoint(value, model);
  21116. }
  21117. else {
  21118. if (__DEV__) {
  21119. console.warn(key + ': ' + (view
  21120. ? 'The found component do not support containPoint.'
  21121. : 'No view mapping to the found component.'
  21122. ));
  21123. }
  21124. }
  21125. }
  21126. else {
  21127. if (__DEV__) {
  21128. console.warn(key + ': containPoint is not supported');
  21129. }
  21130. }
  21131. }, this);
  21132. }, this);
  21133. return !!result;
  21134. };
  21135. /**
  21136. * Get visual from series or data.
  21137. * @param {string|Object} finder
  21138. * If string, e.g., 'series', means {seriesIndex: 0}.
  21139. * If Object, could contain some of these properties below:
  21140. * {
  21141. * seriesIndex / seriesId / seriesName,
  21142. * dataIndex / dataIndexInside
  21143. * }
  21144. * If dataIndex is not specified, series visual will be fetched,
  21145. * but not data item visual.
  21146. * If all of seriesIndex, seriesId, seriesName are not specified,
  21147. * visual will be fetched from first series.
  21148. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21149. */
  21150. echartsProto.getVisual = function (finder, visualType) {
  21151. var ecModel = this._model;
  21152. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21153. var seriesModel = finder.seriesModel;
  21154. if (__DEV__) {
  21155. if (!seriesModel) {
  21156. console.warn('There is no specified seires model');
  21157. }
  21158. }
  21159. var data = seriesModel.getData();
  21160. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21161. ? finder.dataIndexInside
  21162. : finder.hasOwnProperty('dataIndex')
  21163. ? data.indexOfRawIndex(finder.dataIndex)
  21164. : null;
  21165. return dataIndexInside != null
  21166. ? data.getItemVisual(dataIndexInside, visualType)
  21167. : data.getVisual(visualType);
  21168. };
  21169. /**
  21170. * Get view of corresponding component model
  21171. * @param {module:echarts/model/Component} componentModel
  21172. * @return {module:echarts/view/Component}
  21173. */
  21174. echartsProto.getViewOfComponentModel = function (componentModel) {
  21175. return this._componentsMap[componentModel.__viewId];
  21176. };
  21177. /**
  21178. * Get view of corresponding series model
  21179. * @param {module:echarts/model/Series} seriesModel
  21180. * @return {module:echarts/view/Chart}
  21181. */
  21182. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21183. return this._chartsMap[seriesModel.__viewId];
  21184. };
  21185. var updateMethods = {
  21186. prepareAndUpdate: function (payload) {
  21187. prepare(this);
  21188. updateMethods.update.call(this, payload);
  21189. },
  21190. /**
  21191. * @param {Object} payload
  21192. * @private
  21193. */
  21194. update: function (payload) {
  21195. // console.profile && console.profile('update');
  21196. var ecModel = this._model;
  21197. var api = this._api;
  21198. var zr = this._zr;
  21199. var coordSysMgr = this._coordSysMgr;
  21200. var scheduler = this._scheduler;
  21201. // update before setOption
  21202. if (!ecModel) {
  21203. return;
  21204. }
  21205. ecModel.restoreData(payload);
  21206. scheduler.performSeriesTasks(ecModel);
  21207. // TODO
  21208. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21209. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21210. // Create new coordinate system each update
  21211. // In LineView may save the old coordinate system and use it to get the orignal point
  21212. coordSysMgr.create(ecModel, api);
  21213. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);
  21214. // Current stream render is not supported in data process. So we can update
  21215. // stream modes after data processing, where the filtered data is used to
  21216. // deteming whether use progressive rendering.
  21217. updateStreamModes(this, ecModel);
  21218. stackSeriesData(ecModel);
  21219. coordSysMgr.update(ecModel, api);
  21220. clearColorPalette(ecModel);
  21221. scheduler.performVisualTasks(visualFuncs, ecModel, payload);
  21222. render(this, ecModel, api, payload);
  21223. // Set background
  21224. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21225. var painter = zr.painter;
  21226. // TODO all use clearColor ?
  21227. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  21228. zr.configLayer(0, {
  21229. clearColor: backgroundColor
  21230. });
  21231. }
  21232. else {
  21233. // In IE8
  21234. if (!env$1.canvasSupported) {
  21235. var colorArr = parse(backgroundColor);
  21236. backgroundColor = stringify(colorArr, 'rgb');
  21237. if (colorArr[3] === 0) {
  21238. backgroundColor = 'transparent';
  21239. }
  21240. }
  21241. if (backgroundColor.colorStops || backgroundColor.image) {
  21242. // Gradient background
  21243. // FIXME Fixed layer?
  21244. zr.configLayer(0, {
  21245. clearColor: backgroundColor
  21246. });
  21247. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  21248. this._dom.style.background = 'transparent';
  21249. }
  21250. else {
  21251. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  21252. zr.configLayer(0, {
  21253. clearColor: null
  21254. });
  21255. }
  21256. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  21257. this._dom.style.background = backgroundColor;
  21258. }
  21259. }
  21260. performPostUpdateFuncs(ecModel, api);
  21261. // console.profile && console.profileEnd('update');
  21262. },
  21263. /**
  21264. * @param {Object} payload
  21265. * @private
  21266. */
  21267. updateTransform: function (payload) {
  21268. var ecModel = this._model;
  21269. var ecIns = this;
  21270. var api = this._api;
  21271. // update before setOption
  21272. if (!ecModel) {
  21273. return;
  21274. }
  21275. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21276. var componentDirtyList = [];
  21277. ecModel.eachComponent(function (componentType, componentModel) {
  21278. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21279. if (componentView && componentView.__alive) {
  21280. if (componentView.updateTransform) {
  21281. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21282. result && result.update && componentDirtyList.push(componentView);
  21283. }
  21284. else {
  21285. componentDirtyList.push(componentView);
  21286. }
  21287. }
  21288. });
  21289. var seriesDirtyMap = createHashMap();
  21290. ecModel.eachSeries(function (seriesModel) {
  21291. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21292. if (chartView.updateTransform) {
  21293. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21294. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21295. }
  21296. else {
  21297. seriesDirtyMap.set(seriesModel.uid, 1);
  21298. }
  21299. });
  21300. clearColorPalette(ecModel);
  21301. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21302. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21303. this._scheduler.performVisualTasks(
  21304. visualFuncs, ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21305. );
  21306. // Currently, not call render of components. Geo render cost a lot.
  21307. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21308. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21309. performPostUpdateFuncs(ecModel, this._api);
  21310. },
  21311. /**
  21312. * @param {Object} payload
  21313. * @private
  21314. */
  21315. updateView: function (payload) {
  21316. var ecModel = this._model;
  21317. // update before setOption
  21318. if (!ecModel) {
  21319. return;
  21320. }
  21321. Chart.markUpdateMethod(payload, 'updateView');
  21322. clearColorPalette(ecModel);
  21323. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21324. this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21325. render(this, this._model, this._api, payload);
  21326. performPostUpdateFuncs(ecModel, this._api);
  21327. },
  21328. /**
  21329. * @param {Object} payload
  21330. * @private
  21331. */
  21332. updateVisual: function (payload) {
  21333. updateMethods.update.call(this, payload);
  21334. // var ecModel = this._model;
  21335. // // update before setOption
  21336. // if (!ecModel) {
  21337. // return;
  21338. // }
  21339. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21340. // clearColorPalette(ecModel);
  21341. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21342. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {visualType: 'visual', setDirty: true});
  21343. // render(this, this._model, this._api, payload);
  21344. // performPostUpdateFuncs(ecModel, this._api);
  21345. },
  21346. /**
  21347. * @param {Object} payload
  21348. * @private
  21349. */
  21350. updateLayout: function (payload) {
  21351. updateMethods.update.call(this, payload);
  21352. // var ecModel = this._model;
  21353. // // update before setOption
  21354. // if (!ecModel) {
  21355. // return;
  21356. // }
  21357. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21358. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21359. // // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21360. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21361. // render(this, this._model, this._api, payload);
  21362. // performPostUpdateFuncs(ecModel, this._api);
  21363. }
  21364. };
  21365. function prepare(ecIns) {
  21366. var ecModel = ecIns._model;
  21367. var scheduler = ecIns._scheduler;
  21368. scheduler.restorePipelines(ecModel);
  21369. scheduler.prepareStageTasks(dataProcessorFuncs);
  21370. scheduler.prepareStageTasks(visualFuncs);
  21371. prepareView(ecIns, 'component', ecModel, scheduler);
  21372. prepareView(ecIns, 'chart', ecModel, scheduler);
  21373. scheduler.plan();
  21374. }
  21375. /**
  21376. * @private
  21377. */
  21378. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21379. var ecModel = ecIns._model;
  21380. // broadcast
  21381. if (!mainType) {
  21382. // FIXME
  21383. // Chart will not be update directly here, except set dirty.
  21384. // But there is no such scenario now.
  21385. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21386. return;
  21387. }
  21388. var query = {};
  21389. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21390. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21391. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21392. var condition = {mainType: mainType, query: query};
  21393. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21394. // If dispatchAction before setOption, do nothing.
  21395. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21396. callView(ecIns[
  21397. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21398. ][model.__viewId]);
  21399. }, ecIns);
  21400. function callView(view) {
  21401. view && view.__alive && view[method] && view[method](
  21402. view.__model, ecModel, ecIns._api, payload
  21403. );
  21404. }
  21405. }
  21406. /**
  21407. * Resize the chart
  21408. * @param {Object} opts
  21409. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21410. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21411. * @param {boolean} [opts.silent=false]
  21412. */
  21413. echartsProto.resize = function (opts) {
  21414. if (__DEV__) {
  21415. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21416. }
  21417. this._zr.resize(opts);
  21418. var ecModel = this._model;
  21419. // Resize loading effect
  21420. this._loadingFX && this._loadingFX.resize();
  21421. if (!ecModel) {
  21422. return;
  21423. }
  21424. var optionChanged = ecModel.resetOption('media');
  21425. refresh(this, optionChanged, opts && opts.silent);
  21426. };
  21427. function refresh(ecIns, needPrepare, silent) {
  21428. ecIns[IN_MAIN_PROCESS] = true;
  21429. needPrepare && prepare(ecIns);
  21430. updateMethods.update.call(ecIns);
  21431. ecIns[IN_MAIN_PROCESS] = false;
  21432. flushPendingActions.call(ecIns, silent);
  21433. triggerUpdatedEvent.call(ecIns, silent);
  21434. }
  21435. function updateStreamModes(ecIns, ecModel) {
  21436. var chartsMap = ecIns._chartsMap;
  21437. var scheduler = ecIns._scheduler;
  21438. ecModel.eachSeries(function (seriesModel) {
  21439. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21440. });
  21441. }
  21442. /**
  21443. * Show loading effect
  21444. * @param {string} [name='default']
  21445. * @param {Object} [cfg]
  21446. */
  21447. echartsProto.showLoading = function (name, cfg) {
  21448. if (isObject(name)) {
  21449. cfg = name;
  21450. name = '';
  21451. }
  21452. name = name || 'default';
  21453. this.hideLoading();
  21454. if (!loadingEffects[name]) {
  21455. if (__DEV__) {
  21456. console.warn('Loading effects ' + name + ' not exists.');
  21457. }
  21458. return;
  21459. }
  21460. var el = loadingEffects[name](this._api, cfg);
  21461. var zr = this._zr;
  21462. this._loadingFX = el;
  21463. zr.add(el);
  21464. };
  21465. /**
  21466. * Hide loading effect
  21467. */
  21468. echartsProto.hideLoading = function () {
  21469. this._loadingFX && this._zr.remove(this._loadingFX);
  21470. this._loadingFX = null;
  21471. };
  21472. /**
  21473. * @param {Object} eventObj
  21474. * @return {Object}
  21475. */
  21476. echartsProto.makeActionFromEvent = function (eventObj) {
  21477. var payload = extend({}, eventObj);
  21478. payload.type = eventActionMap[eventObj.type];
  21479. return payload;
  21480. };
  21481. /**
  21482. * @pubilc
  21483. * @param {Object} payload
  21484. * @param {string} [payload.type] Action type
  21485. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21486. * @param {boolean} [opt.silent=false] Whether trigger events.
  21487. * @param {boolean} [opt.flush=undefined]
  21488. * true: Flush immediately, and then pixel in canvas can be fetched
  21489. * immediately. Caution: it might affect performance.
  21490. * false: Not not flush.
  21491. * undefined: Auto decide whether perform flush.
  21492. */
  21493. echartsProto.dispatchAction = function (payload, opt) {
  21494. if (!isObject(opt)) {
  21495. opt = {silent: !!opt};
  21496. }
  21497. if (!actions[payload.type]) {
  21498. return;
  21499. }
  21500. // Avoid dispatch action before setOption. Especially in `connect`.
  21501. if (!this._model) {
  21502. return;
  21503. }
  21504. // May dispatchAction in rendering procedure
  21505. if (this[IN_MAIN_PROCESS]) {
  21506. this._pendingActions.push(payload);
  21507. return;
  21508. }
  21509. doDispatchAction.call(this, payload, opt.silent);
  21510. if (opt.flush) {
  21511. this._zr.flush(true);
  21512. }
  21513. else if (opt.flush !== false && env$1.browser.weChat) {
  21514. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21515. // hang when sliding page (on touch event), which cause that zr does not
  21516. // refresh util user interaction finished, which is not expected.
  21517. // But `dispatchAction` may be called too frequently when pan on touch
  21518. // screen, which impacts performance if do not throttle them.
  21519. this._throttledZrFlush();
  21520. }
  21521. flushPendingActions.call(this, opt.silent);
  21522. triggerUpdatedEvent.call(this, opt.silent);
  21523. };
  21524. function doDispatchAction(payload, silent) {
  21525. var payloadType = payload.type;
  21526. var escapeConnect = payload.escapeConnect;
  21527. var actionWrap = actions[payloadType];
  21528. var actionInfo = actionWrap.actionInfo;
  21529. var cptType = (actionInfo.update || 'update').split(':');
  21530. var updateMethod = cptType.pop();
  21531. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21532. this[IN_MAIN_PROCESS] = true;
  21533. var payloads = [payload];
  21534. var batched = false;
  21535. // Batch action
  21536. if (payload.batch) {
  21537. batched = true;
  21538. payloads = map(payload.batch, function (item) {
  21539. item = defaults(extend({}, item), payload);
  21540. item.batch = null;
  21541. return item;
  21542. });
  21543. }
  21544. var eventObjBatch = [];
  21545. var eventObj;
  21546. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21547. each(payloads, function (batchItem) {
  21548. // Action can specify the event by return it.
  21549. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21550. // Emit event outside
  21551. eventObj = eventObj || extend({}, batchItem);
  21552. // Convert type to eventType
  21553. eventObj.type = actionInfo.event || eventObj.type;
  21554. eventObjBatch.push(eventObj);
  21555. // light update does not perform data process, layout and visual.
  21556. if (isHighDown) {
  21557. // method, payload, mainType, subType
  21558. updateDirectly(this, updateMethod, batchItem, 'series');
  21559. }
  21560. else if (cptType) {
  21561. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21562. }
  21563. }, this);
  21564. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21565. // Still dirty
  21566. if (this[OPTION_UPDATED]) {
  21567. // FIXME Pass payload ?
  21568. prepare(this);
  21569. updateMethods.update.call(this, payload);
  21570. this[OPTION_UPDATED] = false;
  21571. }
  21572. else {
  21573. updateMethods[updateMethod].call(this, payload);
  21574. }
  21575. }
  21576. // Follow the rule of action batch
  21577. if (batched) {
  21578. eventObj = {
  21579. type: actionInfo.event || payloadType,
  21580. escapeConnect: escapeConnect,
  21581. batch: eventObjBatch
  21582. };
  21583. }
  21584. else {
  21585. eventObj = eventObjBatch[0];
  21586. }
  21587. this[IN_MAIN_PROCESS] = false;
  21588. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21589. }
  21590. function flushPendingActions(silent) {
  21591. var pendingActions = this._pendingActions;
  21592. while (pendingActions.length) {
  21593. var payload = pendingActions.shift();
  21594. doDispatchAction.call(this, payload, silent);
  21595. }
  21596. }
  21597. function triggerUpdatedEvent(silent) {
  21598. !silent && this.trigger('updated');
  21599. }
  21600. /**
  21601. * @param {Object} params
  21602. * @param {number} params.seriesIndex
  21603. * @param {Array|TypedArray} params.data
  21604. */
  21605. echartsProto.appendData = function (params) {
  21606. var seriesIndex = params.seriesIndex;
  21607. var ecModel = this.getModel();
  21608. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21609. if (__DEV__) {
  21610. assert(params.data && seriesModel);
  21611. }
  21612. seriesModel.appendData(params);
  21613. this._scheduler.unfinished = true;
  21614. };
  21615. /**
  21616. * Register event
  21617. * @method
  21618. */
  21619. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21620. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21621. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21622. /**
  21623. * Prepare view instances of charts and components
  21624. * @param {module:echarts/model/Global} ecModel
  21625. * @private
  21626. */
  21627. function prepareView(ecIns, type, ecModel, scheduler) {
  21628. var isComponent = type === 'component';
  21629. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21630. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21631. var zr = ecIns._zr;
  21632. var api = ecIns._api;
  21633. for (var i = 0; i < viewList.length; i++) {
  21634. viewList[i].__alive = false;
  21635. }
  21636. isComponent
  21637. ? ecModel.eachComponent(function (componentType, model) {
  21638. componentType !== 'series' && doPrepare(model);
  21639. })
  21640. : ecModel.eachSeries(doPrepare);
  21641. function doPrepare(model) {
  21642. // Consider: id same and type changed.
  21643. var viewId = '_ec_' + model.id + '_' + model.type;
  21644. var view = viewMap[viewId];
  21645. if (!view) {
  21646. var classType = parseClassType(model.type);
  21647. var Clazz = isComponent
  21648. ? Component$1.getClass(classType.main, classType.sub)
  21649. : Chart.getClass(classType.sub);
  21650. if (__DEV__) {
  21651. assert(Clazz, classType.sub + ' does not exist.');
  21652. }
  21653. view = new Clazz();
  21654. view.init(ecModel, api);
  21655. viewMap[viewId] = view;
  21656. viewList.push(view);
  21657. zr.add(view.group);
  21658. }
  21659. model.__viewId = view.__id = viewId;
  21660. view.__alive = true;
  21661. view.__model = model;
  21662. view.group.__ecComponentInfo = {
  21663. mainType: model.mainType,
  21664. index: model.componentIndex
  21665. };
  21666. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21667. }
  21668. for (var i = 0; i < viewList.length;) {
  21669. var view = viewList[i];
  21670. if (!view.__alive) {
  21671. !isComponent && view.renderTask.dispose();
  21672. zr.remove(view.group);
  21673. view.dispose(ecModel, api);
  21674. viewList.splice(i, 1);
  21675. delete viewMap[view.__id];
  21676. view.__id = view.group.__ecComponentInfo = null;
  21677. }
  21678. else {
  21679. i++;
  21680. }
  21681. }
  21682. }
  21683. /**
  21684. * @private
  21685. */
  21686. function stackSeriesData(ecModel) {
  21687. var stackedDataMap = {};
  21688. ecModel.eachSeries(function (series) {
  21689. var stack = series.get('stack');
  21690. var data = series.getData();
  21691. if (stack && data.type === 'list') {
  21692. var previousStack = stackedDataMap[stack];
  21693. // Avoid conflict with Object.prototype
  21694. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  21695. data.stackedOn = previousStack;
  21696. }
  21697. stackedDataMap[stack] = data;
  21698. }
  21699. });
  21700. }
  21701. // /**
  21702. // * Encode visual infomation from data after data processing
  21703. // *
  21704. // * @param {module:echarts/model/Global} ecModel
  21705. // * @param {object} layout
  21706. // * @param {boolean} [layoutFilter] `true`: only layout,
  21707. // * `false`: only not layout,
  21708. // * `null`/`undefined`: all.
  21709. // * @param {string} taskBaseTag
  21710. // * @private
  21711. // */
  21712. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21713. // each(visualFuncs, function (visual, index) {
  21714. // var isLayout = visual.isLayout;
  21715. // if (layoutFilter == null
  21716. // || (layoutFilter === false && !isLayout)
  21717. // || (layoutFilter === true && isLayout)
  21718. // ) {
  21719. // visual.func(ecModel, api, payload);
  21720. // }
  21721. // });
  21722. // }
  21723. function clearColorPalette(ecModel) {
  21724. ecModel.clearColorPalette();
  21725. ecModel.eachSeries(function (seriesModel) {
  21726. seriesModel.clearColorPalette();
  21727. });
  21728. }
  21729. function render(ecIns, ecModel, api, payload) {
  21730. renderComponents(ecIns, ecModel, api, payload);
  21731. each(ecIns._chartsViews, function (chart) {
  21732. chart.__alive = false;
  21733. });
  21734. renderSeries(ecIns, ecModel, api, payload);
  21735. // Remove groups of unrendered charts
  21736. each(ecIns._chartsViews, function (chart) {
  21737. if (!chart.__alive) {
  21738. chart.remove(ecModel, api);
  21739. }
  21740. });
  21741. }
  21742. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  21743. each(dirtyList || ecIns._componentsViews, function (componentView) {
  21744. var componentModel = componentView.__model;
  21745. componentView.render(componentModel, ecModel, api, payload);
  21746. updateZ(componentModel, componentView);
  21747. });
  21748. }
  21749. /**
  21750. * Render each chart and component
  21751. * @private
  21752. */
  21753. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  21754. // Render all charts
  21755. var scheduler = ecIns._scheduler;
  21756. var unfinished;
  21757. ecModel.eachSeries(function (seriesModel) {
  21758. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21759. chartView.__alive = true;
  21760. var renderTask = chartView.renderTask;
  21761. scheduler.updatePayload(renderTask, payload);
  21762. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  21763. renderTask.dirty();
  21764. }
  21765. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  21766. chartView.group.silent = !!seriesModel.get('silent');
  21767. updateZ(seriesModel, chartView);
  21768. updateBlend(seriesModel, chartView);
  21769. });
  21770. scheduler.unfinished |= unfinished;
  21771. // If use hover layer
  21772. updateHoverLayerStatus(ecIns._zr, ecModel);
  21773. // Add aria
  21774. aria(ecIns._zr.dom, ecModel);
  21775. }
  21776. function performPostUpdateFuncs(ecModel, api) {
  21777. each(postUpdateFuncs, function (func) {
  21778. func(ecModel, api);
  21779. });
  21780. }
  21781. var MOUSE_EVENT_NAMES = [
  21782. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  21783. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  21784. ];
  21785. /**
  21786. * @private
  21787. */
  21788. echartsProto._initEvents = function () {
  21789. each(MOUSE_EVENT_NAMES, function (eveName) {
  21790. this._zr.on(eveName, function (e) {
  21791. var ecModel = this.getModel();
  21792. var el = e.target;
  21793. var params;
  21794. // no e.target when 'globalout'.
  21795. if (eveName === 'globalout') {
  21796. params = {};
  21797. }
  21798. else if (el && el.dataIndex != null) {
  21799. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  21800. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  21801. }
  21802. // If element has custom eventData of components
  21803. else if (el && el.eventData) {
  21804. params = extend({}, el.eventData);
  21805. }
  21806. if (params) {
  21807. params.event = e;
  21808. params.type = eveName;
  21809. this.trigger(eveName, params);
  21810. }
  21811. }, this);
  21812. }, this);
  21813. each(eventActionMap, function (actionType, eventType) {
  21814. this._messageCenter.on(eventType, function (event) {
  21815. this.trigger(eventType, event);
  21816. }, this);
  21817. }, this);
  21818. };
  21819. /**
  21820. * @return {boolean}
  21821. */
  21822. echartsProto.isDisposed = function () {
  21823. return this._disposed;
  21824. };
  21825. /**
  21826. * Clear
  21827. */
  21828. echartsProto.clear = function () {
  21829. this.setOption({ series: [] }, true);
  21830. };
  21831. /**
  21832. * Dispose instance
  21833. */
  21834. echartsProto.dispose = function () {
  21835. if (this._disposed) {
  21836. if (__DEV__) {
  21837. console.warn('Instance ' + this.id + ' has been disposed');
  21838. }
  21839. return;
  21840. }
  21841. this._disposed = true;
  21842. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  21843. var api = this._api;
  21844. var ecModel = this._model;
  21845. each(this._componentsViews, function (component) {
  21846. component.dispose(ecModel, api);
  21847. });
  21848. each(this._chartsViews, function (chart) {
  21849. chart.dispose(ecModel, api);
  21850. });
  21851. // Dispose after all views disposed
  21852. this._zr.dispose();
  21853. delete instances[this.id];
  21854. };
  21855. mixin(ECharts, Eventful);
  21856. function updateHoverLayerStatus(zr, ecModel) {
  21857. var storage = zr.storage;
  21858. var elCount = 0;
  21859. storage.traverse(function (el) {
  21860. if (!el.isGroup) {
  21861. elCount++;
  21862. }
  21863. });
  21864. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  21865. storage.traverse(function (el) {
  21866. if (!el.isGroup) {
  21867. // Don't switch back.
  21868. el.useHoverLayer = true;
  21869. }
  21870. });
  21871. }
  21872. }
  21873. /**
  21874. * Update chart progressive and blend.
  21875. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21876. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21877. */
  21878. function updateBlend(seriesModel, chartView) {
  21879. var blendMode = seriesModel.get('blendMode') || null;
  21880. if (__DEV__) {
  21881. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  21882. console.warn('Only canvas support blendMode');
  21883. }
  21884. }
  21885. chartView.group.traverse(function (el) {
  21886. // FIXME marker and other components
  21887. if (!el.isGroup) {
  21888. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  21889. if (el.style.blend !== blendMode) {
  21890. el.setStyle('blend', blendMode);
  21891. }
  21892. }
  21893. if (el.eachPendingDisplayable) {
  21894. el.eachPendingDisplayable(function (displayable) {
  21895. displayable.setStyle('blend', blendMode);
  21896. });
  21897. }
  21898. });
  21899. }
  21900. /**
  21901. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21902. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21903. */
  21904. function updateZ(model, view) {
  21905. var z = model.get('z');
  21906. var zlevel = model.get('zlevel');
  21907. // Set z and zlevel
  21908. view.group.traverse(function (el) {
  21909. if (el.type !== 'group') {
  21910. z != null && (el.z = z);
  21911. zlevel != null && (el.zlevel = zlevel);
  21912. }
  21913. });
  21914. }
  21915. function createExtensionAPI(ecInstance) {
  21916. var coordSysMgr = ecInstance._coordSysMgr;
  21917. return extend(new ExtensionAPI(ecInstance), {
  21918. // Inject methods
  21919. getCoordinateSystems: bind(
  21920. coordSysMgr.getCoordinateSystems, coordSysMgr
  21921. ),
  21922. getComponentByElement: function (el) {
  21923. while (el) {
  21924. var modelInfo = el.__ecComponentInfo;
  21925. if (modelInfo != null) {
  21926. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  21927. }
  21928. el = el.parent;
  21929. }
  21930. }
  21931. });
  21932. }
  21933. /**
  21934. * @type {Object} key: actionType.
  21935. * @inner
  21936. */
  21937. var actions = {};
  21938. /**
  21939. * Map eventType to actionType
  21940. * @type {Object}
  21941. */
  21942. var eventActionMap = {};
  21943. /**
  21944. * Data processor functions of each stage
  21945. * @type {Array.<Object.<string, Function>>}
  21946. * @inner
  21947. */
  21948. var dataProcessorFuncs = [];
  21949. /**
  21950. * @type {Array.<Function>}
  21951. * @inner
  21952. */
  21953. var optionPreprocessorFuncs = [];
  21954. /**
  21955. * @type {Array.<Function>}
  21956. * @inner
  21957. */
  21958. var postUpdateFuncs = [];
  21959. /**
  21960. * Visual encoding functions of each stage
  21961. * @type {Array.<Object.<string, Function>>}
  21962. */
  21963. var visualFuncs = [];
  21964. /**
  21965. * Theme storage
  21966. * @type {Object.<key, Object>}
  21967. */
  21968. var themeStorage = {};
  21969. /**
  21970. * Loading effects
  21971. */
  21972. var loadingEffects = {};
  21973. var instances = {};
  21974. var connectedGroups = {};
  21975. var idBase = new Date() - 0;
  21976. var groupIdBase = new Date() - 0;
  21977. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  21978. var mapDataStores = {};
  21979. function enableConnect(chart) {
  21980. var STATUS_PENDING = 0;
  21981. var STATUS_UPDATING = 1;
  21982. var STATUS_UPDATED = 2;
  21983. var STATUS_KEY = '__connectUpdateStatus';
  21984. function updateConnectedChartsStatus(charts, status) {
  21985. for (var i = 0; i < charts.length; i++) {
  21986. var otherChart = charts[i];
  21987. otherChart[STATUS_KEY] = status;
  21988. }
  21989. }
  21990. each(eventActionMap, function (actionType, eventType) {
  21991. chart._messageCenter.on(eventType, function (event) {
  21992. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  21993. if (event && event.escapeConnect) {
  21994. return;
  21995. }
  21996. var action = chart.makeActionFromEvent(event);
  21997. var otherCharts = [];
  21998. each(instances, function (otherChart) {
  21999. if (otherChart !== chart && otherChart.group === chart.group) {
  22000. otherCharts.push(otherChart);
  22001. }
  22002. });
  22003. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22004. each(otherCharts, function (otherChart) {
  22005. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22006. otherChart.dispatchAction(action);
  22007. }
  22008. });
  22009. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22010. }
  22011. });
  22012. });
  22013. }
  22014. /**
  22015. * @param {HTMLElement} dom
  22016. * @param {Object} [theme]
  22017. * @param {Object} opts
  22018. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22019. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22020. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22021. * Can be 'auto' (the same as null/undefined)
  22022. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22023. * Can be 'auto' (the same as null/undefined)
  22024. */
  22025. function init(dom, theme$$1, opts) {
  22026. if (__DEV__) {
  22027. // Check version
  22028. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22029. throw new Error(
  22030. 'zrender/src ' + version$1
  22031. + ' is too old for ECharts ' + version
  22032. + '. Current version need ZRender '
  22033. + dependencies.zrender + '+'
  22034. );
  22035. }
  22036. if (!dom) {
  22037. throw new Error('Initialize failed: invalid dom.');
  22038. }
  22039. }
  22040. var existInstance = getInstanceByDom(dom);
  22041. if (existInstance) {
  22042. if (__DEV__) {
  22043. console.warn('There is a chart instance already initialized on the dom.');
  22044. }
  22045. return existInstance;
  22046. }
  22047. if (__DEV__) {
  22048. if (isDom(dom)
  22049. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22050. && (
  22051. (!dom.clientWidth && (!opts || opts.width == null))
  22052. || (!dom.clientHeight && (!opts || opts.height == null))
  22053. )
  22054. ) {
  22055. console.warn('Can\'t get dom width or height');
  22056. }
  22057. }
  22058. var chart = new ECharts(dom, theme$$1, opts);
  22059. chart.id = 'ec_' + idBase++;
  22060. instances[chart.id] = chart;
  22061. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22062. enableConnect(chart);
  22063. return chart;
  22064. }
  22065. /**
  22066. * @return {string|Array.<module:echarts~ECharts>} groupId
  22067. */
  22068. function connect(groupId) {
  22069. // Is array of charts
  22070. if (isArray(groupId)) {
  22071. var charts = groupId;
  22072. groupId = null;
  22073. // If any chart has group
  22074. each(charts, function (chart) {
  22075. if (chart.group != null) {
  22076. groupId = chart.group;
  22077. }
  22078. });
  22079. groupId = groupId || ('g_' + groupIdBase++);
  22080. each(charts, function (chart) {
  22081. chart.group = groupId;
  22082. });
  22083. }
  22084. connectedGroups[groupId] = true;
  22085. return groupId;
  22086. }
  22087. /**
  22088. * @DEPRECATED
  22089. * @return {string} groupId
  22090. */
  22091. function disConnect(groupId) {
  22092. connectedGroups[groupId] = false;
  22093. }
  22094. /**
  22095. * @return {string} groupId
  22096. */
  22097. var disconnect = disConnect;
  22098. /**
  22099. * Dispose a chart instance
  22100. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22101. */
  22102. function dispose(chart) {
  22103. if (typeof chart === 'string') {
  22104. chart = instances[chart];
  22105. }
  22106. else if (!(chart instanceof ECharts)){
  22107. // Try to treat as dom
  22108. chart = getInstanceByDom(chart);
  22109. }
  22110. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22111. chart.dispose();
  22112. }
  22113. }
  22114. /**
  22115. * @param {HTMLElement} dom
  22116. * @return {echarts~ECharts}
  22117. */
  22118. function getInstanceByDom(dom) {
  22119. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22120. }
  22121. /**
  22122. * @param {string} key
  22123. * @return {echarts~ECharts}
  22124. */
  22125. function getInstanceById(key) {
  22126. return instances[key];
  22127. }
  22128. /**
  22129. * Register theme
  22130. */
  22131. function registerTheme(name, theme$$1) {
  22132. themeStorage[name] = theme$$1;
  22133. }
  22134. /**
  22135. * Register option preprocessor
  22136. * @param {Function} preprocessorFunc
  22137. */
  22138. function registerPreprocessor(preprocessorFunc) {
  22139. optionPreprocessorFuncs.push(preprocessorFunc);
  22140. }
  22141. /**
  22142. * @param {number} [priority=1000]
  22143. * @param {Object|Function} processor
  22144. */
  22145. function registerProcessor(priority, processor) {
  22146. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22147. }
  22148. /**
  22149. * Register postUpdater
  22150. * @param {Function} postUpdateFunc
  22151. */
  22152. function registerPostUpdate(postUpdateFunc) {
  22153. postUpdateFuncs.push(postUpdateFunc);
  22154. }
  22155. /**
  22156. * Usage:
  22157. * registerAction('someAction', 'someEvent', function () { ... });
  22158. * registerAction('someAction', function () { ... });
  22159. * registerAction(
  22160. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22161. * function () { ... }
  22162. * );
  22163. *
  22164. * @param {(string|Object)} actionInfo
  22165. * @param {string} actionInfo.type
  22166. * @param {string} [actionInfo.event]
  22167. * @param {string} [actionInfo.update]
  22168. * @param {string} [eventName]
  22169. * @param {Function} action
  22170. */
  22171. function registerAction(actionInfo, eventName, action) {
  22172. if (typeof eventName === 'function') {
  22173. action = eventName;
  22174. eventName = '';
  22175. }
  22176. var actionType = isObject(actionInfo)
  22177. ? actionInfo.type
  22178. : ([actionInfo, actionInfo = {
  22179. event: eventName
  22180. }][0]);
  22181. // Event name is all lowercase
  22182. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22183. eventName = actionInfo.event;
  22184. // Validate action type and event name.
  22185. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22186. if (!actions[actionType]) {
  22187. actions[actionType] = {action: action, actionInfo: actionInfo};
  22188. }
  22189. eventActionMap[eventName] = actionType;
  22190. }
  22191. /**
  22192. * @param {string} type
  22193. * @param {*} CoordinateSystem
  22194. */
  22195. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22196. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22197. }
  22198. /**
  22199. * Get dimensions of specified coordinate system.
  22200. * @param {string} type
  22201. * @return {Array.<string|Object>}
  22202. */
  22203. function getCoordinateSystemDimensions(type) {
  22204. var coordSysCreator = CoordinateSystemManager.get(type);
  22205. if (coordSysCreator) {
  22206. return coordSysCreator.getDimensionsInfo
  22207. ? coordSysCreator.getDimensionsInfo()
  22208. : coordSysCreator.dimensions.slice();
  22209. }
  22210. }
  22211. /**
  22212. * Layout is a special stage of visual encoding
  22213. * Most visual encoding like color are common for different chart
  22214. * But each chart has it's own layout algorithm
  22215. *
  22216. * @param {number} [priority=1000]
  22217. * @param {Function} layoutTask
  22218. */
  22219. function registerLayout(priority, layoutTask) {
  22220. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22221. }
  22222. /**
  22223. * @param {number} [priority=3000]
  22224. * @param {module:echarts/stream/Task} visualTask
  22225. */
  22226. function registerVisual(priority, visualTask) {
  22227. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22228. }
  22229. /**
  22230. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22231. */
  22232. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22233. if (isFunction(priority) || isObject(priority)) {
  22234. fn = priority;
  22235. priority = defaultPriority;
  22236. }
  22237. if (__DEV__) {
  22238. if (isNaN(priority) || priority == null) {
  22239. throw new Error('Illegal priority');
  22240. }
  22241. // Check duplicate
  22242. each(targetList, function (wrap) {
  22243. assert(wrap.__raw !== fn);
  22244. });
  22245. }
  22246. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22247. stageHandler.__prio = priority;
  22248. stageHandler.__raw = fn;
  22249. targetList.push(stageHandler);
  22250. return stageHandler;
  22251. }
  22252. /**
  22253. * @param {string} name
  22254. */
  22255. function registerLoading(name, loadingFx) {
  22256. loadingEffects[name] = loadingFx;
  22257. }
  22258. /**
  22259. * @param {Object} opts
  22260. * @param {string} [superClass]
  22261. */
  22262. function extendComponentModel(opts/*, superClass*/) {
  22263. // var Clazz = ComponentModel;
  22264. // if (superClass) {
  22265. // var classType = parseClassType(superClass);
  22266. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22267. // }
  22268. return ComponentModel.extend(opts);
  22269. }
  22270. /**
  22271. * @param {Object} opts
  22272. * @param {string} [superClass]
  22273. */
  22274. function extendComponentView(opts/*, superClass*/) {
  22275. // var Clazz = ComponentView;
  22276. // if (superClass) {
  22277. // var classType = parseClassType(superClass);
  22278. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22279. // }
  22280. return Component$1.extend(opts);
  22281. }
  22282. /**
  22283. * @param {Object} opts
  22284. * @param {string} [superClass]
  22285. */
  22286. function extendSeriesModel(opts/*, superClass*/) {
  22287. // var Clazz = SeriesModel;
  22288. // if (superClass) {
  22289. // superClass = 'series.' + superClass.replace('series.', '');
  22290. // var classType = parseClassType(superClass);
  22291. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22292. // }
  22293. return SeriesModel.extend(opts);
  22294. }
  22295. /**
  22296. * @param {Object} opts
  22297. * @param {string} [superClass]
  22298. */
  22299. function extendChartView(opts/*, superClass*/) {
  22300. // var Clazz = ChartView;
  22301. // if (superClass) {
  22302. // superClass = superClass.replace('series.', '');
  22303. // var classType = parseClassType(superClass);
  22304. // Clazz = ChartView.getClass(classType.main, true);
  22305. // }
  22306. return Chart.extend(opts);
  22307. }
  22308. /**
  22309. * ZRender need a canvas context to do measureText.
  22310. * But in node environment canvas may be created by node-canvas.
  22311. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22312. *
  22313. * Be careful of using it in the browser.
  22314. *
  22315. * @param {Function} creator
  22316. * @example
  22317. * var Canvas = require('canvas');
  22318. * var echarts = require('echarts');
  22319. * echarts.setCanvasCreator(function () {
  22320. * // Small size is enough.
  22321. * return new Canvas(32, 32);
  22322. * });
  22323. */
  22324. function setCanvasCreator(creator) {
  22325. $override('createCanvas', creator);
  22326. }
  22327. /**
  22328. * @param {string} mapName
  22329. * @param {Object|string} geoJson
  22330. * @param {Object} [specialAreas]
  22331. *
  22332. * @example
  22333. * $.get('USA.json', function (geoJson) {
  22334. * echarts.registerMap('USA', geoJson);
  22335. * // Or
  22336. * echarts.registerMap('USA', {
  22337. * geoJson: geoJson,
  22338. * specialAreas: {}
  22339. * })
  22340. * });
  22341. */
  22342. function registerMap(mapName, geoJson, specialAreas) {
  22343. if (geoJson.geoJson && !geoJson.features) {
  22344. specialAreas = geoJson.specialAreas;
  22345. geoJson = geoJson.geoJson;
  22346. }
  22347. if (typeof geoJson === 'string') {
  22348. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22349. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22350. }
  22351. mapDataStores[mapName] = {
  22352. geoJson: geoJson,
  22353. specialAreas: specialAreas
  22354. };
  22355. }
  22356. /**
  22357. * @param {string} mapName
  22358. * @return {Object}
  22359. */
  22360. function getMap(mapName) {
  22361. return mapDataStores[mapName];
  22362. }
  22363. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22364. registerPreprocessor(backwardCompat);
  22365. registerLoading('default', loadingDefault);
  22366. // Default actions
  22367. registerAction({
  22368. type: 'highlight',
  22369. event: 'highlight',
  22370. update: 'highlight'
  22371. }, noop);
  22372. registerAction({
  22373. type: 'downplay',
  22374. event: 'downplay',
  22375. update: 'downplay'
  22376. }, noop);
  22377. // Default theme
  22378. registerTheme('light', lightTheme);
  22379. registerTheme('dark', theme);
  22380. // For backward compatibility, where the namespace `dataTool` will
  22381. // be mounted on `echarts` is the extension `dataTool` is imported.
  22382. var dataTool = {};
  22383. function defaultKeyGetter(item) {
  22384. return item;
  22385. }
  22386. /**
  22387. * @param {Array} oldArr
  22388. * @param {Array} newArr
  22389. * @param {Function} oldKeyGetter
  22390. * @param {Function} newKeyGetter
  22391. * @param {Object} [context] Can be visited by this.context in callback.
  22392. */
  22393. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22394. this._old = oldArr;
  22395. this._new = newArr;
  22396. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22397. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22398. this.context = context;
  22399. }
  22400. DataDiffer.prototype = {
  22401. constructor: DataDiffer,
  22402. /**
  22403. * Callback function when add a data
  22404. */
  22405. add: function (func) {
  22406. this._add = func;
  22407. return this;
  22408. },
  22409. /**
  22410. * Callback function when update a data
  22411. */
  22412. update: function (func) {
  22413. this._update = func;
  22414. return this;
  22415. },
  22416. /**
  22417. * Callback function when remove a data
  22418. */
  22419. remove: function (func) {
  22420. this._remove = func;
  22421. return this;
  22422. },
  22423. execute: function () {
  22424. var oldArr = this._old;
  22425. var newArr = this._new;
  22426. var oldDataIndexMap = {};
  22427. var newDataIndexMap = {};
  22428. var oldDataKeyArr = [];
  22429. var newDataKeyArr = [];
  22430. var i;
  22431. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22432. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22433. // Travel by inverted order to make sure order consistency
  22434. // when duplicate keys exists (consider newDataIndex.pop() below).
  22435. // For performance consideration, these code below do not look neat.
  22436. for (i = 0; i < oldArr.length; i++) {
  22437. var key = oldDataKeyArr[i];
  22438. var idx = newDataIndexMap[key];
  22439. // idx can never be empty array here. see 'set null' logic below.
  22440. if (idx != null) {
  22441. // Consider there is duplicate key (for example, use dataItem.name as key).
  22442. // We should make sure every item in newArr and oldArr can be visited.
  22443. var len = idx.length;
  22444. if (len) {
  22445. len === 1 && (newDataIndexMap[key] = null);
  22446. idx = idx.unshift();
  22447. }
  22448. else {
  22449. newDataIndexMap[key] = null;
  22450. }
  22451. this._update && this._update(idx, i);
  22452. }
  22453. else {
  22454. this._remove && this._remove(i);
  22455. }
  22456. }
  22457. for (var i = 0; i < newDataKeyArr.length; i++) {
  22458. var key = newDataKeyArr[i];
  22459. if (newDataIndexMap.hasOwnProperty(key)) {
  22460. var idx = newDataIndexMap[key];
  22461. if (idx == null) {
  22462. continue;
  22463. }
  22464. // idx can never be empty array here. see 'set null' logic above.
  22465. if (!idx.length) {
  22466. this._add && this._add(idx);
  22467. }
  22468. else {
  22469. for (var j = 0, len = idx.length; j < len; j++) {
  22470. this._add && this._add(idx[j]);
  22471. }
  22472. }
  22473. }
  22474. }
  22475. }
  22476. };
  22477. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22478. for (var i = 0; i < arr.length; i++) {
  22479. // Add prefix to avoid conflict with Object.prototype.
  22480. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22481. var existence = map[key];
  22482. if (existence == null) {
  22483. keyArr.push(key);
  22484. map[key] = i;
  22485. }
  22486. else {
  22487. if (!existence.length) {
  22488. map[key] = existence = [existence];
  22489. }
  22490. existence.push(i);
  22491. }
  22492. }
  22493. }
  22494. var OTHER_DIMENSIONS = createHashMap([
  22495. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22496. ]);
  22497. function summarizeDimensions(data) {
  22498. var summary = {};
  22499. var encode = summary.encode = {};
  22500. var coordDimMap = summary.coordDimMap = createHashMap();
  22501. var defaultedLabel = [];
  22502. each$1(data.dimensions, function (dimName) {
  22503. var dimItem = data.getDimensionInfo(dimName);
  22504. var coordDim = dimItem.coordDim;
  22505. if (coordDim) {
  22506. if (__DEV__) {
  22507. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22508. }
  22509. var coordDimArr = encode[coordDim];
  22510. if (!encode.hasOwnProperty(coordDim)) {
  22511. coordDimArr = encode[coordDim] = [];
  22512. }
  22513. coordDimArr[dimItem.coordDimIndex] = dimName;
  22514. if (dimItem.isSysCoord && mayLabelDimType(dimItem.type)) {
  22515. // Use the last coord dim (and label friendly) as default label,
  22516. // because both show x, y on label is not look good, and usually
  22517. // y axis is more focusd conventionally.
  22518. defaultedLabel[0] = dimName;
  22519. }
  22520. coordDimMap.set(coordDim, 1);
  22521. }
  22522. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22523. var otherDimArr = encode[otherDim];
  22524. if (!encode.hasOwnProperty(otherDim)) {
  22525. otherDimArr = encode[otherDim] = [];
  22526. }
  22527. var dimIndex = dimItem.otherDims[otherDim];
  22528. if (dimIndex != null && dimIndex !== false) {
  22529. otherDimArr[dimIndex] = dimItem.name;
  22530. }
  22531. });
  22532. });
  22533. var dataDimsOnCoord = [];
  22534. coordDimMap.each(function (v, coordDim) {
  22535. dataDimsOnCoord = dataDimsOnCoord.concat(encode[coordDim]);
  22536. });
  22537. summary.dataDimsOnCoord = dataDimsOnCoord;
  22538. var encodeLabel = encode.label;
  22539. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22540. // in this way. Use label.formatter instead. May be remove this approach someday.
  22541. if (encodeLabel && encodeLabel.length) {
  22542. defaultedLabel = encodeLabel.slice();
  22543. }
  22544. var defaultedTooltip = defaultedLabel.slice();
  22545. var encodeTooltip = encode.tooltip;
  22546. if (encodeTooltip && encodeTooltip.length) {
  22547. defaultedTooltip = encodeTooltip.slice();
  22548. }
  22549. encode.defaultedLabel = defaultedLabel;
  22550. encode.defaultedTooltip = defaultedTooltip;
  22551. return summary;
  22552. }
  22553. function getDimensionTypeByAxis(axisType) {
  22554. return axisType === 'category'
  22555. ? 'ordinal'
  22556. : axisType === 'time'
  22557. ? 'time'
  22558. : 'float';
  22559. }
  22560. function mayLabelDimType(dimType) {
  22561. // In most cases, ordinal and time do not suitable for label.
  22562. // Ordinal info can be displayed on axis. Time is too long.
  22563. return !(dimType === 'ordinal' || dimType === 'time');
  22564. }
  22565. // function findTheLastDimMayLabel(data) {
  22566. // // Get last value dim
  22567. // var dimensions = data.dimensions.slice();
  22568. // var valueType;
  22569. // var valueDim;
  22570. // while (dimensions.length && (
  22571. // valueDim = dimensions.pop(),
  22572. // valueType = data.getDimensionInfo(valueDim).type,
  22573. // valueType === 'ordinal' || valueType === 'time'
  22574. // )) {} // jshint ignore:line
  22575. // return valueDim;
  22576. // }
  22577. /**
  22578. * List for data storage
  22579. * @module echarts/data/List
  22580. */
  22581. var isObject$4 = isObject$1;
  22582. var UNDEFINED = 'undefined';
  22583. var globalObj = typeof window === UNDEFINED ? global : window;
  22584. // Use prefix to avoid index to be the same as otherIdList[idx],
  22585. // which will cause weird udpate animation.
  22586. var ID_PREFIX = 'e\0\0';
  22587. var dataCtors = {
  22588. 'float': typeof globalObj.Float64Array === UNDEFINED
  22589. ? Array : globalObj.Float64Array,
  22590. 'int': typeof globalObj.Int32Array === UNDEFINED
  22591. ? Array : globalObj.Int32Array,
  22592. // Ordinal data type can be string or int
  22593. 'ordinal': Array,
  22594. 'number': Array,
  22595. 'time': Array
  22596. };
  22597. function getIndicesCtor(list) {
  22598. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22599. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22600. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22601. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22602. }
  22603. function cloneChunk(originalChunk) {
  22604. var Ctor = originalChunk.constructor;
  22605. // Only shallow clone is enough when Array.
  22606. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22607. }
  22608. var TRANSFERABLE_PROPERTIES = [
  22609. 'stackedOn', 'hasItemOption', '_nameList', '_idList',
  22610. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22611. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22612. ];
  22613. function transferProperties(a, b) {
  22614. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22615. if (b.hasOwnProperty(propName)) {
  22616. a[propName] = b[propName];
  22617. }
  22618. });
  22619. a.__wrappedMethods = b.__wrappedMethods;
  22620. }
  22621. /**
  22622. * @constructor
  22623. * @alias module:echarts/data/List
  22624. *
  22625. * @param {Array.<string|Object>} dimensions
  22626. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22627. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22628. * Spetial fields: {
  22629. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22630. * }
  22631. * @param {module:echarts/model/Model} hostModel
  22632. */
  22633. var List = function (dimensions, hostModel) {
  22634. dimensions = dimensions || ['x', 'y'];
  22635. var dimensionInfos = {};
  22636. var dimensionNames = [];
  22637. for (var i = 0; i < dimensions.length; i++) {
  22638. var dimensionName;
  22639. var dimensionInfo = {};
  22640. if (typeof dimensions[i] === 'string') {
  22641. dimensionName = dimensions[i];
  22642. dimensionInfo = {
  22643. name: dimensionName,
  22644. coordDim: dimensionName,
  22645. coordDimIndex: 0,
  22646. stackable: false,
  22647. // Type can be 'float', 'int', 'number'
  22648. // Default is float64
  22649. type: 'float'
  22650. };
  22651. }
  22652. else {
  22653. dimensionInfo = dimensions[i];
  22654. dimensionName = dimensionInfo.name;
  22655. dimensionInfo.type = dimensionInfo.type || 'float';
  22656. if (!dimensionInfo.coordDim) {
  22657. dimensionInfo.coordDim = dimensionName;
  22658. dimensionInfo.coordDimIndex = 0;
  22659. }
  22660. }
  22661. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22662. dimensionNames.push(dimensionName);
  22663. dimensionInfos[dimensionName] = dimensionInfo;
  22664. dimensionInfo.index = i;
  22665. }
  22666. /**
  22667. * @readOnly
  22668. * @type {Array.<string>}
  22669. */
  22670. this.dimensions = dimensionNames;
  22671. /**
  22672. * Infomation of each data dimension, like data type.
  22673. * @type {Object}
  22674. */
  22675. this._dimensionInfos = dimensionInfos;
  22676. /**
  22677. * @type {module:echarts/model/Model}
  22678. */
  22679. this.hostModel = hostModel;
  22680. /**
  22681. * @type {module:echarts/model/Model}
  22682. */
  22683. this.dataType;
  22684. /**
  22685. * Indices stores the indices of data subset after filtered.
  22686. * This data subset will be used in chart.
  22687. * @type {Array.<number>}
  22688. * @readOnly
  22689. */
  22690. this._indices = null;
  22691. this._count = 0;
  22692. this._rawCount = 0;
  22693. /**
  22694. * Data storage
  22695. * @type {Object.<key, Array.<TypedArray|Array>>}
  22696. * @private
  22697. */
  22698. this._storage = {};
  22699. /**
  22700. * @type {Array.<string>}
  22701. */
  22702. this._nameList = [];
  22703. /**
  22704. * @type {Array.<string>}
  22705. */
  22706. this._idList = [];
  22707. /**
  22708. * Models of data option is stored sparse for optimizing memory cost
  22709. * @type {Array.<module:echarts/model/Model>}
  22710. * @private
  22711. */
  22712. this._optionModels = [];
  22713. /**
  22714. * @param {module:echarts/data/List}
  22715. */
  22716. this.stackedOn = null;
  22717. /**
  22718. * Global visual properties after visual coding
  22719. * @type {Object}
  22720. * @private
  22721. */
  22722. this._visual = {};
  22723. /**
  22724. * Globel layout properties.
  22725. * @type {Object}
  22726. * @private
  22727. */
  22728. this._layout = {};
  22729. /**
  22730. * Item visual properties after visual coding
  22731. * @type {Array.<Object>}
  22732. * @private
  22733. */
  22734. this._itemVisuals = [];
  22735. /**
  22736. * Key: visual type, Value: boolean
  22737. * @type {Object}
  22738. * @readOnly
  22739. */
  22740. this.hasItemVisual = {};
  22741. /**
  22742. * Item layout properties after layout
  22743. * @type {Array.<Object>}
  22744. * @private
  22745. */
  22746. this._itemLayouts = [];
  22747. /**
  22748. * Graphic elemnents
  22749. * @type {Array.<module:zrender/Element>}
  22750. * @private
  22751. */
  22752. this._graphicEls = [];
  22753. /**
  22754. * Max size of each chunk.
  22755. * @type {number}
  22756. * @private
  22757. */
  22758. this._chunkSize = 1e5;
  22759. /**
  22760. * @type {number}
  22761. * @private
  22762. */
  22763. this._chunkCount = 0;
  22764. /**
  22765. * @type {Array.<Array|Object>}
  22766. * @private
  22767. */
  22768. this._rawData;
  22769. /**
  22770. * Raw extent will not be cloned, but only transfered.
  22771. * It will not be calculated util needed.
  22772. * key: dim,
  22773. * value: {end: number, extent: Array.<number>}
  22774. * @type {Object}
  22775. * @private
  22776. */
  22777. this._rawExtent = {};
  22778. /**
  22779. * @type {Object}
  22780. * @private
  22781. */
  22782. this._extent = {};
  22783. /**
  22784. * key: dim
  22785. * value: extent
  22786. * @type {Object}
  22787. * @private
  22788. */
  22789. this._approximateExtent = {};
  22790. /**
  22791. * Cache summary info for fast visit. See "dimensionHelper".
  22792. * @type {Object}
  22793. * @private
  22794. */
  22795. this._dimensionsSummary = summarizeDimensions(this);
  22796. };
  22797. var listProto = List.prototype;
  22798. listProto.type = 'list';
  22799. /**
  22800. * If each data item has it's own option
  22801. * @type {boolean}
  22802. */
  22803. listProto.hasItemOption = true;
  22804. /**
  22805. * Get dimension name
  22806. * @param {string|number} dim
  22807. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22808. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22809. * @return {string} Concrete dim name.
  22810. */
  22811. listProto.getDimension = function (dim) {
  22812. if (!isNaN(dim)) {
  22813. dim = this.dimensions[dim] || dim;
  22814. }
  22815. return dim;
  22816. };
  22817. /**
  22818. * Get type and stackable info of particular dimension
  22819. * @param {string|number} dim
  22820. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22821. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22822. */
  22823. listProto.getDimensionInfo = function (dim) {
  22824. // Do not clone, because there may be categories in dimInfo.
  22825. return this._dimensionInfos[this.getDimension(dim)];
  22826. };
  22827. /**
  22828. * @return {Array.<string>} concrete dimension name list on coord.
  22829. */
  22830. listProto.getDimensionsOnCoord = function () {
  22831. return this._dimensionsSummary.dataDimsOnCoord.slice();
  22832. };
  22833. /**
  22834. * @param {string} coordDim
  22835. * @param {number|Array} [idx=0] A coordDim may map to more than one data dim.
  22836. * If idx is `true`, return a array of all mapped dims.
  22837. * @return {string|Array.<string>} concrete data dim.
  22838. * If idx is number, and not found, return null/undefined.
  22839. * If idx is `true`, and not found, return empty array.
  22840. */
  22841. listProto.mapDimension = function (coordDim, idx) {
  22842. var dims = this._dimensionsSummary.encode[coordDim];
  22843. return idx === true
  22844. ? (dims && dims.slice() || [])
  22845. : dims
  22846. ? dims[idx || 0]
  22847. : null;
  22848. };
  22849. /**
  22850. * Initialize from data
  22851. * @param {Array.<Object|number|Array>} data source or data or data provider.
  22852. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  22853. * defualt label/tooltip.
  22854. * A name can be specified in encode.itemName,
  22855. * or dataItem.name (only for series option data),
  22856. * or provided in nameList from outside.
  22857. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  22858. */
  22859. listProto.initData = function (data, nameList, dimValueGetter) {
  22860. var notProvider = Source.isInstance(data) || isArrayLike(data);
  22861. if (notProvider) {
  22862. data = new DefaultDataProvider(data, this.dimensions.length);
  22863. }
  22864. if (__DEV__) {
  22865. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  22866. throw new Error('Inavlid data provider.');
  22867. }
  22868. }
  22869. this._rawData = data;
  22870. // Clear
  22871. this._storage = {};
  22872. this._indices = null;
  22873. this._nameList = nameList || [];
  22874. this._idList = [];
  22875. this._nameRepeatCount = {};
  22876. if (!dimValueGetter) {
  22877. this.hasItemOption = false;
  22878. }
  22879. /**
  22880. * @readOnly
  22881. */
  22882. this.defaultDimValueGetter = defaultDimValueGetters[
  22883. this._rawData.getSource().sourceFormat
  22884. ];
  22885. // Default dim value getter
  22886. this._dimValueGetter = dimValueGetter = dimValueGetter
  22887. || this.defaultDimValueGetter;
  22888. // Reset raw extent.
  22889. this._rawExtent = {};
  22890. this._initDataFromProvider(0, data.count());
  22891. // If data has no item option.
  22892. if (data.pure) {
  22893. this.hasItemOption = false;
  22894. }
  22895. };
  22896. listProto.getProvider = function () {
  22897. return this._rawData;
  22898. };
  22899. listProto.appendData = function (data) {
  22900. if (__DEV__) {
  22901. assert$1(!this._indices, 'appendData can only be called on raw data.');
  22902. }
  22903. var rawData = this._rawData;
  22904. var start = this.count();
  22905. rawData.appendData(data);
  22906. var end = rawData.count();
  22907. if (!rawData.persistent) {
  22908. end += start;
  22909. }
  22910. this._initDataFromProvider(start, end);
  22911. };
  22912. listProto._initDataFromProvider = function (start, end) {
  22913. // Optimize.
  22914. if (start >= end) {
  22915. return;
  22916. }
  22917. var chunkSize = this._chunkSize;
  22918. var rawData = this._rawData;
  22919. var storage = this._storage;
  22920. var dimensions = this.dimensions;
  22921. var dimensionInfoMap = this._dimensionInfos;
  22922. var nameList = this._nameList;
  22923. var idList = this._idList;
  22924. var rawExtent = this._rawExtent;
  22925. var nameRepeatCount = this._nameRepeatCount = {};
  22926. var nameDimIdx;
  22927. var chunkCount = this._chunkCount;
  22928. var lastChunkIndex = chunkCount - 1;
  22929. for (var i = 0; i < dimensions.length; i++) {
  22930. var dim = dimensions[i];
  22931. if (!rawExtent[dim]) {
  22932. rawExtent[dim] = [Infinity, -Infinity];
  22933. }
  22934. var dimInfo = dimensionInfoMap[dim];
  22935. if (dimInfo.otherDims.itemName === 0) {
  22936. nameDimIdx = this._nameDimIdx = i;
  22937. }
  22938. if (dimInfo.otherDims.itemId === 0) {
  22939. this._idDimIdx = i;
  22940. }
  22941. var DataCtor = dataCtors[dimInfo.type];
  22942. if (!storage[dim]) {
  22943. storage[dim] = [];
  22944. }
  22945. var resizeChunkArray = storage[dim][lastChunkIndex];
  22946. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  22947. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  22948. // The cost of the copy is probably inconsiderable
  22949. // within the initial chunkSize.
  22950. for (var j = 0; j < resizeChunkArray.length; j++) {
  22951. newStore[j] = resizeChunkArray[j];
  22952. }
  22953. storage[dim][lastChunkIndex] = newStore;
  22954. }
  22955. // Create new chunks.
  22956. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  22957. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  22958. }
  22959. this._chunkCount = storage[dim].length;
  22960. }
  22961. for (var idx = start; idx < end; idx++) {
  22962. // NOTICE: Try not to write things into dataItem
  22963. var dataItem = rawData.getItem(idx);
  22964. // Each data item is value
  22965. // [1, 2]
  22966. // 2
  22967. // Bar chart, line chart which uses category axis
  22968. // only gives the 'y' value. 'x' value is the indices of category
  22969. // Use a tempValue to normalize the value to be a (x, y) value
  22970. var chunkIndex = Math.floor(idx / chunkSize);
  22971. var chunkOffset = idx % chunkSize;
  22972. // Store the data by dimensions
  22973. for (var k = 0; k < dimensions.length; k++) {
  22974. var dim = dimensions[k];
  22975. var dimStorage = storage[dim][chunkIndex];
  22976. // PENDING NULL is empty or zero
  22977. var val = this._dimValueGetter(dataItem, dim, idx, k);
  22978. dimStorage[chunkOffset] = val;
  22979. if (val < rawExtent[dim][0]) {
  22980. rawExtent[dim][0] = val;
  22981. }
  22982. if (val > rawExtent[dim][1]) {
  22983. rawExtent[dim][1] = val;
  22984. }
  22985. }
  22986. // ??? FIXME not check by pure but sourceFormat?
  22987. // TODO refactor these logic.
  22988. if (!rawData.pure) {
  22989. var name = nameList[idx];
  22990. if (dataItem && !name) {
  22991. if (nameDimIdx != null) {
  22992. name = this._getNameFromStore(idx);
  22993. }
  22994. else if (dataItem.name != null) {
  22995. // There is no other place to persistent dataItem.name,
  22996. // so save it to nameList.
  22997. nameList[idx] = name = dataItem.name;
  22998. }
  22999. }
  23000. // Try using the id in option
  23001. // id or name is used on dynamical data, mapping old and new items.
  23002. var id = dataItem == null ? null : dataItem.id;
  23003. if (id == null && name != null) {
  23004. // Use name as id and add counter to avoid same name
  23005. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23006. id = name;
  23007. if (nameRepeatCount[name] > 0) {
  23008. id += '__ec__' + nameRepeatCount[name];
  23009. }
  23010. nameRepeatCount[name]++;
  23011. }
  23012. id != null && (idList[idx] = id);
  23013. }
  23014. }
  23015. if (!rawData.persistent && rawData.clean) {
  23016. // Clean unused data if data source is typed array.
  23017. rawData.clean();
  23018. }
  23019. this._rawCount = this._count = end;
  23020. // Reset data extent
  23021. this._extent = {};
  23022. };
  23023. // TODO refactor
  23024. listProto._getNameFromStore = function (rawIndex) {
  23025. var nameDimIdx = this._nameDimIdx;
  23026. if (nameDimIdx != null) {
  23027. var chunkSize = this._chunkSize;
  23028. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23029. var chunkOffset = rawIndex % chunkSize;
  23030. var dim = this.dimensions[nameDimIdx];
  23031. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23032. if (ordinalMeta) {
  23033. return ordinalMeta.categories[rawIndex];
  23034. }
  23035. else {
  23036. var chunk = this._storage[dim][chunkIndex];
  23037. return chunk && chunk[chunkOffset];
  23038. }
  23039. }
  23040. };
  23041. // TODO refactor
  23042. listProto._getIdFromStore = function (rawIndex) {
  23043. var idDimIdx = this._idDimIdx;
  23044. if (idDimIdx != null) {
  23045. var chunkSize = this._chunkSize;
  23046. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23047. var chunkOffset = rawIndex % chunkSize;
  23048. var dim = this.dimensions[idDimIdx];
  23049. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23050. if (ordinalMeta) {
  23051. return ordinalMeta.categories[rawIndex];
  23052. }
  23053. else {
  23054. var chunk = this._storage[dim][chunkIndex];
  23055. return chunk && chunk[chunkOffset];
  23056. }
  23057. }
  23058. };
  23059. /**
  23060. * @return {number}
  23061. */
  23062. listProto.count = function () {
  23063. return this._count;
  23064. };
  23065. listProto.getIndices = function () {
  23066. if (this._indices) {
  23067. var Ctor = this._indices.constructor;
  23068. return new Ctor(this._indices.buffer, 0, this._count);
  23069. }
  23070. var Ctor = getIndicesCtor(this);
  23071. var arr = new Ctor(this.count());
  23072. for (var i = 0; i < arr.length; i++) {
  23073. arr[i] = i;
  23074. }
  23075. return arr;
  23076. };
  23077. /**
  23078. * Get value. Return NaN if idx is out of range.
  23079. * @param {string} dim Dim must be concrete name.
  23080. * @param {number} idx
  23081. * @param {boolean} stack
  23082. * @return {number}
  23083. */
  23084. listProto.get = function (dim, idx, stack) {
  23085. if (!(idx >= 0 && idx < this._count)) {
  23086. return NaN;
  23087. }
  23088. var storage = this._storage;
  23089. if (!storage[dim]) {
  23090. // TODO Warn ?
  23091. return NaN;
  23092. }
  23093. idx = this.getRawIndex(idx);
  23094. var chunkIndex = Math.floor(idx / this._chunkSize);
  23095. var chunkOffset = idx % this._chunkSize;
  23096. var chunkStore = storage[dim][chunkIndex];
  23097. var value = chunkStore[chunkOffset];
  23098. // FIXME ordinal data type is not stackable
  23099. if (stack) {
  23100. var dimensionInfo = this._dimensionInfos[dim];
  23101. if (dimensionInfo && dimensionInfo.stackable) {
  23102. var stackedOn = this.stackedOn;
  23103. while (stackedOn) {
  23104. // Get no stacked data of stacked on
  23105. var stackedValue = stackedOn.get(dim, idx);
  23106. // Considering positive stack, negative stack and empty data
  23107. if ((value >= 0 && stackedValue > 0) // Positive stack
  23108. || (value <= 0 && stackedValue < 0) // Negative stack
  23109. ) {
  23110. value += stackedValue;
  23111. }
  23112. stackedOn = stackedOn.stackedOn;
  23113. }
  23114. }
  23115. }
  23116. return value;
  23117. };
  23118. // FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23119. // Hack a much simpler _getFast
  23120. listProto._getFast = function (dim, rawIdx) {
  23121. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23122. var chunkOffset = rawIdx % this._chunkSize;
  23123. var chunkStore = this._storage[dim][chunkIndex];
  23124. return chunkStore[chunkOffset];
  23125. };
  23126. /**
  23127. * Get value for multi dimensions.
  23128. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23129. * @param {number} idx
  23130. * @param {boolean} stack
  23131. * @return {number}
  23132. */
  23133. listProto.getValues = function (dimensions, idx, stack) {
  23134. var values = [];
  23135. if (!isArray(dimensions)) {
  23136. stack = idx;
  23137. idx = dimensions;
  23138. dimensions = this.dimensions;
  23139. }
  23140. for (var i = 0, len = dimensions.length; i < len; i++) {
  23141. values.push(this.get(dimensions[i], idx, stack));
  23142. }
  23143. return values;
  23144. };
  23145. /**
  23146. * If value is NaN. Inlcuding '-'
  23147. * Only check the coord dimensions.
  23148. * @param {string} dim
  23149. * @param {number} idx
  23150. * @return {number}
  23151. */
  23152. listProto.hasValue = function (idx) {
  23153. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23154. var dimensionInfos = this._dimensionInfos;
  23155. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23156. if (
  23157. // Ordinal type can be string or number
  23158. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23159. // FIXME check ordinal when using index?
  23160. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23161. ) {
  23162. return false;
  23163. }
  23164. }
  23165. return true;
  23166. };
  23167. /**
  23168. * Get extent of data in one dimension
  23169. * @param {string} dim
  23170. * @param {boolean} stack
  23171. */
  23172. listProto.getDataExtent = function (dim, stack) {
  23173. // Make sure use concrete dim as cache name.
  23174. dim = this.getDimension(dim);
  23175. var dimData = this._storage[dim];
  23176. var initialExtent = [Infinity, -Infinity];
  23177. stack = (stack || false) && this.isStacked(dim);
  23178. if (!dimData) {
  23179. return initialExtent;
  23180. }
  23181. // Make more strict checkings to ensure hitting cache.
  23182. var currEnd = this.count();
  23183. var cacheName = [dim, !!stack].join('_');
  23184. // Consider the most cases when using data zoom, `getDataExtent`
  23185. // happened before filtering. We cache raw extent, which is not
  23186. // necessary to be cleared and recalculated when restore data.
  23187. var useRaw = !this._indices && !stack;
  23188. var dimExtent;
  23189. if (useRaw) {
  23190. return this._rawExtent[dim].slice();
  23191. }
  23192. dimExtent = this._extent[cacheName];
  23193. if (dimExtent) {
  23194. return dimExtent.slice();
  23195. }
  23196. dimExtent = initialExtent;
  23197. var min = dimExtent[0];
  23198. var max = dimExtent[1];
  23199. for (var i = 0; i < currEnd; i++) {
  23200. var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23201. value < min && (min = value);
  23202. value > max && (max = value);
  23203. }
  23204. dimExtent = [min, max];
  23205. this._extent[cacheName] = dimExtent;
  23206. return dimExtent;
  23207. };
  23208. /**
  23209. * Optimize for the scenario that data is filtered by a given extent.
  23210. * Consider that if data amount is more than hundreds of thousand,
  23211. * extent calculation will cost more than 10ms and the cache will
  23212. * be erased because of the filtering.
  23213. */
  23214. listProto.getApproximateExtent = function (dim, stack) {
  23215. dim = this.getDimension(dim);
  23216. return this._approximateExtent[dim] || this.getDataExtent(dim, stack);
  23217. };
  23218. listProto.setApproximateExtent = function (extent, dim, stack) {
  23219. dim = this.getDimension(dim);
  23220. this._approximateExtent[dim] = extent.slice();
  23221. };
  23222. listProto.isStacked = function (concreteDim) {
  23223. var dimensionInfo = this._dimensionInfos[concreteDim];
  23224. return dimensionInfo && dimensionInfo.stackable && this.stackedOn;
  23225. };
  23226. /**
  23227. * Get sum of data in one dimension
  23228. * @param {string} dim
  23229. * @param {boolean} stack
  23230. */
  23231. listProto.getSum = function (dim, stack) {
  23232. var dimData = this._storage[dim];
  23233. var sum = 0;
  23234. if (dimData) {
  23235. for (var i = 0, len = this.count(); i < len; i++) {
  23236. var value = this.get(dim, i, stack);
  23237. if (!isNaN(value)) {
  23238. sum += value;
  23239. }
  23240. }
  23241. }
  23242. return sum;
  23243. };
  23244. /**
  23245. * Retreive the index with given value
  23246. * @param {number} idx
  23247. * @param {number} value
  23248. * @return {number}
  23249. */
  23250. // FIXME Precision of float value
  23251. listProto.indexOf = function (dim, value) {
  23252. var storage = this._storage;
  23253. var dimData = storage[dim];
  23254. var chunkSize = this._chunkSize;
  23255. if (dimData) {
  23256. for (var i = 0, len = this.count(); i < len; i++) {
  23257. var chunkIndex = Math.floor(i / chunkSize);
  23258. var chunkOffset = i % chunkSize;
  23259. if (dimData[chunkIndex][chunkOffset] === value) {
  23260. return i;
  23261. }
  23262. }
  23263. }
  23264. return -1;
  23265. };
  23266. /**
  23267. * Retreive the index with given name
  23268. * @param {number} idx
  23269. * @param {number} name
  23270. * @return {number}
  23271. */
  23272. listProto.indexOfName = function (name) {
  23273. for (var i = 0, len = this.count(); i < len; i++) {
  23274. if (this.getName(i) === name) {
  23275. return i;
  23276. }
  23277. }
  23278. return -1;
  23279. };
  23280. /**
  23281. * Retreive the index with given raw data index
  23282. * @param {number} idx
  23283. * @param {number} name
  23284. * @return {number}
  23285. */
  23286. listProto.indexOfRawIndex = function (rawIndex) {
  23287. if (!this._indices) {
  23288. return rawIndex;
  23289. }
  23290. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23291. return -1;
  23292. }
  23293. // Indices are ascending
  23294. var indices = this._indices;
  23295. // If rawIndex === dataIndex
  23296. var rawDataIndex = indices[rawIndex];
  23297. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23298. return rawIndex;
  23299. }
  23300. var left = 0;
  23301. var right = this._count - 1;
  23302. while (left <= right) {
  23303. var mid = (left + right) / 2 | 0;
  23304. if (indices[mid] < rawIndex) {
  23305. left = mid + 1;
  23306. }
  23307. else if (indices[mid] > rawIndex) {
  23308. right = mid - 1;
  23309. }
  23310. else {
  23311. return mid;
  23312. }
  23313. }
  23314. return -1;
  23315. };
  23316. /**
  23317. * Retreive the index of nearest value
  23318. * @param {string} dim
  23319. * @param {number} value
  23320. * @param {boolean} stack If given value is after stacked
  23321. * @param {number} [maxDistance=Infinity]
  23322. * @return {Array.<number>} Considere multiple points has the same value.
  23323. */
  23324. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  23325. var storage = this._storage;
  23326. var dimData = storage[dim];
  23327. var nearestIndices = [];
  23328. if (!dimData) {
  23329. return nearestIndices;
  23330. }
  23331. if (maxDistance == null) {
  23332. maxDistance = Infinity;
  23333. }
  23334. var minDist = Number.MAX_VALUE;
  23335. var minDiff = -1;
  23336. for (var i = 0, len = this.count(); i < len; i++) {
  23337. var diff = value - this.get(dim, i, stack);
  23338. var dist = Math.abs(diff);
  23339. if (diff <= maxDistance && dist <= minDist) {
  23340. // For the case of two data are same on xAxis, which has sequence data.
  23341. // Show the nearest index
  23342. // https://github.com/ecomfe/echarts/issues/2869
  23343. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23344. minDist = dist;
  23345. minDiff = diff;
  23346. nearestIndices.length = 0;
  23347. }
  23348. nearestIndices.push(i);
  23349. }
  23350. }
  23351. return nearestIndices;
  23352. };
  23353. /**
  23354. * Get raw data index
  23355. * @param {number} idx
  23356. * @return {number}
  23357. */
  23358. listProto.getRawIndex = getRawIndexWithoutIndices;
  23359. function getRawIndexWithoutIndices(idx) {
  23360. return idx;
  23361. }
  23362. function getRawIndexWithIndices(idx) {
  23363. if (idx < this._count && idx >= 0) {
  23364. return this._indices[idx];
  23365. }
  23366. return -1;
  23367. }
  23368. /**
  23369. * Get raw data item
  23370. * @param {number} idx
  23371. * @return {number}
  23372. */
  23373. listProto.getRawDataItem = function (idx) {
  23374. if (!this._rawData.persistent) {
  23375. var val = [];
  23376. for (var i = 0; i < this.dimensions.length; i++) {
  23377. var dim = this.dimensions[i];
  23378. val.push(this.get(dim, idx));
  23379. }
  23380. return val;
  23381. }
  23382. else {
  23383. return this._rawData.getItem(this.getRawIndex(idx));
  23384. }
  23385. };
  23386. /**
  23387. * @param {number} idx
  23388. * @param {boolean} [notDefaultIdx=false]
  23389. * @return {string}
  23390. */
  23391. listProto.getName = function (idx) {
  23392. var rawIndex = this.getRawIndex(idx);
  23393. return this._nameList[rawIndex]
  23394. || this._getNameFromStore(rawIndex)
  23395. || '';
  23396. };
  23397. /**
  23398. * @param {number} idx
  23399. * @param {boolean} [notDefaultIdx=false]
  23400. * @return {string}
  23401. */
  23402. listProto.getId = function (idx) {
  23403. return getId(this, this.getRawIndex(idx));
  23404. };
  23405. function getId(list, rawIndex) {
  23406. var id = list._idList[rawIndex];
  23407. if (id == null) {
  23408. id = list._getIdFromStore(rawIndex);
  23409. }
  23410. if (id == null) {
  23411. // FIXME Check the usage in graph, should not use prefix.
  23412. id = ID_PREFIX + rawIndex;
  23413. }
  23414. return id;
  23415. }
  23416. function normalizeDimensions(dimensions) {
  23417. if (!isArray(dimensions)) {
  23418. dimensions = [dimensions];
  23419. }
  23420. return dimensions;
  23421. }
  23422. function validateDimensions(list, dims) {
  23423. for (var i = 0; i < dims.length; i++) {
  23424. // stroage may be empty when no data, so use
  23425. // dimensionInfos to check.
  23426. if (!list._dimensionInfos[dims[i]]) {
  23427. console.error('Unkown dimension ' + dims[i]);
  23428. }
  23429. }
  23430. }
  23431. /**
  23432. * Data iteration
  23433. * @param {string|Array.<string>}
  23434. * @param {Function} cb
  23435. * @param {boolean} [stack=false]
  23436. * @param {*} [context=this]
  23437. *
  23438. * @example
  23439. * list.each('x', function (x, idx) {});
  23440. * list.each(['x', 'y'], function (x, y, idx) {});
  23441. * list.each(function (idx) {})
  23442. */
  23443. listProto.each = function (dims, cb, stack, context) {
  23444. 'use strict';
  23445. if (!this._count) {
  23446. return;
  23447. }
  23448. if (typeof dims === 'function') {
  23449. context = stack;
  23450. stack = cb;
  23451. cb = dims;
  23452. dims = [];
  23453. }
  23454. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23455. if (__DEV__) {
  23456. validateDimensions(this, dims);
  23457. }
  23458. var dimSize = dims.length;
  23459. context = context || this;
  23460. for (var i = 0; i < this.count(); i++) {
  23461. // Simple optimization
  23462. switch (dimSize) {
  23463. case 0:
  23464. cb.call(context, i);
  23465. break;
  23466. case 1:
  23467. cb.call(context, this.get(dims[0], i, stack), i);
  23468. break;
  23469. case 2:
  23470. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  23471. break;
  23472. default:
  23473. var k = 0;
  23474. var value = [];
  23475. for (; k < dimSize; k++) {
  23476. value[k] = this.get(dims[k], i, stack);
  23477. }
  23478. // Index
  23479. value[k] = i;
  23480. cb.apply(context, value);
  23481. }
  23482. }
  23483. };
  23484. /**
  23485. * Data filter
  23486. * @param {string|Array.<string>}
  23487. * @param {Function} cb
  23488. * @param {boolean} [stack=false]
  23489. * @param {*} [context=this]
  23490. */
  23491. listProto.filterSelf = function (dimensions, cb, stack, context) {
  23492. 'use strict';
  23493. if (!this._count) {
  23494. return;
  23495. }
  23496. if (typeof dimensions === 'function') {
  23497. context = stack;
  23498. stack = cb;
  23499. cb = dimensions;
  23500. dimensions = [];
  23501. }
  23502. stack = stack || false;
  23503. context = context || this;
  23504. dimensions = map(
  23505. normalizeDimensions(dimensions), this.getDimension, this
  23506. );
  23507. if (__DEV__) {
  23508. validateDimensions(this, dimensions);
  23509. }
  23510. var count = this.count();
  23511. var Ctor = getIndicesCtor(this);
  23512. var newIndices = new Ctor(count);
  23513. var value = [];
  23514. var dimSize = dimensions.length;
  23515. var offset = 0;
  23516. var dim0 = dimensions[0];
  23517. for (var i = 0; i < count; i++) {
  23518. var keep;
  23519. var rawIdx = this.getRawIndex(i);
  23520. // Simple optimization
  23521. if (dimSize === 0) {
  23522. keep = cb.call(context, i);
  23523. }
  23524. else if (dimSize === 1) {
  23525. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIdx);
  23526. keep = cb.call(context, val, i);
  23527. }
  23528. else {
  23529. for (var k = 0; k < dimSize; k++) {
  23530. value[k] = stack ? this.get(dimensions[k], i, true) : this._getFast(dim0, rawIdx);
  23531. }
  23532. value[k] = i;
  23533. keep = cb.apply(context, value);
  23534. }
  23535. if (keep) {
  23536. newIndices[offset++] = rawIdx;
  23537. }
  23538. }
  23539. // Set indices after filtered.
  23540. if (offset < count) {
  23541. this._indices = newIndices;
  23542. }
  23543. this._count = offset;
  23544. // Reset data extent
  23545. this._extent = {};
  23546. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23547. return this;
  23548. };
  23549. /**
  23550. * Select data in range. (For optimization of filter)
  23551. * (Manually inline code, support 5 million data filtering in data zoom.)
  23552. */
  23553. listProto.selectRange = function (range, stack) {
  23554. 'use strict';
  23555. if (!this._count) {
  23556. return;
  23557. }
  23558. stack = stack || false;
  23559. var dimensions = [];
  23560. for (var dim in range) {
  23561. if (range.hasOwnProperty(dim)) {
  23562. dimensions.push(dim);
  23563. }
  23564. }
  23565. if (__DEV__) {
  23566. validateDimensions(this, dimensions);
  23567. }
  23568. var dimSize = dimensions.length;
  23569. if (!dimSize) {
  23570. return;
  23571. }
  23572. var originalCount = this.count();
  23573. var Ctor = getIndicesCtor(this);
  23574. var newIndices = new Ctor(originalCount);
  23575. var offset = 0;
  23576. var dim0 = dimensions[0];
  23577. var min = range[dim0][0];
  23578. var max = range[dim0][1];
  23579. var quickFinished = false;
  23580. if (!this._indices && !stack) {
  23581. // Extreme optimization for common case. About 2x faster in chrome.
  23582. var idx = 0;
  23583. if (dimSize === 1) {
  23584. var dimStorage = this._storage[dimensions[0]];
  23585. for (var k = 0; k < this._chunkCount; k++) {
  23586. var chunkStorage = dimStorage[k];
  23587. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23588. for (var i = 0; i < len; i++) {
  23589. var val = chunkStorage[i];
  23590. if (val >= min && val <= max) {
  23591. newIndices[offset++] = idx;
  23592. }
  23593. idx++;
  23594. }
  23595. }
  23596. quickFinished = true;
  23597. }
  23598. else if (dimSize === 2) {
  23599. var dimStorage = this._storage[dim0];
  23600. var dimStorage2 = this._storage[dimensions[1]];
  23601. var min2 = range[dimensions[1]][0];
  23602. var max2 = range[dimensions[1]][1];
  23603. for (var k = 0; k < this._chunkCount; k++) {
  23604. var chunkStorage = dimStorage[k];
  23605. var chunkStorage2= dimStorage2[k];
  23606. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23607. for (var i = 0; i < len; i++) {
  23608. var val = chunkStorage[i];
  23609. var val2 = chunkStorage2[i];
  23610. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23611. newIndices[offset++] = idx;
  23612. }
  23613. idx++;
  23614. }
  23615. }
  23616. quickFinished = true;
  23617. }
  23618. }
  23619. if (!quickFinished) {
  23620. if (dimSize === 1) {
  23621. stack = stack || this.isStacked(dim0);
  23622. for (var i = 0; i < originalCount; i++) {
  23623. var rawIndex = this.getRawIndex(i);
  23624. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23625. if (val >= min && val <= max) {
  23626. newIndices[offset++] = rawIndex;
  23627. }
  23628. }
  23629. }
  23630. else {
  23631. for (var i = 0; i < originalCount; i++) {
  23632. var keep = true;
  23633. var rawIndex = this.getRawIndex(i);
  23634. for (var k = 0; k < dimSize; k++) {
  23635. var dimk = dimensions[k];
  23636. var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23637. if (val < range[dimk][0] || val > range[dimk][1]) {
  23638. keep = false;
  23639. }
  23640. }
  23641. if (keep) {
  23642. newIndices[offset++] = this.getRawIndex(i);
  23643. }
  23644. }
  23645. }
  23646. }
  23647. // Set indices after filtered.
  23648. if (offset < originalCount) {
  23649. this._indices = newIndices;
  23650. }
  23651. this._count = offset;
  23652. // Reset data extent
  23653. this._extent = {};
  23654. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23655. return this;
  23656. };
  23657. /**
  23658. * Data mapping to a plain array
  23659. * @param {string|Array.<string>} [dimensions]
  23660. * @param {Function} cb
  23661. * @param {boolean} [stack=false]
  23662. * @param {*} [context=this]
  23663. * @return {Array}
  23664. */
  23665. listProto.mapArray = function (dimensions, cb, stack, context) {
  23666. 'use strict';
  23667. if (typeof dimensions === 'function') {
  23668. context = stack;
  23669. stack = cb;
  23670. cb = dimensions;
  23671. dimensions = [];
  23672. }
  23673. var result = [];
  23674. this.each(dimensions, function () {
  23675. result.push(cb && cb.apply(this, arguments));
  23676. }, stack, context);
  23677. return result;
  23678. };
  23679. // Data in excludeDimensions is copied, otherwise transfered.
  23680. function cloneListForMapAndSample(original, excludeDimensions) {
  23681. var allDimensions = original.dimensions;
  23682. var list = new List(
  23683. map(allDimensions, original.getDimensionInfo, original),
  23684. original.hostModel
  23685. );
  23686. // FIXME If needs stackedOn, value may already been stacked
  23687. transferProperties(list, original);
  23688. var storage = list._storage = {};
  23689. var originalStorage = original._storage;
  23690. // Init storage
  23691. for (var i = 0; i < allDimensions.length; i++) {
  23692. var dim = allDimensions[i];
  23693. if (originalStorage[dim]) {
  23694. storage[dim] = indexOf(excludeDimensions, dim) >= 0
  23695. ? cloneDimStore(originalStorage[dim])
  23696. // Direct reference for other dimensions
  23697. : originalStorage[dim];
  23698. }
  23699. }
  23700. return list;
  23701. }
  23702. function cloneDimStore(originalDimStore) {
  23703. var newDimStore = new Array(originalDimStore.length);
  23704. for (var j = 0; j < originalDimStore.length; j++) {
  23705. newDimStore[j] = cloneChunk(originalDimStore[j]);
  23706. }
  23707. return newDimStore;
  23708. }
  23709. /**
  23710. * Data mapping to a new List with given dimensions
  23711. * @param {string|Array.<string>} dimensions
  23712. * @param {Function} cb
  23713. * @param {boolean} [stack=false]
  23714. * @param {*} [context=this]
  23715. * @return {Array}
  23716. */
  23717. listProto.map = function (dimensions, cb, stack, context) {
  23718. 'use strict';
  23719. dimensions = map(
  23720. normalizeDimensions(dimensions), this.getDimension, this
  23721. );
  23722. if (__DEV__) {
  23723. validateDimensions(this, dimensions);
  23724. }
  23725. var list = cloneListForMapAndSample(this, dimensions);
  23726. // Following properties are all immutable.
  23727. // So we can reference to the same value
  23728. list._indices = this._indices;
  23729. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23730. var storage = list._storage;
  23731. var tmpRetValue = [];
  23732. var chunkSize = this._chunkSize;
  23733. var dimSize = dimensions.length;
  23734. var dataCount = this.count();
  23735. var values = [];
  23736. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  23737. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  23738. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex, stack);
  23739. }
  23740. values[dimSize] = dataIndex;
  23741. var retValue = cb && cb.apply(context, values);
  23742. if (retValue != null) {
  23743. // a number or string (in oridinal dimension)?
  23744. if (typeof retValue !== 'object') {
  23745. tmpRetValue[0] = retValue;
  23746. retValue = tmpRetValue;
  23747. }
  23748. var rawIndex = this.getRawIndex(dataIndex);
  23749. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23750. var chunkOffset = rawIndex % chunkSize;
  23751. for (var i = 0; i < retValue.length; i++) {
  23752. var dim = dimensions[i];
  23753. var dimStore = storage[dim];
  23754. if (dimStore) {
  23755. dimStore[chunkIndex][chunkOffset] = retValue[i];
  23756. }
  23757. }
  23758. }
  23759. }
  23760. return list;
  23761. };
  23762. /**
  23763. * Large data down sampling on given dimension
  23764. * @param {string} dimension
  23765. * @param {number} rate
  23766. * @param {Function} sampleValue
  23767. * @param {Function} sampleIndex Sample index for name and id
  23768. */
  23769. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  23770. var list = cloneListForMapAndSample(this, [dimension]);
  23771. var targetStorage = list._storage;
  23772. var frameValues = [];
  23773. var frameSize = Math.floor(1 / rate);
  23774. var dimStore = targetStorage[dimension];
  23775. var len = this.count();
  23776. var chunkSize = this._chunkSize;
  23777. var newIndices = new (getIndicesCtor(this))(len);
  23778. var offset = 0;
  23779. for (var i = 0; i < len; i += frameSize) {
  23780. // Last frame
  23781. if (frameSize > len - i) {
  23782. frameSize = len - i;
  23783. frameValues.length = frameSize;
  23784. }
  23785. for (var k = 0; k < frameSize; k++) {
  23786. var dataIdx = this.getRawIndex(i + k);
  23787. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  23788. var originalChunkOffset = dataIdx % chunkSize;
  23789. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  23790. }
  23791. var value = sampleValue(frameValues);
  23792. var sampleFrameIdx = this.getRawIndex(
  23793. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  23794. );
  23795. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  23796. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  23797. // Only write value on the filtered data
  23798. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  23799. newIndices[offset++] = sampleFrameIdx;
  23800. }
  23801. list._count = offset;
  23802. list._indices = newIndices;
  23803. list.getRawIndex = getRawIndexWithIndices;
  23804. return list;
  23805. };
  23806. /**
  23807. * Get model of one data item.
  23808. *
  23809. * @param {number} idx
  23810. */
  23811. // FIXME Model proxy ?
  23812. listProto.getItemModel = function (idx) {
  23813. var hostModel = this.hostModel;
  23814. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  23815. };
  23816. /**
  23817. * Create a data differ
  23818. * @param {module:echarts/data/List} otherList
  23819. * @return {module:echarts/data/DataDiffer}
  23820. */
  23821. listProto.diff = function (otherList) {
  23822. var thisList = this;
  23823. return new DataDiffer(
  23824. otherList ? otherList.getIndices() : [],
  23825. this.getIndices(),
  23826. function (idx) {
  23827. return getId(otherList, idx);
  23828. },
  23829. function (idx) {
  23830. return getId(thisList, idx);
  23831. }
  23832. );
  23833. };
  23834. /**
  23835. * Get visual property.
  23836. * @param {string} key
  23837. */
  23838. listProto.getVisual = function (key) {
  23839. var visual = this._visual;
  23840. return visual && visual[key];
  23841. };
  23842. /**
  23843. * Set visual property
  23844. * @param {string|Object} key
  23845. * @param {*} [value]
  23846. *
  23847. * @example
  23848. * setVisual('color', color);
  23849. * setVisual({
  23850. * 'color': color
  23851. * });
  23852. */
  23853. listProto.setVisual = function (key, val) {
  23854. if (isObject$4(key)) {
  23855. for (var name in key) {
  23856. if (key.hasOwnProperty(name)) {
  23857. this.setVisual(name, key[name]);
  23858. }
  23859. }
  23860. return;
  23861. }
  23862. this._visual = this._visual || {};
  23863. this._visual[key] = val;
  23864. };
  23865. /**
  23866. * Set layout property.
  23867. * @param {string|Object} key
  23868. * @param {*} [val]
  23869. */
  23870. listProto.setLayout = function (key, val) {
  23871. if (isObject$4(key)) {
  23872. for (var name in key) {
  23873. if (key.hasOwnProperty(name)) {
  23874. this.setLayout(name, key[name]);
  23875. }
  23876. }
  23877. return;
  23878. }
  23879. this._layout[key] = val;
  23880. };
  23881. /**
  23882. * Get layout property.
  23883. * @param {string} key.
  23884. * @return {*}
  23885. */
  23886. listProto.getLayout = function (key) {
  23887. return this._layout[key];
  23888. };
  23889. /**
  23890. * Get layout of single data item
  23891. * @param {number} idx
  23892. */
  23893. listProto.getItemLayout = function (idx) {
  23894. return this._itemLayouts[idx];
  23895. };
  23896. /**
  23897. * Set layout of single data item
  23898. * @param {number} idx
  23899. * @param {Object} layout
  23900. * @param {boolean=} [merge=false]
  23901. */
  23902. listProto.setItemLayout = function (idx, layout, merge$$1) {
  23903. this._itemLayouts[idx] = merge$$1
  23904. ? extend(this._itemLayouts[idx] || {}, layout)
  23905. : layout;
  23906. };
  23907. /**
  23908. * Clear all layout of single data item
  23909. */
  23910. listProto.clearItemLayouts = function () {
  23911. this._itemLayouts.length = 0;
  23912. };
  23913. /**
  23914. * Get visual property of single data item
  23915. * @param {number} idx
  23916. * @param {string} key
  23917. * @param {boolean} [ignoreParent=false]
  23918. */
  23919. listProto.getItemVisual = function (idx, key, ignoreParent) {
  23920. var itemVisual = this._itemVisuals[idx];
  23921. var val = itemVisual && itemVisual[key];
  23922. if (val == null && !ignoreParent) {
  23923. // Use global visual property
  23924. return this.getVisual(key);
  23925. }
  23926. return val;
  23927. };
  23928. /**
  23929. * Set visual property of single data item
  23930. *
  23931. * @param {number} idx
  23932. * @param {string|Object} key
  23933. * @param {*} [value]
  23934. *
  23935. * @example
  23936. * setItemVisual(0, 'color', color);
  23937. * setItemVisual(0, {
  23938. * 'color': color
  23939. * });
  23940. */
  23941. listProto.setItemVisual = function (idx, key, value) {
  23942. var itemVisual = this._itemVisuals[idx] || {};
  23943. var hasItemVisual = this.hasItemVisual;
  23944. this._itemVisuals[idx] = itemVisual;
  23945. if (isObject$4(key)) {
  23946. for (var name in key) {
  23947. if (key.hasOwnProperty(name)) {
  23948. itemVisual[name] = key[name];
  23949. hasItemVisual[name] = true;
  23950. }
  23951. }
  23952. return;
  23953. }
  23954. itemVisual[key] = value;
  23955. hasItemVisual[key] = true;
  23956. };
  23957. /**
  23958. * Clear itemVisuals and list visual.
  23959. */
  23960. listProto.clearAllVisual = function () {
  23961. this._visual = {};
  23962. this._itemVisuals = [];
  23963. this.hasItemVisual = {};
  23964. };
  23965. var setItemDataAndSeriesIndex = function (child) {
  23966. child.seriesIndex = this.seriesIndex;
  23967. child.dataIndex = this.dataIndex;
  23968. child.dataType = this.dataType;
  23969. };
  23970. /**
  23971. * Set graphic element relative to data. It can be set as null
  23972. * @param {number} idx
  23973. * @param {module:zrender/Element} [el]
  23974. */
  23975. listProto.setItemGraphicEl = function (idx, el) {
  23976. var hostModel = this.hostModel;
  23977. if (el) {
  23978. // Add data index and series index for indexing the data by element
  23979. // Useful in tooltip
  23980. el.dataIndex = idx;
  23981. el.dataType = this.dataType;
  23982. el.seriesIndex = hostModel && hostModel.seriesIndex;
  23983. if (el.type === 'group') {
  23984. el.traverse(setItemDataAndSeriesIndex, el);
  23985. }
  23986. }
  23987. this._graphicEls[idx] = el;
  23988. };
  23989. /**
  23990. * @param {number} idx
  23991. * @return {module:zrender/Element}
  23992. */
  23993. listProto.getItemGraphicEl = function (idx) {
  23994. return this._graphicEls[idx];
  23995. };
  23996. /**
  23997. * @param {Function} cb
  23998. * @param {*} context
  23999. */
  24000. listProto.eachItemGraphicEl = function (cb, context) {
  24001. each$1(this._graphicEls, function (el, idx) {
  24002. if (el) {
  24003. cb && cb.call(context, el, idx);
  24004. }
  24005. });
  24006. };
  24007. /**
  24008. * Shallow clone a new list except visual and layout properties, and graph elements.
  24009. * New list only change the indices.
  24010. */
  24011. listProto.cloneShallow = function (list) {
  24012. if (!list) {
  24013. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24014. list = new List(dimensionInfoList, this.hostModel);
  24015. }
  24016. // FIXME
  24017. list._storage = this._storage;
  24018. transferProperties(list, this);
  24019. // Clone will not change the data extent and indices
  24020. if (this._indices) {
  24021. var Ctor = this._indices.constructor;
  24022. list._indices = new Ctor(this._indices);
  24023. }
  24024. else {
  24025. list._indices = null;
  24026. }
  24027. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24028. list._extent = clone(this._extent);
  24029. list._approximateExtent = clone(this._approximateExtent);
  24030. return list;
  24031. };
  24032. /**
  24033. * Wrap some method to add more feature
  24034. * @param {string} methodName
  24035. * @param {Function} injectFunction
  24036. */
  24037. listProto.wrapMethod = function (methodName, injectFunction) {
  24038. var originalMethod = this[methodName];
  24039. if (typeof originalMethod !== 'function') {
  24040. return;
  24041. }
  24042. this.__wrappedMethods = this.__wrappedMethods || [];
  24043. this.__wrappedMethods.push(methodName);
  24044. this[methodName] = function () {
  24045. var res = originalMethod.apply(this, arguments);
  24046. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24047. };
  24048. };
  24049. // Methods that create a new list based on this list should be listed here.
  24050. // Notice that those method should `RETURN` the new list.
  24051. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24052. // Methods that change indices of this list should be listed here.
  24053. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24054. /**
  24055. * @deprecated
  24056. * Use `echarts/data/helper/createDimensions` instead.
  24057. */
  24058. /**
  24059. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24060. *
  24061. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24062. * and guessing from the data structure.
  24063. * If no 'value' dimension specified, the first no-named dimension will be
  24064. * named as 'value'.
  24065. *
  24066. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24067. * provides not only dim template, but also default order.
  24068. * properties: 'name', 'type', 'displayName'.
  24069. * `name` of each item provides default coord name.
  24070. * [{dimsDef: [string...]}, ...] can be specified to give names.
  24071. * [{ordinalMeta}] can be specified.
  24072. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24073. * @param {Object} [opt]
  24074. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24075. * For example: ['asdf', {name, type}, ...].
  24076. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24077. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  24078. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  24079. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  24080. * If not specified, extra dim names will be:
  24081. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  24082. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24083. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24084. * @return {Array.<Object>} [{
  24085. * name: string mandatory,
  24086. * displayName: string, the origin name in dimsDef, see source helper.
  24087. * If displayName given, the tooltip will displayed vertically.
  24088. * coordDim: string mandatory,
  24089. * isSysCoord: boolean True if the coord is from sys dimension.
  24090. * coordDimIndex: number mandatory,
  24091. * type: string optional,
  24092. * otherDims: { never null/undefined
  24093. * tooltip: number optional,
  24094. * label: number optional,
  24095. * itemName: number optional,
  24096. * seriesName: number optional,
  24097. * },
  24098. * isExtraCoord: boolean true or undefined.
  24099. * other props ...
  24100. * }]
  24101. */
  24102. function completeDimensions(sysDims, source, opt) {
  24103. if (!Source.isInstance(source)) {
  24104. source = Source.seriesDataToSource(source);
  24105. }
  24106. opt = opt || {};
  24107. sysDims = (sysDims || []).slice();
  24108. var dimsDef = (opt.dimsDef || []).slice();
  24109. var encodeDef = createHashMap(opt.encodeDef);
  24110. var dataDimNameMap = createHashMap();
  24111. var coordDimNameMap = createHashMap();
  24112. // var valueCandidate;
  24113. var result = [];
  24114. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24115. // Apply user defined dims (`name` and `type`) and init result.
  24116. for (var i = 0; i < dimCount; i++) {
  24117. var dimDefItem = dimsDef[i] = extend(
  24118. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24119. );
  24120. var userDimName = dimDefItem.name;
  24121. var resultItem = result[i] = {otherDims: {}};
  24122. // Name will be applied later for avoiding duplication.
  24123. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24124. // Only if `series.dimensions` is defined in option
  24125. // displayName, will be set, and dimension will be diplayed vertically in
  24126. // tooltip by default.
  24127. resultItem.name = resultItem.displayName = userDimName;
  24128. dataDimNameMap.set(userDimName, i);
  24129. }
  24130. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24131. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24132. }
  24133. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24134. encodeDef.each(function (dataDims, coordDim) {
  24135. dataDims = normalizeToArray(dataDims).slice();
  24136. var validDataDims = encodeDef.set(coordDim, []);
  24137. each$1(dataDims, function (resultDimIdx, idx) {
  24138. // The input resultDimIdx can be dim name or index.
  24139. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24140. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24141. validDataDims[idx] = resultDimIdx;
  24142. applyDim(result[resultDimIdx], coordDim, idx);
  24143. }
  24144. });
  24145. });
  24146. // Apply templetes and default order from `sysDims`.
  24147. var availDimIdx = 0;
  24148. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24149. var coordDim;
  24150. var sysDimItem;
  24151. var sysDimItemDimsDef;
  24152. var sysDimItemOtherDims;
  24153. if (isString(sysDimItem)) {
  24154. coordDim = sysDimItem;
  24155. sysDimItem = {};
  24156. }
  24157. else {
  24158. coordDim = sysDimItem.name;
  24159. var ordinalMeta = sysDimItem.ordinalMeta;
  24160. sysDimItem.ordinalMeta = null;
  24161. sysDimItem = clone(sysDimItem);
  24162. sysDimItem.ordinalMeta = ordinalMeta;
  24163. // `coordDimIndex` should not be set directly.
  24164. sysDimItemDimsDef = sysDimItem.dimsDef;
  24165. sysDimItemOtherDims = sysDimItem.otherDims;
  24166. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24167. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24168. }
  24169. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24170. // dimensions provides default dim sequences.
  24171. if (!dataDims.length) {
  24172. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24173. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24174. availDimIdx++;
  24175. }
  24176. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24177. }
  24178. }
  24179. // Apply templates.
  24180. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24181. var resultItem = result[resultDimIdx];
  24182. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24183. if (resultItem.name == null && sysDimItemDimsDef) {
  24184. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24185. }
  24186. resultItem.isSysCoord = true;
  24187. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24188. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24189. });
  24190. });
  24191. function applyDim(resultItem, coordDim, coordDimIndex) {
  24192. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24193. resultItem.otherDims[coordDim] = coordDimIndex;
  24194. }
  24195. else {
  24196. resultItem.coordDim = coordDim;
  24197. resultItem.coordDimIndex = coordDimIndex;
  24198. coordDimNameMap.set(coordDim, true);
  24199. }
  24200. }
  24201. // Make sure the first extra dim is 'value'.
  24202. var extra = opt.extraPrefix || 'value';
  24203. // Set dim `name` and other `coordDim` and other props.
  24204. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24205. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24206. var coordDim = resultItem.coordDim;
  24207. coordDim == null && (
  24208. resultItem.coordDim = genName(
  24209. extra, coordDimNameMap, opt.extraFromZero
  24210. ),
  24211. resultItem.coordDimIndex = 0,
  24212. resultItem.isExtraCoord = true
  24213. );
  24214. resultItem.name == null && (resultItem.name = genName(
  24215. resultItem.coordDim,
  24216. dataDimNameMap
  24217. ));
  24218. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24219. resultItem.type = 'ordinal';
  24220. }
  24221. }
  24222. return result;
  24223. }
  24224. // ??? TODO
  24225. // Originally detect dimCount by data[0]. Should we
  24226. // optimize it to only by sysDims and dimensions and encode.
  24227. // So only necessary dims will be initialized.
  24228. // But
  24229. // (1) custom series should be considered. where other dims
  24230. // may be visited.
  24231. // (2) sometimes user need to calcualte bubble size or use visualMap
  24232. // on other dimensions besides coordSys needed.
  24233. function getDimCount(source, sysDims, dimsDef, dimCount) {
  24234. if (dimCount == null) {
  24235. dimCount = Math.max(
  24236. source.dimensionsDetectCount || 1,
  24237. sysDims.length,
  24238. dimsDef.length
  24239. );
  24240. each$1(sysDims, function (sysDimItem) {
  24241. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24242. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24243. });
  24244. }
  24245. return dimCount;
  24246. }
  24247. function genName(name, map$$1, fromZero) {
  24248. if (fromZero || map$$1.get(name) != null) {
  24249. var i = 0;
  24250. while (map$$1.get(name + i) != null) {
  24251. i++;
  24252. }
  24253. name += i;
  24254. }
  24255. map$$1.set(name, true);
  24256. return name;
  24257. }
  24258. /**
  24259. * Substitute `completeDimensions`.
  24260. * `completeDimensions` is to be deprecated.
  24261. */
  24262. /**
  24263. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24264. * @param {Object|Array} [opt]
  24265. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24266. * @param {number} [opt.dimensionsCount]
  24267. * @param {string} [opt.extraPrefix]
  24268. * @param {boolean} [opt.extraFromZero]
  24269. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24270. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24271. * @return {Array.<Object>} dimensionsInfo
  24272. */
  24273. var createDimensions = function (source, opt) {
  24274. opt = opt || {};
  24275. return completeDimensions(opt.coordDimensions || [], source, {
  24276. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24277. encodeDef: opt.encodeDefine || source.encodeDefine,
  24278. dimCount: opt.dimensionsCount,
  24279. extraPrefix: opt.extraPrefix,
  24280. extraFromZero: opt.extraFromZero
  24281. });
  24282. };
  24283. /**
  24284. * @param {module:echarts/data/Source|Array} source Or raw data.
  24285. * @param {module:echarts/model/Series} seriesModel
  24286. */
  24287. function createListFromArray(source, seriesModel) {
  24288. if (!Source.isInstance(source)) {
  24289. source = Source.seriesDataToSource(source);
  24290. }
  24291. var coordSysName = seriesModel.get('coordinateSystem');
  24292. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24293. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24294. var coordSysDimDefs;
  24295. if (coordSysDefine) {
  24296. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24297. var dimInfo = {name: dim};
  24298. var axisModel = coordSysDefine.axisMap.get(dim);
  24299. if (axisModel) {
  24300. var axisType = axisModel.get('type');
  24301. dimInfo.type = getDimensionTypeByAxis(axisType);
  24302. dimInfo.stackable = isStackable(axisType);
  24303. }
  24304. return dimInfo;
  24305. });
  24306. }
  24307. if (!coordSysDimDefs) {
  24308. // Get dimensions from registered coordinate system
  24309. coordSysDimDefs = (registeredCoordSys && (
  24310. registeredCoordSys.getDimensionsInfo
  24311. ? registeredCoordSys.getDimensionsInfo()
  24312. : registeredCoordSys.dimensions.slice()
  24313. )) || ['x', 'y'];
  24314. }
  24315. var dimInfoList = createDimensions(source, {
  24316. coordDimensions: coordSysDimDefs
  24317. });
  24318. var firstCategoryDimIndex;
  24319. var hasNameEncode;
  24320. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24321. var coordDim = dimInfo.coordDim;
  24322. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24323. if (categoryAxisModel) {
  24324. if (firstCategoryDimIndex == null) {
  24325. firstCategoryDimIndex = dimIndex;
  24326. }
  24327. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24328. }
  24329. if (dimInfo.otherDims.itemName != null) {
  24330. hasNameEncode = true;
  24331. }
  24332. });
  24333. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24334. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24335. }
  24336. var list = new List(dimInfoList, seriesModel);
  24337. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24338. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24339. // Use dataIndex as ordinal value in categoryAxis
  24340. return dimIndex === firstCategoryDimIndex
  24341. ? dataIndex
  24342. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24343. }
  24344. : null;
  24345. list.hasItemOption = false;
  24346. list.initData(source, null, dimValueGetter);
  24347. return list;
  24348. }
  24349. function isStackable(axisType) {
  24350. return axisType !== 'category' && axisType !== 'time';
  24351. }
  24352. function isNeedCompleteOrdinalData(source) {
  24353. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24354. var sampleItem = firstDataNotNull(source.data || []);
  24355. return sampleItem != null
  24356. && !isArray(getDataItemValue(sampleItem));
  24357. }
  24358. }
  24359. function firstDataNotNull(data) {
  24360. var i = 0;
  24361. while (i < data.length && data[i] == null) {
  24362. i++;
  24363. }
  24364. return data[i];
  24365. }
  24366. /**
  24367. * // Scale class management
  24368. * @module echarts/scale/Scale
  24369. */
  24370. /**
  24371. * @param {Object} [setting]
  24372. */
  24373. function Scale(setting) {
  24374. this._setting = setting || {};
  24375. /**
  24376. * Extent
  24377. * @type {Array.<number>}
  24378. * @protected
  24379. */
  24380. this._extent = [Infinity, -Infinity];
  24381. /**
  24382. * Step is calculated in adjustExtent
  24383. * @type {Array.<number>}
  24384. * @protected
  24385. */
  24386. this._interval = 0;
  24387. this.init && this.init.apply(this, arguments);
  24388. }
  24389. /**
  24390. * Parse input val to valid inner number.
  24391. * @param {*} val
  24392. * @return {number}
  24393. */
  24394. Scale.prototype.parse = function (val) {
  24395. // Notice: This would be a trap here, If the implementation
  24396. // of this method depends on extent, and this method is used
  24397. // before extent set (like in dataZoom), it would be wrong.
  24398. // Nevertheless, parse does not depend on extent generally.
  24399. return val;
  24400. };
  24401. Scale.prototype.getSetting = function (name) {
  24402. return this._setting[name];
  24403. };
  24404. Scale.prototype.contain = function (val) {
  24405. var extent = this._extent;
  24406. return val >= extent[0] && val <= extent[1];
  24407. };
  24408. /**
  24409. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24410. * @param {number} val
  24411. * @return {number}
  24412. */
  24413. Scale.prototype.normalize = function (val) {
  24414. var extent = this._extent;
  24415. if (extent[1] === extent[0]) {
  24416. return 0.5;
  24417. }
  24418. return (val - extent[0]) / (extent[1] - extent[0]);
  24419. };
  24420. /**
  24421. * Scale normalized value
  24422. * @param {number} val
  24423. * @return {number}
  24424. */
  24425. Scale.prototype.scale = function (val) {
  24426. var extent = this._extent;
  24427. return val * (extent[1] - extent[0]) + extent[0];
  24428. };
  24429. /**
  24430. * Set extent from data
  24431. * @param {Array.<number>} other
  24432. */
  24433. Scale.prototype.unionExtent = function (other) {
  24434. var extent = this._extent;
  24435. other[0] < extent[0] && (extent[0] = other[0]);
  24436. other[1] > extent[1] && (extent[1] = other[1]);
  24437. // not setExtent because in log axis it may transformed to power
  24438. // this.setExtent(extent[0], extent[1]);
  24439. };
  24440. /**
  24441. * Set extent from data
  24442. * @param {module:echarts/data/List} data
  24443. * @param {string} dim
  24444. */
  24445. Scale.prototype.unionExtentFromData = function (data, dim) {
  24446. this.unionExtent(data.getApproximateExtent(dim, true));
  24447. };
  24448. /**
  24449. * Get extent
  24450. * @return {Array.<number>}
  24451. */
  24452. Scale.prototype.getExtent = function () {
  24453. return this._extent.slice();
  24454. };
  24455. /**
  24456. * Set extent
  24457. * @param {number} start
  24458. * @param {number} end
  24459. */
  24460. Scale.prototype.setExtent = function (start, end) {
  24461. var thisExtent = this._extent;
  24462. if (!isNaN(start)) {
  24463. thisExtent[0] = start;
  24464. }
  24465. if (!isNaN(end)) {
  24466. thisExtent[1] = end;
  24467. }
  24468. };
  24469. /**
  24470. * @return {Array.<string>}
  24471. */
  24472. Scale.prototype.getTicksLabels = function () {
  24473. var labels = [];
  24474. var ticks = this.getTicks();
  24475. for (var i = 0; i < ticks.length; i++) {
  24476. labels.push(this.getLabel(ticks[i]));
  24477. }
  24478. return labels;
  24479. };
  24480. /**
  24481. * When axis extent depends on data and no data exists,
  24482. * axis ticks should not be drawn, which is named 'blank'.
  24483. */
  24484. Scale.prototype.isBlank = function () {
  24485. return this._isBlank;
  24486. },
  24487. /**
  24488. * When axis extent depends on data and no data exists,
  24489. * axis ticks should not be drawn, which is named 'blank'.
  24490. */
  24491. Scale.prototype.setBlank = function (isBlank) {
  24492. this._isBlank = isBlank;
  24493. };
  24494. enableClassExtend(Scale);
  24495. enableClassManagement(Scale, {
  24496. registerWhenExtend: true
  24497. });
  24498. /**
  24499. * @constructor
  24500. * @param {Object} [opt]
  24501. * @param {Object} [opt.categories=[]]
  24502. * @param {Object} [opt.needCollect=false]
  24503. * @param {Object} [opt.deduplication=false]
  24504. */
  24505. function OrdinalMeta(opt) {
  24506. /**
  24507. * @readOnly
  24508. * @type {Array.<string>}
  24509. */
  24510. this.categories = opt.categories || [];
  24511. /**
  24512. * @private
  24513. * @type {boolean}
  24514. */
  24515. this._needCollect = opt.needCollect;
  24516. /**
  24517. * @private
  24518. * @type {boolean}
  24519. */
  24520. this._deduplication = opt.deduplication;
  24521. /**
  24522. * @private
  24523. * @type {boolean}
  24524. */
  24525. this._map;
  24526. }
  24527. /**
  24528. * @param {module:echarts/model/Model} axisModel
  24529. * @return {module:echarts/data/OrdinalMeta}
  24530. */
  24531. OrdinalMeta.createByAxisModel = function (axisModel) {
  24532. var option = axisModel.option;
  24533. var data = option.data;
  24534. var categories = data && map(data, getName);
  24535. return new OrdinalMeta({
  24536. categories: categories,
  24537. needCollect: !categories,
  24538. // deduplication is default in axis.
  24539. deduplication: option.dedplication !== false
  24540. });
  24541. };
  24542. var proto$1 = OrdinalMeta.prototype;
  24543. /**
  24544. * @param {string} category
  24545. * @return {number} ordinal
  24546. */
  24547. proto$1.getOrdinal = function (category) {
  24548. return getOrCreateMap(this).get(category);
  24549. };
  24550. /**
  24551. * @param {*} category
  24552. * @return {number} The ordinal. If not found, return NaN.
  24553. */
  24554. proto$1.parseAndCollect = function (category) {
  24555. var index;
  24556. var needCollect = this._needCollect;
  24557. // The value of category dim can be the index of the given category set.
  24558. // This feature is only supported when !needCollect, because we should
  24559. // consider a common case: a value is 2017, which is a number but is
  24560. // expected to be tread as a category. This case usually happen in dataset,
  24561. // where it happent to be no need of the index feature.
  24562. if (typeof category !== 'string' && !needCollect) {
  24563. return category;
  24564. }
  24565. // Optimize for the scenario:
  24566. // category is ['2012-01-01', '2012-01-02', ...], where the input
  24567. // data has been ensured not duplicate and is large data.
  24568. // Notice, if a dataset dimension provide categroies, usually echarts
  24569. // should remove duplication except user tell echarts dont do that
  24570. // (set axis.deduplication = false), because echarts do not know whether
  24571. // the values in the category dimension has duplication (consider the
  24572. // parallel-aqi example)
  24573. if (needCollect && !this._deduplication) {
  24574. index = this.categories.length;
  24575. this.categories[index] = category;
  24576. return index;
  24577. }
  24578. var map$$1 = getOrCreateMap(this);
  24579. index = map$$1.get(category);
  24580. if (index == null) {
  24581. if (needCollect) {
  24582. index = this.categories.length;
  24583. this.categories[index] = category;
  24584. map$$1.set(category, index);
  24585. }
  24586. else {
  24587. index = NaN;
  24588. }
  24589. }
  24590. return index;
  24591. };
  24592. // Consider big data, do not create map until needed.
  24593. function getOrCreateMap(ordinalMeta) {
  24594. return ordinalMeta._map || (
  24595. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  24596. );
  24597. }
  24598. function getName(obj) {
  24599. if (isObject$1(obj) && obj.value != null) {
  24600. return obj.value;
  24601. }
  24602. else {
  24603. return obj + '';
  24604. }
  24605. }
  24606. /**
  24607. * Linear continuous scale
  24608. * @module echarts/coord/scale/Ordinal
  24609. *
  24610. * http://en.wikipedia.org/wiki/Level_of_measurement
  24611. */
  24612. // FIXME only one data
  24613. var scaleProto = Scale.prototype;
  24614. var OrdinalScale = Scale.extend({
  24615. type: 'ordinal',
  24616. /**
  24617. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  24618. */
  24619. init: function (ordinalMeta, extent) {
  24620. // Caution: Should not use instanceof, consider ec-extensions using
  24621. // import approach to get OrdinalMeta class.
  24622. if (!ordinalMeta || isArray(ordinalMeta)) {
  24623. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  24624. }
  24625. this._ordinalMeta = ordinalMeta;
  24626. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  24627. },
  24628. parse: function (val) {
  24629. return typeof val === 'string'
  24630. ? this._ordinalMeta.getOrdinal(val)
  24631. // val might be float.
  24632. : Math.round(val);
  24633. },
  24634. contain: function (rank) {
  24635. rank = this.parse(rank);
  24636. return scaleProto.contain.call(this, rank)
  24637. && this._ordinalMeta.categories[rank] != null;
  24638. },
  24639. /**
  24640. * Normalize given rank or name to linear [0, 1]
  24641. * @param {number|string} [val]
  24642. * @return {number}
  24643. */
  24644. normalize: function (val) {
  24645. return scaleProto.normalize.call(this, this.parse(val));
  24646. },
  24647. scale: function (val) {
  24648. return Math.round(scaleProto.scale.call(this, val));
  24649. },
  24650. /**
  24651. * @return {Array}
  24652. */
  24653. getTicks: function () {
  24654. var ticks = [];
  24655. var extent = this._extent;
  24656. var rank = extent[0];
  24657. while (rank <= extent[1]) {
  24658. ticks.push(rank);
  24659. rank++;
  24660. }
  24661. return ticks;
  24662. },
  24663. /**
  24664. * Get item on rank n
  24665. * @param {number} n
  24666. * @return {string}
  24667. */
  24668. getLabel: function (n) {
  24669. return this._ordinalMeta.categories[n];
  24670. },
  24671. /**
  24672. * @return {number}
  24673. */
  24674. count: function () {
  24675. return this._extent[1] - this._extent[0] + 1;
  24676. },
  24677. /**
  24678. * @override
  24679. */
  24680. unionExtentFromData: function (data, dim) {
  24681. this.unionExtent(data.getApproximateExtent(dim, false));
  24682. },
  24683. niceTicks: noop,
  24684. niceExtent: noop
  24685. });
  24686. /**
  24687. * @return {module:echarts/scale/Time}
  24688. */
  24689. OrdinalScale.create = function () {
  24690. return new OrdinalScale();
  24691. };
  24692. /**
  24693. * For testable.
  24694. */
  24695. var roundNumber$1 = round$1;
  24696. /**
  24697. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  24698. * Should be extent[0] < extent[1].
  24699. * @param {number} splitNumber splitNumber should be >= 1.
  24700. * @param {number} [minInterval]
  24701. * @param {number} [maxInterval]
  24702. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  24703. */
  24704. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  24705. var result = {};
  24706. var span = extent[1] - extent[0];
  24707. var interval = result.interval = nice(span / splitNumber, true);
  24708. if (minInterval != null && interval < minInterval) {
  24709. interval = result.interval = minInterval;
  24710. }
  24711. if (maxInterval != null && interval > maxInterval) {
  24712. interval = result.interval = maxInterval;
  24713. }
  24714. // Tow more digital for tick.
  24715. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  24716. // Niced extent inside original extent
  24717. var niceTickExtent = result.niceTickExtent = [
  24718. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  24719. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  24720. ];
  24721. fixExtent(niceTickExtent, extent);
  24722. return result;
  24723. }
  24724. /**
  24725. * @param {number} interval
  24726. * @return {number} interval precision
  24727. */
  24728. function getIntervalPrecision(interval) {
  24729. // Tow more digital for tick.
  24730. return getPrecisionSafe(interval) + 2;
  24731. }
  24732. function clamp(niceTickExtent, idx, extent) {
  24733. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  24734. }
  24735. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  24736. function fixExtent(niceTickExtent, extent) {
  24737. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  24738. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  24739. clamp(niceTickExtent, 0, extent);
  24740. clamp(niceTickExtent, 1, extent);
  24741. if (niceTickExtent[0] > niceTickExtent[1]) {
  24742. niceTickExtent[0] = niceTickExtent[1];
  24743. }
  24744. }
  24745. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  24746. var ticks = [];
  24747. // If interval is 0, return [];
  24748. if (!interval) {
  24749. return ticks;
  24750. }
  24751. // Consider this case: using dataZoom toolbox, zoom and zoom.
  24752. var safeLimit = 10000;
  24753. if (extent[0] < niceTickExtent[0]) {
  24754. ticks.push(extent[0]);
  24755. }
  24756. var tick = niceTickExtent[0];
  24757. while (tick <= niceTickExtent[1]) {
  24758. ticks.push(tick);
  24759. // Avoid rounding error
  24760. tick = roundNumber$1(tick + interval, intervalPrecision);
  24761. if (tick === ticks[ticks.length - 1]) {
  24762. // Consider out of safe float point, e.g.,
  24763. // -3711126.9907707 + 2e-10 === -3711126.9907707
  24764. break;
  24765. }
  24766. if (ticks.length > safeLimit) {
  24767. return [];
  24768. }
  24769. }
  24770. // Consider this case: the last item of ticks is smaller
  24771. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  24772. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  24773. ticks.push(extent[1]);
  24774. }
  24775. return ticks;
  24776. }
  24777. /**
  24778. * Interval scale
  24779. * @module echarts/scale/Interval
  24780. */
  24781. var roundNumber = round$1;
  24782. /**
  24783. * @alias module:echarts/coord/scale/Interval
  24784. * @constructor
  24785. */
  24786. var IntervalScale = Scale.extend({
  24787. type: 'interval',
  24788. _interval: 0,
  24789. _intervalPrecision: 2,
  24790. setExtent: function (start, end) {
  24791. var thisExtent = this._extent;
  24792. //start,end may be a Number like '25',so...
  24793. if (!isNaN(start)) {
  24794. thisExtent[0] = parseFloat(start);
  24795. }
  24796. if (!isNaN(end)) {
  24797. thisExtent[1] = parseFloat(end);
  24798. }
  24799. },
  24800. unionExtent: function (other) {
  24801. var extent = this._extent;
  24802. other[0] < extent[0] && (extent[0] = other[0]);
  24803. other[1] > extent[1] && (extent[1] = other[1]);
  24804. // unionExtent may called by it's sub classes
  24805. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  24806. },
  24807. /**
  24808. * Get interval
  24809. */
  24810. getInterval: function () {
  24811. return this._interval;
  24812. },
  24813. /**
  24814. * Set interval
  24815. */
  24816. setInterval: function (interval) {
  24817. this._interval = interval;
  24818. // Dropped auto calculated niceExtent and use user setted extent
  24819. // We assume user wan't to set both interval, min, max to get a better result
  24820. this._niceExtent = this._extent.slice();
  24821. this._intervalPrecision = getIntervalPrecision(interval);
  24822. },
  24823. /**
  24824. * @return {Array.<number>}
  24825. */
  24826. getTicks: function () {
  24827. return intervalScaleGetTicks(
  24828. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  24829. );
  24830. },
  24831. /**
  24832. * @return {Array.<string>}
  24833. */
  24834. getTicksLabels: function () {
  24835. var labels = [];
  24836. var ticks = this.getTicks();
  24837. for (var i = 0; i < ticks.length; i++) {
  24838. labels.push(this.getLabel(ticks[i]));
  24839. }
  24840. return labels;
  24841. },
  24842. /**
  24843. * @param {number} data
  24844. * @param {Object} [opt]
  24845. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  24846. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  24847. * @return {string}
  24848. */
  24849. getLabel: function (data, opt) {
  24850. if (data == null) {
  24851. return '';
  24852. }
  24853. var precision = opt && opt.precision;
  24854. if (precision == null) {
  24855. precision = getPrecisionSafe(data) || 0;
  24856. }
  24857. else if (precision === 'auto') {
  24858. // Should be more precise then tick.
  24859. precision = this._intervalPrecision;
  24860. }
  24861. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  24862. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  24863. data = roundNumber(data, precision, true);
  24864. return addCommas(data);
  24865. },
  24866. /**
  24867. * Update interval and extent of intervals for nice ticks
  24868. *
  24869. * @param {number} [splitNumber = 5] Desired number of ticks
  24870. * @param {number} [minInterval]
  24871. * @param {number} [maxInterval]
  24872. */
  24873. niceTicks: function (splitNumber, minInterval, maxInterval) {
  24874. splitNumber = splitNumber || 5;
  24875. var extent = this._extent;
  24876. var span = extent[1] - extent[0];
  24877. if (!isFinite(span)) {
  24878. return;
  24879. }
  24880. // User may set axis min 0 and data are all negative
  24881. // FIXME If it needs to reverse ?
  24882. if (span < 0) {
  24883. span = -span;
  24884. extent.reverse();
  24885. }
  24886. var result = intervalScaleNiceTicks(
  24887. extent, splitNumber, minInterval, maxInterval
  24888. );
  24889. this._intervalPrecision = result.intervalPrecision;
  24890. this._interval = result.interval;
  24891. this._niceExtent = result.niceTickExtent;
  24892. },
  24893. /**
  24894. * Nice extent.
  24895. * @param {Object} opt
  24896. * @param {number} [opt.splitNumber = 5] Given approx tick number
  24897. * @param {boolean} [opt.fixMin=false]
  24898. * @param {boolean} [opt.fixMax=false]
  24899. * @param {boolean} [opt.minInterval]
  24900. * @param {boolean} [opt.maxInterval]
  24901. */
  24902. niceExtent: function (opt) {
  24903. var extent = this._extent;
  24904. // If extent start and end are same, expand them
  24905. if (extent[0] === extent[1]) {
  24906. if (extent[0] !== 0) {
  24907. // Expand extent
  24908. var expandSize = extent[0];
  24909. // In the fowllowing case
  24910. // Axis has been fixed max 100
  24911. // Plus data are all 100 and axis extent are [100, 100].
  24912. // Extend to the both side will cause expanded max is larger than fixed max.
  24913. // So only expand to the smaller side.
  24914. if (!opt.fixMax) {
  24915. extent[1] += expandSize / 2;
  24916. extent[0] -= expandSize / 2;
  24917. }
  24918. else {
  24919. extent[0] -= expandSize / 2;
  24920. }
  24921. }
  24922. else {
  24923. extent[1] = 1;
  24924. }
  24925. }
  24926. var span = extent[1] - extent[0];
  24927. // If there are no data and extent are [Infinity, -Infinity]
  24928. if (!isFinite(span)) {
  24929. extent[0] = 0;
  24930. extent[1] = 1;
  24931. }
  24932. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  24933. // var extent = this._extent;
  24934. var interval = this._interval;
  24935. if (!opt.fixMin) {
  24936. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  24937. }
  24938. if (!opt.fixMax) {
  24939. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  24940. }
  24941. }
  24942. });
  24943. /**
  24944. * @return {module:echarts/scale/Time}
  24945. */
  24946. IntervalScale.create = function () {
  24947. return new IntervalScale();
  24948. };
  24949. var STACK_PREFIX = '__ec_stack_';
  24950. function getSeriesStackId(seriesModel) {
  24951. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  24952. }
  24953. function getAxisKey(axis) {
  24954. return axis.dim + axis.index;
  24955. }
  24956. /**
  24957. * @param {Object} opt
  24958. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  24959. * @param {number} opt.count Positive interger.
  24960. * @param {number} [opt.barWidth]
  24961. * @param {number} [opt.barMaxWidth]
  24962. * @param {number} [opt.barGap]
  24963. * @param {number} [opt.barCategoryGap]
  24964. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  24965. */
  24966. function calBarWidthAndOffset(barSeries, api) {
  24967. var seriesInfoList = map(barSeries, function (seriesModel) {
  24968. var data = seriesModel.getData();
  24969. var cartesian = seriesModel.coordinateSystem;
  24970. var baseAxis = cartesian.getBaseAxis();
  24971. var axisExtent = baseAxis.getExtent();
  24972. var bandWidth = baseAxis.type === 'category'
  24973. ? baseAxis.getBandWidth()
  24974. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  24975. var barWidth = parsePercent$1(
  24976. seriesModel.get('barWidth'), bandWidth
  24977. );
  24978. var barMaxWidth = parsePercent$1(
  24979. seriesModel.get('barMaxWidth'), bandWidth
  24980. );
  24981. var barGap = seriesModel.get('barGap');
  24982. var barCategoryGap = seriesModel.get('barCategoryGap');
  24983. return {
  24984. bandWidth: bandWidth,
  24985. barWidth: barWidth,
  24986. barMaxWidth: barMaxWidth,
  24987. barGap: barGap,
  24988. barCategoryGap: barCategoryGap,
  24989. axisKey: getAxisKey(baseAxis),
  24990. stackId: getSeriesStackId(seriesModel)
  24991. };
  24992. });
  24993. return doCalBarWidthAndOffset(seriesInfoList, api);
  24994. }
  24995. function doCalBarWidthAndOffset(seriesInfoList, api) {
  24996. // Columns info on each category axis. Key is cartesian name
  24997. var columnsMap = {};
  24998. each$1(seriesInfoList, function (seriesInfo, idx) {
  24999. var axisKey = seriesInfo.axisKey;
  25000. var bandWidth = seriesInfo.bandWidth;
  25001. var columnsOnAxis = columnsMap[axisKey] || {
  25002. bandWidth: bandWidth,
  25003. remainedWidth: bandWidth,
  25004. autoWidthCount: 0,
  25005. categoryGap: '20%',
  25006. gap: '30%',
  25007. stacks: {}
  25008. };
  25009. var stacks = columnsOnAxis.stacks;
  25010. columnsMap[axisKey] = columnsOnAxis;
  25011. var stackId = seriesInfo.stackId;
  25012. if (!stacks[stackId]) {
  25013. columnsOnAxis.autoWidthCount++;
  25014. }
  25015. stacks[stackId] = stacks[stackId] || {
  25016. width: 0,
  25017. maxWidth: 0
  25018. };
  25019. // Caution: In a single coordinate system, these barGrid attributes
  25020. // will be shared by series. Consider that they have default values,
  25021. // only the attributes set on the last series will work.
  25022. // Do not change this fact unless there will be a break change.
  25023. // TODO
  25024. var barWidth = seriesInfo.barWidth;
  25025. if (barWidth && !stacks[stackId].width) {
  25026. // See #6312, do not restrict width.
  25027. stacks[stackId].width = barWidth;
  25028. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25029. columnsOnAxis.remainedWidth -= barWidth;
  25030. }
  25031. var barMaxWidth = seriesInfo.barMaxWidth;
  25032. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25033. var barGap = seriesInfo.barGap;
  25034. (barGap != null) && (columnsOnAxis.gap = barGap);
  25035. var barCategoryGap = seriesInfo.barCategoryGap;
  25036. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25037. });
  25038. var result = {};
  25039. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25040. result[coordSysName] = {};
  25041. var stacks = columnsOnAxis.stacks;
  25042. var bandWidth = columnsOnAxis.bandWidth;
  25043. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25044. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25045. var remainedWidth = columnsOnAxis.remainedWidth;
  25046. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25047. var autoWidth = (remainedWidth - categoryGap)
  25048. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25049. autoWidth = Math.max(autoWidth, 0);
  25050. // Find if any auto calculated bar exceeded maxBarWidth
  25051. each$1(stacks, function (column, stack) {
  25052. var maxWidth = column.maxWidth;
  25053. if (maxWidth && maxWidth < autoWidth) {
  25054. maxWidth = Math.min(maxWidth, remainedWidth);
  25055. if (column.width) {
  25056. maxWidth = Math.min(maxWidth, column.width);
  25057. }
  25058. remainedWidth -= maxWidth;
  25059. column.width = maxWidth;
  25060. autoWidthCount--;
  25061. }
  25062. });
  25063. // Recalculate width again
  25064. autoWidth = (remainedWidth - categoryGap)
  25065. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25066. autoWidth = Math.max(autoWidth, 0);
  25067. var widthSum = 0;
  25068. var lastColumn;
  25069. each$1(stacks, function (column, idx) {
  25070. if (!column.width) {
  25071. column.width = autoWidth;
  25072. }
  25073. lastColumn = column;
  25074. widthSum += column.width * (1 + barGapPercent);
  25075. });
  25076. if (lastColumn) {
  25077. widthSum -= lastColumn.width * barGapPercent;
  25078. }
  25079. var offset = -widthSum / 2;
  25080. each$1(stacks, function (column, stackId) {
  25081. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25082. offset: offset,
  25083. width: column.width
  25084. };
  25085. offset += column.width * (1 + barGapPercent);
  25086. });
  25087. });
  25088. return result;
  25089. }
  25090. /**
  25091. * @param {string} seriesType
  25092. * @param {module:echarts/model/Global} ecModel
  25093. * @param {module:echarts/ExtensionAPI} api
  25094. */
  25095. function layout(seriesType, ecModel, api) {
  25096. var barWidthAndOffset = calBarWidthAndOffset(
  25097. filter(
  25098. ecModel.getSeriesByType(seriesType),
  25099. function (seriesModel) {
  25100. return !ecModel.isSeriesFiltered(seriesModel)
  25101. && seriesModel.coordinateSystem
  25102. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25103. }
  25104. )
  25105. );
  25106. var lastStackCoords = {};
  25107. var lastStackCoordsOrigin = {};
  25108. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25109. // Check series coordinate, do layout for cartesian2d only
  25110. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  25111. return;
  25112. }
  25113. var data = seriesModel.getData();
  25114. var cartesian = seriesModel.coordinateSystem;
  25115. var baseAxis = cartesian.getBaseAxis();
  25116. var stackId = getSeriesStackId(seriesModel);
  25117. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25118. var columnOffset = columnLayoutInfo.offset;
  25119. var columnWidth = columnLayoutInfo.width;
  25120. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25121. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25122. var valueAxisStart = baseAxis.onZero
  25123. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25124. : valueAxis.getGlobalExtent()[0];
  25125. var coordDims = [
  25126. data.mapDimension('x'),
  25127. data.mapDimension('y')
  25128. ];
  25129. var coords = data.mapArray(coordDims, function (x, y) {
  25130. return cartesian.dataToPoint([x, y]);
  25131. }, true);
  25132. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25133. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  25134. data.setLayout({
  25135. offset: columnOffset,
  25136. size: columnWidth
  25137. });
  25138. data.each(data.mapDimension(valueAxis.dim), function (value, idx) {
  25139. if (isNaN(value)) {
  25140. return;
  25141. }
  25142. if (!lastStackCoords[stackId][idx]) {
  25143. lastStackCoords[stackId][idx] = {
  25144. p: valueAxisStart, // Positive stack
  25145. n: valueAxisStart // Negative stack
  25146. };
  25147. lastStackCoordsOrigin[stackId][idx] = {
  25148. p: valueAxisStart, // Positive stack
  25149. n: valueAxisStart // Negative stack
  25150. };
  25151. }
  25152. var sign = value >= 0 ? 'p' : 'n';
  25153. var coord = coords[idx];
  25154. var lastCoord = lastStackCoords[stackId][idx][sign];
  25155. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  25156. var x;
  25157. var y;
  25158. var width;
  25159. var height;
  25160. if (valueAxis.isHorizontal()) {
  25161. x = lastCoord;
  25162. y = coord[1] + columnOffset;
  25163. width = coord[0] - lastCoordOrigin;
  25164. height = columnWidth;
  25165. lastStackCoordsOrigin[stackId][idx][sign] += width;
  25166. if (Math.abs(width) < barMinHeight) {
  25167. width = (width < 0 ? -1 : 1) * barMinHeight;
  25168. }
  25169. lastStackCoords[stackId][idx][sign] += width;
  25170. }
  25171. else {
  25172. x = coord[0] + columnOffset;
  25173. y = lastCoord;
  25174. width = columnWidth;
  25175. height = coord[1] - lastCoordOrigin;
  25176. lastStackCoordsOrigin[stackId][idx][sign] += height;
  25177. if (Math.abs(height) < barMinHeight) {
  25178. // Include zero to has a positive bar
  25179. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25180. }
  25181. lastStackCoords[stackId][idx][sign] += height;
  25182. }
  25183. data.setItemLayout(idx, {
  25184. x: x,
  25185. y: y,
  25186. width: width,
  25187. height: height
  25188. });
  25189. }, true);
  25190. }, this);
  25191. }
  25192. // [About UTC and local time zone]:
  25193. // In most cases, `number.parseDate` will treat input data string as local time
  25194. // (except time zone is specified in time string). And `format.formateTime` returns
  25195. // local time by default. option.useUTC is false by default. This design have
  25196. // concidered these common case:
  25197. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25198. // in local time by default.
  25199. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25200. // as its original time, without any time difference.
  25201. var intervalScaleProto = IntervalScale.prototype;
  25202. var mathCeil = Math.ceil;
  25203. var mathFloor = Math.floor;
  25204. var ONE_SECOND = 1000;
  25205. var ONE_MINUTE = ONE_SECOND * 60;
  25206. var ONE_HOUR = ONE_MINUTE * 60;
  25207. var ONE_DAY = ONE_HOUR * 24;
  25208. // FIXME 公用?
  25209. var bisect = function (a, x, lo, hi) {
  25210. while (lo < hi) {
  25211. var mid = lo + hi >>> 1;
  25212. if (a[mid][1] < x) {
  25213. lo = mid + 1;
  25214. }
  25215. else {
  25216. hi = mid;
  25217. }
  25218. }
  25219. return lo;
  25220. };
  25221. /**
  25222. * @alias module:echarts/coord/scale/Time
  25223. * @constructor
  25224. */
  25225. var TimeScale = IntervalScale.extend({
  25226. type: 'time',
  25227. /**
  25228. * @override
  25229. */
  25230. getLabel: function (val) {
  25231. var stepLvl = this._stepLvl;
  25232. var date = new Date(val);
  25233. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25234. },
  25235. /**
  25236. * @override
  25237. */
  25238. niceExtent: function (opt) {
  25239. var extent = this._extent;
  25240. // If extent start and end are same, expand them
  25241. if (extent[0] === extent[1]) {
  25242. // Expand extent
  25243. extent[0] -= ONE_DAY;
  25244. extent[1] += ONE_DAY;
  25245. }
  25246. // If there are no data and extent are [Infinity, -Infinity]
  25247. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25248. var d = new Date();
  25249. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25250. extent[0] = extent[1] - ONE_DAY;
  25251. }
  25252. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25253. // var extent = this._extent;
  25254. var interval = this._interval;
  25255. if (!opt.fixMin) {
  25256. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25257. }
  25258. if (!opt.fixMax) {
  25259. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25260. }
  25261. },
  25262. /**
  25263. * @override
  25264. */
  25265. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25266. approxTickNum = approxTickNum || 10;
  25267. var extent = this._extent;
  25268. var span = extent[1] - extent[0];
  25269. var approxInterval = span / approxTickNum;
  25270. if (minInterval != null && approxInterval < minInterval) {
  25271. approxInterval = minInterval;
  25272. }
  25273. if (maxInterval != null && approxInterval > maxInterval) {
  25274. approxInterval = maxInterval;
  25275. }
  25276. var scaleLevelsLen = scaleLevels.length;
  25277. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25278. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25279. var interval = level[1];
  25280. // Same with interval scale if span is much larger than 1 year
  25281. if (level[0] === 'year') {
  25282. var yearSpan = span / interval;
  25283. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25284. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25285. var yearStep = nice(yearSpan / approxTickNum, true);
  25286. interval *= yearStep;
  25287. }
  25288. var timezoneOffset = this.getSetting('useUTC')
  25289. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25290. var niceExtent = [
  25291. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25292. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25293. ];
  25294. fixExtent(niceExtent, extent);
  25295. this._stepLvl = level;
  25296. // Interval will be used in getTicks
  25297. this._interval = interval;
  25298. this._niceExtent = niceExtent;
  25299. },
  25300. parse: function (val) {
  25301. // val might be float.
  25302. return +parseDate(val);
  25303. }
  25304. });
  25305. each$1(['contain', 'normalize'], function (methodName) {
  25306. TimeScale.prototype[methodName] = function (val) {
  25307. return intervalScaleProto[methodName].call(this, this.parse(val));
  25308. };
  25309. });
  25310. // Steps from d3
  25311. var scaleLevels = [
  25312. // Format interval
  25313. ['hh:mm:ss', ONE_SECOND], // 1s
  25314. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25315. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25316. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25317. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25318. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25319. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25320. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25321. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25322. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25323. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25324. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25325. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25326. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25327. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25328. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25329. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25330. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25331. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25332. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25333. ['week', ONE_DAY * 7], // 7d
  25334. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25335. ['week', ONE_DAY * 14], // 2w
  25336. ['week', ONE_DAY * 21], // 3w
  25337. ['month', ONE_DAY * 31], // 1M
  25338. ['week', ONE_DAY * 42], // 6w
  25339. ['month', ONE_DAY * 62], // 2M
  25340. ['week', ONE_DAY * 42], // 10w
  25341. ['quarter', ONE_DAY * 380 / 4], // 3M
  25342. ['month', ONE_DAY * 31 * 4], // 4M
  25343. ['month', ONE_DAY * 31 * 5], // 5M
  25344. ['half-year', ONE_DAY * 380 / 2], // 6M
  25345. ['month', ONE_DAY * 31 * 8], // 8M
  25346. ['month', ONE_DAY * 31 * 10], // 10M
  25347. ['year', ONE_DAY * 380] // 1Y
  25348. ];
  25349. /**
  25350. * @param {module:echarts/model/Model}
  25351. * @return {module:echarts/scale/Time}
  25352. */
  25353. TimeScale.create = function (model) {
  25354. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25355. };
  25356. /**
  25357. * Log scale
  25358. * @module echarts/scale/Log
  25359. */
  25360. // Use some method of IntervalScale
  25361. var scaleProto$1 = Scale.prototype;
  25362. var intervalScaleProto$1 = IntervalScale.prototype;
  25363. var getPrecisionSafe$1 = getPrecisionSafe;
  25364. var roundingErrorFix = round$1;
  25365. var mathFloor$1 = Math.floor;
  25366. var mathCeil$1 = Math.ceil;
  25367. var mathPow$1 = Math.pow;
  25368. var mathLog = Math.log;
  25369. var LogScale = Scale.extend({
  25370. type: 'log',
  25371. base: 10,
  25372. $constructor: function () {
  25373. Scale.apply(this, arguments);
  25374. this._originalScale = new IntervalScale();
  25375. },
  25376. /**
  25377. * @return {Array.<number>}
  25378. */
  25379. getTicks: function () {
  25380. var originalScale = this._originalScale;
  25381. var extent = this._extent;
  25382. var originalExtent = originalScale.getExtent();
  25383. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25384. var powVal = round$1(mathPow$1(this.base, val));
  25385. // Fix #4158
  25386. powVal = (val === extent[0] && originalScale.__fixMin)
  25387. ? fixRoundingError(powVal, originalExtent[0])
  25388. : powVal;
  25389. powVal = (val === extent[1] && originalScale.__fixMax)
  25390. ? fixRoundingError(powVal, originalExtent[1])
  25391. : powVal;
  25392. return powVal;
  25393. }, this);
  25394. },
  25395. /**
  25396. * @param {number} val
  25397. * @return {string}
  25398. */
  25399. getLabel: intervalScaleProto$1.getLabel,
  25400. /**
  25401. * @param {number} val
  25402. * @return {number}
  25403. */
  25404. scale: function (val) {
  25405. val = scaleProto$1.scale.call(this, val);
  25406. return mathPow$1(this.base, val);
  25407. },
  25408. /**
  25409. * @param {number} start
  25410. * @param {number} end
  25411. */
  25412. setExtent: function (start, end) {
  25413. var base = this.base;
  25414. start = mathLog(start) / mathLog(base);
  25415. end = mathLog(end) / mathLog(base);
  25416. intervalScaleProto$1.setExtent.call(this, start, end);
  25417. },
  25418. /**
  25419. * @return {number} end
  25420. */
  25421. getExtent: function () {
  25422. var base = this.base;
  25423. var extent = scaleProto$1.getExtent.call(this);
  25424. extent[0] = mathPow$1(base, extent[0]);
  25425. extent[1] = mathPow$1(base, extent[1]);
  25426. // Fix #4158
  25427. var originalScale = this._originalScale;
  25428. var originalExtent = originalScale.getExtent();
  25429. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25430. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25431. return extent;
  25432. },
  25433. /**
  25434. * @param {Array.<number>} extent
  25435. */
  25436. unionExtent: function (extent) {
  25437. this._originalScale.unionExtent(extent);
  25438. var base = this.base;
  25439. extent[0] = mathLog(extent[0]) / mathLog(base);
  25440. extent[1] = mathLog(extent[1]) / mathLog(base);
  25441. scaleProto$1.unionExtent.call(this, extent);
  25442. },
  25443. /**
  25444. * @override
  25445. */
  25446. unionExtentFromData: function (data, dim) {
  25447. this.unionExtent(data.getApproximateExtent(dim, true, function (val) {
  25448. return val > 0;
  25449. }));
  25450. },
  25451. /**
  25452. * Update interval and extent of intervals for nice ticks
  25453. * @param {number} [approxTickNum = 10] Given approx tick number
  25454. */
  25455. niceTicks: function (approxTickNum) {
  25456. approxTickNum = approxTickNum || 10;
  25457. var extent = this._extent;
  25458. var span = extent[1] - extent[0];
  25459. if (span === Infinity || span <= 0) {
  25460. return;
  25461. }
  25462. var interval = quantity(span);
  25463. var err = approxTickNum / span * interval;
  25464. // Filter ticks to get closer to the desired count.
  25465. if (err <= 0.5) {
  25466. interval *= 10;
  25467. }
  25468. // Interval should be integer
  25469. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  25470. interval *= 10;
  25471. }
  25472. var niceExtent = [
  25473. round$1(mathCeil$1(extent[0] / interval) * interval),
  25474. round$1(mathFloor$1(extent[1] / interval) * interval)
  25475. ];
  25476. this._interval = interval;
  25477. this._niceExtent = niceExtent;
  25478. },
  25479. /**
  25480. * Nice extent.
  25481. * @override
  25482. */
  25483. niceExtent: function (opt) {
  25484. intervalScaleProto$1.niceExtent.call(this, opt);
  25485. var originalScale = this._originalScale;
  25486. originalScale.__fixMin = opt.fixMin;
  25487. originalScale.__fixMax = opt.fixMax;
  25488. }
  25489. });
  25490. each$1(['contain', 'normalize'], function (methodName) {
  25491. LogScale.prototype[methodName] = function (val) {
  25492. val = mathLog(val) / mathLog(this.base);
  25493. return scaleProto$1[methodName].call(this, val);
  25494. };
  25495. });
  25496. LogScale.create = function () {
  25497. return new LogScale();
  25498. };
  25499. function fixRoundingError(val, originalVal) {
  25500. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  25501. }
  25502. /**
  25503. * Get axis scale extent before niced.
  25504. * Item of returned array can only be number (including Infinity and NaN).
  25505. */
  25506. function getScaleExtent(scale, model) {
  25507. var scaleType = scale.type;
  25508. var min = model.getMin();
  25509. var max = model.getMax();
  25510. var fixMin = min != null;
  25511. var fixMax = max != null;
  25512. var originalExtent = scale.getExtent();
  25513. var axisDataLen;
  25514. var boundaryGap;
  25515. var span;
  25516. if (scaleType === 'ordinal') {
  25517. axisDataLen = model.getCategories().length;
  25518. }
  25519. else {
  25520. boundaryGap = model.get('boundaryGap');
  25521. if (!isArray(boundaryGap)) {
  25522. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  25523. }
  25524. if (typeof boundaryGap[0] === 'boolean') {
  25525. if (__DEV__) {
  25526. console.warn('Boolean type for boundaryGap is only '
  25527. + 'allowed for ordinal axis. Please use string in '
  25528. + 'percentage instead, e.g., "20%". Currently, '
  25529. + 'boundaryGap is set to be 0.');
  25530. }
  25531. boundaryGap = [0, 0];
  25532. }
  25533. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  25534. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  25535. span = (originalExtent[1] - originalExtent[0])
  25536. || Math.abs(originalExtent[0]);
  25537. }
  25538. // Notice: When min/max is not set (that is, when there are null/undefined,
  25539. // which is the most common case), these cases should be ensured:
  25540. // (1) For 'ordinal', show all axis.data.
  25541. // (2) For others:
  25542. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  25543. // disabled).
  25544. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  25545. // be the result that originalExtent enlarged by boundaryGap.
  25546. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  25547. // FIXME
  25548. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  25549. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  25550. // that the results processed by boundaryGap are positive/negative?
  25551. if (min == null) {
  25552. min = scaleType === 'ordinal'
  25553. ? (axisDataLen ? 0 : NaN)
  25554. : originalExtent[0] - boundaryGap[0] * span;
  25555. }
  25556. if (max == null) {
  25557. max = scaleType === 'ordinal'
  25558. ? (axisDataLen ? axisDataLen - 1 : NaN)
  25559. : originalExtent[1] + boundaryGap[1] * span;
  25560. }
  25561. if (min === 'dataMin') {
  25562. min = originalExtent[0];
  25563. }
  25564. else if (typeof min === 'function') {
  25565. min = min({
  25566. min: originalExtent[0],
  25567. max: originalExtent[1]
  25568. });
  25569. }
  25570. if (max === 'dataMax') {
  25571. max = originalExtent[1];
  25572. }
  25573. else if (typeof max === 'function') {
  25574. max = max({
  25575. min: originalExtent[0],
  25576. max: originalExtent[1]
  25577. });
  25578. }
  25579. (min == null || !isFinite(min)) && (min = NaN);
  25580. (max == null || !isFinite(max)) && (max = NaN);
  25581. scale.setBlank(eqNaN(min) || eqNaN(max));
  25582. // Evaluate if axis needs cross zero
  25583. if (model.getNeedCrossZero()) {
  25584. // Axis is over zero and min is not set
  25585. if (min > 0 && max > 0 && !fixMin) {
  25586. min = 0;
  25587. }
  25588. // Axis is under zero and max is not set
  25589. if (min < 0 && max < 0 && !fixMax) {
  25590. max = 0;
  25591. }
  25592. }
  25593. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  25594. // is base axis
  25595. var ecModel = model.ecModel;
  25596. if (ecModel) {
  25597. var isBaseAxisAndHasBarSeries = filter(ecModel.getSeriesByType('bar'), function (seriesModel) {
  25598. return seriesModel.getBaseAxis() === model.axis;
  25599. }).length > 0;
  25600. if ((scaleType === 'time' || scaleType === 'interval') && isBaseAxisAndHasBarSeries) {
  25601. // Adjust axis min and max to account for overflow
  25602. var adjustedScale = adjustScaleForOverflow(min, max, model);
  25603. min = adjustedScale.min;
  25604. max = adjustedScale.max;
  25605. }
  25606. }
  25607. return [min, max];
  25608. }
  25609. function adjustScaleForOverflow(min, max, model) {
  25610. var ecModel = model.ecModel;
  25611. // Get Axis Length
  25612. var axisExtent = model.axis.getExtent();
  25613. var axisLength = axisExtent[1] - axisExtent[0];
  25614. // Calculate placement of bars on axis
  25615. var barWidthAndOffset = calBarWidthAndOffset(filter(
  25616. ecModel.getSeriesByType('bar'),
  25617. function (seriesModel) {
  25618. return !ecModel.isSeriesFiltered(seriesModel)
  25619. && seriesModel.coordinateSystem
  25620. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25621. }
  25622. ));
  25623. // Get bars on current base axis and calculate min and max overflow
  25624. var baseAxisKey = model.axis.dim + model.axis.index;
  25625. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  25626. if (barsOnCurrentAxis === undefined) {
  25627. return {min: min, max: max};
  25628. }
  25629. var minOverflow = Infinity;
  25630. each$1(barsOnCurrentAxis, function (item) {
  25631. minOverflow = Math.min(item.offset, minOverflow);
  25632. });
  25633. var maxOverflow = -Infinity;
  25634. each$1(barsOnCurrentAxis, function (item) {
  25635. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  25636. });
  25637. var totalOverFlow = Math.abs(minOverflow) + maxOverflow;
  25638. // Calulate required buffer based on old range and overflow
  25639. var oldRange = max - min;
  25640. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  25641. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  25642. max += overflowBuffer * (maxOverflow / totalOverFlow);
  25643. min -= overflowBuffer * (minOverflow / totalOverFlow);
  25644. return {min: min, max: max};
  25645. }
  25646. function niceScaleExtent(scale, model) {
  25647. var extent = getScaleExtent(scale, model);
  25648. var fixMin = model.getMin() != null;
  25649. var fixMax = model.getMax() != null;
  25650. var splitNumber = model.get('splitNumber');
  25651. if (scale.type === 'log') {
  25652. scale.base = model.get('logBase');
  25653. }
  25654. var scaleType = scale.type;
  25655. scale.setExtent(extent[0], extent[1]);
  25656. scale.niceExtent({
  25657. splitNumber: splitNumber,
  25658. fixMin: fixMin,
  25659. fixMax: fixMax,
  25660. minInterval: (scaleType === 'interval' || scaleType === 'time')
  25661. ? model.get('minInterval') : null,
  25662. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  25663. ? model.get('maxInterval') : null
  25664. });
  25665. // If some one specified the min, max. And the default calculated interval
  25666. // is not good enough. He can specify the interval. It is often appeared
  25667. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  25668. // to be 60.
  25669. // FIXME
  25670. var interval = model.get('interval');
  25671. if (interval != null) {
  25672. scale.setInterval && scale.setInterval(interval);
  25673. }
  25674. }
  25675. /**
  25676. * @param {module:echarts/model/Model} model
  25677. * @param {string} [axisType] Default retrieve from model.type
  25678. * @return {module:echarts/scale/*}
  25679. */
  25680. function createScaleByModel(model, axisType) {
  25681. axisType = axisType || model.get('type');
  25682. if (axisType) {
  25683. switch (axisType) {
  25684. // Buildin scale
  25685. case 'category':
  25686. return new OrdinalScale(
  25687. model.getOrdinalMeta
  25688. ? model.getOrdinalMeta()
  25689. : model.getCategories(),
  25690. [Infinity, -Infinity]
  25691. );
  25692. case 'value':
  25693. return new IntervalScale();
  25694. // Extended scale, like time and log
  25695. default:
  25696. return (Scale.getClass(axisType) || IntervalScale).create(model);
  25697. }
  25698. }
  25699. }
  25700. /**
  25701. * Check if the axis corss 0
  25702. */
  25703. function ifAxisCrossZero(axis) {
  25704. var dataExtent = axis.scale.getExtent();
  25705. var min = dataExtent[0];
  25706. var max = dataExtent[1];
  25707. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  25708. }
  25709. /**
  25710. * @param {Array.<number>} tickCoords In axis self coordinate.
  25711. * @param {Array.<string>} labels
  25712. * @param {string} font
  25713. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  25714. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  25715. * @return {number}
  25716. */
  25717. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  25718. var textSpaceTakenRect;
  25719. var autoLabelInterval = 0;
  25720. var accumulatedLabelInterval = 0;
  25721. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  25722. var step = 1;
  25723. if (labels.length > 40) {
  25724. // Simple optimization for large amount of labels
  25725. step = Math.floor(labels.length / 40);
  25726. }
  25727. for (var i = 0; i < tickCoords.length; i += step) {
  25728. var tickCoord = tickCoords[i];
  25729. // Not precise, do not consider align and vertical align
  25730. // and each distance from axis line yet.
  25731. var rect = getBoundingRect(
  25732. labels[i], font, 'center', 'top'
  25733. );
  25734. rect.x += tickCoord * Math.cos(rotation);
  25735. rect.y += tickCoord * Math.sin(rotation);
  25736. // Magic number
  25737. rect.width *= 1.3;
  25738. rect.height *= 1.3;
  25739. if (!textSpaceTakenRect) {
  25740. textSpaceTakenRect = rect.clone();
  25741. }
  25742. // There is no space for current label;
  25743. else if (textSpaceTakenRect.intersect(rect)) {
  25744. accumulatedLabelInterval++;
  25745. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  25746. }
  25747. else {
  25748. textSpaceTakenRect.union(rect);
  25749. // Reset
  25750. accumulatedLabelInterval = 0;
  25751. }
  25752. }
  25753. if (autoLabelInterval === 0 && step > 1) {
  25754. return step;
  25755. }
  25756. return (autoLabelInterval + 1) * step - 1;
  25757. }
  25758. /**
  25759. * @param {Object} axis
  25760. * @param {Function} labelFormatter
  25761. * @return {Array.<string>}
  25762. */
  25763. function getFormattedLabels(axis, labelFormatter) {
  25764. var scale = axis.scale;
  25765. var labels = scale.getTicksLabels();
  25766. var ticks = scale.getTicks();
  25767. if (typeof labelFormatter === 'string') {
  25768. labelFormatter = (function (tpl) {
  25769. return function (val) {
  25770. return tpl.replace('{value}', val != null ? val : '');
  25771. };
  25772. })(labelFormatter);
  25773. // Consider empty array
  25774. return map(labels, labelFormatter);
  25775. }
  25776. else if (typeof labelFormatter === 'function') {
  25777. return map(ticks, function (tick, idx) {
  25778. return labelFormatter(
  25779. getAxisRawValue(axis, tick),
  25780. idx
  25781. );
  25782. }, this);
  25783. }
  25784. else {
  25785. return labels;
  25786. }
  25787. }
  25788. function getAxisRawValue(axis, value) {
  25789. // In category axis with data zoom, tick is not the original
  25790. // index of axis.data. So tick should not be exposed to user
  25791. // in category axis.
  25792. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  25793. }
  25794. var axisModelCommonMixin = {
  25795. /**
  25796. * Format labels
  25797. * @return {Array.<string>}
  25798. */
  25799. getFormattedLabels: function () {
  25800. return getFormattedLabels(
  25801. this.axis,
  25802. this.get('axisLabel.formatter')
  25803. );
  25804. },
  25805. /**
  25806. * @param {boolean} origin
  25807. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  25808. */
  25809. getMin: function (origin) {
  25810. var option = this.option;
  25811. var min = (!origin && option.rangeStart != null)
  25812. ? option.rangeStart : option.min;
  25813. if (this.axis
  25814. && min != null
  25815. && min !== 'dataMin'
  25816. && typeof min !== 'function'
  25817. && !eqNaN(min)
  25818. ) {
  25819. min = this.axis.scale.parse(min);
  25820. }
  25821. return min;
  25822. },
  25823. /**
  25824. * @param {boolean} origin
  25825. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  25826. */
  25827. getMax: function (origin) {
  25828. var option = this.option;
  25829. var max = (!origin && option.rangeEnd != null)
  25830. ? option.rangeEnd : option.max;
  25831. if (this.axis
  25832. && max != null
  25833. && max !== 'dataMax'
  25834. && typeof max !== 'function'
  25835. && !eqNaN(max)
  25836. ) {
  25837. max = this.axis.scale.parse(max);
  25838. }
  25839. return max;
  25840. },
  25841. /**
  25842. * @return {boolean}
  25843. */
  25844. getNeedCrossZero: function () {
  25845. var option = this.option;
  25846. return (option.rangeStart != null || option.rangeEnd != null)
  25847. ? false : !option.scale;
  25848. },
  25849. /**
  25850. * Should be implemented by each axis model if necessary.
  25851. * @return {module:echarts/model/Component} coordinate system model
  25852. */
  25853. getCoordSysModel: noop,
  25854. /**
  25855. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  25856. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  25857. */
  25858. setRange: function (rangeStart, rangeEnd) {
  25859. this.option.rangeStart = rangeStart;
  25860. this.option.rangeEnd = rangeEnd;
  25861. },
  25862. /**
  25863. * Reset range
  25864. */
  25865. resetRange: function () {
  25866. // rangeStart and rangeEnd is readonly.
  25867. this.option.rangeStart = this.option.rangeEnd = null;
  25868. }
  25869. };
  25870. // Symbol factory
  25871. /**
  25872. * Triangle shape
  25873. * @inner
  25874. */
  25875. var Triangle = extendShape({
  25876. type: 'triangle',
  25877. shape: {
  25878. cx: 0,
  25879. cy: 0,
  25880. width: 0,
  25881. height: 0
  25882. },
  25883. buildPath: function (path, shape) {
  25884. var cx = shape.cx;
  25885. var cy = shape.cy;
  25886. var width = shape.width / 2;
  25887. var height = shape.height / 2;
  25888. path.moveTo(cx, cy - height);
  25889. path.lineTo(cx + width, cy + height);
  25890. path.lineTo(cx - width, cy + height);
  25891. path.closePath();
  25892. }
  25893. });
  25894. /**
  25895. * Diamond shape
  25896. * @inner
  25897. */
  25898. var Diamond = extendShape({
  25899. type: 'diamond',
  25900. shape: {
  25901. cx: 0,
  25902. cy: 0,
  25903. width: 0,
  25904. height: 0
  25905. },
  25906. buildPath: function (path, shape) {
  25907. var cx = shape.cx;
  25908. var cy = shape.cy;
  25909. var width = shape.width / 2;
  25910. var height = shape.height / 2;
  25911. path.moveTo(cx, cy - height);
  25912. path.lineTo(cx + width, cy);
  25913. path.lineTo(cx, cy + height);
  25914. path.lineTo(cx - width, cy);
  25915. path.closePath();
  25916. }
  25917. });
  25918. /**
  25919. * Pin shape
  25920. * @inner
  25921. */
  25922. var Pin = extendShape({
  25923. type: 'pin',
  25924. shape: {
  25925. // x, y on the cusp
  25926. x: 0,
  25927. y: 0,
  25928. width: 0,
  25929. height: 0
  25930. },
  25931. buildPath: function (path, shape) {
  25932. var x = shape.x;
  25933. var y = shape.y;
  25934. var w = shape.width / 5 * 3;
  25935. // Height must be larger than width
  25936. var h = Math.max(w, shape.height);
  25937. var r = w / 2;
  25938. // Dist on y with tangent point and circle center
  25939. var dy = r * r / (h - r);
  25940. var cy = y - h + r + dy;
  25941. var angle = Math.asin(dy / r);
  25942. // Dist on x with tangent point and circle center
  25943. var dx = Math.cos(angle) * r;
  25944. var tanX = Math.sin(angle);
  25945. var tanY = Math.cos(angle);
  25946. var cpLen = r * 0.6;
  25947. var cpLen2 = r * 0.7;
  25948. path.moveTo(x - dx, cy + dy);
  25949. path.arc(
  25950. x, cy, r,
  25951. Math.PI - angle,
  25952. Math.PI * 2 + angle
  25953. );
  25954. path.bezierCurveTo(
  25955. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  25956. x, y - cpLen2,
  25957. x, y
  25958. );
  25959. path.bezierCurveTo(
  25960. x, y - cpLen2,
  25961. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  25962. x - dx, cy + dy
  25963. );
  25964. path.closePath();
  25965. }
  25966. });
  25967. /**
  25968. * Arrow shape
  25969. * @inner
  25970. */
  25971. var Arrow = extendShape({
  25972. type: 'arrow',
  25973. shape: {
  25974. x: 0,
  25975. y: 0,
  25976. width: 0,
  25977. height: 0
  25978. },
  25979. buildPath: function (ctx, shape) {
  25980. var height = shape.height;
  25981. var width = shape.width;
  25982. var x = shape.x;
  25983. var y = shape.y;
  25984. var dx = width / 3 * 2;
  25985. ctx.moveTo(x, y);
  25986. ctx.lineTo(x + dx, y + height);
  25987. ctx.lineTo(x, y + height / 4 * 3);
  25988. ctx.lineTo(x - dx, y + height);
  25989. ctx.lineTo(x, y);
  25990. ctx.closePath();
  25991. }
  25992. });
  25993. /**
  25994. * Map of path contructors
  25995. * @type {Object.<string, module:zrender/graphic/Path>}
  25996. */
  25997. var symbolCtors = {
  25998. line: Line,
  25999. rect: Rect,
  26000. roundRect: Rect,
  26001. square: Rect,
  26002. circle: Circle,
  26003. diamond: Diamond,
  26004. pin: Pin,
  26005. arrow: Arrow,
  26006. triangle: Triangle
  26007. };
  26008. var symbolShapeMakers = {
  26009. line: function (x, y, w, h, shape) {
  26010. // FIXME
  26011. shape.x1 = x;
  26012. shape.y1 = y + h / 2;
  26013. shape.x2 = x + w;
  26014. shape.y2 = y + h / 2;
  26015. },
  26016. rect: function (x, y, w, h, shape) {
  26017. shape.x = x;
  26018. shape.y = y;
  26019. shape.width = w;
  26020. shape.height = h;
  26021. },
  26022. roundRect: function (x, y, w, h, shape) {
  26023. shape.x = x;
  26024. shape.y = y;
  26025. shape.width = w;
  26026. shape.height = h;
  26027. shape.r = Math.min(w, h) / 4;
  26028. },
  26029. square: function (x, y, w, h, shape) {
  26030. var size = Math.min(w, h);
  26031. shape.x = x;
  26032. shape.y = y;
  26033. shape.width = size;
  26034. shape.height = size;
  26035. },
  26036. circle: function (x, y, w, h, shape) {
  26037. // Put circle in the center of square
  26038. shape.cx = x + w / 2;
  26039. shape.cy = y + h / 2;
  26040. shape.r = Math.min(w, h) / 2;
  26041. },
  26042. diamond: function (x, y, w, h, shape) {
  26043. shape.cx = x + w / 2;
  26044. shape.cy = y + h / 2;
  26045. shape.width = w;
  26046. shape.height = h;
  26047. },
  26048. pin: function (x, y, w, h, shape) {
  26049. shape.x = x + w / 2;
  26050. shape.y = y + h / 2;
  26051. shape.width = w;
  26052. shape.height = h;
  26053. },
  26054. arrow: function (x, y, w, h, shape) {
  26055. shape.x = x + w / 2;
  26056. shape.y = y + h / 2;
  26057. shape.width = w;
  26058. shape.height = h;
  26059. },
  26060. triangle: function (x, y, w, h, shape) {
  26061. shape.cx = x + w / 2;
  26062. shape.cy = y + h / 2;
  26063. shape.width = w;
  26064. shape.height = h;
  26065. }
  26066. };
  26067. var symbolBuildProxies = {};
  26068. each$1(symbolCtors, function (Ctor, name) {
  26069. symbolBuildProxies[name] = new Ctor();
  26070. });
  26071. var SymbolClz = extendShape({
  26072. type: 'symbol',
  26073. shape: {
  26074. symbolType: '',
  26075. x: 0,
  26076. y: 0,
  26077. width: 0,
  26078. height: 0
  26079. },
  26080. beforeBrush: function () {
  26081. var style = this.style;
  26082. var shape = this.shape;
  26083. // FIXME
  26084. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26085. style.textPosition = ['50%', '40%'];
  26086. style.textAlign = 'center';
  26087. style.textVerticalAlign = 'middle';
  26088. }
  26089. },
  26090. buildPath: function (ctx, shape, inBundle) {
  26091. var symbolType = shape.symbolType;
  26092. var proxySymbol = symbolBuildProxies[symbolType];
  26093. if (shape.symbolType !== 'none') {
  26094. if (!proxySymbol) {
  26095. // Default rect
  26096. symbolType = 'rect';
  26097. proxySymbol = symbolBuildProxies[symbolType];
  26098. }
  26099. symbolShapeMakers[symbolType](
  26100. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26101. );
  26102. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26103. }
  26104. }
  26105. });
  26106. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26107. function symbolPathSetColor(color, innerColor) {
  26108. if (this.type !== 'image') {
  26109. var symbolStyle = this.style;
  26110. var symbolShape = this.shape;
  26111. if (symbolShape && symbolShape.symbolType === 'line') {
  26112. symbolStyle.stroke = color;
  26113. }
  26114. else if (this.__isEmptyBrush) {
  26115. symbolStyle.stroke = color;
  26116. symbolStyle.fill = innerColor || '#fff';
  26117. }
  26118. else {
  26119. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26120. symbolStyle.fill && (symbolStyle.fill = color);
  26121. symbolStyle.stroke && (symbolStyle.stroke = color);
  26122. }
  26123. this.dirty(false);
  26124. }
  26125. }
  26126. /**
  26127. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26128. * @param {string} symbolType
  26129. * @param {number} x
  26130. * @param {number} y
  26131. * @param {number} w
  26132. * @param {number} h
  26133. * @param {string} color
  26134. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26135. * for path and image only.
  26136. */
  26137. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26138. // TODO Support image object, DynamicImage.
  26139. var isEmpty = symbolType.indexOf('empty') === 0;
  26140. if (isEmpty) {
  26141. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26142. }
  26143. var symbolPath;
  26144. if (symbolType.indexOf('image://') === 0) {
  26145. symbolPath = makeImage(
  26146. symbolType.slice(8),
  26147. new BoundingRect(x, y, w, h),
  26148. keepAspect ? 'center' : 'cover'
  26149. );
  26150. }
  26151. else if (symbolType.indexOf('path://') === 0) {
  26152. symbolPath = makePath(
  26153. symbolType.slice(7),
  26154. {},
  26155. new BoundingRect(x, y, w, h),
  26156. keepAspect ? 'center' : 'cover'
  26157. );
  26158. }
  26159. else {
  26160. symbolPath = new SymbolClz({
  26161. shape: {
  26162. symbolType: symbolType,
  26163. x: x,
  26164. y: y,
  26165. width: w,
  26166. height: h
  26167. }
  26168. });
  26169. }
  26170. symbolPath.__isEmptyBrush = isEmpty;
  26171. symbolPath.setColor = symbolPathSetColor;
  26172. symbolPath.setColor(color);
  26173. return symbolPath;
  26174. }
  26175. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26176. /**
  26177. * Create a muti dimension List structure from seriesModel.
  26178. * @param {module:echarts/model/Model} seriesModel
  26179. * @return {module:echarts/data/List} list
  26180. */
  26181. function createList(seriesModel) {
  26182. return createListFromArray(seriesModel.getSource(), seriesModel);
  26183. }
  26184. /**
  26185. * Create scale
  26186. * @param {Array.<number>} dataExtent
  26187. * @param {Object|module:echarts/Model} option
  26188. */
  26189. function createScale(dataExtent, option) {
  26190. var axisModel = option;
  26191. if (!Model.isInstance(option)) {
  26192. axisModel = new Model(option);
  26193. mixin(axisModel, axisModelCommonMixin);
  26194. }
  26195. var scale = createScaleByModel(axisModel);
  26196. scale.setExtent(dataExtent[0], dataExtent[1]);
  26197. niceScaleExtent(scale, axisModel);
  26198. return scale;
  26199. }
  26200. /**
  26201. * Mixin common methods to axis model,
  26202. *
  26203. * Inlcude methods
  26204. * `getFormattedLabels() => Array.<string>`
  26205. * `getCategories() => Array.<string>`
  26206. * `getMin(origin: boolean) => number`
  26207. * `getMax(origin: boolean) => number`
  26208. * `getNeedCrossZero() => boolean`
  26209. * `setRange(start: number, end: number)`
  26210. * `resetRange()`
  26211. */
  26212. function mixinAxisModelCommonMethods(Model$$1) {
  26213. mixin(Model$$1, axisModelCommonMixin);
  26214. }
  26215. var helper = (Object.freeze || Object)({
  26216. createList: createList,
  26217. getLayoutRect: getLayoutRect,
  26218. createScale: createScale,
  26219. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26220. completeDimensions: completeDimensions,
  26221. createDimensions: createDimensions,
  26222. createSymbol: createSymbol
  26223. });
  26224. var EPSILON$3 = 1e-8;
  26225. function isAroundEqual$1(a, b) {
  26226. return Math.abs(a - b) < EPSILON$3;
  26227. }
  26228. function contain$1(points, x, y) {
  26229. var w = 0;
  26230. var p = points[0];
  26231. if (!p) {
  26232. return false;
  26233. }
  26234. for (var i = 1; i < points.length; i++) {
  26235. var p2 = points[i];
  26236. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26237. p = p2;
  26238. }
  26239. // Close polygon
  26240. var p0 = points[0];
  26241. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26242. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26243. }
  26244. return w !== 0;
  26245. }
  26246. /**
  26247. * @module echarts/coord/geo/Region
  26248. */
  26249. /**
  26250. * @param {string} name
  26251. * @param {Array} geometries
  26252. * @param {Array.<number>} cp
  26253. */
  26254. function Region(name, geometries, cp) {
  26255. /**
  26256. * @type {string}
  26257. * @readOnly
  26258. */
  26259. this.name = name;
  26260. /**
  26261. * @type {Array.<Array>}
  26262. * @readOnly
  26263. */
  26264. this.geometries = geometries;
  26265. if (!cp) {
  26266. var rect = this.getBoundingRect();
  26267. cp = [
  26268. rect.x + rect.width / 2,
  26269. rect.y + rect.height / 2
  26270. ];
  26271. }
  26272. else {
  26273. cp = [cp[0], cp[1]];
  26274. }
  26275. /**
  26276. * @type {Array.<number>}
  26277. */
  26278. this.center = cp;
  26279. }
  26280. Region.prototype = {
  26281. constructor: Region,
  26282. properties: null,
  26283. /**
  26284. * @return {module:zrender/core/BoundingRect}
  26285. */
  26286. getBoundingRect: function () {
  26287. var rect = this._rect;
  26288. if (rect) {
  26289. return rect;
  26290. }
  26291. var MAX_NUMBER = Number.MAX_VALUE;
  26292. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26293. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26294. var min2 = [];
  26295. var max2 = [];
  26296. var geometries = this.geometries;
  26297. for (var i = 0; i < geometries.length; i++) {
  26298. // Only support polygon
  26299. if (geometries[i].type !== 'polygon') {
  26300. continue;
  26301. }
  26302. // Doesn't consider hole
  26303. var exterior = geometries[i].exterior;
  26304. fromPoints(exterior, min2, max2);
  26305. min(min$$1, min$$1, min2);
  26306. max(max$$1, max$$1, max2);
  26307. }
  26308. // No data
  26309. if (i === 0) {
  26310. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26311. }
  26312. return (this._rect = new BoundingRect(
  26313. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26314. ));
  26315. },
  26316. /**
  26317. * @param {<Array.<number>} coord
  26318. * @return {boolean}
  26319. */
  26320. contain: function (coord) {
  26321. var rect = this.getBoundingRect();
  26322. var geometries = this.geometries;
  26323. if (!rect.contain(coord[0], coord[1])) {
  26324. return false;
  26325. }
  26326. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26327. // Only support polygon.
  26328. if (geometries[i].type !== 'polygon') {
  26329. continue;
  26330. }
  26331. var exterior = geometries[i].exterior;
  26332. var interiors = geometries[i].interiors;
  26333. if (contain$1(exterior, coord[0], coord[1])) {
  26334. // Not in the region if point is in the hole.
  26335. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26336. if (contain$1(interiors[k])) {
  26337. continue loopGeo;
  26338. }
  26339. }
  26340. return true;
  26341. }
  26342. }
  26343. return false;
  26344. },
  26345. transformTo: function (x, y, width, height) {
  26346. var rect = this.getBoundingRect();
  26347. var aspect = rect.width / rect.height;
  26348. if (!width) {
  26349. width = aspect * height;
  26350. }
  26351. else if (!height) {
  26352. height = width / aspect ;
  26353. }
  26354. var target = new BoundingRect(x, y, width, height);
  26355. var transform = rect.calculateTransform(target);
  26356. var geometries = this.geometries;
  26357. for (var i = 0; i < geometries.length; i++) {
  26358. // Only support polygon.
  26359. if (geometries[i].type !== 'polygon') {
  26360. continue;
  26361. }
  26362. var exterior = geometries[i].exterior;
  26363. var interiors = geometries[i].interiors;
  26364. for (var p = 0; p < exterior.length; p++) {
  26365. applyTransform(exterior[p], exterior[p], transform);
  26366. }
  26367. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26368. for (var p = 0; p < interiors[h].length; p++) {
  26369. applyTransform(interiors[h][p], interiors[h][p], transform);
  26370. }
  26371. }
  26372. }
  26373. rect = this._rect;
  26374. rect.copy(target);
  26375. // Update center
  26376. this.center = [
  26377. rect.x + rect.width / 2,
  26378. rect.y + rect.height / 2
  26379. ];
  26380. }
  26381. };
  26382. /**
  26383. * Parse and decode geo json
  26384. * @module echarts/coord/geo/parseGeoJson
  26385. */
  26386. function decode(json) {
  26387. if (!json.UTF8Encoding) {
  26388. return json;
  26389. }
  26390. var encodeScale = json.UTF8Scale;
  26391. if (encodeScale == null) {
  26392. encodeScale = 1024;
  26393. }
  26394. var features = json.features;
  26395. for (var f = 0; f < features.length; f++) {
  26396. var feature = features[f];
  26397. var geometry = feature.geometry;
  26398. var coordinates = geometry.coordinates;
  26399. var encodeOffsets = geometry.encodeOffsets;
  26400. for (var c = 0; c < coordinates.length; c++) {
  26401. var coordinate = coordinates[c];
  26402. if (geometry.type === 'Polygon') {
  26403. coordinates[c] = decodePolygon(
  26404. coordinate,
  26405. encodeOffsets[c],
  26406. encodeScale
  26407. );
  26408. }
  26409. else if (geometry.type === 'MultiPolygon') {
  26410. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26411. var polygon = coordinate[c2];
  26412. coordinate[c2] = decodePolygon(
  26413. polygon,
  26414. encodeOffsets[c][c2],
  26415. encodeScale
  26416. );
  26417. }
  26418. }
  26419. }
  26420. }
  26421. // Has been decoded
  26422. json.UTF8Encoding = false;
  26423. return json;
  26424. }
  26425. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26426. var result = [];
  26427. var prevX = encodeOffsets[0];
  26428. var prevY = encodeOffsets[1];
  26429. for (var i = 0; i < coordinate.length; i += 2) {
  26430. var x = coordinate.charCodeAt(i) - 64;
  26431. var y = coordinate.charCodeAt(i + 1) - 64;
  26432. // ZigZag decoding
  26433. x = (x >> 1) ^ (-(x & 1));
  26434. y = (y >> 1) ^ (-(y & 1));
  26435. // Delta deocding
  26436. x += prevX;
  26437. y += prevY;
  26438. prevX = x;
  26439. prevY = y;
  26440. // Dequantize
  26441. result.push([x / encodeScale, y / encodeScale]);
  26442. }
  26443. return result;
  26444. }
  26445. /**
  26446. * @alias module:echarts/coord/geo/parseGeoJson
  26447. * @param {Object} geoJson
  26448. * @return {module:zrender/container/Group}
  26449. */
  26450. var parseGeoJSON = function (geoJson) {
  26451. decode(geoJson);
  26452. return map(filter(geoJson.features, function (featureObj) {
  26453. // Output of mapshaper may have geometry null
  26454. return featureObj.geometry
  26455. && featureObj.properties
  26456. && featureObj.geometry.coordinates.length > 0;
  26457. }), function (featureObj) {
  26458. var properties = featureObj.properties;
  26459. var geo = featureObj.geometry;
  26460. var coordinates = geo.coordinates;
  26461. var geometries = [];
  26462. if (geo.type === 'Polygon') {
  26463. geometries.push({
  26464. type: 'polygon',
  26465. // According to the GeoJSON specification.
  26466. // First must be exterior, and the rest are all interior(holes).
  26467. exterior: coordinates[0],
  26468. interiors: coordinates.slice(1)
  26469. });
  26470. }
  26471. if (geo.type === 'MultiPolygon') {
  26472. each$1(coordinates, function (item) {
  26473. if (item[0]) {
  26474. geometries.push({
  26475. type: 'polygon',
  26476. exterior: item[0],
  26477. interiors: item.slice(1)
  26478. });
  26479. }
  26480. });
  26481. }
  26482. var region = new Region(
  26483. properties.name,
  26484. geometries,
  26485. properties.cp
  26486. );
  26487. region.properties = properties;
  26488. return region;
  26489. });
  26490. };
  26491. var linearMap$1 = linearMap;
  26492. function fixExtentWithBands(extent, nTick) {
  26493. var size = extent[1] - extent[0];
  26494. var len = nTick;
  26495. var margin = size / len / 2;
  26496. extent[0] += margin;
  26497. extent[1] -= margin;
  26498. }
  26499. var normalizedExtent = [0, 1];
  26500. /**
  26501. * @name module:echarts/coord/CartesianAxis
  26502. * @constructor
  26503. */
  26504. var Axis = function (dim, scale, extent) {
  26505. /**
  26506. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  26507. * @type {string}
  26508. */
  26509. this.dim = dim;
  26510. /**
  26511. * Axis scale
  26512. * @type {module:echarts/coord/scale/*}
  26513. */
  26514. this.scale = scale;
  26515. /**
  26516. * @type {Array.<number>}
  26517. * @private
  26518. */
  26519. this._extent = extent || [0, 0];
  26520. /**
  26521. * @type {boolean}
  26522. */
  26523. this.inverse = false;
  26524. /**
  26525. * Usually true when axis has a ordinal scale
  26526. * @type {boolean}
  26527. */
  26528. this.onBand = false;
  26529. /**
  26530. * @private
  26531. * @type {number}
  26532. */
  26533. this._labelInterval;
  26534. };
  26535. Axis.prototype = {
  26536. constructor: Axis,
  26537. /**
  26538. * If axis extent contain given coord
  26539. * @param {number} coord
  26540. * @return {boolean}
  26541. */
  26542. contain: function (coord) {
  26543. var extent = this._extent;
  26544. var min = Math.min(extent[0], extent[1]);
  26545. var max = Math.max(extent[0], extent[1]);
  26546. return coord >= min && coord <= max;
  26547. },
  26548. /**
  26549. * If axis extent contain given data
  26550. * @param {number} data
  26551. * @return {boolean}
  26552. */
  26553. containData: function (data) {
  26554. return this.contain(this.dataToCoord(data));
  26555. },
  26556. /**
  26557. * Get coord extent.
  26558. * @return {Array.<number>}
  26559. */
  26560. getExtent: function () {
  26561. return this._extent.slice();
  26562. },
  26563. /**
  26564. * Get precision used for formatting
  26565. * @param {Array.<number>} [dataExtent]
  26566. * @return {number}
  26567. */
  26568. getPixelPrecision: function (dataExtent) {
  26569. return getPixelPrecision(
  26570. dataExtent || this.scale.getExtent(),
  26571. this._extent
  26572. );
  26573. },
  26574. /**
  26575. * Set coord extent
  26576. * @param {number} start
  26577. * @param {number} end
  26578. */
  26579. setExtent: function (start, end) {
  26580. var extent = this._extent;
  26581. extent[0] = start;
  26582. extent[1] = end;
  26583. },
  26584. /**
  26585. * Convert data to coord. Data is the rank if it has a ordinal scale
  26586. * @param {number} data
  26587. * @param {boolean} clamp
  26588. * @return {number}
  26589. */
  26590. dataToCoord: function (data, clamp) {
  26591. var extent = this._extent;
  26592. var scale = this.scale;
  26593. data = scale.normalize(data);
  26594. if (this.onBand && scale.type === 'ordinal') {
  26595. extent = extent.slice();
  26596. fixExtentWithBands(extent, scale.count());
  26597. }
  26598. return linearMap$1(data, normalizedExtent, extent, clamp);
  26599. },
  26600. /**
  26601. * Convert coord to data. Data is the rank if it has a ordinal scale
  26602. * @param {number} coord
  26603. * @param {boolean} clamp
  26604. * @return {number}
  26605. */
  26606. coordToData: function (coord, clamp) {
  26607. var extent = this._extent;
  26608. var scale = this.scale;
  26609. if (this.onBand && scale.type === 'ordinal') {
  26610. extent = extent.slice();
  26611. fixExtentWithBands(extent, scale.count());
  26612. }
  26613. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  26614. return this.scale.scale(t);
  26615. },
  26616. /**
  26617. * Convert pixel point to data in axis
  26618. * @param {Array.<number>} point
  26619. * @param {boolean} clamp
  26620. * @return {number} data
  26621. */
  26622. pointToData: function (point, clamp) {
  26623. // Should be implemented in derived class if necessary.
  26624. },
  26625. /**
  26626. * @return {Array.<number>}
  26627. */
  26628. getTicksCoords: function (alignWithLabel) {
  26629. if (this.onBand && !alignWithLabel) {
  26630. var bands = this.getBands();
  26631. var coords = [];
  26632. for (var i = 0; i < bands.length; i++) {
  26633. coords.push(bands[i][0]);
  26634. }
  26635. if (bands[i - 1]) {
  26636. coords.push(bands[i - 1][1]);
  26637. }
  26638. return coords;
  26639. }
  26640. else {
  26641. return map(this.scale.getTicks(), this.dataToCoord, this);
  26642. }
  26643. },
  26644. /**
  26645. * Coords of labels are on the ticks or on the middle of bands
  26646. * @return {Array.<number>}
  26647. */
  26648. getLabelsCoords: function () {
  26649. return map(this.scale.getTicks(), this.dataToCoord, this);
  26650. },
  26651. /**
  26652. * Get bands.
  26653. *
  26654. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  26655. * |---1---|---2---|---3---|---4---|.
  26656. *
  26657. * @return {Array}
  26658. */
  26659. // FIXME Situation when labels is on ticks
  26660. getBands: function () {
  26661. var extent = this.getExtent();
  26662. var bands = [];
  26663. var len = this.scale.count();
  26664. var start = extent[0];
  26665. var end = extent[1];
  26666. var span = end - start;
  26667. for (var i = 0; i < len; i++) {
  26668. bands.push([
  26669. span * i / len + start,
  26670. span * (i + 1) / len + start
  26671. ]);
  26672. }
  26673. return bands;
  26674. },
  26675. /**
  26676. * Get width of band
  26677. * @return {number}
  26678. */
  26679. getBandWidth: function () {
  26680. var axisExtent = this._extent;
  26681. var dataExtent = this.scale.getExtent();
  26682. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  26683. // Fix #2728, avoid NaN when only one data.
  26684. len === 0 && (len = 1);
  26685. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  26686. return Math.abs(size) / len;
  26687. },
  26688. /**
  26689. * @abstract
  26690. * @return {boolean} Is horizontal
  26691. */
  26692. isHorizontal: null,
  26693. /**
  26694. * @abstract
  26695. * @return {number} Get axis rotate, by degree.
  26696. */
  26697. getRotate: null,
  26698. /**
  26699. * Get interval of the axis label.
  26700. * To get precise result, at least one of `getRotate` and `isHorizontal`
  26701. * should be implemented.
  26702. * @return {number}
  26703. */
  26704. getLabelInterval: function () {
  26705. var labelInterval = this._labelInterval;
  26706. if (!labelInterval) {
  26707. var axisModel = this.model;
  26708. var labelModel = axisModel.getModel('axisLabel');
  26709. labelInterval = labelModel.get('interval');
  26710. if (this.type === 'category'
  26711. && (labelInterval == null || labelInterval === 'auto')
  26712. ) {
  26713. labelInterval = getAxisLabelInterval(
  26714. map(this.scale.getTicks(), this.dataToCoord, this),
  26715. axisModel.getFormattedLabels(),
  26716. labelModel.getFont(),
  26717. this.getRotate
  26718. ? this.getRotate()
  26719. : (this.isHorizontal && !this.isHorizontal())
  26720. ? 90
  26721. : 0,
  26722. labelModel.get('rotate')
  26723. );
  26724. }
  26725. this._labelInterval = labelInterval;
  26726. }
  26727. return labelInterval;
  26728. }
  26729. };
  26730. /**
  26731. * Do not mount those modules on 'src/echarts' for better tree shaking.
  26732. */
  26733. var parseGeoJson = parseGeoJSON;
  26734. var ecUtil = {};
  26735. each$1([
  26736. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  26737. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  26738. 'extend', 'defaults', 'clone', 'merge'
  26739. ],
  26740. function (name) {
  26741. ecUtil[name] = zrUtil[name];
  26742. }
  26743. );
  26744. var DatasetModel = extendComponentModel({
  26745. type: 'dataset',
  26746. /**
  26747. * @protected
  26748. */
  26749. defaultOption: {
  26750. // 'row', 'column'
  26751. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  26752. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  26753. sourceHeader: null,
  26754. dimensions: null,
  26755. source: null
  26756. },
  26757. optionUpdated: function () {
  26758. detectSourceFormat(this);
  26759. }
  26760. });
  26761. extendComponentView({type: 'dataset'});
  26762. SeriesModel.extend({
  26763. type: 'series.line',
  26764. dependencies: ['grid', 'polar'],
  26765. getInitialData: function (option, ecModel) {
  26766. if (__DEV__) {
  26767. var coordSys = option.coordinateSystem;
  26768. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  26769. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  26770. }
  26771. }
  26772. return createListFromArray(this.getSource(), this);
  26773. },
  26774. defaultOption: {
  26775. zlevel: 0, // 一级层叠
  26776. z: 2, // 二级层叠
  26777. coordinateSystem: 'cartesian2d',
  26778. legendHoverLink: true,
  26779. hoverAnimation: true,
  26780. // stack: null
  26781. // xAxisIndex: 0,
  26782. // yAxisIndex: 0,
  26783. // polarIndex: 0,
  26784. // If clip the overflow value
  26785. clipOverflow: true,
  26786. // cursor: null,
  26787. label: {
  26788. position: 'top'
  26789. },
  26790. // itemStyle: {
  26791. // },
  26792. lineStyle: {
  26793. width: 2,
  26794. type: 'solid'
  26795. },
  26796. // areaStyle: {origin: 'auto'},
  26797. // false, 'start', 'end', 'middle'
  26798. step: false,
  26799. // Disabled if step is true
  26800. smooth: false,
  26801. smoothMonotone: null,
  26802. // 拐点图形类型
  26803. symbol: 'emptyCircle',
  26804. // 拐点图形大小
  26805. symbolSize: 4,
  26806. // 拐点图形旋转控制
  26807. symbolRotate: null,
  26808. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  26809. showSymbol: true,
  26810. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  26811. showAllSymbol: false,
  26812. // 是否连接断点
  26813. connectNulls: false,
  26814. // 数据过滤,'average', 'max', 'min', 'sum'
  26815. sampling: 'none',
  26816. animationEasing: 'linear',
  26817. // Disable progressive
  26818. progressive: 0,
  26819. hoverLayerThreshold: Infinity
  26820. }
  26821. });
  26822. /**
  26823. * @param {module:echarts/data/List} data
  26824. * @param {number} dataIndex
  26825. * @return {string} label string. Not null/undefined
  26826. */
  26827. function getDefaultLabel(data, dataIndex) {
  26828. var labelDims = data.mapDimension('defaultedLabel', true);
  26829. var len = labelDims.length;
  26830. // Simple optimization (in lots of cases, label dims length is 1)
  26831. if (len === 1) {
  26832. return retrieveRawValue(data, dataIndex, labelDims[0]);
  26833. }
  26834. else if (len) {
  26835. var vals = [];
  26836. for (var i = 0; i < labelDims.length; i++) {
  26837. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  26838. vals.push(val);
  26839. }
  26840. return vals.join(' ');
  26841. }
  26842. }
  26843. /**
  26844. * @module echarts/chart/helper/Symbol
  26845. */
  26846. function getSymbolSize(data, idx) {
  26847. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  26848. return symbolSize instanceof Array
  26849. ? symbolSize.slice()
  26850. : [+symbolSize, +symbolSize];
  26851. }
  26852. function getScale(symbolSize) {
  26853. return [symbolSize[0] / 2, symbolSize[1] / 2];
  26854. }
  26855. /**
  26856. * @constructor
  26857. * @alias {module:echarts/chart/helper/Symbol}
  26858. * @param {module:echarts/data/List} data
  26859. * @param {number} idx
  26860. * @extends {module:zrender/graphic/Group}
  26861. */
  26862. function SymbolClz$1(data, idx, seriesScope) {
  26863. Group.call(this);
  26864. this.updateData(data, idx, seriesScope);
  26865. }
  26866. var symbolProto = SymbolClz$1.prototype;
  26867. function driftSymbol(dx, dy) {
  26868. this.parent.drift(dx, dy);
  26869. }
  26870. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  26871. // Remove paths created before
  26872. this.removeAll();
  26873. var color = data.getItemVisual(idx, 'color');
  26874. // var symbolPath = createSymbol(
  26875. // symbolType, -0.5, -0.5, 1, 1, color
  26876. // );
  26877. // If width/height are set too small (e.g., set to 1) on ios10
  26878. // and macOS Sierra, a circle stroke become a rect, no matter what
  26879. // the scale is set. So we set width/height as 2. See #4150.
  26880. var symbolPath = createSymbol(
  26881. symbolType, -1, -1, 2, 2, color
  26882. );
  26883. symbolPath.attr({
  26884. z2: 100,
  26885. culling: true,
  26886. scale: getScale(symbolSize)
  26887. });
  26888. // Rewrite drift method
  26889. symbolPath.drift = driftSymbol;
  26890. this._symbolType = symbolType;
  26891. this.add(symbolPath);
  26892. };
  26893. /**
  26894. * Stop animation
  26895. * @param {boolean} toLastFrame
  26896. */
  26897. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  26898. this.childAt(0).stopAnimation(toLastFrame);
  26899. };
  26900. /**
  26901. * FIXME:
  26902. * Caution: This method breaks the encapsulation of this module,
  26903. * but it indeed brings convenience. So do not use the method
  26904. * unless you detailedly know all the implements of `Symbol`,
  26905. * especially animation.
  26906. *
  26907. * Get symbol path element.
  26908. */
  26909. symbolProto.getSymbolPath = function () {
  26910. return this.childAt(0);
  26911. };
  26912. /**
  26913. * Get scale(aka, current symbol size).
  26914. * Including the change caused by animation
  26915. */
  26916. symbolProto.getScale = function () {
  26917. return this.childAt(0).scale;
  26918. };
  26919. /**
  26920. * Highlight symbol
  26921. */
  26922. symbolProto.highlight = function () {
  26923. this.childAt(0).trigger('emphasis');
  26924. };
  26925. /**
  26926. * Downplay symbol
  26927. */
  26928. symbolProto.downplay = function () {
  26929. this.childAt(0).trigger('normal');
  26930. };
  26931. /**
  26932. * @param {number} zlevel
  26933. * @param {number} z
  26934. */
  26935. symbolProto.setZ = function (zlevel, z) {
  26936. var symbolPath = this.childAt(0);
  26937. symbolPath.zlevel = zlevel;
  26938. symbolPath.z = z;
  26939. };
  26940. symbolProto.setDraggable = function (draggable) {
  26941. var symbolPath = this.childAt(0);
  26942. symbolPath.draggable = draggable;
  26943. symbolPath.cursor = draggable ? 'move' : 'pointer';
  26944. };
  26945. /**
  26946. * Update symbol properties
  26947. * @param {module:echarts/data/List} data
  26948. * @param {number} idx
  26949. * @param {Object} [seriesScope]
  26950. * @param {Object} [seriesScope.itemStyle]
  26951. * @param {Object} [seriesScope.hoverItemStyle]
  26952. * @param {Object} [seriesScope.symbolRotate]
  26953. * @param {Object} [seriesScope.symbolOffset]
  26954. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  26955. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  26956. * @param {boolean} [seriesScope.hoverAnimation]
  26957. * @param {Object} [seriesScope.cursorStyle]
  26958. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  26959. * @param {string} [seriesScope.symbolInnerColor]
  26960. * @param {Object} [seriesScope.fadeIn=false]
  26961. */
  26962. symbolProto.updateData = function (data, idx, seriesScope) {
  26963. this.silent = false;
  26964. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  26965. var seriesModel = data.hostModel;
  26966. var symbolSize = getSymbolSize(data, idx);
  26967. var isInit = symbolType !== this._symbolType;
  26968. if (isInit) {
  26969. this._createSymbol(symbolType, data, idx, symbolSize);
  26970. }
  26971. else {
  26972. var symbolPath = this.childAt(0);
  26973. symbolPath.silent = false;
  26974. updateProps(symbolPath, {
  26975. scale: getScale(symbolSize)
  26976. }, seriesModel, idx);
  26977. }
  26978. this._updateCommon(data, idx, symbolSize, seriesScope);
  26979. if (isInit) {
  26980. var symbolPath = this.childAt(0);
  26981. var fadeIn = seriesScope && seriesScope.fadeIn;
  26982. var target = {scale: symbolPath.scale.slice()};
  26983. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  26984. symbolPath.scale = [0, 0];
  26985. fadeIn && (symbolPath.style.opacity = 0);
  26986. initProps(symbolPath, target, seriesModel, idx);
  26987. }
  26988. this._seriesModel = seriesModel;
  26989. };
  26990. // Update common properties
  26991. var normalStyleAccessPath = ['itemStyle'];
  26992. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  26993. var normalLabelAccessPath = ['label'];
  26994. var emphasisLabelAccessPath = ['emphasis', 'label'];
  26995. /**
  26996. * @param {module:echarts/data/List} data
  26997. * @param {number} idx
  26998. * @param {Array.<number>} symbolSize
  26999. * @param {Object} [seriesScope]
  27000. */
  27001. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27002. var symbolPath = this.childAt(0);
  27003. var seriesModel = data.hostModel;
  27004. var color = data.getItemVisual(idx, 'color');
  27005. // Reset style
  27006. if (symbolPath.type !== 'image') {
  27007. symbolPath.useStyle({
  27008. strokeNoScale: true
  27009. });
  27010. }
  27011. var itemStyle = seriesScope && seriesScope.itemStyle;
  27012. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27013. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27014. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27015. var labelModel = seriesScope && seriesScope.labelModel;
  27016. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27017. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27018. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27019. if (!seriesScope || data.hasItemOption) {
  27020. var itemModel = (seriesScope && seriesScope.itemModel)
  27021. ? seriesScope.itemModel : data.getItemModel(idx);
  27022. // Color must be excluded.
  27023. // Because symbol provide setColor individually to set fill and stroke
  27024. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27025. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27026. symbolRotate = itemModel.getShallow('symbolRotate');
  27027. symbolOffset = itemModel.getShallow('symbolOffset');
  27028. labelModel = itemModel.getModel(normalLabelAccessPath);
  27029. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27030. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27031. cursorStyle = itemModel.getShallow('cursor');
  27032. }
  27033. else {
  27034. hoverItemStyle = extend({}, hoverItemStyle);
  27035. }
  27036. var elStyle = symbolPath.style;
  27037. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27038. if (symbolOffset) {
  27039. symbolPath.attr('position', [
  27040. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27041. parsePercent$1(symbolOffset[1], symbolSize[1])
  27042. ]);
  27043. }
  27044. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27045. // PENDING setColor before setStyle!!!
  27046. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27047. symbolPath.setStyle(itemStyle);
  27048. var opacity = data.getItemVisual(idx, 'opacity');
  27049. if (opacity != null) {
  27050. elStyle.opacity = opacity;
  27051. }
  27052. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27053. setLabelStyle(
  27054. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27055. {
  27056. labelFetcher: seriesModel,
  27057. labelDataIndex: idx,
  27058. defaultText: getLabelDefaultText,
  27059. isRectText: true,
  27060. autoColor: color
  27061. }
  27062. );
  27063. // Do not execute util needed.
  27064. function getLabelDefaultText(idx, opt) {
  27065. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27066. }
  27067. symbolPath.off('mouseover')
  27068. .off('mouseout')
  27069. .off('emphasis')
  27070. .off('normal');
  27071. symbolPath.hoverStyle = hoverItemStyle;
  27072. // FIXME
  27073. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27074. setHoverStyle(symbolPath);
  27075. var scale = getScale(symbolSize);
  27076. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27077. var onEmphasis = function() {
  27078. var ratio = scale[1] / scale[0];
  27079. this.animateTo({
  27080. scale: [
  27081. Math.max(scale[0] * 1.1, scale[0] + 3),
  27082. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27083. ]
  27084. }, 400, 'elasticOut');
  27085. };
  27086. var onNormal = function() {
  27087. this.animateTo({
  27088. scale: scale
  27089. }, 400, 'elasticOut');
  27090. };
  27091. symbolPath.on('mouseover', onEmphasis)
  27092. .on('mouseout', onNormal)
  27093. .on('emphasis', onEmphasis)
  27094. .on('normal', onNormal);
  27095. }
  27096. };
  27097. /**
  27098. * @param {Function} cb
  27099. * @param {Object} [opt]
  27100. * @param {Object} [opt.keepLabel=true]
  27101. */
  27102. symbolProto.fadeOut = function (cb, opt) {
  27103. var symbolPath = this.childAt(0);
  27104. // Avoid mistaken hover when fading out
  27105. this.silent = symbolPath.silent = true;
  27106. // Not show text when animating
  27107. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27108. updateProps(
  27109. symbolPath,
  27110. {
  27111. style: {opacity: 0},
  27112. scale: [0, 0]
  27113. },
  27114. this._seriesModel,
  27115. this.dataIndex,
  27116. cb
  27117. );
  27118. };
  27119. inherits(SymbolClz$1, Group);
  27120. /**
  27121. * @module echarts/chart/helper/SymbolDraw
  27122. */
  27123. /**
  27124. * @constructor
  27125. * @alias module:echarts/chart/helper/SymbolDraw
  27126. * @param {module:zrender/graphic/Group} [symbolCtor]
  27127. */
  27128. function SymbolDraw(symbolCtor) {
  27129. this.group = new Group();
  27130. this._symbolCtor = symbolCtor || SymbolClz$1;
  27131. }
  27132. var symbolDrawProto = SymbolDraw.prototype;
  27133. function symbolNeedsDraw(data, point, idx, isIgnore) {
  27134. return point && !isNaN(point[0]) && !isNaN(point[1])
  27135. && !(isIgnore && isIgnore(idx))
  27136. && data.getItemVisual(idx, 'symbol') !== 'none';
  27137. }
  27138. /**
  27139. * Update symbols draw by new data
  27140. * @param {module:echarts/data/List} data
  27141. * @param {Array.<boolean>} [isIgnore]
  27142. */
  27143. symbolDrawProto.updateData = function (data, isIgnore) {
  27144. var group = this.group;
  27145. var seriesModel = data.hostModel;
  27146. var oldData = this._data;
  27147. var SymbolCtor = this._symbolCtor;
  27148. var seriesScope = makeSeriesScope(data);
  27149. // There is no oldLineData only when first rendering or switching from
  27150. // stream mode to normal mode, where previous elements should be removed.
  27151. if (!oldData) {
  27152. group.removeAll();
  27153. }
  27154. data.diff(oldData)
  27155. .add(function (newIdx) {
  27156. var point = data.getItemLayout(newIdx);
  27157. if (symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27158. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27159. symbolEl.attr('position', point);
  27160. data.setItemGraphicEl(newIdx, symbolEl);
  27161. group.add(symbolEl);
  27162. }
  27163. })
  27164. .update(function (newIdx, oldIdx) {
  27165. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27166. var point = data.getItemLayout(newIdx);
  27167. if (!symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27168. group.remove(symbolEl);
  27169. return;
  27170. }
  27171. if (!symbolEl) {
  27172. symbolEl = new SymbolCtor(data, newIdx);
  27173. symbolEl.attr('position', point);
  27174. }
  27175. else {
  27176. symbolEl.updateData(data, newIdx, seriesScope);
  27177. updateProps(symbolEl, {
  27178. position: point
  27179. }, seriesModel);
  27180. }
  27181. // Add back
  27182. group.add(symbolEl);
  27183. data.setItemGraphicEl(newIdx, symbolEl);
  27184. })
  27185. .remove(function (oldIdx) {
  27186. var el = oldData.getItemGraphicEl(oldIdx);
  27187. el && el.fadeOut(function () {
  27188. group.remove(el);
  27189. });
  27190. })
  27191. .execute();
  27192. this._data = data;
  27193. };
  27194. symbolDrawProto.isPersistent = function () {
  27195. return true;
  27196. };
  27197. symbolDrawProto.updateLayout = function () {
  27198. var data = this._data;
  27199. if (data) {
  27200. // Not use animation
  27201. data.eachItemGraphicEl(function (el, idx) {
  27202. var point = data.getItemLayout(idx);
  27203. el.attr('position', point);
  27204. });
  27205. }
  27206. };
  27207. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27208. this._seriesScope = makeSeriesScope(data);
  27209. this._data = null;
  27210. this.group.removeAll();
  27211. };
  27212. symbolDrawProto.incrementalUpdate = function (taskParams, data, isIgnore) {
  27213. function updateIncrementalAndHover(el) {
  27214. if (!el.isGroup) {
  27215. el.incremental = el.useHoverLayer = true;
  27216. }
  27217. }
  27218. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27219. var point = data.getItemLayout(idx);
  27220. if (symbolNeedsDraw(data, point, idx, isIgnore)) {
  27221. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27222. el.traverse(updateIncrementalAndHover);
  27223. el.attr('position', point);
  27224. this.group.add(el);
  27225. data.setItemGraphicEl(idx, el);
  27226. }
  27227. }
  27228. };
  27229. symbolDrawProto.remove = function (enableAnimation) {
  27230. var group = this.group;
  27231. var data = this._data;
  27232. if (data) {
  27233. if (enableAnimation) {
  27234. data.eachItemGraphicEl(function (el) {
  27235. el.fadeOut(function () {
  27236. group.remove(el);
  27237. });
  27238. });
  27239. }
  27240. else {
  27241. group.removeAll();
  27242. }
  27243. }
  27244. };
  27245. function makeSeriesScope(data) {
  27246. var seriesModel = data.hostModel;
  27247. return {
  27248. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27249. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27250. symbolRotate: seriesModel.get('symbolRotate'),
  27251. symbolOffset: seriesModel.get('symbolOffset'),
  27252. hoverAnimation: seriesModel.get('hoverAnimation'),
  27253. labelModel: seriesModel.getModel('label'),
  27254. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27255. cursorStyle: seriesModel.get('cursor')
  27256. };
  27257. }
  27258. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27259. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27260. // not do well in performance when roam with fixed dataZoom window.
  27261. function sign$1(val) {
  27262. return val >= 0 ? 1 : -1;
  27263. }
  27264. function getStackedOnPoint(coordSys, data, idx) {
  27265. var baseAxis = coordSys.getBaseAxis();
  27266. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27267. var valueStart = baseAxis.onZero
  27268. ? 0 : valueAxis.scale.getExtent()[0];
  27269. var valueDim = valueAxis.dim;
  27270. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  27271. var stackedOnSameSign;
  27272. var stackedOn = data.stackedOn;
  27273. var val = data.get(valueDim, idx);
  27274. // Find first stacked value with same sign
  27275. while (stackedOn &&
  27276. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  27277. ) {
  27278. stackedOnSameSign = stackedOn;
  27279. break;
  27280. }
  27281. var stackedData = [];
  27282. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27283. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27284. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27285. return coordSys.dataToPoint(stackedData);
  27286. }
  27287. // function convertToIntId(newIdList, oldIdList) {
  27288. // // Generate int id instead of string id.
  27289. // // Compare string maybe slow in score function of arrDiff
  27290. // // Assume id in idList are all unique
  27291. // var idIndicesMap = {};
  27292. // var idx = 0;
  27293. // for (var i = 0; i < newIdList.length; i++) {
  27294. // idIndicesMap[newIdList[i]] = idx;
  27295. // newIdList[i] = idx++;
  27296. // }
  27297. // for (var i = 0; i < oldIdList.length; i++) {
  27298. // var oldId = oldIdList[i];
  27299. // // Same with newIdList
  27300. // if (idIndicesMap[oldId]) {
  27301. // oldIdList[i] = idIndicesMap[oldId];
  27302. // }
  27303. // else {
  27304. // oldIdList[i] = idx++;
  27305. // }
  27306. // }
  27307. // }
  27308. function diffData(oldData, newData) {
  27309. var diffResult = [];
  27310. newData.diff(oldData)
  27311. .add(function (idx) {
  27312. diffResult.push({cmd: '+', idx: idx});
  27313. })
  27314. .update(function (newIdx, oldIdx) {
  27315. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27316. })
  27317. .remove(function (idx) {
  27318. diffResult.push({cmd: '-', idx: idx});
  27319. })
  27320. .execute();
  27321. return diffResult;
  27322. }
  27323. var lineAnimationDiff = function (
  27324. oldData, newData,
  27325. oldStackedOnPoints, newStackedOnPoints,
  27326. oldCoordSys, newCoordSys
  27327. ) {
  27328. var diff = diffData(oldData, newData);
  27329. // var newIdList = newData.mapArray(newData.getId);
  27330. // var oldIdList = oldData.mapArray(oldData.getId);
  27331. // convertToIntId(newIdList, oldIdList);
  27332. // // FIXME One data ?
  27333. // diff = arrayDiff(oldIdList, newIdList);
  27334. var currPoints = [];
  27335. var nextPoints = [];
  27336. // Points for stacking base line
  27337. var currStackedPoints = [];
  27338. var nextStackedPoints = [];
  27339. var status = [];
  27340. var sortedIndices = [];
  27341. var rawIndices = [];
  27342. var dims = newCoordSys.dimensions;
  27343. for (var i = 0; i < diff.length; i++) {
  27344. var diffItem = diff[i];
  27345. var pointAdded = true;
  27346. // FIXME, animation is not so perfect when dataZoom window moves fast
  27347. // Which is in case remvoing or add more than one data in the tail or head
  27348. switch (diffItem.cmd) {
  27349. case '=':
  27350. var currentPt = oldData.getItemLayout(diffItem.idx);
  27351. var nextPt = newData.getItemLayout(diffItem.idx1);
  27352. // If previous data is NaN, use next point directly
  27353. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27354. currentPt = nextPt.slice();
  27355. }
  27356. currPoints.push(currentPt);
  27357. nextPoints.push(nextPt);
  27358. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27359. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27360. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27361. break;
  27362. case '+':
  27363. var idx = diffItem.idx;
  27364. currPoints.push(
  27365. oldCoordSys.dataToPoint([
  27366. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  27367. ])
  27368. );
  27369. nextPoints.push(newData.getItemLayout(idx).slice());
  27370. currStackedPoints.push(
  27371. getStackedOnPoint(oldCoordSys, newData, idx)
  27372. );
  27373. nextStackedPoints.push(newStackedOnPoints[idx]);
  27374. rawIndices.push(newData.getRawIndex(idx));
  27375. break;
  27376. case '-':
  27377. var idx = diffItem.idx;
  27378. var rawIndex = oldData.getRawIndex(idx);
  27379. // Data is replaced. In the case of dynamic data queue
  27380. // FIXME FIXME FIXME
  27381. if (rawIndex !== idx) {
  27382. currPoints.push(oldData.getItemLayout(idx));
  27383. nextPoints.push(newCoordSys.dataToPoint([
  27384. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  27385. ]));
  27386. currStackedPoints.push(oldStackedOnPoints[idx]);
  27387. nextStackedPoints.push(
  27388. getStackedOnPoint(
  27389. newCoordSys, oldData, idx
  27390. )
  27391. );
  27392. rawIndices.push(rawIndex);
  27393. }
  27394. else {
  27395. pointAdded = false;
  27396. }
  27397. }
  27398. // Original indices
  27399. if (pointAdded) {
  27400. status.push(diffItem);
  27401. sortedIndices.push(sortedIndices.length);
  27402. }
  27403. }
  27404. // Diff result may be crossed if all items are changed
  27405. // Sort by data index
  27406. sortedIndices.sort(function (a, b) {
  27407. return rawIndices[a] - rawIndices[b];
  27408. });
  27409. var sortedCurrPoints = [];
  27410. var sortedNextPoints = [];
  27411. var sortedCurrStackedPoints = [];
  27412. var sortedNextStackedPoints = [];
  27413. var sortedStatus = [];
  27414. for (var i = 0; i < sortedIndices.length; i++) {
  27415. var idx = sortedIndices[i];
  27416. sortedCurrPoints[i] = currPoints[idx];
  27417. sortedNextPoints[i] = nextPoints[idx];
  27418. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  27419. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  27420. sortedStatus[i] = status[idx];
  27421. }
  27422. return {
  27423. current: sortedCurrPoints,
  27424. next: sortedNextPoints,
  27425. stackedOnCurrent: sortedCurrStackedPoints,
  27426. stackedOnNext: sortedNextStackedPoints,
  27427. status: sortedStatus
  27428. };
  27429. };
  27430. // Poly path support NaN point
  27431. var vec2Min = min;
  27432. var vec2Max = max;
  27433. var scaleAndAdd$1 = scaleAndAdd;
  27434. var v2Copy = copy;
  27435. // Temporary variable
  27436. var v = [];
  27437. var cp0 = [];
  27438. var cp1 = [];
  27439. function isPointNull(p) {
  27440. return isNaN(p[0]) || isNaN(p[1]);
  27441. }
  27442. function drawSegment(
  27443. ctx, points, start, segLen, allLen,
  27444. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  27445. ) {
  27446. var prevIdx = 0;
  27447. var idx = start;
  27448. for (var k = 0; k < segLen; k++) {
  27449. var p = points[idx];
  27450. if (idx >= allLen || idx < 0) {
  27451. break;
  27452. }
  27453. if (isPointNull(p)) {
  27454. if (connectNulls) {
  27455. idx += dir;
  27456. continue;
  27457. }
  27458. break;
  27459. }
  27460. if (idx === start) {
  27461. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  27462. v2Copy(cp0, p);
  27463. }
  27464. else {
  27465. if (smooth > 0) {
  27466. var nextIdx = idx + dir;
  27467. var nextP = points[nextIdx];
  27468. if (connectNulls) {
  27469. // Find next point not null
  27470. while (nextP && isPointNull(points[nextIdx])) {
  27471. nextIdx += dir;
  27472. nextP = points[nextIdx];
  27473. }
  27474. }
  27475. var ratioNextSeg = 0.5;
  27476. var prevP = points[prevIdx];
  27477. var nextP = points[nextIdx];
  27478. // Last point
  27479. if (!nextP || isPointNull(nextP)) {
  27480. v2Copy(cp1, p);
  27481. }
  27482. else {
  27483. // If next data is null in not connect case
  27484. if (isPointNull(nextP) && !connectNulls) {
  27485. nextP = p;
  27486. }
  27487. sub(v, nextP, prevP);
  27488. var lenPrevSeg;
  27489. var lenNextSeg;
  27490. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  27491. var dim = smoothMonotone === 'x' ? 0 : 1;
  27492. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  27493. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  27494. }
  27495. else {
  27496. lenPrevSeg = dist(p, prevP);
  27497. lenNextSeg = dist(p, nextP);
  27498. }
  27499. // Use ratio of seg length
  27500. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  27501. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  27502. }
  27503. // Smooth constraint
  27504. vec2Min(cp0, cp0, smoothMax);
  27505. vec2Max(cp0, cp0, smoothMin);
  27506. vec2Min(cp1, cp1, smoothMax);
  27507. vec2Max(cp1, cp1, smoothMin);
  27508. ctx.bezierCurveTo(
  27509. cp0[0], cp0[1],
  27510. cp1[0], cp1[1],
  27511. p[0], p[1]
  27512. );
  27513. // cp0 of next segment
  27514. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  27515. }
  27516. else {
  27517. ctx.lineTo(p[0], p[1]);
  27518. }
  27519. }
  27520. prevIdx = idx;
  27521. idx += dir;
  27522. }
  27523. return k;
  27524. }
  27525. function getBoundingBox(points, smoothConstraint) {
  27526. var ptMin = [Infinity, Infinity];
  27527. var ptMax = [-Infinity, -Infinity];
  27528. if (smoothConstraint) {
  27529. for (var i = 0; i < points.length; i++) {
  27530. var pt = points[i];
  27531. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  27532. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  27533. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  27534. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  27535. }
  27536. }
  27537. return {
  27538. min: smoothConstraint ? ptMin : ptMax,
  27539. max: smoothConstraint ? ptMax : ptMin
  27540. };
  27541. }
  27542. var Polyline$1 = Path.extend({
  27543. type: 'ec-polyline',
  27544. shape: {
  27545. points: [],
  27546. smooth: 0,
  27547. smoothConstraint: true,
  27548. smoothMonotone: null,
  27549. connectNulls: false
  27550. },
  27551. style: {
  27552. fill: null,
  27553. stroke: '#000'
  27554. },
  27555. brush: fixClipWithShadow(Path.prototype.brush),
  27556. buildPath: function (ctx, shape) {
  27557. var points = shape.points;
  27558. var i = 0;
  27559. var len$$1 = points.length;
  27560. var result = getBoundingBox(points, shape.smoothConstraint);
  27561. if (shape.connectNulls) {
  27562. // Must remove first and last null values avoid draw error in polygon
  27563. for (; len$$1 > 0; len$$1--) {
  27564. if (!isPointNull(points[len$$1 - 1])) {
  27565. break;
  27566. }
  27567. }
  27568. for (; i < len$$1; i++) {
  27569. if (!isPointNull(points[i])) {
  27570. break;
  27571. }
  27572. }
  27573. }
  27574. while (i < len$$1) {
  27575. i += drawSegment(
  27576. ctx, points, i, len$$1, len$$1,
  27577. 1, result.min, result.max, shape.smooth,
  27578. shape.smoothMonotone, shape.connectNulls
  27579. ) + 1;
  27580. }
  27581. }
  27582. });
  27583. var Polygon$1 = Path.extend({
  27584. type: 'ec-polygon',
  27585. shape: {
  27586. points: [],
  27587. // Offset between stacked base points and points
  27588. stackedOnPoints: [],
  27589. smooth: 0,
  27590. stackedOnSmooth: 0,
  27591. smoothConstraint: true,
  27592. smoothMonotone: null,
  27593. connectNulls: false
  27594. },
  27595. brush: fixClipWithShadow(Path.prototype.brush),
  27596. buildPath: function (ctx, shape) {
  27597. var points = shape.points;
  27598. var stackedOnPoints = shape.stackedOnPoints;
  27599. var i = 0;
  27600. var len$$1 = points.length;
  27601. var smoothMonotone = shape.smoothMonotone;
  27602. var bbox = getBoundingBox(points, shape.smoothConstraint);
  27603. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  27604. if (shape.connectNulls) {
  27605. // Must remove first and last null values avoid draw error in polygon
  27606. for (; len$$1 > 0; len$$1--) {
  27607. if (!isPointNull(points[len$$1 - 1])) {
  27608. break;
  27609. }
  27610. }
  27611. for (; i < len$$1; i++) {
  27612. if (!isPointNull(points[i])) {
  27613. break;
  27614. }
  27615. }
  27616. }
  27617. while (i < len$$1) {
  27618. var k = drawSegment(
  27619. ctx, points, i, len$$1, len$$1,
  27620. 1, bbox.min, bbox.max, shape.smooth,
  27621. smoothMonotone, shape.connectNulls
  27622. );
  27623. drawSegment(
  27624. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  27625. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  27626. smoothMonotone, shape.connectNulls
  27627. );
  27628. i += k + 1;
  27629. ctx.closePath();
  27630. }
  27631. }
  27632. });
  27633. // FIXME step not support polar
  27634. function isPointsSame(points1, points2) {
  27635. if (points1.length !== points2.length) {
  27636. return;
  27637. }
  27638. for (var i = 0; i < points1.length; i++) {
  27639. var p1 = points1[i];
  27640. var p2 = points2[i];
  27641. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  27642. return;
  27643. }
  27644. }
  27645. return true;
  27646. }
  27647. function getSmooth(smooth) {
  27648. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  27649. }
  27650. function getAxisExtentWithGap(axis) {
  27651. var extent = axis.getGlobalExtent();
  27652. if (axis.onBand) {
  27653. // Remove extra 1px to avoid line miter in clipped edge
  27654. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  27655. var dir = extent[1] > extent[0] ? 1 : -1;
  27656. extent[0] += dir * halfBandWidth;
  27657. extent[1] -= dir * halfBandWidth;
  27658. }
  27659. return extent;
  27660. }
  27661. function sign(val) {
  27662. return val >= 0 ? 1 : -1;
  27663. }
  27664. /**
  27665. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  27666. * @param {module:echarts/data/List} data
  27667. * @param {Array.<Array.<number>>} points
  27668. * @param {string} origin origin of areaStyle. Valid values: 'auto', 'start',
  27669. * 'end'.
  27670. * auto: from axisLine to data
  27671. * start: from min to data
  27672. * end: from data to max
  27673. * @private
  27674. */
  27675. function getStackedOnPoints(seriesModel, coordSys, data, origin) {
  27676. var baseAxis = coordSys.getBaseAxis();
  27677. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27678. var valueStart = 0;
  27679. var extent = valueAxis.scale.getExtent();
  27680. if (origin === 'start') {
  27681. valueStart = extent[0];
  27682. }
  27683. else if (origin === 'end') {
  27684. valueStart = extent[1];
  27685. }
  27686. else {
  27687. // auto
  27688. var extent = valueAxis.scale.getExtent();
  27689. if (extent[0] > 0) {
  27690. // Both positive
  27691. valueStart = extent[0];
  27692. }
  27693. else if (extent[1] < 0) {
  27694. // Both negative
  27695. valueStart = extent[1];
  27696. }
  27697. // If is one positive, and one negative, onZero shall be true
  27698. }
  27699. var valueCoordDim = valueAxis.dim;
  27700. var baseDataOffset = valueCoordDim === 'x' || valueCoordDim === 'radius' ? 1 : 0;
  27701. var valueDim = data.mapDimension(valueCoordDim);
  27702. return data.mapArray(valueDim ? [valueDim] : [], function (val, idx) {
  27703. var stackedOnSameSign;
  27704. var stackedOn = data.stackedOn;
  27705. // Find first stacked value with same sign
  27706. while (stackedOn &&
  27707. sign(stackedOn.get(valueDim, idx)) === sign(val)
  27708. ) {
  27709. stackedOnSameSign = stackedOn;
  27710. break;
  27711. }
  27712. var stackedData = [];
  27713. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27714. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27715. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27716. return coordSys.dataToPoint(stackedData);
  27717. }, true);
  27718. }
  27719. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  27720. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  27721. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  27722. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  27723. var x = Math.min(xExtent[0], xExtent[1]);
  27724. var y = Math.min(yExtent[0], yExtent[1]);
  27725. var width = Math.max(xExtent[0], xExtent[1]) - x;
  27726. var height = Math.max(yExtent[0], yExtent[1]) - y;
  27727. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  27728. // Expand clip shape to avoid clipping when line value exceeds axis
  27729. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  27730. if (isHorizontal) {
  27731. y -= expandSize;
  27732. height += expandSize * 2;
  27733. }
  27734. else {
  27735. x -= expandSize;
  27736. width += expandSize * 2;
  27737. }
  27738. var clipPath = new Rect({
  27739. shape: {
  27740. x: x,
  27741. y: y,
  27742. width: width,
  27743. height: height
  27744. }
  27745. });
  27746. if (hasAnimation) {
  27747. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  27748. initProps(clipPath, {
  27749. shape: {
  27750. width: width,
  27751. height: height
  27752. }
  27753. }, seriesModel);
  27754. }
  27755. return clipPath;
  27756. }
  27757. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  27758. var angleAxis = polar.getAngleAxis();
  27759. var radiusAxis = polar.getRadiusAxis();
  27760. var radiusExtent = radiusAxis.getExtent();
  27761. var angleExtent = angleAxis.getExtent();
  27762. var RADIAN = Math.PI / 180;
  27763. var clipPath = new Sector({
  27764. shape: {
  27765. cx: polar.cx,
  27766. cy: polar.cy,
  27767. r0: radiusExtent[0],
  27768. r: radiusExtent[1],
  27769. startAngle: -angleExtent[0] * RADIAN,
  27770. endAngle: -angleExtent[1] * RADIAN,
  27771. clockwise: angleAxis.inverse
  27772. }
  27773. });
  27774. if (hasAnimation) {
  27775. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  27776. initProps(clipPath, {
  27777. shape: {
  27778. endAngle: -angleExtent[1] * RADIAN
  27779. }
  27780. }, seriesModel);
  27781. }
  27782. return clipPath;
  27783. }
  27784. function createClipShape(coordSys, hasAnimation, seriesModel) {
  27785. return coordSys.type === 'polar'
  27786. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  27787. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  27788. }
  27789. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  27790. var baseAxis = coordSys.getBaseAxis();
  27791. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  27792. var stepPoints = [];
  27793. for (var i = 0; i < points.length - 1; i++) {
  27794. var nextPt = points[i + 1];
  27795. var pt = points[i];
  27796. stepPoints.push(pt);
  27797. var stepPt = [];
  27798. switch (stepTurnAt) {
  27799. case 'end':
  27800. stepPt[baseIndex] = nextPt[baseIndex];
  27801. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27802. // default is start
  27803. stepPoints.push(stepPt);
  27804. break;
  27805. case 'middle':
  27806. // default is start
  27807. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  27808. var stepPt2 = [];
  27809. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  27810. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27811. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  27812. stepPoints.push(stepPt);
  27813. stepPoints.push(stepPt2);
  27814. break;
  27815. default:
  27816. stepPt[baseIndex] = pt[baseIndex];
  27817. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  27818. // default is start
  27819. stepPoints.push(stepPt);
  27820. }
  27821. }
  27822. // Last points
  27823. points[i] && stepPoints.push(points[i]);
  27824. return stepPoints;
  27825. }
  27826. function getVisualGradient(data, coordSys) {
  27827. var visualMetaList = data.getVisual('visualMeta');
  27828. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  27829. // When data.count() is 0, gradient range can not be calculated.
  27830. return;
  27831. }
  27832. var visualMeta;
  27833. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  27834. // Can only be x or y
  27835. if (visualMetaList[i].dimension < 2) {
  27836. visualMeta = visualMetaList[i];
  27837. break;
  27838. }
  27839. }
  27840. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  27841. if (__DEV__) {
  27842. console.warn('Visual map on line style only support x or y dimension.');
  27843. }
  27844. return;
  27845. }
  27846. // If the area to be rendered is bigger than area defined by LinearGradient,
  27847. // the canvas spec prescribes that the color of the first stop and the last
  27848. // stop should be used. But if two stops are added at offset 0, in effect
  27849. // browsers use the color of the second stop to render area outside
  27850. // LinearGradient. So we can only infinitesimally extend area defined in
  27851. // LinearGradient to render `outerColors`.
  27852. var dimension = visualMeta.dimension;
  27853. var dimName = data.dimensions[dimension];
  27854. var axis = coordSys.getAxis(dimName);
  27855. // dataToCoor mapping may not be linear, but must be monotonic.
  27856. var colorStops = map(visualMeta.stops, function (stop) {
  27857. return {
  27858. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  27859. color: stop.color
  27860. };
  27861. });
  27862. var stopLen = colorStops.length;
  27863. var outerColors = visualMeta.outerColors.slice();
  27864. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  27865. colorStops.reverse();
  27866. outerColors.reverse();
  27867. }
  27868. var tinyExtent = 10; // Arbitrary value: 10px
  27869. var minCoord = colorStops[0].coord - tinyExtent;
  27870. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  27871. var coordSpan = maxCoord - minCoord;
  27872. if (coordSpan < 1e-3) {
  27873. return 'transparent';
  27874. }
  27875. each$1(colorStops, function (stop) {
  27876. stop.offset = (stop.coord - minCoord) / coordSpan;
  27877. });
  27878. colorStops.push({
  27879. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  27880. color: outerColors[1] || 'transparent'
  27881. });
  27882. colorStops.unshift({ // notice colorStops.length have been changed.
  27883. offset: stopLen ? colorStops[0].offset : 0.5,
  27884. color: outerColors[0] || 'transparent'
  27885. });
  27886. // zrUtil.each(colorStops, function (colorStop) {
  27887. // // Make sure each offset has rounded px to avoid not sharp edge
  27888. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  27889. // });
  27890. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  27891. gradient[dimName] = minCoord;
  27892. gradient[dimName + '2'] = maxCoord;
  27893. return gradient;
  27894. }
  27895. Chart.extend({
  27896. type: 'line',
  27897. init: function () {
  27898. var lineGroup = new Group();
  27899. var symbolDraw = new SymbolDraw();
  27900. this.group.add(symbolDraw.group);
  27901. this._symbolDraw = symbolDraw;
  27902. this._lineGroup = lineGroup;
  27903. },
  27904. render: function (seriesModel, ecModel, api) {
  27905. var coordSys = seriesModel.coordinateSystem;
  27906. var group = this.group;
  27907. var data = seriesModel.getData();
  27908. var lineStyleModel = seriesModel.getModel('lineStyle');
  27909. var areaStyleModel = seriesModel.getModel('areaStyle');
  27910. var points = data.mapArray(data.getItemLayout, true);
  27911. var isCoordSysPolar = coordSys.type === 'polar';
  27912. var prevCoordSys = this._coordSys;
  27913. var symbolDraw = this._symbolDraw;
  27914. var polyline = this._polyline;
  27915. var polygon = this._polygon;
  27916. var lineGroup = this._lineGroup;
  27917. var hasAnimation = seriesModel.get('animation');
  27918. var isAreaChart = !areaStyleModel.isEmpty();
  27919. var origin = areaStyleModel.get('origin');
  27920. var stackedOnPoints = getStackedOnPoints(seriesModel, coordSys, data, origin);
  27921. var showSymbol = seriesModel.get('showSymbol');
  27922. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  27923. && this._getSymbolIgnoreFunc(data, coordSys);
  27924. // Remove temporary symbols
  27925. var oldData = this._data;
  27926. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  27927. if (el.__temp) {
  27928. group.remove(el);
  27929. oldData.setItemGraphicEl(idx, null);
  27930. }
  27931. });
  27932. // Remove previous created symbols if showSymbol changed to false
  27933. if (!showSymbol) {
  27934. symbolDraw.remove();
  27935. }
  27936. group.add(lineGroup);
  27937. // FIXME step not support polar
  27938. var step = !isCoordSysPolar && seriesModel.get('step');
  27939. // Initialization animation or coordinate system changed
  27940. if (
  27941. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  27942. ) {
  27943. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  27944. if (step) {
  27945. // TODO If stacked series is not step
  27946. points = turnPointsIntoStep(points, coordSys, step);
  27947. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  27948. }
  27949. polyline = this._newPolyline(points, coordSys, hasAnimation);
  27950. if (isAreaChart) {
  27951. polygon = this._newPolygon(
  27952. points, stackedOnPoints,
  27953. coordSys, hasAnimation
  27954. );
  27955. }
  27956. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  27957. }
  27958. else {
  27959. if (isAreaChart && !polygon) {
  27960. // If areaStyle is added
  27961. polygon = this._newPolygon(
  27962. points, stackedOnPoints,
  27963. coordSys, hasAnimation
  27964. );
  27965. }
  27966. else if (polygon && !isAreaChart) {
  27967. // If areaStyle is removed
  27968. lineGroup.remove(polygon);
  27969. polygon = this._polygon = null;
  27970. }
  27971. // Update clipPath
  27972. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  27973. // Always update, or it is wrong in the case turning on legend
  27974. // because points are not changed
  27975. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  27976. // Stop symbol animation and sync with line points
  27977. // FIXME performance?
  27978. data.eachItemGraphicEl(function (el) {
  27979. el.stopAnimation(true);
  27980. });
  27981. // In the case data zoom triggerred refreshing frequently
  27982. // Data may not change if line has a category axis. So it should animate nothing
  27983. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  27984. || !isPointsSame(this._points, points)
  27985. ) {
  27986. if (hasAnimation) {
  27987. this._updateAnimation(
  27988. data, stackedOnPoints, coordSys, api, step
  27989. );
  27990. }
  27991. else {
  27992. // Not do it in update with animation
  27993. if (step) {
  27994. // TODO If stacked series is not step
  27995. points = turnPointsIntoStep(points, coordSys, step);
  27996. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  27997. }
  27998. polyline.setShape({
  27999. points: points
  28000. });
  28001. polygon && polygon.setShape({
  28002. points: points,
  28003. stackedOnPoints: stackedOnPoints
  28004. });
  28005. }
  28006. }
  28007. }
  28008. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28009. polyline.useStyle(defaults(
  28010. // Use color in lineStyle first
  28011. lineStyleModel.getLineStyle(),
  28012. {
  28013. fill: 'none',
  28014. stroke: visualColor,
  28015. lineJoin: 'bevel'
  28016. }
  28017. ));
  28018. var smooth = seriesModel.get('smooth');
  28019. smooth = getSmooth(seriesModel.get('smooth'));
  28020. polyline.setShape({
  28021. smooth: smooth,
  28022. smoothMonotone: seriesModel.get('smoothMonotone'),
  28023. connectNulls: seriesModel.get('connectNulls')
  28024. });
  28025. if (polygon) {
  28026. var stackedOn = data.stackedOn;
  28027. var stackedOnSmooth = 0;
  28028. polygon.useStyle(defaults(
  28029. areaStyleModel.getAreaStyle(),
  28030. {
  28031. fill: visualColor,
  28032. opacity: 0.7,
  28033. lineJoin: 'bevel'
  28034. }
  28035. ));
  28036. if (stackedOn) {
  28037. var stackedOnSeries = stackedOn.hostModel;
  28038. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28039. }
  28040. polygon.setShape({
  28041. smooth: smooth,
  28042. stackedOnSmooth: stackedOnSmooth,
  28043. smoothMonotone: seriesModel.get('smoothMonotone'),
  28044. connectNulls: seriesModel.get('connectNulls')
  28045. });
  28046. }
  28047. this._data = data;
  28048. // Save the coordinate system for transition animation when data changed
  28049. this._coordSys = coordSys;
  28050. this._stackedOnPoints = stackedOnPoints;
  28051. this._points = points;
  28052. this._step = step;
  28053. },
  28054. dispose: function () {},
  28055. highlight: function (seriesModel, ecModel, api, payload) {
  28056. var data = seriesModel.getData();
  28057. var dataIndex = queryDataIndex(data, payload);
  28058. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28059. var symbol = data.getItemGraphicEl(dataIndex);
  28060. if (!symbol) {
  28061. // Create a temporary symbol if it is not exists
  28062. var pt = data.getItemLayout(dataIndex);
  28063. if (!pt) {
  28064. // Null data
  28065. return;
  28066. }
  28067. symbol = new SymbolClz$1(data, dataIndex);
  28068. symbol.position = pt;
  28069. symbol.setZ(
  28070. seriesModel.get('zlevel'),
  28071. seriesModel.get('z')
  28072. );
  28073. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28074. symbol.__temp = true;
  28075. data.setItemGraphicEl(dataIndex, symbol);
  28076. // Stop scale animation
  28077. symbol.stopSymbolAnimation(true);
  28078. this.group.add(symbol);
  28079. }
  28080. symbol.highlight();
  28081. }
  28082. else {
  28083. // Highlight whole series
  28084. Chart.prototype.highlight.call(
  28085. this, seriesModel, ecModel, api, payload
  28086. );
  28087. }
  28088. },
  28089. downplay: function (seriesModel, ecModel, api, payload) {
  28090. var data = seriesModel.getData();
  28091. var dataIndex = queryDataIndex(data, payload);
  28092. if (dataIndex != null && dataIndex >= 0) {
  28093. var symbol = data.getItemGraphicEl(dataIndex);
  28094. if (symbol) {
  28095. if (symbol.__temp) {
  28096. data.setItemGraphicEl(dataIndex, null);
  28097. this.group.remove(symbol);
  28098. }
  28099. else {
  28100. symbol.downplay();
  28101. }
  28102. }
  28103. }
  28104. else {
  28105. // FIXME
  28106. // can not downplay completely.
  28107. // Downplay whole series
  28108. Chart.prototype.downplay.call(
  28109. this, seriesModel, ecModel, api, payload
  28110. );
  28111. }
  28112. },
  28113. /**
  28114. * @param {module:zrender/container/Group} group
  28115. * @param {Array.<Array.<number>>} points
  28116. * @private
  28117. */
  28118. _newPolyline: function (points) {
  28119. var polyline = this._polyline;
  28120. // Remove previous created polyline
  28121. if (polyline) {
  28122. this._lineGroup.remove(polyline);
  28123. }
  28124. polyline = new Polyline$1({
  28125. shape: {
  28126. points: points
  28127. },
  28128. silent: true,
  28129. z2: 10
  28130. });
  28131. this._lineGroup.add(polyline);
  28132. this._polyline = polyline;
  28133. return polyline;
  28134. },
  28135. /**
  28136. * @param {module:zrender/container/Group} group
  28137. * @param {Array.<Array.<number>>} stackedOnPoints
  28138. * @param {Array.<Array.<number>>} points
  28139. * @private
  28140. */
  28141. _newPolygon: function (points, stackedOnPoints) {
  28142. var polygon = this._polygon;
  28143. // Remove previous created polygon
  28144. if (polygon) {
  28145. this._lineGroup.remove(polygon);
  28146. }
  28147. polygon = new Polygon$1({
  28148. shape: {
  28149. points: points,
  28150. stackedOnPoints: stackedOnPoints
  28151. },
  28152. silent: true
  28153. });
  28154. this._lineGroup.add(polygon);
  28155. this._polygon = polygon;
  28156. return polygon;
  28157. },
  28158. /**
  28159. * @private
  28160. */
  28161. _getSymbolIgnoreFunc: function (data, coordSys) {
  28162. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28163. // `getLabelInterval` is provided by echarts/component/axis
  28164. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28165. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28166. }
  28167. },
  28168. /**
  28169. * @private
  28170. */
  28171. // FIXME Two value axis
  28172. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  28173. var polyline = this._polyline;
  28174. var polygon = this._polygon;
  28175. var seriesModel = data.hostModel;
  28176. var diff = lineAnimationDiff(
  28177. this._data, data,
  28178. this._stackedOnPoints, stackedOnPoints,
  28179. this._coordSys, coordSys
  28180. );
  28181. var current = diff.current;
  28182. var stackedOnCurrent = diff.stackedOnCurrent;
  28183. var next = diff.next;
  28184. var stackedOnNext = diff.stackedOnNext;
  28185. if (step) {
  28186. // TODO If stacked series is not step
  28187. current = turnPointsIntoStep(diff.current, coordSys, step);
  28188. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28189. next = turnPointsIntoStep(diff.next, coordSys, step);
  28190. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28191. }
  28192. // `diff.current` is subset of `current` (which should be ensured by
  28193. // turnPointsIntoStep), so points in `__points` can be updated when
  28194. // points in `current` are update during animation.
  28195. polyline.shape.__points = diff.current;
  28196. polyline.shape.points = current;
  28197. updateProps(polyline, {
  28198. shape: {
  28199. points: next
  28200. }
  28201. }, seriesModel);
  28202. if (polygon) {
  28203. polygon.setShape({
  28204. points: current,
  28205. stackedOnPoints: stackedOnCurrent
  28206. });
  28207. updateProps(polygon, {
  28208. shape: {
  28209. points: next,
  28210. stackedOnPoints: stackedOnNext
  28211. }
  28212. }, seriesModel);
  28213. }
  28214. var updatedDataInfo = [];
  28215. var diffStatus = diff.status;
  28216. for (var i = 0; i < diffStatus.length; i++) {
  28217. var cmd = diffStatus[i].cmd;
  28218. if (cmd === '=') {
  28219. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28220. if (el) {
  28221. updatedDataInfo.push({
  28222. el: el,
  28223. ptIdx: i // Index of points
  28224. });
  28225. }
  28226. }
  28227. }
  28228. if (polyline.animators && polyline.animators.length) {
  28229. polyline.animators[0].during(function () {
  28230. for (var i = 0; i < updatedDataInfo.length; i++) {
  28231. var el = updatedDataInfo[i].el;
  28232. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28233. }
  28234. });
  28235. }
  28236. },
  28237. remove: function (ecModel) {
  28238. var group = this.group;
  28239. var oldData = this._data;
  28240. this._lineGroup.removeAll();
  28241. this._symbolDraw.remove(true);
  28242. // Remove temporary created elements when highlighting
  28243. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28244. if (el.__temp) {
  28245. group.remove(el);
  28246. oldData.setItemGraphicEl(idx, null);
  28247. }
  28248. });
  28249. this._polyline =
  28250. this._polygon =
  28251. this._coordSys =
  28252. this._points =
  28253. this._stackedOnPoints =
  28254. this._data = null;
  28255. }
  28256. });
  28257. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28258. // Encoding visual for all series include which is filtered for legend drawing
  28259. return {
  28260. seriesType: seriesType,
  28261. performRawSeries: true,
  28262. reset: function (seriesModel, ecModel, api) {
  28263. var data = seriesModel.getData();
  28264. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28265. var symbolSize = seriesModel.get('symbolSize');
  28266. data.setVisual({
  28267. legendSymbol: legendSymbol || symbolType,
  28268. symbol: symbolType,
  28269. symbolSize: symbolSize
  28270. });
  28271. // Only visible series has each data be visual encoded
  28272. if (ecModel.isSeriesFiltered(seriesModel)) {
  28273. return;
  28274. }
  28275. var hasCallback = typeof symbolSize === 'function';
  28276. function dataEach(data, idx) {
  28277. if (typeof symbolSize === 'function') {
  28278. var rawValue = seriesModel.getRawValue(idx);
  28279. // FIXME
  28280. var params = seriesModel.getDataParams(idx);
  28281. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28282. }
  28283. if (data.hasItemOption) {
  28284. var itemModel = data.getItemModel(idx);
  28285. var itemSymbolType = itemModel.getShallow('symbol', true);
  28286. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28287. // If has item symbol
  28288. if (itemSymbolType != null) {
  28289. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28290. }
  28291. if (itemSymbolSize != null) {
  28292. // PENDING Transform symbolSize ?
  28293. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  28294. }
  28295. }
  28296. }
  28297. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  28298. }
  28299. };
  28300. };
  28301. var pointsLayout = function (seriesType) {
  28302. return {
  28303. seriesType: seriesType,
  28304. plan: createRenderPlanner(),
  28305. reset: function (seriesModel) {
  28306. var data = seriesModel.getData();
  28307. var coordSys = seriesModel.coordinateSystem;
  28308. var pipelineContext = seriesModel.pipelineContext;
  28309. var isLargeRender = pipelineContext.large;
  28310. if (!coordSys) {
  28311. return;
  28312. }
  28313. var dims = map(coordSys.dimensions, function (dim) {
  28314. return data.getDimension(data.mapDimension(dim));
  28315. }).slice(0, 2);
  28316. var dimLen = dims.length;
  28317. function progress(params, data) {
  28318. var segCount = params.end - params.start;
  28319. var points = isLargeRender && new Float32Array(segCount * dimLen);
  28320. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  28321. var point;
  28322. if (dimLen === 1) {
  28323. var x = data.get(dims[0], i, true);
  28324. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  28325. }
  28326. else {
  28327. var x = tmpIn[0] = data.get(dims[0], i, true);
  28328. var y = tmpIn[1] = data.get(dims[1], i, true);
  28329. // Also {Array.<number>}, not undefined to avoid if...else... statement
  28330. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  28331. }
  28332. if (isLargeRender) {
  28333. points[offset++] = point ? point[0] : NaN;
  28334. points[offset++] = point ? point[1] : NaN;
  28335. }
  28336. else {
  28337. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  28338. }
  28339. }
  28340. isLargeRender && data.setLayout('symbolPoints', points);
  28341. }
  28342. return dimLen && {progress: progress};
  28343. }
  28344. };
  28345. };
  28346. var samplers = {
  28347. average: function (frame) {
  28348. var sum = 0;
  28349. var count = 0;
  28350. for (var i = 0; i < frame.length; i++) {
  28351. if (!isNaN(frame[i])) {
  28352. sum += frame[i];
  28353. count++;
  28354. }
  28355. }
  28356. // Return NaN if count is 0
  28357. return count === 0 ? NaN : sum / count;
  28358. },
  28359. sum: function (frame) {
  28360. var sum = 0;
  28361. for (var i = 0; i < frame.length; i++) {
  28362. // Ignore NaN
  28363. sum += frame[i] || 0;
  28364. }
  28365. return sum;
  28366. },
  28367. max: function (frame) {
  28368. var max = -Infinity;
  28369. for (var i = 0; i < frame.length; i++) {
  28370. frame[i] > max && (max = frame[i]);
  28371. }
  28372. return max;
  28373. },
  28374. min: function (frame) {
  28375. var min = Infinity;
  28376. for (var i = 0; i < frame.length; i++) {
  28377. frame[i] < min && (min = frame[i]);
  28378. }
  28379. return min;
  28380. },
  28381. // TODO
  28382. // Median
  28383. nearest: function (frame) {
  28384. return frame[0];
  28385. }
  28386. };
  28387. var indexSampler = function (frame, value) {
  28388. return Math.round(frame.length / 2);
  28389. };
  28390. var dataSample = function (seriesType) {
  28391. return {
  28392. seriesType: seriesType,
  28393. reset: function (seriesModel, ecModel, api) {
  28394. var data = seriesModel.getData();
  28395. var sampling = seriesModel.get('sampling');
  28396. var coordSys = seriesModel.coordinateSystem;
  28397. // Only cartesian2d support down sampling
  28398. if (coordSys.type === 'cartesian2d' && sampling) {
  28399. var baseAxis = coordSys.getBaseAxis();
  28400. var valueAxis = coordSys.getOtherAxis(baseAxis);
  28401. var extent = baseAxis.getExtent();
  28402. // Coordinste system has been resized
  28403. var size = extent[1] - extent[0];
  28404. var rate = Math.round(data.count() / size);
  28405. if (rate > 1) {
  28406. var sampler;
  28407. if (typeof sampling === 'string') {
  28408. sampler = samplers[sampling];
  28409. }
  28410. else if (typeof sampling === 'function') {
  28411. sampler = sampling;
  28412. }
  28413. if (sampler) {
  28414. seriesModel.setData(data.downSample(
  28415. valueAxis.dim, 1 / rate, sampler, indexSampler
  28416. ));
  28417. }
  28418. }
  28419. }
  28420. }
  28421. };
  28422. };
  28423. /**
  28424. * Cartesian coordinate system
  28425. * @module echarts/coord/Cartesian
  28426. *
  28427. */
  28428. function dimAxisMapper(dim) {
  28429. return this._axes[dim];
  28430. }
  28431. /**
  28432. * @alias module:echarts/coord/Cartesian
  28433. * @constructor
  28434. */
  28435. var Cartesian = function (name) {
  28436. this._axes = {};
  28437. this._dimList = [];
  28438. /**
  28439. * @type {string}
  28440. */
  28441. this.name = name || '';
  28442. };
  28443. Cartesian.prototype = {
  28444. constructor: Cartesian,
  28445. type: 'cartesian',
  28446. /**
  28447. * Get axis
  28448. * @param {number|string} dim
  28449. * @return {module:echarts/coord/Cartesian~Axis}
  28450. */
  28451. getAxis: function (dim) {
  28452. return this._axes[dim];
  28453. },
  28454. /**
  28455. * Get axes list
  28456. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  28457. */
  28458. getAxes: function () {
  28459. return map(this._dimList, dimAxisMapper, this);
  28460. },
  28461. /**
  28462. * Get axes list by given scale type
  28463. */
  28464. getAxesByScale: function (scaleType) {
  28465. scaleType = scaleType.toLowerCase();
  28466. return filter(
  28467. this.getAxes(),
  28468. function (axis) {
  28469. return axis.scale.type === scaleType;
  28470. }
  28471. );
  28472. },
  28473. /**
  28474. * Add axis
  28475. * @param {module:echarts/coord/Cartesian.Axis}
  28476. */
  28477. addAxis: function (axis) {
  28478. var dim = axis.dim;
  28479. this._axes[dim] = axis;
  28480. this._dimList.push(dim);
  28481. },
  28482. /**
  28483. * Convert data to coord in nd space
  28484. * @param {Array.<number>|Object.<string, number>} val
  28485. * @return {Array.<number>|Object.<string, number>}
  28486. */
  28487. dataToCoord: function (val) {
  28488. return this._dataCoordConvert(val, 'dataToCoord');
  28489. },
  28490. /**
  28491. * Convert coord in nd space to data
  28492. * @param {Array.<number>|Object.<string, number>} val
  28493. * @return {Array.<number>|Object.<string, number>}
  28494. */
  28495. coordToData: function (val) {
  28496. return this._dataCoordConvert(val, 'coordToData');
  28497. },
  28498. _dataCoordConvert: function (input, method) {
  28499. var dimList = this._dimList;
  28500. var output = input instanceof Array ? [] : {};
  28501. for (var i = 0; i < dimList.length; i++) {
  28502. var dim = dimList[i];
  28503. var axis = this._axes[dim];
  28504. output[dim] = axis[method](input[dim]);
  28505. }
  28506. return output;
  28507. }
  28508. };
  28509. function Cartesian2D(name) {
  28510. Cartesian.call(this, name);
  28511. }
  28512. Cartesian2D.prototype = {
  28513. constructor: Cartesian2D,
  28514. type: 'cartesian2d',
  28515. /**
  28516. * @type {Array.<string>}
  28517. * @readOnly
  28518. */
  28519. dimensions: ['x', 'y'],
  28520. /**
  28521. * Base axis will be used on stacking.
  28522. *
  28523. * @return {module:echarts/coord/cartesian/Axis2D}
  28524. */
  28525. getBaseAxis: function () {
  28526. return this.getAxesByScale('ordinal')[0]
  28527. || this.getAxesByScale('time')[0]
  28528. || this.getAxis('x');
  28529. },
  28530. /**
  28531. * If contain point
  28532. * @param {Array.<number>} point
  28533. * @return {boolean}
  28534. */
  28535. containPoint: function (point) {
  28536. var axisX = this.getAxis('x');
  28537. var axisY = this.getAxis('y');
  28538. return axisX.contain(axisX.toLocalCoord(point[0]))
  28539. && axisY.contain(axisY.toLocalCoord(point[1]));
  28540. },
  28541. /**
  28542. * If contain data
  28543. * @param {Array.<number>} data
  28544. * @return {boolean}
  28545. */
  28546. containData: function (data) {
  28547. return this.getAxis('x').containData(data[0])
  28548. && this.getAxis('y').containData(data[1]);
  28549. },
  28550. /**
  28551. * @param {Array.<number>} data
  28552. * @param {Array.<number>} out
  28553. * @return {Array.<number>}
  28554. */
  28555. dataToPoint: function (data, reserved, out) {
  28556. var xAxis = this.getAxis('x');
  28557. var yAxis = this.getAxis('y');
  28558. out = out || [];
  28559. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  28560. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  28561. return out;
  28562. },
  28563. /**
  28564. * @param {Array.<number>} data
  28565. * @param {Array.<number>} out
  28566. * @return {Array.<number>}
  28567. */
  28568. clampData: function (data, out) {
  28569. var xAxisExtent = this.getAxis('x').scale.getExtent();
  28570. var yAxisExtent = this.getAxis('y').scale.getExtent();
  28571. out = out || [];
  28572. out[0] = Math.min(
  28573. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  28574. Math.max(xAxisExtent[0], xAxisExtent[1])
  28575. );
  28576. out[1] = Math.min(
  28577. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  28578. Math.max(yAxisExtent[0], yAxisExtent[1])
  28579. );
  28580. return out;
  28581. },
  28582. /**
  28583. * @param {Array.<number>} point
  28584. * @param {Array.<number>} out
  28585. * @return {Array.<number>}
  28586. */
  28587. pointToData: function (point, out) {
  28588. var xAxis = this.getAxis('x');
  28589. var yAxis = this.getAxis('y');
  28590. out = out || [];
  28591. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  28592. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  28593. return out;
  28594. },
  28595. /**
  28596. * Get other axis
  28597. * @param {module:echarts/coord/cartesian/Axis2D} axis
  28598. */
  28599. getOtherAxis: function (axis) {
  28600. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  28601. }
  28602. };
  28603. inherits(Cartesian2D, Cartesian);
  28604. /**
  28605. * Extend axis 2d
  28606. * @constructor module:echarts/coord/cartesian/Axis2D
  28607. * @extends {module:echarts/coord/cartesian/Axis}
  28608. * @param {string} dim
  28609. * @param {*} scale
  28610. * @param {Array.<number>} coordExtent
  28611. * @param {string} axisType
  28612. * @param {string} position
  28613. */
  28614. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  28615. Axis.call(this, dim, scale, coordExtent);
  28616. /**
  28617. * Axis type
  28618. * - 'category'
  28619. * - 'value'
  28620. * - 'time'
  28621. * - 'log'
  28622. * @type {string}
  28623. */
  28624. this.type = axisType || 'value';
  28625. /**
  28626. * Axis position
  28627. * - 'top'
  28628. * - 'bottom'
  28629. * - 'left'
  28630. * - 'right'
  28631. */
  28632. this.position = position || 'bottom';
  28633. };
  28634. Axis2D.prototype = {
  28635. constructor: Axis2D,
  28636. /**
  28637. * Index of axis, can be used as key
  28638. */
  28639. index: 0,
  28640. /**
  28641. * If axis is on the zero position of the other axis
  28642. * @type {boolean}
  28643. */
  28644. onZero: false,
  28645. /**
  28646. * Axis model
  28647. * @param {module:echarts/coord/cartesian/AxisModel}
  28648. */
  28649. model: null,
  28650. isHorizontal: function () {
  28651. var position = this.position;
  28652. return position === 'top' || position === 'bottom';
  28653. },
  28654. /**
  28655. * Each item cooresponds to this.getExtent(), which
  28656. * means globalExtent[0] may greater than globalExtent[1],
  28657. * unless `asc` is input.
  28658. *
  28659. * @param {boolean} [asc]
  28660. * @return {Array.<number>}
  28661. */
  28662. getGlobalExtent: function (asc) {
  28663. var ret = this.getExtent();
  28664. ret[0] = this.toGlobalCoord(ret[0]);
  28665. ret[1] = this.toGlobalCoord(ret[1]);
  28666. asc && ret[0] > ret[1] && ret.reverse();
  28667. return ret;
  28668. },
  28669. getOtherAxis: function () {
  28670. this.grid.getOtherAxis();
  28671. },
  28672. /**
  28673. * If label is ignored.
  28674. * Automatically used when axis is category and label can not be all shown
  28675. * @param {number} idx
  28676. * @return {boolean}
  28677. */
  28678. isLabelIgnored: function (idx) {
  28679. if (this.type === 'category') {
  28680. var labelInterval = this.getLabelInterval();
  28681. return ((typeof labelInterval === 'function')
  28682. && !labelInterval(idx, this.scale.getLabel(idx)))
  28683. || idx % (labelInterval + 1);
  28684. }
  28685. },
  28686. /**
  28687. * @override
  28688. */
  28689. pointToData: function (point, clamp) {
  28690. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  28691. },
  28692. /**
  28693. * Transform global coord to local coord,
  28694. * i.e. var localCoord = axis.toLocalCoord(80);
  28695. * designate by module:echarts/coord/cartesian/Grid.
  28696. * @type {Function}
  28697. */
  28698. toLocalCoord: null,
  28699. /**
  28700. * Transform global coord to local coord,
  28701. * i.e. var globalCoord = axis.toLocalCoord(40);
  28702. * designate by module:echarts/coord/cartesian/Grid.
  28703. * @type {Function}
  28704. */
  28705. toGlobalCoord: null
  28706. };
  28707. inherits(Axis2D, Axis);
  28708. var defaultOption = {
  28709. show: true,
  28710. zlevel: 0, // 一级层叠
  28711. z: 0, // 二级层叠
  28712. // 反向坐标轴
  28713. inverse: false,
  28714. // 坐标轴名字,默认为空
  28715. name: '',
  28716. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  28717. nameLocation: 'end',
  28718. // 坐标轴名字旋转,degree。
  28719. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  28720. nameTruncate: {
  28721. maxWidth: null,
  28722. ellipsis: '...',
  28723. placeholder: '.'
  28724. },
  28725. // 坐标轴文字样式,默认取全局样式
  28726. nameTextStyle: {},
  28727. // 文字与轴线距离
  28728. nameGap: 15,
  28729. silent: false, // Default false to support tooltip.
  28730. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  28731. tooltip: {
  28732. show: false
  28733. },
  28734. axisPointer: {},
  28735. // 坐标轴线
  28736. axisLine: {
  28737. // 默认显示,属性show控制显示与否
  28738. show: true,
  28739. onZero: true,
  28740. onZeroAxisIndex: null,
  28741. // 属性lineStyle控制线条样式
  28742. lineStyle: {
  28743. color: '#333',
  28744. width: 1,
  28745. type: 'solid'
  28746. },
  28747. // 坐标轴两端的箭头
  28748. symbol: ['none', 'none'],
  28749. symbolSize: [10, 15]
  28750. },
  28751. // 坐标轴小标记
  28752. axisTick: {
  28753. // 属性show控制显示与否,默认显示
  28754. show: true,
  28755. // 控制小标记是否在grid里
  28756. inside: false,
  28757. // 属性length控制线长
  28758. length: 5,
  28759. // 属性lineStyle控制线条样式
  28760. lineStyle: {
  28761. width: 1
  28762. }
  28763. },
  28764. // 坐标轴文本标签,详见axis.axisLabel
  28765. axisLabel: {
  28766. show: true,
  28767. // 控制文本标签是否在grid里
  28768. inside: false,
  28769. rotate: 0,
  28770. showMinLabel: null, // true | false | null (auto)
  28771. showMaxLabel: null, // true | false | null (auto)
  28772. margin: 8,
  28773. // formatter: null,
  28774. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  28775. fontSize: 12
  28776. },
  28777. // 分隔线
  28778. splitLine: {
  28779. // 默认显示,属性show控制显示与否
  28780. show: true,
  28781. // 属性lineStyle(详见lineStyle)控制线条样式
  28782. lineStyle: {
  28783. color: ['#ccc'],
  28784. width: 1,
  28785. type: 'solid'
  28786. }
  28787. },
  28788. // 分隔区域
  28789. splitArea: {
  28790. // 默认不显示,属性show控制显示与否
  28791. show: false,
  28792. // 属性areaStyle(详见areaStyle)控制区域样式
  28793. areaStyle: {
  28794. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  28795. }
  28796. }
  28797. };
  28798. var axisDefault = {};
  28799. axisDefault.categoryAxis = merge({
  28800. // 类目起始和结束两端空白策略
  28801. boundaryGap: true,
  28802. // Set false to faster category collection.
  28803. // Only usefull in the case like: category is
  28804. // ['2012-01-01', '2012-01-02', ...], where the input
  28805. // data has been ensured not duplicate and is large data.
  28806. // null means "auto":
  28807. // if axis.data provided, do not deduplication,
  28808. // else do deduplication.
  28809. deduplication: null,
  28810. // splitArea: {
  28811. // show: false
  28812. // },
  28813. splitLine: {
  28814. show: false
  28815. },
  28816. // 坐标轴小标记
  28817. axisTick: {
  28818. // If tick is align with label when boundaryGap is true
  28819. alignWithLabel: false,
  28820. interval: 'auto'
  28821. },
  28822. // 坐标轴文本标签,详见axis.axisLabel
  28823. axisLabel: {
  28824. interval: 'auto'
  28825. }
  28826. }, defaultOption);
  28827. axisDefault.valueAxis = merge({
  28828. // 数值起始和结束两端空白策略
  28829. boundaryGap: [0, 0],
  28830. // TODO
  28831. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  28832. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  28833. // min: null,
  28834. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  28835. // max: null,
  28836. // Readonly prop, specifies start value of the range when using data zoom.
  28837. // rangeStart: null
  28838. // Readonly prop, specifies end value of the range when using data zoom.
  28839. // rangeEnd: null
  28840. // 脱离0值比例,放大聚焦到最终_min,_max区间
  28841. // scale: false,
  28842. // 分割段数,默认为5
  28843. splitNumber: 5
  28844. // Minimum interval
  28845. // minInterval: null
  28846. // maxInterval: null
  28847. }, defaultOption);
  28848. // FIXME
  28849. axisDefault.timeAxis = defaults({
  28850. scale: true,
  28851. min: 'dataMin',
  28852. max: 'dataMax'
  28853. }, axisDefault.valueAxis);
  28854. axisDefault.logAxis = defaults({
  28855. scale: true,
  28856. logBase: 10
  28857. }, axisDefault.valueAxis);
  28858. // FIXME axisType is fixed ?
  28859. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  28860. /**
  28861. * Generate sub axis model class
  28862. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  28863. * @param {module:echarts/model/Component} BaseAxisModelClass
  28864. * @param {Function} axisTypeDefaulter
  28865. * @param {Object} [extraDefaultOption]
  28866. */
  28867. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  28868. each$1(AXIS_TYPES, function (axisType) {
  28869. BaseAxisModelClass.extend({
  28870. /**
  28871. * @readOnly
  28872. */
  28873. type: axisName + 'Axis.' + axisType,
  28874. mergeDefaultAndTheme: function (option, ecModel) {
  28875. var layoutMode = this.layoutMode;
  28876. var inputPositionParams = layoutMode
  28877. ? getLayoutParams(option) : {};
  28878. var themeModel = ecModel.getTheme();
  28879. merge(option, themeModel.get(axisType + 'Axis'));
  28880. merge(option, this.getDefaultOption());
  28881. option.type = axisTypeDefaulter(axisName, option);
  28882. if (layoutMode) {
  28883. mergeLayoutParam(option, inputPositionParams, layoutMode);
  28884. }
  28885. },
  28886. /**
  28887. * @override
  28888. */
  28889. optionUpdated: function () {
  28890. var thisOption = this.option;
  28891. if (thisOption.type === 'category') {
  28892. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  28893. }
  28894. },
  28895. /**
  28896. * Should not be called before all of 'getInitailData' finished.
  28897. * Because categories are collected during initializing data.
  28898. */
  28899. getCategories: function () {
  28900. // FIXME
  28901. // warning if called before all of 'getInitailData' finished.
  28902. if (this.option.type === 'category') {
  28903. return this.__ordinalMeta.categories;
  28904. }
  28905. },
  28906. getOrdinalMeta: function () {
  28907. return this.__ordinalMeta;
  28908. },
  28909. defaultOption: mergeAll(
  28910. [
  28911. {},
  28912. axisDefault[axisType + 'Axis'],
  28913. extraDefaultOption
  28914. ],
  28915. true
  28916. )
  28917. });
  28918. });
  28919. ComponentModel.registerSubTypeDefaulter(
  28920. axisName + 'Axis',
  28921. curry(axisTypeDefaulter, axisName)
  28922. );
  28923. };
  28924. var AxisModel = ComponentModel.extend({
  28925. type: 'cartesian2dAxis',
  28926. /**
  28927. * @type {module:echarts/coord/cartesian/Axis2D}
  28928. */
  28929. axis: null,
  28930. /**
  28931. * @override
  28932. */
  28933. init: function () {
  28934. AxisModel.superApply(this, 'init', arguments);
  28935. this.resetRange();
  28936. },
  28937. /**
  28938. * @override
  28939. */
  28940. mergeOption: function () {
  28941. AxisModel.superApply(this, 'mergeOption', arguments);
  28942. this.resetRange();
  28943. },
  28944. /**
  28945. * @override
  28946. */
  28947. restoreData: function () {
  28948. AxisModel.superApply(this, 'restoreData', arguments);
  28949. this.resetRange();
  28950. },
  28951. /**
  28952. * @override
  28953. * @return {module:echarts/model/Component}
  28954. */
  28955. getCoordSysModel: function () {
  28956. return this.ecModel.queryComponents({
  28957. mainType: 'grid',
  28958. index: this.option.gridIndex,
  28959. id: this.option.gridId
  28960. })[0];
  28961. }
  28962. });
  28963. function getAxisType(axisDim, option) {
  28964. // Default axis with data is category axis
  28965. return option.type || (option.data ? 'category' : 'value');
  28966. }
  28967. merge(AxisModel.prototype, axisModelCommonMixin);
  28968. var extraOption = {
  28969. // gridIndex: 0,
  28970. // gridId: '',
  28971. // Offset is for multiple axis on the same position
  28972. offset: 0
  28973. };
  28974. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  28975. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  28976. // Grid 是在有直角坐标系的时候必须要存在的
  28977. // 所以这里也要被 Cartesian2D 依赖
  28978. ComponentModel.extend({
  28979. type: 'grid',
  28980. dependencies: ['xAxis', 'yAxis'],
  28981. layoutMode: 'box',
  28982. /**
  28983. * @type {module:echarts/coord/cartesian/Grid}
  28984. */
  28985. coordinateSystem: null,
  28986. defaultOption: {
  28987. show: false,
  28988. zlevel: 0,
  28989. z: 0,
  28990. left: '10%',
  28991. top: 60,
  28992. right: '10%',
  28993. bottom: 60,
  28994. // If grid size contain label
  28995. containLabel: false,
  28996. // width: {totalWidth} - left - right,
  28997. // height: {totalHeight} - top - bottom,
  28998. backgroundColor: 'rgba(0,0,0,0)',
  28999. borderWidth: 1,
  29000. borderColor: '#ccc'
  29001. }
  29002. });
  29003. /**
  29004. * Grid is a region which contains at most 4 cartesian systems
  29005. *
  29006. * TODO Default cartesian
  29007. */
  29008. // Depends on GridModel, AxisModel, which performs preprocess.
  29009. var each$6 = each$1;
  29010. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29011. var niceScaleExtent$1 = niceScaleExtent;
  29012. /**
  29013. * Check if the axis is used in the specified grid
  29014. * @inner
  29015. */
  29016. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29017. return axisModel.getCoordSysModel() === gridModel;
  29018. }
  29019. function rotateTextRect(textRect, rotate) {
  29020. var rotateRadians = rotate * Math.PI / 180;
  29021. var boundingBox = textRect.plain();
  29022. var beforeWidth = boundingBox.width;
  29023. var beforeHeight = boundingBox.height;
  29024. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29025. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29026. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29027. return rotatedRect;
  29028. }
  29029. function getLabelUnionRect(axis) {
  29030. var axisModel = axis.model;
  29031. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29032. var axisLabelModel = axisModel.getModel('axisLabel');
  29033. var rect;
  29034. var step = 1;
  29035. var labelCount = labels.length;
  29036. if (labelCount > 40) {
  29037. // Simple optimization for large amount of labels
  29038. step = Math.ceil(labelCount / 40);
  29039. }
  29040. for (var i = 0; i < labelCount; i += step) {
  29041. if (!axis.isLabelIgnored(i)) {
  29042. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29043. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29044. rect ? rect.union(singleRect) : (rect = singleRect);
  29045. }
  29046. }
  29047. return rect;
  29048. }
  29049. function Grid(gridModel, ecModel, api) {
  29050. /**
  29051. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29052. * @private
  29053. */
  29054. this._coordsMap = {};
  29055. /**
  29056. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29057. * @private
  29058. */
  29059. this._coordsList = [];
  29060. /**
  29061. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29062. * @private
  29063. */
  29064. this._axesMap = {};
  29065. /**
  29066. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29067. * @private
  29068. */
  29069. this._axesList = [];
  29070. this._initCartesian(gridModel, ecModel, api);
  29071. this.model = gridModel;
  29072. }
  29073. var gridProto = Grid.prototype;
  29074. gridProto.type = 'grid';
  29075. gridProto.axisPointerEnabled = true;
  29076. gridProto.getRect = function () {
  29077. return this._rect;
  29078. };
  29079. gridProto.update = function (ecModel, api) {
  29080. var axesMap = this._axesMap;
  29081. this._updateScale(ecModel, this.model);
  29082. each$6(axesMap.x, function (xAxis) {
  29083. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29084. });
  29085. each$6(axesMap.y, function (yAxis) {
  29086. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29087. });
  29088. each$6(axesMap.x, function (xAxis) {
  29089. fixAxisOnZero(axesMap, 'y', xAxis);
  29090. });
  29091. each$6(axesMap.y, function (yAxis) {
  29092. fixAxisOnZero(axesMap, 'x', yAxis);
  29093. });
  29094. // Resize again if containLabel is enabled
  29095. // FIXME It may cause getting wrong grid size in data processing stage
  29096. this.resize(this.model, api);
  29097. };
  29098. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29099. // onZero can not be enabled in these two situations:
  29100. // 1. When any other axis is a category axis.
  29101. // 2. When no axis is cross 0 point.
  29102. var axes = axesMap[otherAxisDim];
  29103. if (!axis.onZero) {
  29104. return;
  29105. }
  29106. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29107. // If target axis is specified.
  29108. if (onZeroAxisIndex != null) {
  29109. var otherAxis = axes[onZeroAxisIndex];
  29110. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29111. axis.onZero = false;
  29112. }
  29113. return;
  29114. }
  29115. for (var idx in axes) {
  29116. if (axes.hasOwnProperty(idx)) {
  29117. var otherAxis = axes[idx];
  29118. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29119. onZeroAxisIndex = +idx;
  29120. break;
  29121. }
  29122. }
  29123. }
  29124. if (onZeroAxisIndex == null) {
  29125. axis.onZero = false;
  29126. }
  29127. axis.onZeroAxisIndex = onZeroAxisIndex;
  29128. }
  29129. function canNotOnZeroToAxis(axis) {
  29130. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29131. }
  29132. /**
  29133. * Resize the grid
  29134. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29135. * @param {module:echarts/ExtensionAPI} api
  29136. */
  29137. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29138. var gridRect = getLayoutRect(
  29139. gridModel.getBoxLayoutParams(), {
  29140. width: api.getWidth(),
  29141. height: api.getHeight()
  29142. });
  29143. this._rect = gridRect;
  29144. var axesList = this._axesList;
  29145. adjustAxes();
  29146. // Minus label size
  29147. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29148. each$6(axesList, function (axis) {
  29149. if (!axis.model.get('axisLabel.inside')) {
  29150. var labelUnionRect = getLabelUnionRect(axis);
  29151. if (labelUnionRect) {
  29152. var dim = axis.isHorizontal() ? 'height' : 'width';
  29153. var margin = axis.model.get('axisLabel.margin');
  29154. gridRect[dim] -= labelUnionRect[dim] + margin;
  29155. if (axis.position === 'top') {
  29156. gridRect.y += labelUnionRect.height + margin;
  29157. }
  29158. else if (axis.position === 'left') {
  29159. gridRect.x += labelUnionRect.width + margin;
  29160. }
  29161. }
  29162. }
  29163. });
  29164. adjustAxes();
  29165. }
  29166. function adjustAxes() {
  29167. each$6(axesList, function (axis) {
  29168. var isHorizontal = axis.isHorizontal();
  29169. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29170. var idx = axis.inverse ? 1 : 0;
  29171. axis.setExtent(extent[idx], extent[1 - idx]);
  29172. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29173. });
  29174. }
  29175. };
  29176. /**
  29177. * @param {string} axisType
  29178. * @param {number} [axisIndex]
  29179. */
  29180. gridProto.getAxis = function (axisType, axisIndex) {
  29181. var axesMapOnDim = this._axesMap[axisType];
  29182. if (axesMapOnDim != null) {
  29183. if (axisIndex == null) {
  29184. // Find first axis
  29185. for (var name in axesMapOnDim) {
  29186. if (axesMapOnDim.hasOwnProperty(name)) {
  29187. return axesMapOnDim[name];
  29188. }
  29189. }
  29190. }
  29191. return axesMapOnDim[axisIndex];
  29192. }
  29193. };
  29194. /**
  29195. * @return {Array.<module:echarts/coord/Axis>}
  29196. */
  29197. gridProto.getAxes = function () {
  29198. return this._axesList.slice();
  29199. };
  29200. /**
  29201. * Usage:
  29202. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29203. * grid.getCartesian(xAxisIndex);
  29204. * grid.getCartesian(null, yAxisIndex);
  29205. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29206. *
  29207. * @param {number|Object} [xAxisIndex]
  29208. * @param {number} [yAxisIndex]
  29209. */
  29210. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29211. if (xAxisIndex != null && yAxisIndex != null) {
  29212. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29213. return this._coordsMap[key];
  29214. }
  29215. if (isObject$1(xAxisIndex)) {
  29216. yAxisIndex = xAxisIndex.yAxisIndex;
  29217. xAxisIndex = xAxisIndex.xAxisIndex;
  29218. }
  29219. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29220. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29221. if (coordList[i].getAxis('x').index === xAxisIndex
  29222. || coordList[i].getAxis('y').index === yAxisIndex
  29223. ) {
  29224. return coordList[i];
  29225. }
  29226. }
  29227. };
  29228. gridProto.getCartesians = function () {
  29229. return this._coordsList.slice();
  29230. };
  29231. /**
  29232. * @implements
  29233. * see {module:echarts/CoodinateSystem}
  29234. */
  29235. gridProto.convertToPixel = function (ecModel, finder, value) {
  29236. var target = this._findConvertTarget(ecModel, finder);
  29237. return target.cartesian
  29238. ? target.cartesian.dataToPoint(value)
  29239. : target.axis
  29240. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29241. : null;
  29242. };
  29243. /**
  29244. * @implements
  29245. * see {module:echarts/CoodinateSystem}
  29246. */
  29247. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29248. var target = this._findConvertTarget(ecModel, finder);
  29249. return target.cartesian
  29250. ? target.cartesian.pointToData(value)
  29251. : target.axis
  29252. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29253. : null;
  29254. };
  29255. /**
  29256. * @inner
  29257. */
  29258. gridProto._findConvertTarget = function (ecModel, finder) {
  29259. var seriesModel = finder.seriesModel;
  29260. var xAxisModel = finder.xAxisModel
  29261. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29262. var yAxisModel = finder.yAxisModel
  29263. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29264. var gridModel = finder.gridModel;
  29265. var coordsList = this._coordsList;
  29266. var cartesian;
  29267. var axis;
  29268. if (seriesModel) {
  29269. cartesian = seriesModel.coordinateSystem;
  29270. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29271. }
  29272. else if (xAxisModel && yAxisModel) {
  29273. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29274. }
  29275. else if (xAxisModel) {
  29276. axis = this.getAxis('x', xAxisModel.componentIndex);
  29277. }
  29278. else if (yAxisModel) {
  29279. axis = this.getAxis('y', yAxisModel.componentIndex);
  29280. }
  29281. // Lowest priority.
  29282. else if (gridModel) {
  29283. var grid = gridModel.coordinateSystem;
  29284. if (grid === this) {
  29285. cartesian = this._coordsList[0];
  29286. }
  29287. }
  29288. return {cartesian: cartesian, axis: axis};
  29289. };
  29290. /**
  29291. * @implements
  29292. * see {module:echarts/CoodinateSystem}
  29293. */
  29294. gridProto.containPoint = function (point) {
  29295. var coord = this._coordsList[0];
  29296. if (coord) {
  29297. return coord.containPoint(point);
  29298. }
  29299. };
  29300. /**
  29301. * Initialize cartesian coordinate systems
  29302. * @private
  29303. */
  29304. gridProto._initCartesian = function (gridModel, ecModel, api) {
  29305. var axisPositionUsed = {
  29306. left: false,
  29307. right: false,
  29308. top: false,
  29309. bottom: false
  29310. };
  29311. var axesMap = {
  29312. x: {},
  29313. y: {}
  29314. };
  29315. var axesCount = {
  29316. x: 0,
  29317. y: 0
  29318. };
  29319. /// Create axis
  29320. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  29321. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  29322. if (!axesCount.x || !axesCount.y) {
  29323. // Roll back when there no either x or y axis
  29324. this._axesMap = {};
  29325. this._axesList = [];
  29326. return;
  29327. }
  29328. this._axesMap = axesMap;
  29329. /// Create cartesian2d
  29330. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  29331. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  29332. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29333. var cartesian = new Cartesian2D(key);
  29334. cartesian.grid = this;
  29335. cartesian.model = gridModel;
  29336. this._coordsMap[key] = cartesian;
  29337. this._coordsList.push(cartesian);
  29338. cartesian.addAxis(xAxis);
  29339. cartesian.addAxis(yAxis);
  29340. }, this);
  29341. }, this);
  29342. function createAxisCreator(axisType) {
  29343. return function (axisModel, idx) {
  29344. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  29345. return;
  29346. }
  29347. var axisPosition = axisModel.get('position');
  29348. if (axisType === 'x') {
  29349. // Fix position
  29350. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  29351. // Default bottom of X
  29352. axisPosition = 'bottom';
  29353. if (axisPositionUsed[axisPosition]) {
  29354. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  29355. }
  29356. }
  29357. }
  29358. else {
  29359. // Fix position
  29360. if (axisPosition !== 'left' && axisPosition !== 'right') {
  29361. // Default left of Y
  29362. axisPosition = 'left';
  29363. if (axisPositionUsed[axisPosition]) {
  29364. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  29365. }
  29366. }
  29367. }
  29368. axisPositionUsed[axisPosition] = true;
  29369. var axis = new Axis2D(
  29370. axisType, createScaleByModel(axisModel),
  29371. [0, 0],
  29372. axisModel.get('type'),
  29373. axisPosition
  29374. );
  29375. var isCategory = axis.type === 'category';
  29376. axis.onBand = isCategory && axisModel.get('boundaryGap');
  29377. axis.inverse = axisModel.get('inverse');
  29378. axis.onZero = axisModel.get('axisLine.onZero');
  29379. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  29380. // Inject axis into axisModel
  29381. axisModel.axis = axis;
  29382. // Inject axisModel into axis
  29383. axis.model = axisModel;
  29384. // Inject grid info axis
  29385. axis.grid = this;
  29386. // Index of axis, can be used as key
  29387. axis.index = idx;
  29388. this._axesList.push(axis);
  29389. axesMap[axisType][idx] = axis;
  29390. axesCount[axisType]++;
  29391. };
  29392. }
  29393. };
  29394. /**
  29395. * Update cartesian properties from series
  29396. * @param {module:echarts/model/Option} option
  29397. * @private
  29398. */
  29399. gridProto._updateScale = function (ecModel, gridModel) {
  29400. // Reset scale
  29401. each$1(this._axesList, function (axis) {
  29402. axis.scale.setExtent(Infinity, -Infinity);
  29403. });
  29404. ecModel.eachSeries(function (seriesModel) {
  29405. if (isCartesian2D(seriesModel)) {
  29406. var axesModels = findAxesModels(seriesModel, ecModel);
  29407. var xAxisModel = axesModels[0];
  29408. var yAxisModel = axesModels[1];
  29409. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  29410. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  29411. ) {
  29412. return;
  29413. }
  29414. var cartesian = this.getCartesian(
  29415. xAxisModel.componentIndex, yAxisModel.componentIndex
  29416. );
  29417. var data = seriesModel.getData();
  29418. var xAxis = cartesian.getAxis('x');
  29419. var yAxis = cartesian.getAxis('y');
  29420. if (data.type === 'list') {
  29421. unionExtent(data, xAxis, seriesModel);
  29422. unionExtent(data, yAxis, seriesModel);
  29423. }
  29424. }
  29425. }, this);
  29426. function unionExtent(data, axis, seriesModel) {
  29427. each$6(data.mapDimension(axis.dim, true), function (dim) {
  29428. axis.scale.unionExtentFromData(data, dim);
  29429. });
  29430. }
  29431. };
  29432. /**
  29433. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  29434. * @return {Object} {baseAxes: [], otherAxes: []}
  29435. */
  29436. gridProto.getTooltipAxes = function (dim) {
  29437. var baseAxes = [];
  29438. var otherAxes = [];
  29439. each$6(this.getCartesians(), function (cartesian) {
  29440. var baseAxis = (dim != null && dim !== 'auto')
  29441. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  29442. var otherAxis = cartesian.getOtherAxis(baseAxis);
  29443. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  29444. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  29445. });
  29446. return {baseAxes: baseAxes, otherAxes: otherAxes};
  29447. };
  29448. /**
  29449. * @inner
  29450. */
  29451. function updateAxisTransform(axis, coordBase) {
  29452. var axisExtent = axis.getExtent();
  29453. var axisExtentSum = axisExtent[0] + axisExtent[1];
  29454. // Fast transform
  29455. axis.toGlobalCoord = axis.dim === 'x'
  29456. ? function (coord) {
  29457. return coord + coordBase;
  29458. }
  29459. : function (coord) {
  29460. return axisExtentSum - coord + coordBase;
  29461. };
  29462. axis.toLocalCoord = axis.dim === 'x'
  29463. ? function (coord) {
  29464. return coord - coordBase;
  29465. }
  29466. : function (coord) {
  29467. return axisExtentSum - coord + coordBase;
  29468. };
  29469. }
  29470. var axesTypes = ['xAxis', 'yAxis'];
  29471. /**
  29472. * @inner
  29473. */
  29474. function findAxesModels(seriesModel, ecModel) {
  29475. return map(axesTypes, function (axisType) {
  29476. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  29477. if (__DEV__) {
  29478. if (!axisModel) {
  29479. throw new Error(axisType + ' "' + retrieve(
  29480. seriesModel.get(axisType + 'Index'),
  29481. seriesModel.get(axisType + 'Id'),
  29482. 0
  29483. ) + '" not found');
  29484. }
  29485. }
  29486. return axisModel;
  29487. });
  29488. }
  29489. /**
  29490. * @inner
  29491. */
  29492. function isCartesian2D(seriesModel) {
  29493. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  29494. }
  29495. Grid.create = function (ecModel, api) {
  29496. var grids = [];
  29497. ecModel.eachComponent('grid', function (gridModel, idx) {
  29498. var grid = new Grid(gridModel, ecModel, api);
  29499. grid.name = 'grid_' + idx;
  29500. // dataSampling requires axis extent, so resize
  29501. // should be performed in create stage.
  29502. grid.resize(gridModel, api, true);
  29503. gridModel.coordinateSystem = grid;
  29504. grids.push(grid);
  29505. });
  29506. // Inject the coordinateSystems into seriesModel
  29507. ecModel.eachSeries(function (seriesModel) {
  29508. if (!isCartesian2D(seriesModel)) {
  29509. return;
  29510. }
  29511. var axesModels = findAxesModels(seriesModel, ecModel);
  29512. var xAxisModel = axesModels[0];
  29513. var yAxisModel = axesModels[1];
  29514. var gridModel = xAxisModel.getCoordSysModel();
  29515. if (__DEV__) {
  29516. if (!gridModel) {
  29517. throw new Error(
  29518. 'Grid "' + retrieve(
  29519. xAxisModel.get('gridIndex'),
  29520. xAxisModel.get('gridId'),
  29521. 0
  29522. ) + '" not found'
  29523. );
  29524. }
  29525. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  29526. throw new Error('xAxis and yAxis must use the same grid');
  29527. }
  29528. }
  29529. var grid = gridModel.coordinateSystem;
  29530. seriesModel.coordinateSystem = grid.getCartesian(
  29531. xAxisModel.componentIndex, yAxisModel.componentIndex
  29532. );
  29533. });
  29534. return grids;
  29535. };
  29536. // For deciding which dimensions to use when creating list data
  29537. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  29538. CoordinateSystemManager.register('cartesian2d', Grid);
  29539. var PI$2 = Math.PI;
  29540. function makeAxisEventDataBase(axisModel) {
  29541. var eventData = {
  29542. componentType: axisModel.mainType
  29543. };
  29544. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  29545. return eventData;
  29546. }
  29547. /**
  29548. * A final axis is translated and rotated from a "standard axis".
  29549. * So opt.position and opt.rotation is required.
  29550. *
  29551. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  29552. * for example: (0, 0) ------------> (0, 50)
  29553. *
  29554. * nameDirection or tickDirection or labelDirection is 1 means tick
  29555. * or label is below the standard axis, whereas is -1 means above
  29556. * the standard axis. labelOffset means offset between label and axis,
  29557. * which is useful when 'onZero', where axisLabel is in the grid and
  29558. * label in outside grid.
  29559. *
  29560. * Tips: like always,
  29561. * positive rotation represents anticlockwise, and negative rotation
  29562. * represents clockwise.
  29563. * The direction of position coordinate is the same as the direction
  29564. * of screen coordinate.
  29565. *
  29566. * Do not need to consider axis 'inverse', which is auto processed by
  29567. * axis extent.
  29568. *
  29569. * @param {module:zrender/container/Group} group
  29570. * @param {Object} axisModel
  29571. * @param {Object} opt Standard axis parameters.
  29572. * @param {Array.<number>} opt.position [x, y]
  29573. * @param {number} opt.rotation by radian
  29574. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  29575. * @param {number} [opt.tickDirection=1] 1 or -1
  29576. * @param {number} [opt.labelDirection=1] 1 or -1
  29577. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  29578. * @param {string} [opt.axisLabelShow] default get from axisModel.
  29579. * @param {string} [opt.axisName] default get from axisModel.
  29580. * @param {number} [opt.axisNameAvailableWidth]
  29581. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  29582. * @param {number} [opt.labelInterval] Default label interval when label
  29583. * interval from model is null or 'auto'.
  29584. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  29585. * @param {number} [opt.nameTruncateMaxWidth]
  29586. */
  29587. var AxisBuilder = function (axisModel, opt) {
  29588. /**
  29589. * @readOnly
  29590. */
  29591. this.opt = opt;
  29592. /**
  29593. * @readOnly
  29594. */
  29595. this.axisModel = axisModel;
  29596. // Default value
  29597. defaults(
  29598. opt,
  29599. {
  29600. labelOffset: 0,
  29601. nameDirection: 1,
  29602. tickDirection: 1,
  29603. labelDirection: 1,
  29604. silent: true
  29605. }
  29606. );
  29607. /**
  29608. * @readOnly
  29609. */
  29610. this.group = new Group();
  29611. // FIXME Not use a seperate text group?
  29612. var dumbGroup = new Group({
  29613. position: opt.position.slice(),
  29614. rotation: opt.rotation
  29615. });
  29616. // this.group.add(dumbGroup);
  29617. // this._dumbGroup = dumbGroup;
  29618. dumbGroup.updateTransform();
  29619. this._transform = dumbGroup.transform;
  29620. this._dumbGroup = dumbGroup;
  29621. };
  29622. AxisBuilder.prototype = {
  29623. constructor: AxisBuilder,
  29624. hasBuilder: function (name) {
  29625. return !!builders[name];
  29626. },
  29627. add: function (name) {
  29628. builders[name].call(this);
  29629. },
  29630. getGroup: function () {
  29631. return this.group;
  29632. }
  29633. };
  29634. var builders = {
  29635. /**
  29636. * @private
  29637. */
  29638. axisLine: function () {
  29639. var opt = this.opt;
  29640. var axisModel = this.axisModel;
  29641. if (!axisModel.get('axisLine.show')) {
  29642. return;
  29643. }
  29644. var extent = this.axisModel.axis.getExtent();
  29645. var matrix = this._transform;
  29646. var pt1 = [extent[0], 0];
  29647. var pt2 = [extent[1], 0];
  29648. if (matrix) {
  29649. applyTransform(pt1, pt1, matrix);
  29650. applyTransform(pt2, pt2, matrix);
  29651. }
  29652. var lineStyle = extend(
  29653. {
  29654. lineCap: 'round'
  29655. },
  29656. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  29657. );
  29658. this.group.add(new Line(subPixelOptimizeLine({
  29659. // Id for animation
  29660. anid: 'line',
  29661. shape: {
  29662. x1: pt1[0],
  29663. y1: pt1[1],
  29664. x2: pt2[0],
  29665. y2: pt2[1]
  29666. },
  29667. style: lineStyle,
  29668. strokeContainThreshold: opt.strokeContainThreshold || 5,
  29669. silent: true,
  29670. z2: 1
  29671. })));
  29672. var arrows = axisModel.get('axisLine.symbol');
  29673. var arrowSize = axisModel.get('axisLine.symbolSize');
  29674. if (arrows != null) {
  29675. if (typeof arrows === 'string') {
  29676. // Use the same arrow for start and end point
  29677. arrows = [arrows, arrows];
  29678. }
  29679. if (typeof arrowSize === 'string'
  29680. || typeof arrowSize === 'number'
  29681. ) {
  29682. // Use the same size for width and height
  29683. arrowSize = [arrowSize, arrowSize];
  29684. }
  29685. var symbolWidth = arrowSize[0];
  29686. var symbolHeight = arrowSize[1];
  29687. each$1([
  29688. [opt.rotation + Math.PI / 2, pt1],
  29689. [opt.rotation - Math.PI / 2, pt2]
  29690. ], function (item, index) {
  29691. if (arrows[index] !== 'none' && arrows[index] != null) {
  29692. var symbol = createSymbol(
  29693. arrows[index],
  29694. -symbolWidth / 2,
  29695. -symbolHeight / 2,
  29696. symbolWidth,
  29697. symbolHeight,
  29698. lineStyle.stroke,
  29699. true
  29700. );
  29701. symbol.attr({
  29702. rotation: item[0],
  29703. position: item[1],
  29704. silent: true
  29705. });
  29706. this.group.add(symbol);
  29707. }
  29708. }, this);
  29709. }
  29710. },
  29711. /**
  29712. * @private
  29713. */
  29714. axisTickLabel: function () {
  29715. var axisModel = this.axisModel;
  29716. var opt = this.opt;
  29717. var tickEls = buildAxisTick(this, axisModel, opt);
  29718. var labelEls = buildAxisLabel(this, axisModel, opt);
  29719. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  29720. },
  29721. /**
  29722. * @private
  29723. */
  29724. axisName: function () {
  29725. var opt = this.opt;
  29726. var axisModel = this.axisModel;
  29727. var name = retrieve(opt.axisName, axisModel.get('name'));
  29728. if (!name) {
  29729. return;
  29730. }
  29731. var nameLocation = axisModel.get('nameLocation');
  29732. var nameDirection = opt.nameDirection;
  29733. var textStyleModel = axisModel.getModel('nameTextStyle');
  29734. var gap = axisModel.get('nameGap') || 0;
  29735. var extent = this.axisModel.axis.getExtent();
  29736. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  29737. var pos = [
  29738. nameLocation === 'start'
  29739. ? extent[0] - gapSignal * gap
  29740. : nameLocation === 'end'
  29741. ? extent[1] + gapSignal * gap
  29742. : (extent[0] + extent[1]) / 2, // 'middle'
  29743. // Reuse labelOffset.
  29744. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  29745. ];
  29746. var labelLayout;
  29747. var nameRotation = axisModel.get('nameRotate');
  29748. if (nameRotation != null) {
  29749. nameRotation = nameRotation * PI$2 / 180; // To radian.
  29750. }
  29751. var axisNameAvailableWidth;
  29752. if (isNameLocationCenter(nameLocation)) {
  29753. labelLayout = innerTextLayout(
  29754. opt.rotation,
  29755. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  29756. nameDirection
  29757. );
  29758. }
  29759. else {
  29760. labelLayout = endTextLayout(
  29761. opt, nameLocation, nameRotation || 0, extent
  29762. );
  29763. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  29764. if (axisNameAvailableWidth != null) {
  29765. axisNameAvailableWidth = Math.abs(
  29766. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  29767. );
  29768. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  29769. }
  29770. }
  29771. var textFont = textStyleModel.getFont();
  29772. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  29773. var ellipsis = truncateOpt.ellipsis;
  29774. var maxWidth = retrieve(
  29775. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  29776. );
  29777. // FIXME
  29778. // truncate rich text? (consider performance)
  29779. var truncatedText = (ellipsis != null && maxWidth != null)
  29780. ? truncateText$1(
  29781. name, maxWidth, textFont, ellipsis,
  29782. {minChar: 2, placeholder: truncateOpt.placeholder}
  29783. )
  29784. : name;
  29785. var tooltipOpt = axisModel.get('tooltip', true);
  29786. var mainType = axisModel.mainType;
  29787. var formatterParams = {
  29788. componentType: mainType,
  29789. name: name,
  29790. $vars: ['name']
  29791. };
  29792. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  29793. var textEl = new Text({
  29794. // Id for animation
  29795. anid: 'name',
  29796. __fullText: name,
  29797. __truncatedText: truncatedText,
  29798. position: pos,
  29799. rotation: labelLayout.rotation,
  29800. silent: isSilent(axisModel),
  29801. z2: 1,
  29802. tooltip: (tooltipOpt && tooltipOpt.show)
  29803. ? extend({
  29804. content: name,
  29805. formatter: function () {
  29806. return name;
  29807. },
  29808. formatterParams: formatterParams
  29809. }, tooltipOpt)
  29810. : null
  29811. });
  29812. setTextStyle(textEl.style, textStyleModel, {
  29813. text: truncatedText,
  29814. textFont: textFont,
  29815. textFill: textStyleModel.getTextColor()
  29816. || axisModel.get('axisLine.lineStyle.color'),
  29817. textAlign: labelLayout.textAlign,
  29818. textVerticalAlign: labelLayout.textVerticalAlign
  29819. });
  29820. if (axisModel.get('triggerEvent')) {
  29821. textEl.eventData = makeAxisEventDataBase(axisModel);
  29822. textEl.eventData.targetType = 'axisName';
  29823. textEl.eventData.name = name;
  29824. }
  29825. // FIXME
  29826. this._dumbGroup.add(textEl);
  29827. textEl.updateTransform();
  29828. this.group.add(textEl);
  29829. textEl.decomposeTransform();
  29830. }
  29831. };
  29832. /**
  29833. * @public
  29834. * @static
  29835. * @param {Object} opt
  29836. * @param {number} axisRotation in radian
  29837. * @param {number} textRotation in radian
  29838. * @param {number} direction
  29839. * @return {Object} {
  29840. * rotation, // according to axis
  29841. * textAlign,
  29842. * textVerticalAlign
  29843. * }
  29844. */
  29845. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  29846. var rotationDiff = remRadian(textRotation - axisRotation);
  29847. var textAlign;
  29848. var textVerticalAlign;
  29849. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  29850. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  29851. textAlign = 'center';
  29852. }
  29853. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  29854. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  29855. textAlign = 'center';
  29856. }
  29857. else {
  29858. textVerticalAlign = 'middle';
  29859. if (rotationDiff > 0 && rotationDiff < PI$2) {
  29860. textAlign = direction > 0 ? 'right' : 'left';
  29861. }
  29862. else {
  29863. textAlign = direction > 0 ? 'left' : 'right';
  29864. }
  29865. }
  29866. return {
  29867. rotation: rotationDiff,
  29868. textAlign: textAlign,
  29869. textVerticalAlign: textVerticalAlign
  29870. };
  29871. };
  29872. function endTextLayout(opt, textPosition, textRotate, extent) {
  29873. var rotationDiff = remRadian(textRotate - opt.rotation);
  29874. var textAlign;
  29875. var textVerticalAlign;
  29876. var inverse = extent[0] > extent[1];
  29877. var onLeft = (textPosition === 'start' && !inverse)
  29878. || (textPosition !== 'start' && inverse);
  29879. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  29880. textVerticalAlign = onLeft ? 'bottom' : 'top';
  29881. textAlign = 'center';
  29882. }
  29883. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  29884. textVerticalAlign = onLeft ? 'top' : 'bottom';
  29885. textAlign = 'center';
  29886. }
  29887. else {
  29888. textVerticalAlign = 'middle';
  29889. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  29890. textAlign = onLeft ? 'left' : 'right';
  29891. }
  29892. else {
  29893. textAlign = onLeft ? 'right' : 'left';
  29894. }
  29895. }
  29896. return {
  29897. rotation: rotationDiff,
  29898. textAlign: textAlign,
  29899. textVerticalAlign: textVerticalAlign
  29900. };
  29901. }
  29902. function isSilent(axisModel) {
  29903. var tooltipOpt = axisModel.get('tooltip');
  29904. return axisModel.get('silent')
  29905. // Consider mouse cursor, add these restrictions.
  29906. || !(
  29907. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  29908. );
  29909. }
  29910. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  29911. // If min or max are user set, we need to check
  29912. // If the tick on min(max) are overlap on their neighbour tick
  29913. // If they are overlapped, we need to hide the min(max) tick label
  29914. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29915. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29916. // FIXME
  29917. // Have not consider onBand yet, where tick els is more than label els.
  29918. labelEls = labelEls || [];
  29919. tickEls = tickEls || [];
  29920. var firstLabel = labelEls[0];
  29921. var nextLabel = labelEls[1];
  29922. var lastLabel = labelEls[labelEls.length - 1];
  29923. var prevLabel = labelEls[labelEls.length - 2];
  29924. var firstTick = tickEls[0];
  29925. var nextTick = tickEls[1];
  29926. var lastTick = tickEls[tickEls.length - 1];
  29927. var prevTick = tickEls[tickEls.length - 2];
  29928. if (showMinLabel === false) {
  29929. ignoreEl(firstLabel);
  29930. ignoreEl(firstTick);
  29931. }
  29932. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  29933. if (showMinLabel) {
  29934. ignoreEl(nextLabel);
  29935. ignoreEl(nextTick);
  29936. }
  29937. else {
  29938. ignoreEl(firstLabel);
  29939. ignoreEl(firstTick);
  29940. }
  29941. }
  29942. if (showMaxLabel === false) {
  29943. ignoreEl(lastLabel);
  29944. ignoreEl(lastTick);
  29945. }
  29946. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  29947. if (showMaxLabel) {
  29948. ignoreEl(prevLabel);
  29949. ignoreEl(prevTick);
  29950. }
  29951. else {
  29952. ignoreEl(lastLabel);
  29953. ignoreEl(lastTick);
  29954. }
  29955. }
  29956. }
  29957. function ignoreEl(el) {
  29958. el && (el.ignore = true);
  29959. }
  29960. function isTwoLabelOverlapped(current, next, labelLayout) {
  29961. // current and next has the same rotation.
  29962. var firstRect = current && current.getBoundingRect().clone();
  29963. var nextRect = next && next.getBoundingRect().clone();
  29964. if (!firstRect || !nextRect) {
  29965. return;
  29966. }
  29967. // When checking intersect of two rotated labels, we use mRotationBack
  29968. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  29969. var mRotationBack = identity([]);
  29970. rotate(mRotationBack, mRotationBack, -current.rotation);
  29971. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  29972. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  29973. return firstRect.intersect(nextRect);
  29974. }
  29975. function isNameLocationCenter(nameLocation) {
  29976. return nameLocation === 'middle' || nameLocation === 'center';
  29977. }
  29978. /**
  29979. * @static
  29980. */
  29981. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  29982. axis,
  29983. i,
  29984. interval,
  29985. ticksCnt,
  29986. showMinLabel,
  29987. showMaxLabel
  29988. ) {
  29989. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  29990. return false;
  29991. }
  29992. // FIXME
  29993. // Have not consider label overlap (if label is too long) yet.
  29994. var rawTick;
  29995. var scale$$1 = axis.scale;
  29996. return scale$$1.type === 'ordinal'
  29997. && (
  29998. typeof interval === 'function'
  29999. ? (
  30000. rawTick = scale$$1.getTicks()[i],
  30001. !interval(rawTick, scale$$1.getLabel(rawTick))
  30002. )
  30003. : i % (interval + 1)
  30004. );
  30005. };
  30006. /**
  30007. * @static
  30008. */
  30009. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30010. var interval = model.get('interval');
  30011. if (interval == null || interval == 'auto') {
  30012. interval = labelInterval;
  30013. }
  30014. return interval;
  30015. };
  30016. function buildAxisTick(axisBuilder, axisModel, opt) {
  30017. var axis = axisModel.axis;
  30018. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30019. return;
  30020. }
  30021. var tickModel = axisModel.getModel('axisTick');
  30022. var lineStyleModel = tickModel.getModel('lineStyle');
  30023. var tickLen = tickModel.get('length');
  30024. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30025. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30026. // FIXME
  30027. // Corresponds to ticksCoords ?
  30028. var ticks = axis.scale.getTicks();
  30029. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30030. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30031. var pt1 = [];
  30032. var pt2 = [];
  30033. var matrix = axisBuilder._transform;
  30034. var tickEls = [];
  30035. var ticksCnt = ticksCoords.length;
  30036. for (var i = 0; i < ticksCnt; i++) {
  30037. // Only ordinal scale support tick interval
  30038. if (ifIgnoreOnTick$1(
  30039. axis, i, tickInterval, ticksCnt,
  30040. showMinLabel, showMaxLabel
  30041. )) {
  30042. continue;
  30043. }
  30044. var tickCoord = ticksCoords[i];
  30045. pt1[0] = tickCoord;
  30046. pt1[1] = 0;
  30047. pt2[0] = tickCoord;
  30048. pt2[1] = opt.tickDirection * tickLen;
  30049. if (matrix) {
  30050. applyTransform(pt1, pt1, matrix);
  30051. applyTransform(pt2, pt2, matrix);
  30052. }
  30053. // Tick line, Not use group transform to have better line draw
  30054. var tickEl = new Line(subPixelOptimizeLine({
  30055. // Id for animation
  30056. anid: 'tick_' + ticks[i],
  30057. shape: {
  30058. x1: pt1[0],
  30059. y1: pt1[1],
  30060. x2: pt2[0],
  30061. y2: pt2[1]
  30062. },
  30063. style: defaults(
  30064. lineStyleModel.getLineStyle(),
  30065. {
  30066. stroke: axisModel.get('axisLine.lineStyle.color')
  30067. }
  30068. ),
  30069. z2: 2,
  30070. silent: true
  30071. }));
  30072. axisBuilder.group.add(tickEl);
  30073. tickEls.push(tickEl);
  30074. }
  30075. return tickEls;
  30076. }
  30077. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30078. var axis = axisModel.axis;
  30079. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30080. if (!show || axis.scale.isBlank()) {
  30081. return;
  30082. }
  30083. var labelModel = axisModel.getModel('axisLabel');
  30084. var labelMargin = labelModel.get('margin');
  30085. var ticks = axis.scale.getTicks();
  30086. var labels = axisModel.getFormattedLabels();
  30087. // Special label rotate.
  30088. var labelRotation = (
  30089. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30090. ) * PI$2 / 180;
  30091. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30092. var categoryData = axisModel.getCategories();
  30093. var labelEls = [];
  30094. var silent = isSilent(axisModel);
  30095. var triggerEvent = axisModel.get('triggerEvent');
  30096. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30097. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30098. each$1(ticks, function (tickVal, index) {
  30099. if (ifIgnoreOnTick$1(
  30100. axis, index, opt.labelInterval, ticks.length,
  30101. showMinLabel, showMaxLabel
  30102. )) {
  30103. return;
  30104. }
  30105. var itemLabelModel = labelModel;
  30106. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30107. itemLabelModel = new Model(
  30108. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30109. );
  30110. }
  30111. var textColor = itemLabelModel.getTextColor()
  30112. || axisModel.get('axisLine.lineStyle.color');
  30113. var tickCoord = axis.dataToCoord(tickVal);
  30114. var pos = [
  30115. tickCoord,
  30116. opt.labelOffset + opt.labelDirection * labelMargin
  30117. ];
  30118. var labelStr = axis.scale.getLabel(tickVal);
  30119. var textEl = new Text({
  30120. // Id for animation
  30121. anid: 'label_' + tickVal,
  30122. position: pos,
  30123. rotation: labelLayout.rotation,
  30124. silent: silent,
  30125. z2: 10
  30126. });
  30127. setTextStyle(textEl.style, itemLabelModel, {
  30128. text: labels[index],
  30129. textAlign: itemLabelModel.getShallow('align', true)
  30130. || labelLayout.textAlign,
  30131. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30132. || itemLabelModel.getShallow('baseline', true)
  30133. || labelLayout.textVerticalAlign,
  30134. textFill: typeof textColor === 'function'
  30135. ? textColor(
  30136. // (1) In category axis with data zoom, tick is not the original
  30137. // index of axis.data. So tick should not be exposed to user
  30138. // in category axis.
  30139. // (2) Compatible with previous version, which always returns labelStr.
  30140. // But in interval scale labelStr is like '223,445', which maked
  30141. // user repalce ','. So we modify it to return original val but remain
  30142. // it as 'string' to avoid error in replacing.
  30143. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30144. index
  30145. )
  30146. : textColor
  30147. });
  30148. // Pack data for mouse event
  30149. if (triggerEvent) {
  30150. textEl.eventData = makeAxisEventDataBase(axisModel);
  30151. textEl.eventData.targetType = 'axisLabel';
  30152. textEl.eventData.value = labelStr;
  30153. }
  30154. // FIXME
  30155. axisBuilder._dumbGroup.add(textEl);
  30156. textEl.updateTransform();
  30157. labelEls.push(textEl);
  30158. axisBuilder.group.add(textEl);
  30159. textEl.decomposeTransform();
  30160. });
  30161. return labelEls;
  30162. }
  30163. var each$7 = each$1;
  30164. var curry$1 = curry;
  30165. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30166. // allAxesInfo should be updated when setOption performed.
  30167. function collect(ecModel, api) {
  30168. var result = {
  30169. /**
  30170. * key: makeKey(axis.model)
  30171. * value: {
  30172. * axis,
  30173. * coordSys,
  30174. * axisPointerModel,
  30175. * triggerTooltip,
  30176. * involveSeries,
  30177. * snap,
  30178. * seriesModels,
  30179. * seriesDataCount
  30180. * }
  30181. */
  30182. axesInfo: {},
  30183. seriesInvolved: false,
  30184. /**
  30185. * key: makeKey(coordSys.model)
  30186. * value: Object: key makeKey(axis.model), value: axisInfo
  30187. */
  30188. coordSysAxesInfo: {},
  30189. coordSysMap: {}
  30190. };
  30191. collectAxesInfo(result, ecModel, api);
  30192. // Check seriesInvolved for performance, in case too many series in some chart.
  30193. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30194. return result;
  30195. }
  30196. function collectAxesInfo(result, ecModel, api) {
  30197. var globalTooltipModel = ecModel.getComponent('tooltip');
  30198. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30199. // links can only be set on global.
  30200. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30201. var linkGroups = [];
  30202. // Collect axes info.
  30203. each$7(api.getCoordinateSystems(), function (coordSys) {
  30204. // Some coordinate system do not support axes, like geo.
  30205. if (!coordSys.axisPointerEnabled) {
  30206. return;
  30207. }
  30208. var coordSysKey = makeKey(coordSys.model);
  30209. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30210. result.coordSysMap[coordSysKey] = coordSys;
  30211. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30212. // for user. So we enable seting tooltip on coordSys model.
  30213. var coordSysModel = coordSys.model;
  30214. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30215. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30216. // If axis tooltip used, choose tooltip axis for each coordSys.
  30217. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30218. if (coordSys.getTooltipAxes
  30219. && globalTooltipModel
  30220. // If tooltip.showContent is set as false, tooltip will not
  30221. // show but axisPointer will show as normal.
  30222. && baseTooltipModel.get('show')
  30223. ) {
  30224. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30225. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30226. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30227. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30228. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30229. if (triggerAxis || cross) {
  30230. each$7(tooltipAxes.baseAxes, curry$1(
  30231. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30232. ));
  30233. }
  30234. if (cross) {
  30235. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30236. }
  30237. }
  30238. // fromTooltip: true | false | 'cross'
  30239. // triggerTooltip: true | false | null
  30240. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30241. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30242. var axisPointerShow = axisPointerModel.get('show');
  30243. if (!axisPointerShow || (
  30244. axisPointerShow === 'auto'
  30245. && !fromTooltip
  30246. && !isHandleTrigger(axisPointerModel)
  30247. )) {
  30248. return;
  30249. }
  30250. if (triggerTooltip == null) {
  30251. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30252. }
  30253. axisPointerModel = fromTooltip
  30254. ? makeAxisPointerModel(
  30255. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30256. fromTooltip, triggerTooltip
  30257. )
  30258. : axisPointerModel;
  30259. var snap = axisPointerModel.get('snap');
  30260. var key = makeKey(axis.model);
  30261. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30262. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30263. var axisInfo = result.axesInfo[key] = {
  30264. key: key,
  30265. axis: axis,
  30266. coordSys: coordSys,
  30267. axisPointerModel: axisPointerModel,
  30268. triggerTooltip: triggerTooltip,
  30269. involveSeries: involveSeries,
  30270. snap: snap,
  30271. useHandle: isHandleTrigger(axisPointerModel),
  30272. seriesModels: []
  30273. };
  30274. axesInfoInCoordSys[key] = axisInfo;
  30275. result.seriesInvolved |= involveSeries;
  30276. var groupIndex = getLinkGroupIndex(linksOption, axis);
  30277. if (groupIndex != null) {
  30278. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  30279. linkGroup.axesInfo[key] = axisInfo;
  30280. linkGroup.mapper = linksOption[groupIndex].mapper;
  30281. axisInfo.linkGroup = linkGroup;
  30282. }
  30283. }
  30284. });
  30285. }
  30286. function makeAxisPointerModel(
  30287. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  30288. ) {
  30289. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  30290. var volatileOption = {};
  30291. each$7(
  30292. [
  30293. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  30294. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  30295. ],
  30296. function (field) {
  30297. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  30298. }
  30299. );
  30300. // category axis do not auto snap, otherwise some tick that do not
  30301. // has value can not be hovered. value/time/log axis default snap if
  30302. // triggered from tooltip and trigger tooltip.
  30303. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  30304. // Compatibel with previous behavior, tooltip axis do not show label by default.
  30305. // Only these properties can be overrided from tooltip to axisPointer.
  30306. if (tooltipAxisPointerModel.get('type') === 'cross') {
  30307. volatileOption.type = 'line';
  30308. }
  30309. var labelOption = volatileOption.label || (volatileOption.label = {});
  30310. // Follow the convention, do not show label when triggered by tooltip by default.
  30311. labelOption.show == null && (labelOption.show = false);
  30312. if (fromTooltip === 'cross') {
  30313. // When 'cross', both axes show labels.
  30314. labelOption.show = true;
  30315. // If triggerTooltip, this is a base axis, which should better not use cross style
  30316. // (cross style is dashed by default)
  30317. if (!triggerTooltip) {
  30318. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  30319. crossStyle && defaults(labelOption, crossStyle.textStyle);
  30320. }
  30321. }
  30322. return axis.model.getModel(
  30323. 'axisPointer',
  30324. new Model(volatileOption, globalAxisPointerModel, ecModel)
  30325. );
  30326. }
  30327. function collectSeriesInfo(result, ecModel) {
  30328. // Prepare data for axis trigger
  30329. ecModel.eachSeries(function (seriesModel) {
  30330. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  30331. var coordSys = seriesModel.coordinateSystem;
  30332. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  30333. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  30334. if (!coordSys
  30335. || seriesTooltipTrigger === 'none'
  30336. || seriesTooltipTrigger === false
  30337. || seriesTooltipTrigger === 'item'
  30338. || seriesTooltipShow === false
  30339. || seriesModel.get('axisPointer.show', true) === false
  30340. ) {
  30341. return;
  30342. }
  30343. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  30344. var axis = axisInfo.axis;
  30345. if (coordSys.getAxis(axis.dim) === axis) {
  30346. axisInfo.seriesModels.push(seriesModel);
  30347. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  30348. axisInfo.seriesDataCount += seriesModel.getData().count();
  30349. }
  30350. });
  30351. }, this);
  30352. }
  30353. /**
  30354. * For example:
  30355. * {
  30356. * axisPointer: {
  30357. * links: [{
  30358. * xAxisIndex: [2, 4],
  30359. * yAxisIndex: 'all'
  30360. * }, {
  30361. * xAxisId: ['a5', 'a7'],
  30362. * xAxisName: 'xxx'
  30363. * }]
  30364. * }
  30365. * }
  30366. */
  30367. function getLinkGroupIndex(linksOption, axis) {
  30368. var axisModel = axis.model;
  30369. var dim = axis.dim;
  30370. for (var i = 0; i < linksOption.length; i++) {
  30371. var linkOption = linksOption[i] || {};
  30372. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  30373. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  30374. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  30375. ) {
  30376. return i;
  30377. }
  30378. }
  30379. }
  30380. function checkPropInLink(linkPropValue, axisPropValue) {
  30381. return linkPropValue === 'all'
  30382. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  30383. || linkPropValue === axisPropValue;
  30384. }
  30385. function fixValue(axisModel) {
  30386. var axisInfo = getAxisInfo(axisModel);
  30387. if (!axisInfo) {
  30388. return;
  30389. }
  30390. var axisPointerModel = axisInfo.axisPointerModel;
  30391. var scale = axisInfo.axis.scale;
  30392. var option = axisPointerModel.option;
  30393. var status = axisPointerModel.get('status');
  30394. var value = axisPointerModel.get('value');
  30395. // Parse init value for category and time axis.
  30396. if (value != null) {
  30397. value = scale.parse(value);
  30398. }
  30399. var useHandle = isHandleTrigger(axisPointerModel);
  30400. // If `handle` used, `axisPointer` will always be displayed, so value
  30401. // and status should be initialized.
  30402. if (status == null) {
  30403. option.status = useHandle ? 'show' : 'hide';
  30404. }
  30405. var extent = scale.getExtent().slice();
  30406. extent[0] > extent[1] && extent.reverse();
  30407. if (// Pick a value on axis when initializing.
  30408. value == null
  30409. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  30410. // where we should re-pick a value to keep `handle` displaying normally.
  30411. || value > extent[1]
  30412. ) {
  30413. // Make handle displayed on the end of the axis when init, which looks better.
  30414. value = extent[1];
  30415. }
  30416. if (value < extent[0]) {
  30417. value = extent[0];
  30418. }
  30419. option.value = value;
  30420. if (useHandle) {
  30421. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  30422. }
  30423. }
  30424. function getAxisInfo(axisModel) {
  30425. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  30426. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  30427. }
  30428. function getAxisPointerModel(axisModel) {
  30429. var axisInfo = getAxisInfo(axisModel);
  30430. return axisInfo && axisInfo.axisPointerModel;
  30431. }
  30432. function isHandleTrigger(axisPointerModel) {
  30433. return !!axisPointerModel.get('handle.show');
  30434. }
  30435. /**
  30436. * @param {module:echarts/model/Model} model
  30437. * @return {string} unique key
  30438. */
  30439. function makeKey(model) {
  30440. return model.type + '||' + model.id;
  30441. }
  30442. /**
  30443. * Base class of AxisView.
  30444. */
  30445. var AxisView = extendComponentView({
  30446. type: 'axis',
  30447. /**
  30448. * @private
  30449. */
  30450. _axisPointer: null,
  30451. /**
  30452. * @protected
  30453. * @type {string}
  30454. */
  30455. axisPointerClass: null,
  30456. /**
  30457. * @override
  30458. */
  30459. render: function (axisModel, ecModel, api, payload) {
  30460. // FIXME
  30461. // This process should proformed after coordinate systems updated
  30462. // (axis scale updated), and should be performed each time update.
  30463. // So put it here temporarily, although it is not appropriate to
  30464. // put a model-writing procedure in `view`.
  30465. this.axisPointerClass && fixValue(axisModel);
  30466. AxisView.superApply(this, 'render', arguments);
  30467. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  30468. },
  30469. /**
  30470. * Action handler.
  30471. * @public
  30472. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30473. * @param {module:echarts/model/Global} ecModel
  30474. * @param {module:echarts/ExtensionAPI} api
  30475. * @param {Object} payload
  30476. */
  30477. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  30478. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  30479. },
  30480. /**
  30481. * @override
  30482. */
  30483. remove: function (ecModel, api) {
  30484. var axisPointer = this._axisPointer;
  30485. axisPointer && axisPointer.remove(api);
  30486. AxisView.superApply(this, 'remove', arguments);
  30487. },
  30488. /**
  30489. * @override
  30490. */
  30491. dispose: function (ecModel, api) {
  30492. disposeAxisPointer(this, api);
  30493. AxisView.superApply(this, 'dispose', arguments);
  30494. }
  30495. });
  30496. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  30497. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  30498. if (!Clazz) {
  30499. return;
  30500. }
  30501. var axisPointerModel = getAxisPointerModel(axisModel);
  30502. axisPointerModel
  30503. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  30504. .render(axisModel, axisPointerModel, api, forceRender)
  30505. : disposeAxisPointer(axisView, api);
  30506. }
  30507. function disposeAxisPointer(axisView, ecModel, api) {
  30508. var axisPointer = axisView._axisPointer;
  30509. axisPointer && axisPointer.dispose(ecModel, api);
  30510. axisView._axisPointer = null;
  30511. }
  30512. var axisPointerClazz = [];
  30513. AxisView.registerAxisPointerClass = function (type, clazz) {
  30514. if (__DEV__) {
  30515. if (axisPointerClazz[type]) {
  30516. throw new Error('axisPointer ' + type + ' exists');
  30517. }
  30518. }
  30519. axisPointerClazz[type] = clazz;
  30520. };
  30521. AxisView.getAxisPointerClass = function (type) {
  30522. return type && axisPointerClazz[type];
  30523. };
  30524. /**
  30525. * @param {Object} opt {labelInside}
  30526. * @return {Object} {
  30527. * position, rotation, labelDirection, labelOffset,
  30528. * tickDirection, labelRotate, labelInterval, z2
  30529. * }
  30530. */
  30531. function layout$1(gridModel, axisModel, opt) {
  30532. opt = opt || {};
  30533. var grid = gridModel.coordinateSystem;
  30534. var axis = axisModel.axis;
  30535. var layout = {};
  30536. var rawAxisPosition = axis.position;
  30537. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  30538. var axisDim = axis.dim;
  30539. var rect = grid.getRect();
  30540. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  30541. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  30542. var axisOffset = axisModel.get('offset') || 0;
  30543. var posBound = axisDim === 'x'
  30544. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  30545. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  30546. if (axis.onZero) {
  30547. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  30548. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  30549. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  30550. }
  30551. // Axis position
  30552. layout.position = [
  30553. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  30554. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  30555. ];
  30556. // Axis rotation
  30557. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  30558. // Tick and label direction, x y is axisDim
  30559. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  30560. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  30561. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  30562. if (axisModel.get('axisTick.inside')) {
  30563. layout.tickDirection = -layout.tickDirection;
  30564. }
  30565. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  30566. layout.labelDirection = -layout.labelDirection;
  30567. }
  30568. // Special label rotation
  30569. var labelRotate = axisModel.get('axisLabel.rotate');
  30570. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  30571. // label interval when auto mode.
  30572. layout.labelInterval = axis.getLabelInterval();
  30573. // Over splitLine and splitArea
  30574. layout.z2 = 1;
  30575. return layout;
  30576. }
  30577. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  30578. var getInterval = AxisBuilder.getInterval;
  30579. var axisBuilderAttrs = [
  30580. 'axisLine', 'axisTickLabel', 'axisName'
  30581. ];
  30582. var selfBuilderAttrs = [
  30583. 'splitArea', 'splitLine'
  30584. ];
  30585. // function getAlignWithLabel(model, axisModel) {
  30586. // var alignWithLabel = model.get('alignWithLabel');
  30587. // if (alignWithLabel === 'auto') {
  30588. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  30589. // }
  30590. // return alignWithLabel;
  30591. // }
  30592. var CartesianAxisView = AxisView.extend({
  30593. type: 'cartesianAxis',
  30594. axisPointerClass: 'CartesianAxisPointer',
  30595. /**
  30596. * @override
  30597. */
  30598. render: function (axisModel, ecModel, api, payload) {
  30599. this.group.removeAll();
  30600. var oldAxisGroup = this._axisGroup;
  30601. this._axisGroup = new Group();
  30602. this.group.add(this._axisGroup);
  30603. if (!axisModel.get('show')) {
  30604. return;
  30605. }
  30606. var gridModel = axisModel.getCoordSysModel();
  30607. var layout = layout$1(gridModel, axisModel);
  30608. var axisBuilder = new AxisBuilder(axisModel, layout);
  30609. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  30610. this._axisGroup.add(axisBuilder.getGroup());
  30611. each$1(selfBuilderAttrs, function (name) {
  30612. if (axisModel.get(name + '.show')) {
  30613. this['_' + name](axisModel, gridModel, layout.labelInterval);
  30614. }
  30615. }, this);
  30616. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  30617. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  30618. },
  30619. /**
  30620. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30621. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30622. * @param {number|Function} labelInterval
  30623. * @private
  30624. */
  30625. _splitLine: function (axisModel, gridModel, labelInterval) {
  30626. var axis = axisModel.axis;
  30627. if (axis.scale.isBlank()) {
  30628. return;
  30629. }
  30630. var splitLineModel = axisModel.getModel('splitLine');
  30631. var lineStyleModel = splitLineModel.getModel('lineStyle');
  30632. var lineColors = lineStyleModel.get('color');
  30633. var lineInterval = getInterval(splitLineModel, labelInterval);
  30634. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  30635. var gridRect = gridModel.coordinateSystem.getRect();
  30636. var isHorizontal = axis.isHorizontal();
  30637. var lineCount = 0;
  30638. var ticksCoords = axis.getTicksCoords(
  30639. // splitLineModel.get('alignWithLabel')
  30640. );
  30641. var ticks = axis.scale.getTicks();
  30642. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30643. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30644. var p1 = [];
  30645. var p2 = [];
  30646. // Simple optimization
  30647. // Batching the lines if color are the same
  30648. var lineStyle = lineStyleModel.getLineStyle();
  30649. for (var i = 0; i < ticksCoords.length; i++) {
  30650. if (ifIgnoreOnTick(
  30651. axis, i, lineInterval, ticksCoords.length,
  30652. showMinLabel, showMaxLabel
  30653. )) {
  30654. continue;
  30655. }
  30656. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30657. if (isHorizontal) {
  30658. p1[0] = tickCoord;
  30659. p1[1] = gridRect.y;
  30660. p2[0] = tickCoord;
  30661. p2[1] = gridRect.y + gridRect.height;
  30662. }
  30663. else {
  30664. p1[0] = gridRect.x;
  30665. p1[1] = tickCoord;
  30666. p2[0] = gridRect.x + gridRect.width;
  30667. p2[1] = tickCoord;
  30668. }
  30669. var colorIndex = (lineCount++) % lineColors.length;
  30670. this._axisGroup.add(new Line(subPixelOptimizeLine({
  30671. anid: 'line_' + ticks[i],
  30672. shape: {
  30673. x1: p1[0],
  30674. y1: p1[1],
  30675. x2: p2[0],
  30676. y2: p2[1]
  30677. },
  30678. style: defaults({
  30679. stroke: lineColors[colorIndex]
  30680. }, lineStyle),
  30681. silent: true
  30682. })));
  30683. }
  30684. },
  30685. /**
  30686. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30687. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30688. * @param {number|Function} labelInterval
  30689. * @private
  30690. */
  30691. _splitArea: function (axisModel, gridModel, labelInterval) {
  30692. var axis = axisModel.axis;
  30693. if (axis.scale.isBlank()) {
  30694. return;
  30695. }
  30696. var splitAreaModel = axisModel.getModel('splitArea');
  30697. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  30698. var areaColors = areaStyleModel.get('color');
  30699. var gridRect = gridModel.coordinateSystem.getRect();
  30700. var ticksCoords = axis.getTicksCoords(
  30701. // splitAreaModel.get('alignWithLabel')
  30702. );
  30703. var ticks = axis.scale.getTicks();
  30704. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  30705. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  30706. var count = 0;
  30707. var areaInterval = getInterval(splitAreaModel, labelInterval);
  30708. var areaStyle = areaStyleModel.getAreaStyle();
  30709. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  30710. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30711. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30712. for (var i = 1; i < ticksCoords.length; i++) {
  30713. if (ifIgnoreOnTick(
  30714. axis, i, areaInterval, ticksCoords.length,
  30715. showMinLabel, showMaxLabel
  30716. )) {
  30717. continue;
  30718. }
  30719. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30720. var x;
  30721. var y;
  30722. var width;
  30723. var height;
  30724. if (axis.isHorizontal()) {
  30725. x = prevX;
  30726. y = gridRect.y;
  30727. width = tickCoord - x;
  30728. height = gridRect.height;
  30729. }
  30730. else {
  30731. x = gridRect.x;
  30732. y = prevY;
  30733. width = gridRect.width;
  30734. height = tickCoord - y;
  30735. }
  30736. var colorIndex = (count++) % areaColors.length;
  30737. this._axisGroup.add(new Rect({
  30738. anid: 'area_' + ticks[i],
  30739. shape: {
  30740. x: x,
  30741. y: y,
  30742. width: width,
  30743. height: height
  30744. },
  30745. style: defaults({
  30746. fill: areaColors[colorIndex]
  30747. }, areaStyle),
  30748. silent: true
  30749. }));
  30750. prevX = x + width;
  30751. prevY = y + height;
  30752. }
  30753. }
  30754. });
  30755. CartesianAxisView.extend({
  30756. type: 'xAxis'
  30757. });
  30758. CartesianAxisView.extend({
  30759. type: 'yAxis'
  30760. });
  30761. // Grid view
  30762. extendComponentView({
  30763. type: 'grid',
  30764. render: function (gridModel, ecModel) {
  30765. this.group.removeAll();
  30766. if (gridModel.get('show')) {
  30767. this.group.add(new Rect({
  30768. shape: gridModel.coordinateSystem.getRect(),
  30769. style: defaults({
  30770. fill: gridModel.get('backgroundColor')
  30771. }, gridModel.getItemStyle()),
  30772. silent: true,
  30773. z2: -1
  30774. }));
  30775. }
  30776. }
  30777. });
  30778. registerPreprocessor(function (option) {
  30779. // Only create grid when need
  30780. if (option.xAxis && option.yAxis && !option.grid) {
  30781. option.grid = {};
  30782. }
  30783. });
  30784. // In case developer forget to include grid component
  30785. registerVisual(visualSymbol('line', 'circle', 'line'));
  30786. registerLayout(pointsLayout('line'));
  30787. // Down sample after filter
  30788. registerProcessor(
  30789. PRIORITY.PROCESSOR.STATISTIC,
  30790. dataSample('line')
  30791. );
  30792. var BaseBarSeries = SeriesModel.extend({
  30793. type: 'series.__base_bar__',
  30794. getInitialData: function (option, ecModel) {
  30795. return createListFromArray(this.getSource(), this);
  30796. },
  30797. getMarkerPosition: function (value) {
  30798. var coordSys = this.coordinateSystem;
  30799. if (coordSys) {
  30800. // PENDING if clamp ?
  30801. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  30802. var data = this.getData();
  30803. var offset = data.getLayout('offset');
  30804. var size = data.getLayout('size');
  30805. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  30806. pt[offsetIndex] += offset + size / 2;
  30807. return pt;
  30808. }
  30809. return [NaN, NaN];
  30810. },
  30811. defaultOption: {
  30812. zlevel: 0, // 一级层叠
  30813. z: 2, // 二级层叠
  30814. coordinateSystem: 'cartesian2d',
  30815. legendHoverLink: true,
  30816. // stack: null
  30817. // Cartesian coordinate system
  30818. // xAxisIndex: 0,
  30819. // yAxisIndex: 0,
  30820. // 最小高度改为0
  30821. barMinHeight: 0,
  30822. // 最小角度为0,仅对极坐标系下的柱状图有效
  30823. barMinAngle: 0,
  30824. // cursor: null,
  30825. // barMaxWidth: null,
  30826. // 默认自适应
  30827. // barWidth: null,
  30828. // 柱间距离,默认为柱形宽度的30%,可设固定值
  30829. // barGap: '30%',
  30830. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  30831. // barCategoryGap: '20%',
  30832. // label: {
  30833. // show: false
  30834. // },
  30835. itemStyle: {},
  30836. emphasis: {}
  30837. }
  30838. });
  30839. BaseBarSeries.extend({
  30840. type: 'series.bar',
  30841. dependencies: ['grid', 'polar'],
  30842. brushSelector: 'rect'
  30843. });
  30844. function setLabel(
  30845. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  30846. ) {
  30847. var labelModel = itemModel.getModel('label');
  30848. var hoverLabelModel = itemModel.getModel('emphasis.label');
  30849. setLabelStyle(
  30850. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  30851. {
  30852. labelFetcher: seriesModel,
  30853. labelDataIndex: dataIndex,
  30854. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  30855. isRectText: true,
  30856. autoColor: color
  30857. }
  30858. );
  30859. fixPosition(normalStyle);
  30860. fixPosition(hoverStyle);
  30861. }
  30862. function fixPosition(style, labelPositionOutside) {
  30863. if (style.textPosition === 'outside') {
  30864. style.textPosition = labelPositionOutside;
  30865. }
  30866. }
  30867. var getBarItemStyle = makeStyleMapper(
  30868. [
  30869. ['fill', 'color'],
  30870. ['stroke', 'borderColor'],
  30871. ['lineWidth', 'borderWidth'],
  30872. // Compatitable with 2
  30873. ['stroke', 'barBorderColor'],
  30874. ['lineWidth', 'barBorderWidth'],
  30875. ['opacity'],
  30876. ['shadowBlur'],
  30877. ['shadowOffsetX'],
  30878. ['shadowOffsetY'],
  30879. ['shadowColor']
  30880. ]
  30881. );
  30882. var barItemStyle = {
  30883. getBarItemStyle: function (excludes) {
  30884. var style = getBarItemStyle(this, excludes);
  30885. if (this.getBorderLineDash) {
  30886. var lineDash = this.getBorderLineDash();
  30887. lineDash && (style.lineDash = lineDash);
  30888. }
  30889. return style;
  30890. }
  30891. };
  30892. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  30893. // FIXME
  30894. // Just for compatible with ec2.
  30895. extend(Model.prototype, barItemStyle);
  30896. extendChartView({
  30897. type: 'bar',
  30898. render: function (seriesModel, ecModel, api) {
  30899. var coordinateSystemType = seriesModel.get('coordinateSystem');
  30900. if (coordinateSystemType === 'cartesian2d'
  30901. || coordinateSystemType === 'polar'
  30902. ) {
  30903. this._render(seriesModel, ecModel, api);
  30904. }
  30905. else if (__DEV__) {
  30906. console.warn('Only cartesian2d and polar supported for bar.');
  30907. }
  30908. return this.group;
  30909. },
  30910. dispose: noop,
  30911. _render: function (seriesModel, ecModel, api) {
  30912. var group = this.group;
  30913. var data = seriesModel.getData();
  30914. var oldData = this._data;
  30915. var coord = seriesModel.coordinateSystem;
  30916. var baseAxis = coord.getBaseAxis();
  30917. var isHorizontalOrRadial;
  30918. if (coord.type === 'cartesian2d') {
  30919. isHorizontalOrRadial = baseAxis.isHorizontal();
  30920. }
  30921. else if (coord.type === 'polar') {
  30922. isHorizontalOrRadial = baseAxis.dim === 'angle';
  30923. }
  30924. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  30925. data.diff(oldData)
  30926. .add(function (dataIndex) {
  30927. if (!data.hasValue(dataIndex)) {
  30928. return;
  30929. }
  30930. var itemModel = data.getItemModel(dataIndex);
  30931. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  30932. var el = elementCreator[coord.type](
  30933. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  30934. );
  30935. data.setItemGraphicEl(dataIndex, el);
  30936. group.add(el);
  30937. updateStyle(
  30938. el, data, dataIndex, itemModel, layout,
  30939. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30940. );
  30941. })
  30942. .update(function (newIndex, oldIndex) {
  30943. var el = oldData.getItemGraphicEl(oldIndex);
  30944. if (!data.hasValue(newIndex)) {
  30945. group.remove(el);
  30946. return;
  30947. }
  30948. var itemModel = data.getItemModel(newIndex);
  30949. var layout = getLayout[coord.type](data, newIndex, itemModel);
  30950. if (el) {
  30951. updateProps(el, {shape: layout}, animationModel, newIndex);
  30952. }
  30953. else {
  30954. el = elementCreator[coord.type](
  30955. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  30956. );
  30957. }
  30958. data.setItemGraphicEl(newIndex, el);
  30959. // Add back
  30960. group.add(el);
  30961. updateStyle(
  30962. el, data, newIndex, itemModel, layout,
  30963. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30964. );
  30965. })
  30966. .remove(function (dataIndex) {
  30967. var el = oldData.getItemGraphicEl(dataIndex);
  30968. if (coord.type === 'cartesian2d') {
  30969. el && removeRect(dataIndex, animationModel, el);
  30970. }
  30971. else {
  30972. el && removeSector(dataIndex, animationModel, el);
  30973. }
  30974. })
  30975. .execute();
  30976. this._data = data;
  30977. },
  30978. remove: function (ecModel, api) {
  30979. var group = this.group;
  30980. var data = this._data;
  30981. if (ecModel.get('animation')) {
  30982. if (data) {
  30983. data.eachItemGraphicEl(function (el) {
  30984. if (el.type === 'sector') {
  30985. removeSector(el.dataIndex, ecModel, el);
  30986. }
  30987. else {
  30988. removeRect(el.dataIndex, ecModel, el);
  30989. }
  30990. });
  30991. }
  30992. }
  30993. else {
  30994. group.removeAll();
  30995. }
  30996. }
  30997. });
  30998. var elementCreator = {
  30999. cartesian2d: function (
  31000. data, dataIndex, itemModel, layout, isHorizontal,
  31001. animationModel, isUpdate
  31002. ) {
  31003. var rect = new Rect({shape: extend({}, layout)});
  31004. // Animation
  31005. if (animationModel) {
  31006. var rectShape = rect.shape;
  31007. var animateProperty = isHorizontal ? 'height' : 'width';
  31008. var animateTarget = {};
  31009. rectShape[animateProperty] = 0;
  31010. animateTarget[animateProperty] = layout[animateProperty];
  31011. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31012. shape: animateTarget
  31013. }, animationModel, dataIndex);
  31014. }
  31015. return rect;
  31016. },
  31017. polar: function (
  31018. data, dataIndex, itemModel, layout, isRadial,
  31019. animationModel, isUpdate
  31020. ) {
  31021. var sector = new Sector({shape: extend({}, layout)});
  31022. // Animation
  31023. if (animationModel) {
  31024. var sectorShape = sector.shape;
  31025. var animateProperty = isRadial ? 'r' : 'endAngle';
  31026. var animateTarget = {};
  31027. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31028. animateTarget[animateProperty] = layout[animateProperty];
  31029. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31030. shape: animateTarget
  31031. }, animationModel, dataIndex);
  31032. }
  31033. return sector;
  31034. }
  31035. };
  31036. function removeRect(dataIndex, animationModel, el) {
  31037. // Not show text when animating
  31038. el.style.text = null;
  31039. updateProps(el, {
  31040. shape: {
  31041. width: 0
  31042. }
  31043. }, animationModel, dataIndex, function () {
  31044. el.parent && el.parent.remove(el);
  31045. });
  31046. }
  31047. function removeSector(dataIndex, animationModel, el) {
  31048. // Not show text when animating
  31049. el.style.text = null;
  31050. updateProps(el, {
  31051. shape: {
  31052. r: el.shape.r0
  31053. }
  31054. }, animationModel, dataIndex, function () {
  31055. el.parent && el.parent.remove(el);
  31056. });
  31057. }
  31058. var getLayout = {
  31059. cartesian2d: function (data, dataIndex, itemModel) {
  31060. var layout = data.getItemLayout(dataIndex);
  31061. var fixedLineWidth = getLineWidth(itemModel, layout);
  31062. // fix layout with lineWidth
  31063. var signX = layout.width > 0 ? 1 : -1;
  31064. var signY = layout.height > 0 ? 1 : -1;
  31065. return {
  31066. x: layout.x + signX * fixedLineWidth / 2,
  31067. y: layout.y + signY * fixedLineWidth / 2,
  31068. width: layout.width - signX * fixedLineWidth,
  31069. height: layout.height - signY * fixedLineWidth
  31070. };
  31071. },
  31072. polar: function (data, dataIndex, itemModel) {
  31073. var layout = data.getItemLayout(dataIndex);
  31074. return {
  31075. cx: layout.cx,
  31076. cy: layout.cy,
  31077. r0: layout.r0,
  31078. r: layout.r,
  31079. startAngle: layout.startAngle,
  31080. endAngle: layout.endAngle
  31081. };
  31082. }
  31083. };
  31084. function updateStyle(
  31085. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31086. ) {
  31087. var color = data.getItemVisual(dataIndex, 'color');
  31088. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31089. var itemStyleModel = itemModel.getModel('itemStyle');
  31090. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31091. if (!isPolar) {
  31092. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31093. }
  31094. el.useStyle(defaults(
  31095. {
  31096. fill: color,
  31097. opacity: opacity
  31098. },
  31099. itemStyleModel.getBarItemStyle()
  31100. ));
  31101. var cursorStyle = itemModel.getShallow('cursor');
  31102. cursorStyle && el.attr('cursor', cursorStyle);
  31103. var labelPositionOutside = isHorizontal
  31104. ? (layout.height > 0 ? 'bottom' : 'top')
  31105. : (layout.width > 0 ? 'left' : 'right');
  31106. if (!isPolar) {
  31107. setLabel(
  31108. el.style, hoverStyle, itemModel, color,
  31109. seriesModel, dataIndex, labelPositionOutside
  31110. );
  31111. }
  31112. setHoverStyle(el, hoverStyle);
  31113. }
  31114. // In case width or height are too small.
  31115. function getLineWidth(itemModel, rawLayout) {
  31116. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31117. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31118. }
  31119. // In case developer forget to include grid component
  31120. registerLayout(curry(layout, 'bar'));
  31121. // Visual coding for legend
  31122. registerVisual(function (ecModel) {
  31123. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31124. var data = seriesModel.getData();
  31125. data.setVisual('legendSymbol', 'roundRect');
  31126. });
  31127. });
  31128. /**
  31129. * [Usage]:
  31130. * (1)
  31131. * createListSimply(seriesModel, ['value']);
  31132. * (2)
  31133. * createListSimply(seriesModel, {
  31134. * coordDimensions: ['value'],
  31135. * dimensionsCount: 5
  31136. * });
  31137. *
  31138. * @param {module:echarts/model/Series} seriesModel
  31139. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31140. * The options in opt, see `echarts/data/helper/createDimensions`
  31141. * @param {Array.<string>} [nameList]
  31142. * @return {module:echarts/data/List}
  31143. */
  31144. var createListSimply = function (seriesModel, opt, nameList) {
  31145. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31146. var source = seriesModel.getSource();
  31147. var dimensionsInfo = createDimensions(source, opt);
  31148. var list = new List(dimensionsInfo, seriesModel);
  31149. list.initData(source, nameList);
  31150. return list;
  31151. };
  31152. /**
  31153. * Data selectable mixin for chart series.
  31154. * To eanble data select, option of series must have `selectedMode`.
  31155. * And each data item will use `selected` to toggle itself selected status
  31156. */
  31157. var dataSelectableMixin = {
  31158. /**
  31159. * @param {Array.<Object>|module:echars/data/List} targetList
  31160. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31161. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31162. */
  31163. updateSelectedMap: function (targetList) {
  31164. if (isArray(targetList)) {
  31165. this._targetList = targetList.slice();
  31166. }
  31167. else {
  31168. var ecList = targetList;
  31169. var valueDim = ecList.mapDimension('value');
  31170. var targetList = this._targetList = [];
  31171. for (var i = 0, len = ecList.count(); i < len; i++) {
  31172. targetList.push({
  31173. name: ecList.getName(i),
  31174. value: ecList.get(valueDim, i),
  31175. selected: retrieveRawAttr(ecList, i, 'selected')
  31176. });
  31177. }
  31178. }
  31179. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31180. targetMap.set(target.name, target);
  31181. return targetMap;
  31182. }, createHashMap());
  31183. },
  31184. /**
  31185. * Either name or id should be passed as input here.
  31186. * If both of them are defined, id is used.
  31187. *
  31188. * @param {string|undefined} name name of data
  31189. * @param {number|undefined} id dataIndex of data
  31190. */
  31191. // PENGING If selectedMode is null ?
  31192. select: function (name, id) {
  31193. var target = id != null
  31194. ? this._targetList[id]
  31195. : this._selectTargetMap.get(name);
  31196. var selectedMode = this.get('selectedMode');
  31197. if (selectedMode === 'single') {
  31198. this._selectTargetMap.each(function (target) {
  31199. target.selected = false;
  31200. });
  31201. }
  31202. target && (target.selected = true);
  31203. },
  31204. /**
  31205. * Either name or id should be passed as input here.
  31206. * If both of them are defined, id is used.
  31207. *
  31208. * @param {string|undefined} name name of data
  31209. * @param {number|undefined} id dataIndex of data
  31210. */
  31211. unSelect: function (name, id) {
  31212. var target = id != null
  31213. ? this._targetList[id]
  31214. : this._selectTargetMap.get(name);
  31215. // var selectedMode = this.get('selectedMode');
  31216. // selectedMode !== 'single' && target && (target.selected = false);
  31217. target && (target.selected = false);
  31218. },
  31219. /**
  31220. * Either name or id should be passed as input here.
  31221. * If both of them are defined, id is used.
  31222. *
  31223. * @param {string|undefined} name name of data
  31224. * @param {number|undefined} id dataIndex of data
  31225. */
  31226. toggleSelected: function (name, id) {
  31227. var target = id != null
  31228. ? this._targetList[id]
  31229. : this._selectTargetMap.get(name);
  31230. if (target != null) {
  31231. this[target.selected ? 'unSelect' : 'select'](name, id);
  31232. return target.selected;
  31233. }
  31234. },
  31235. /**
  31236. * Either name or id should be passed as input here.
  31237. * If both of them are defined, id is used.
  31238. *
  31239. * @param {string|undefined} name name of data
  31240. * @param {number|undefined} id dataIndex of data
  31241. */
  31242. isSelected: function (name, id) {
  31243. var target = id != null
  31244. ? this._targetList[id]
  31245. : this._selectTargetMap.get(name);
  31246. return target && target.selected;
  31247. }
  31248. };
  31249. var PieSeries = extendSeriesModel({
  31250. type: 'series.pie',
  31251. // Overwrite
  31252. init: function (option) {
  31253. PieSeries.superApply(this, 'init', arguments);
  31254. // Enable legend selection for each data item
  31255. // Use a function instead of direct access because data reference may changed
  31256. this.legendDataProvider = function () {
  31257. return this.getRawData();
  31258. };
  31259. this.updateSelectedMap(this.getRawData());
  31260. this._defaultLabelLine(option);
  31261. },
  31262. // Overwrite
  31263. mergeOption: function (newOption) {
  31264. PieSeries.superCall(this, 'mergeOption', newOption);
  31265. this.updateSelectedMap(this.getRawData());
  31266. },
  31267. getInitialData: function (option, ecModel) {
  31268. return createListSimply(this, ['value']);
  31269. },
  31270. // Overwrite
  31271. getDataParams: function (dataIndex) {
  31272. var data = this.getData();
  31273. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  31274. // FIXME toFixed?
  31275. var valueList = [];
  31276. data.each(data.mapDimension('value'), function (value) {
  31277. valueList.push(value);
  31278. });
  31279. params.percent = getPercentWithPrecision(
  31280. valueList,
  31281. dataIndex,
  31282. data.hostModel.get('percentPrecision')
  31283. );
  31284. params.$vars.push('percent');
  31285. return params;
  31286. },
  31287. _defaultLabelLine: function (option) {
  31288. // Extend labelLine emphasis
  31289. defaultEmphasis(option, 'labelLine', ['show']);
  31290. var labelLineNormalOpt = option.labelLine;
  31291. var labelLineEmphasisOpt = option.emphasis.labelLine;
  31292. // Not show label line if `label.normal.show = false`
  31293. labelLineNormalOpt.show = labelLineNormalOpt.show
  31294. && option.label.show;
  31295. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  31296. && option.emphasis.label.show;
  31297. },
  31298. defaultOption: {
  31299. zlevel: 0,
  31300. z: 2,
  31301. legendHoverLink: true,
  31302. hoverAnimation: true,
  31303. // 默认全局居中
  31304. center: ['50%', '50%'],
  31305. radius: [0, '75%'],
  31306. // 默认顺时针
  31307. clockwise: true,
  31308. startAngle: 90,
  31309. // 最小角度改为0
  31310. minAngle: 0,
  31311. // 选中时扇区偏移量
  31312. selectedOffset: 10,
  31313. // 高亮扇区偏移量
  31314. hoverOffset: 10,
  31315. // If use strategy to avoid label overlapping
  31316. avoidLabelOverlap: true,
  31317. // 选择模式,默认关闭,可选single,multiple
  31318. // selectedMode: false,
  31319. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  31320. // roseType: null,
  31321. percentPrecision: 2,
  31322. // If still show when all data zero.
  31323. stillShowZeroSum: true,
  31324. // cursor: null,
  31325. label: {
  31326. // If rotate around circle
  31327. rotate: false,
  31328. show: true,
  31329. // 'outer', 'inside', 'center'
  31330. position: 'outer'
  31331. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  31332. // 默认使用全局文本样式,详见TEXTSTYLE
  31333. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  31334. },
  31335. // Enabled when label.normal.position is 'outer'
  31336. labelLine: {
  31337. show: true,
  31338. // 引导线两段中的第一段长度
  31339. length: 15,
  31340. // 引导线两段中的第二段长度
  31341. length2: 15,
  31342. smooth: false,
  31343. lineStyle: {
  31344. // color: 各异,
  31345. width: 1,
  31346. type: 'solid'
  31347. }
  31348. },
  31349. itemStyle: {
  31350. borderWidth: 1
  31351. },
  31352. // Animation type canbe expansion, scale
  31353. animationType: 'expansion',
  31354. animationEasing: 'cubicOut'
  31355. }
  31356. });
  31357. mixin(PieSeries, dataSelectableMixin);
  31358. /**
  31359. * @param {module:echarts/model/Series} seriesModel
  31360. * @param {boolean} hasAnimation
  31361. * @inner
  31362. */
  31363. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  31364. var data = seriesModel.getData();
  31365. var dataIndex = this.dataIndex;
  31366. var name = data.getName(dataIndex);
  31367. var selectedOffset = seriesModel.get('selectedOffset');
  31368. api.dispatchAction({
  31369. type: 'pieToggleSelect',
  31370. from: uid,
  31371. name: name,
  31372. seriesId: seriesModel.id
  31373. });
  31374. data.each(function (idx) {
  31375. toggleItemSelected(
  31376. data.getItemGraphicEl(idx),
  31377. data.getItemLayout(idx),
  31378. seriesModel.isSelected(data.getName(idx)),
  31379. selectedOffset,
  31380. hasAnimation
  31381. );
  31382. });
  31383. }
  31384. /**
  31385. * @param {module:zrender/graphic/Sector} el
  31386. * @param {Object} layout
  31387. * @param {boolean} isSelected
  31388. * @param {number} selectedOffset
  31389. * @param {boolean} hasAnimation
  31390. * @inner
  31391. */
  31392. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  31393. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31394. var dx = Math.cos(midAngle);
  31395. var dy = Math.sin(midAngle);
  31396. var offset = isSelected ? selectedOffset : 0;
  31397. var position = [dx * offset, dy * offset];
  31398. hasAnimation
  31399. // animateTo will stop revious animation like update transition
  31400. ? el.animate()
  31401. .when(200, {
  31402. position: position
  31403. })
  31404. .start('bounceOut')
  31405. : el.attr('position', position);
  31406. }
  31407. /**
  31408. * Piece of pie including Sector, Label, LabelLine
  31409. * @constructor
  31410. * @extends {module:zrender/graphic/Group}
  31411. */
  31412. function PiePiece(data, idx) {
  31413. Group.call(this);
  31414. var sector = new Sector({
  31415. z2: 2
  31416. });
  31417. var polyline = new Polyline();
  31418. var text = new Text();
  31419. this.add(sector);
  31420. this.add(polyline);
  31421. this.add(text);
  31422. this.updateData(data, idx, true);
  31423. // Hover to change label and labelLine
  31424. function onEmphasis() {
  31425. polyline.ignore = polyline.hoverIgnore;
  31426. text.ignore = text.hoverIgnore;
  31427. }
  31428. function onNormal() {
  31429. polyline.ignore = polyline.normalIgnore;
  31430. text.ignore = text.normalIgnore;
  31431. }
  31432. this.on('emphasis', onEmphasis)
  31433. .on('normal', onNormal)
  31434. .on('mouseover', onEmphasis)
  31435. .on('mouseout', onNormal);
  31436. }
  31437. var piePieceProto = PiePiece.prototype;
  31438. piePieceProto.updateData = function (data, idx, firstCreate) {
  31439. var sector = this.childAt(0);
  31440. var seriesModel = data.hostModel;
  31441. var itemModel = data.getItemModel(idx);
  31442. var layout = data.getItemLayout(idx);
  31443. var sectorShape = extend({}, layout);
  31444. sectorShape.label = null;
  31445. if (firstCreate) {
  31446. sector.setShape(sectorShape);
  31447. var animationType = seriesModel.getShallow('animationType');
  31448. if (animationType === 'scale') {
  31449. sector.shape.r = layout.r0;
  31450. initProps(sector, {
  31451. shape: {
  31452. r: layout.r
  31453. }
  31454. }, seriesModel, idx);
  31455. }
  31456. // Expansion
  31457. else {
  31458. sector.shape.endAngle = layout.startAngle;
  31459. updateProps(sector, {
  31460. shape: {
  31461. endAngle: layout.endAngle
  31462. }
  31463. }, seriesModel, idx);
  31464. }
  31465. }
  31466. else {
  31467. updateProps(sector, {
  31468. shape: sectorShape
  31469. }, seriesModel, idx);
  31470. }
  31471. // Update common style
  31472. var visualColor = data.getItemVisual(idx, 'color');
  31473. sector.useStyle(
  31474. defaults(
  31475. {
  31476. lineJoin: 'bevel',
  31477. fill: visualColor
  31478. },
  31479. itemModel.getModel('itemStyle').getItemStyle()
  31480. )
  31481. );
  31482. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  31483. var cursorStyle = itemModel.getShallow('cursor');
  31484. cursorStyle && sector.attr('cursor', cursorStyle);
  31485. // Toggle selected
  31486. toggleItemSelected(
  31487. this,
  31488. data.getItemLayout(idx),
  31489. seriesModel.isSelected(null, idx),
  31490. seriesModel.get('selectedOffset'),
  31491. seriesModel.get('animation')
  31492. );
  31493. function onEmphasis() {
  31494. // Sector may has animation of updating data. Force to move to the last frame
  31495. // Or it may stopped on the wrong shape
  31496. sector.stopAnimation(true);
  31497. sector.animateTo({
  31498. shape: {
  31499. r: layout.r + seriesModel.get('hoverOffset')
  31500. }
  31501. }, 300, 'elasticOut');
  31502. }
  31503. function onNormal() {
  31504. sector.stopAnimation(true);
  31505. sector.animateTo({
  31506. shape: {
  31507. r: layout.r
  31508. }
  31509. }, 300, 'elasticOut');
  31510. }
  31511. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  31512. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  31513. sector
  31514. .on('mouseover', onEmphasis)
  31515. .on('mouseout', onNormal)
  31516. .on('emphasis', onEmphasis)
  31517. .on('normal', onNormal);
  31518. }
  31519. this._updateLabel(data, idx);
  31520. setHoverStyle(this);
  31521. };
  31522. piePieceProto._updateLabel = function (data, idx) {
  31523. var labelLine = this.childAt(1);
  31524. var labelText = this.childAt(2);
  31525. var seriesModel = data.hostModel;
  31526. var itemModel = data.getItemModel(idx);
  31527. var layout = data.getItemLayout(idx);
  31528. var labelLayout = layout.label;
  31529. var visualColor = data.getItemVisual(idx, 'color');
  31530. updateProps(labelLine, {
  31531. shape: {
  31532. points: labelLayout.linePoints || [
  31533. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  31534. ]
  31535. }
  31536. }, seriesModel, idx);
  31537. updateProps(labelText, {
  31538. style: {
  31539. x: labelLayout.x,
  31540. y: labelLayout.y
  31541. }
  31542. }, seriesModel, idx);
  31543. labelText.attr({
  31544. rotation: labelLayout.rotation,
  31545. origin: [labelLayout.x, labelLayout.y],
  31546. z2: 10
  31547. });
  31548. var labelModel = itemModel.getModel('label');
  31549. var labelHoverModel = itemModel.getModel('emphasis.label');
  31550. var labelLineModel = itemModel.getModel('labelLine');
  31551. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  31552. var visualColor = data.getItemVisual(idx, 'color');
  31553. setLabelStyle(
  31554. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  31555. {
  31556. labelFetcher: data.hostModel,
  31557. labelDataIndex: idx,
  31558. defaultText: data.getName(idx),
  31559. autoColor: visualColor,
  31560. useInsideStyle: !!labelLayout.inside
  31561. },
  31562. {
  31563. textAlign: labelLayout.textAlign,
  31564. textVerticalAlign: labelLayout.verticalAlign,
  31565. opacity: data.getItemVisual(idx, 'opacity')
  31566. }
  31567. );
  31568. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  31569. labelText.hoverIgnore = !labelHoverModel.get('show');
  31570. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  31571. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  31572. // Default use item visual color
  31573. labelLine.setStyle({
  31574. stroke: visualColor,
  31575. opacity: data.getItemVisual(idx, 'opacity')
  31576. });
  31577. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  31578. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  31579. var smooth = labelLineModel.get('smooth');
  31580. if (smooth && smooth === true) {
  31581. smooth = 0.4;
  31582. }
  31583. labelLine.setShape({
  31584. smooth: smooth
  31585. });
  31586. };
  31587. inherits(PiePiece, Group);
  31588. // Pie view
  31589. var PieView = Chart.extend({
  31590. type: 'pie',
  31591. init: function () {
  31592. var sectorGroup = new Group();
  31593. this._sectorGroup = sectorGroup;
  31594. },
  31595. render: function (seriesModel, ecModel, api, payload) {
  31596. if (payload && (payload.from === this.uid)) {
  31597. return;
  31598. }
  31599. var data = seriesModel.getData();
  31600. var oldData = this._data;
  31601. var group = this.group;
  31602. var hasAnimation = ecModel.get('animation');
  31603. var isFirstRender = !oldData;
  31604. var animationType = seriesModel.get('animationType');
  31605. var onSectorClick = curry(
  31606. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  31607. );
  31608. var selectedMode = seriesModel.get('selectedMode');
  31609. data.diff(oldData)
  31610. .add(function (idx) {
  31611. var piePiece = new PiePiece(data, idx);
  31612. // Default expansion animation
  31613. if (isFirstRender && animationType !== 'scale') {
  31614. piePiece.eachChild(function (child) {
  31615. child.stopAnimation(true);
  31616. });
  31617. }
  31618. selectedMode && piePiece.on('click', onSectorClick);
  31619. data.setItemGraphicEl(idx, piePiece);
  31620. group.add(piePiece);
  31621. })
  31622. .update(function (newIdx, oldIdx) {
  31623. var piePiece = oldData.getItemGraphicEl(oldIdx);
  31624. piePiece.updateData(data, newIdx);
  31625. piePiece.off('click');
  31626. selectedMode && piePiece.on('click', onSectorClick);
  31627. group.add(piePiece);
  31628. data.setItemGraphicEl(newIdx, piePiece);
  31629. })
  31630. .remove(function (idx) {
  31631. var piePiece = oldData.getItemGraphicEl(idx);
  31632. group.remove(piePiece);
  31633. })
  31634. .execute();
  31635. if (
  31636. hasAnimation && isFirstRender && data.count() > 0
  31637. // Default expansion animation
  31638. && animationType !== 'scale'
  31639. ) {
  31640. var shape = data.getItemLayout(0);
  31641. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  31642. var removeClipPath = bind(group.removeClipPath, group);
  31643. group.setClipPath(this._createClipPath(
  31644. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  31645. ));
  31646. }
  31647. this._data = data;
  31648. },
  31649. dispose: function () {},
  31650. _createClipPath: function (
  31651. cx, cy, r, startAngle, clockwise, cb, seriesModel
  31652. ) {
  31653. var clipPath = new Sector({
  31654. shape: {
  31655. cx: cx,
  31656. cy: cy,
  31657. r0: 0,
  31658. r: r,
  31659. startAngle: startAngle,
  31660. endAngle: startAngle,
  31661. clockwise: clockwise
  31662. }
  31663. });
  31664. initProps(clipPath, {
  31665. shape: {
  31666. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  31667. }
  31668. }, seriesModel, cb);
  31669. return clipPath;
  31670. },
  31671. /**
  31672. * @implement
  31673. */
  31674. containPoint: function (point, seriesModel) {
  31675. var data = seriesModel.getData();
  31676. var itemLayout = data.getItemLayout(0);
  31677. if (itemLayout) {
  31678. var dx = point[0] - itemLayout.cx;
  31679. var dy = point[1] - itemLayout.cy;
  31680. var radius = Math.sqrt(dx * dx + dy * dy);
  31681. return radius <= itemLayout.r && radius >= itemLayout.r0;
  31682. }
  31683. }
  31684. });
  31685. var createDataSelectAction = function (seriesType, actionInfos) {
  31686. each$1(actionInfos, function (actionInfo) {
  31687. actionInfo.update = 'updateView';
  31688. /**
  31689. * @payload
  31690. * @property {string} seriesName
  31691. * @property {string} name
  31692. */
  31693. registerAction(actionInfo, function (payload, ecModel) {
  31694. var selected = {};
  31695. ecModel.eachComponent(
  31696. {mainType: 'series', subType: seriesType, query: payload},
  31697. function (seriesModel) {
  31698. if (seriesModel[actionInfo.method]) {
  31699. seriesModel[actionInfo.method](
  31700. payload.name,
  31701. payload.dataIndex
  31702. );
  31703. }
  31704. var data = seriesModel.getData();
  31705. // Create selected map
  31706. data.each(function (idx) {
  31707. var name = data.getName(idx);
  31708. selected[name] = seriesModel.isSelected(name)
  31709. || false;
  31710. });
  31711. }
  31712. );
  31713. return {
  31714. name: payload.name,
  31715. selected: selected
  31716. };
  31717. });
  31718. });
  31719. };
  31720. // Pick color from palette for each data item.
  31721. // Applicable for charts that require applying color palette
  31722. // in data level (like pie, funnel, chord).
  31723. var dataColor = function (seriesType) {
  31724. return {
  31725. getTargetSeries: function (ecModel) {
  31726. // Pie and funnel may use diferrent scope
  31727. var paletteScope = {};
  31728. var seiresModelMap = createHashMap();
  31729. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31730. seriesModel.__paletteScope = paletteScope;
  31731. seiresModelMap.set(seriesModel.uid, seriesModel);
  31732. });
  31733. return seiresModelMap;
  31734. },
  31735. reset: function (seriesModel, ecModel) {
  31736. var dataAll = seriesModel.getRawData();
  31737. var idxMap = {};
  31738. var data = seriesModel.getData();
  31739. data.each(function (idx) {
  31740. var rawIdx = data.getRawIndex(idx);
  31741. idxMap[rawIdx] = idx;
  31742. });
  31743. dataAll.each(function (rawIdx) {
  31744. var filteredIdx = idxMap[rawIdx];
  31745. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  31746. var singleDataColor = filteredIdx != null
  31747. && data.getItemVisual(filteredIdx, 'color', true);
  31748. if (!singleDataColor) {
  31749. // FIXME Performance
  31750. var itemModel = dataAll.getItemModel(rawIdx);
  31751. var color = itemModel.get('itemStyle.color')
  31752. || seriesModel.getColorFromPalette(
  31753. dataAll.getName(rawIdx), seriesModel.__paletteScope,
  31754. dataAll.count()
  31755. );
  31756. // Legend may use the visual info in data before processed
  31757. dataAll.setItemVisual(rawIdx, 'color', color);
  31758. // Data is not filtered
  31759. if (filteredIdx != null) {
  31760. data.setItemVisual(filteredIdx, 'color', color);
  31761. }
  31762. }
  31763. else {
  31764. // Set data all color for legend
  31765. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  31766. }
  31767. });
  31768. }
  31769. };
  31770. };
  31771. // FIXME emphasis label position is not same with normal label position
  31772. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  31773. list.sort(function (a, b) {
  31774. return a.y - b.y;
  31775. });
  31776. // 压
  31777. function shiftDown(start, end, delta, dir) {
  31778. for (var j = start; j < end; j++) {
  31779. list[j].y += delta;
  31780. if (j > start
  31781. && j + 1 < end
  31782. && list[j + 1].y > list[j].y + list[j].height
  31783. ) {
  31784. shiftUp(j, delta / 2);
  31785. return;
  31786. }
  31787. }
  31788. shiftUp(end - 1, delta / 2);
  31789. }
  31790. // 弹
  31791. function shiftUp(end, delta) {
  31792. for (var j = end; j >= 0; j--) {
  31793. list[j].y -= delta;
  31794. if (j > 0
  31795. && list[j].y > list[j - 1].y + list[j - 1].height
  31796. ) {
  31797. break;
  31798. }
  31799. }
  31800. }
  31801. function changeX(list, isDownList, cx, cy, r, dir) {
  31802. var lastDeltaX = dir > 0
  31803. ? isDownList // 右侧
  31804. ? Number.MAX_VALUE // 下
  31805. : 0 // 上
  31806. : isDownList // 左侧
  31807. ? Number.MAX_VALUE // 下
  31808. : 0; // 上
  31809. for (var i = 0, l = list.length; i < l; i++) {
  31810. // Not change x for center label
  31811. if (list[i].position === 'center') {
  31812. continue;
  31813. }
  31814. var deltaY = Math.abs(list[i].y - cy);
  31815. var length = list[i].len;
  31816. var length2 = list[i].len2;
  31817. var deltaX = (deltaY < r + length)
  31818. ? Math.sqrt(
  31819. (r + length + length2) * (r + length + length2)
  31820. - deltaY * deltaY
  31821. )
  31822. : Math.abs(list[i].x - cx);
  31823. if (isDownList && deltaX >= lastDeltaX) {
  31824. // 右下,左下
  31825. deltaX = lastDeltaX - 10;
  31826. }
  31827. if (!isDownList && deltaX <= lastDeltaX) {
  31828. // 右上,左上
  31829. deltaX = lastDeltaX + 10;
  31830. }
  31831. list[i].x = cx + deltaX * dir;
  31832. lastDeltaX = deltaX;
  31833. }
  31834. }
  31835. var lastY = 0;
  31836. var delta;
  31837. var len = list.length;
  31838. var upList = [];
  31839. var downList = [];
  31840. for (var i = 0; i < len; i++) {
  31841. delta = list[i].y - lastY;
  31842. if (delta < 0) {
  31843. shiftDown(i, len, -delta, dir);
  31844. }
  31845. lastY = list[i].y + list[i].height;
  31846. }
  31847. if (viewHeight - lastY < 0) {
  31848. shiftUp(len - 1, lastY - viewHeight);
  31849. }
  31850. for (var i = 0; i < len; i++) {
  31851. if (list[i].y >= cy) {
  31852. downList.push(list[i]);
  31853. }
  31854. else {
  31855. upList.push(list[i]);
  31856. }
  31857. }
  31858. changeX(upList, false, cx, cy, r, dir);
  31859. changeX(downList, true, cx, cy, r, dir);
  31860. }
  31861. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  31862. var leftList = [];
  31863. var rightList = [];
  31864. for (var i = 0; i < labelLayoutList.length; i++) {
  31865. if (labelLayoutList[i].x < cx) {
  31866. leftList.push(labelLayoutList[i]);
  31867. }
  31868. else {
  31869. rightList.push(labelLayoutList[i]);
  31870. }
  31871. }
  31872. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  31873. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  31874. for (var i = 0; i < labelLayoutList.length; i++) {
  31875. var linePoints = labelLayoutList[i].linePoints;
  31876. if (linePoints) {
  31877. var dist = linePoints[1][0] - linePoints[2][0];
  31878. if (labelLayoutList[i].x < cx) {
  31879. linePoints[2][0] = labelLayoutList[i].x + 3;
  31880. }
  31881. else {
  31882. linePoints[2][0] = labelLayoutList[i].x - 3;
  31883. }
  31884. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  31885. linePoints[1][0] = linePoints[2][0] + dist;
  31886. }
  31887. }
  31888. }
  31889. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  31890. var data = seriesModel.getData();
  31891. var labelLayoutList = [];
  31892. var cx;
  31893. var cy;
  31894. var hasLabelRotate = false;
  31895. data.each(function (idx) {
  31896. var layout = data.getItemLayout(idx);
  31897. var itemModel = data.getItemModel(idx);
  31898. var labelModel = itemModel.getModel('label');
  31899. // Use position in normal or emphasis
  31900. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  31901. var labelLineModel = itemModel.getModel('labelLine');
  31902. var labelLineLen = labelLineModel.get('length');
  31903. var labelLineLen2 = labelLineModel.get('length2');
  31904. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31905. var dx = Math.cos(midAngle);
  31906. var dy = Math.sin(midAngle);
  31907. var textX;
  31908. var textY;
  31909. var linePoints;
  31910. var textAlign;
  31911. cx = layout.cx;
  31912. cy = layout.cy;
  31913. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  31914. if (labelPosition === 'center') {
  31915. textX = layout.cx;
  31916. textY = layout.cy;
  31917. textAlign = 'center';
  31918. }
  31919. else {
  31920. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  31921. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  31922. textX = x1 + dx * 3;
  31923. textY = y1 + dy * 3;
  31924. if (!isLabelInside) {
  31925. // For roseType
  31926. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  31927. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  31928. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  31929. var y3 = y2;
  31930. textX = x3 + (dx < 0 ? -5 : 5);
  31931. textY = y3;
  31932. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  31933. }
  31934. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  31935. }
  31936. var font = labelModel.getFont();
  31937. var labelRotate = labelModel.get('rotate')
  31938. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  31939. var text = seriesModel.getFormattedLabel(idx, 'normal')
  31940. || data.getName(idx);
  31941. var textRect = getBoundingRect(
  31942. text, font, textAlign, 'top'
  31943. );
  31944. hasLabelRotate = !!labelRotate;
  31945. layout.label = {
  31946. x: textX,
  31947. y: textY,
  31948. position: labelPosition,
  31949. height: textRect.height,
  31950. len: labelLineLen,
  31951. len2: labelLineLen2,
  31952. linePoints: linePoints,
  31953. textAlign: textAlign,
  31954. verticalAlign: 'middle',
  31955. rotation: labelRotate,
  31956. inside: isLabelInside
  31957. };
  31958. // Not layout the inside label
  31959. if (!isLabelInside) {
  31960. labelLayoutList.push(layout.label);
  31961. }
  31962. });
  31963. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  31964. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  31965. }
  31966. };
  31967. var PI2$4 = Math.PI * 2;
  31968. var RADIAN = Math.PI / 180;
  31969. var pieLayout = function (seriesType, ecModel, api, payload) {
  31970. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31971. var data = seriesModel.getData();
  31972. var valueDim = data.mapDimension('value');
  31973. var center = seriesModel.get('center');
  31974. var radius = seriesModel.get('radius');
  31975. if (!isArray(radius)) {
  31976. radius = [0, radius];
  31977. }
  31978. if (!isArray(center)) {
  31979. center = [center, center];
  31980. }
  31981. var width = api.getWidth();
  31982. var height = api.getHeight();
  31983. var size = Math.min(width, height);
  31984. var cx = parsePercent$1(center[0], width);
  31985. var cy = parsePercent$1(center[1], height);
  31986. var r0 = parsePercent$1(radius[0], size / 2);
  31987. var r = parsePercent$1(radius[1], size / 2);
  31988. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  31989. var minAngle = seriesModel.get('minAngle') * RADIAN;
  31990. var validDataCount = 0;
  31991. data.each(valueDim, function (value) {
  31992. !isNaN(value) && validDataCount++;
  31993. });
  31994. var sum = data.getSum(valueDim);
  31995. // Sum may be 0
  31996. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  31997. var clockwise = seriesModel.get('clockwise');
  31998. var roseType = seriesModel.get('roseType');
  31999. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32000. // [0...max]
  32001. var extent = data.getDataExtent(valueDim);
  32002. extent[0] = 0;
  32003. // In the case some sector angle is smaller than minAngle
  32004. var restAngle = PI2$4;
  32005. var valueSumLargerThanMinAngle = 0;
  32006. var currentAngle = startAngle;
  32007. var dir = clockwise ? 1 : -1;
  32008. data.each(valueDim, function (value, idx) {
  32009. var angle;
  32010. if (isNaN(value)) {
  32011. data.setItemLayout(idx, {
  32012. angle: NaN,
  32013. startAngle: NaN,
  32014. endAngle: NaN,
  32015. clockwise: clockwise,
  32016. cx: cx,
  32017. cy: cy,
  32018. r0: r0,
  32019. r: roseType
  32020. ? NaN
  32021. : r
  32022. });
  32023. return;
  32024. }
  32025. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32026. if (roseType !== 'area') {
  32027. angle = (sum === 0 && stillShowZeroSum)
  32028. ? unitRadian : (value * unitRadian);
  32029. }
  32030. else {
  32031. angle = PI2$4 / validDataCount;
  32032. }
  32033. if (angle < minAngle) {
  32034. angle = minAngle;
  32035. restAngle -= minAngle;
  32036. }
  32037. else {
  32038. valueSumLargerThanMinAngle += value;
  32039. }
  32040. var endAngle = currentAngle + dir * angle;
  32041. data.setItemLayout(idx, {
  32042. angle: angle,
  32043. startAngle: currentAngle,
  32044. endAngle: endAngle,
  32045. clockwise: clockwise,
  32046. cx: cx,
  32047. cy: cy,
  32048. r0: r0,
  32049. r: roseType
  32050. ? linearMap(value, extent, [r0, r])
  32051. : r
  32052. });
  32053. currentAngle = endAngle;
  32054. }, true);
  32055. // Some sector is constrained by minAngle
  32056. // Rest sectors needs recalculate angle
  32057. if (restAngle < PI2$4 && validDataCount) {
  32058. // Average the angle if rest angle is not enough after all angles is
  32059. // Constrained by minAngle
  32060. if (restAngle <= 1e-3) {
  32061. var angle = PI2$4 / validDataCount;
  32062. data.each(valueDim, function (value, idx) {
  32063. if (!isNaN(value)) {
  32064. var layout = data.getItemLayout(idx);
  32065. layout.angle = angle;
  32066. layout.startAngle = startAngle + dir * idx * angle;
  32067. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32068. }
  32069. });
  32070. }
  32071. else {
  32072. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32073. currentAngle = startAngle;
  32074. data.each(valueDim, function (value, idx) {
  32075. if (!isNaN(value)) {
  32076. var layout = data.getItemLayout(idx);
  32077. var angle = layout.angle === minAngle
  32078. ? minAngle : value * unitRadian;
  32079. layout.startAngle = currentAngle;
  32080. layout.endAngle = currentAngle + dir * angle;
  32081. currentAngle += dir * angle;
  32082. }
  32083. });
  32084. }
  32085. }
  32086. labelLayout(seriesModel, r, width, height);
  32087. });
  32088. };
  32089. var dataFilter = function (seriesType) {
  32090. return {
  32091. seriesType: seriesType,
  32092. reset: function (seriesModel, ecModel) {
  32093. var legendModels = ecModel.findComponents({
  32094. mainType: 'legend'
  32095. });
  32096. if (!legendModels || !legendModels.length) {
  32097. return;
  32098. }
  32099. var data = seriesModel.getData();
  32100. data.filterSelf(function (idx) {
  32101. var name = data.getName(idx);
  32102. // If in any legend component the status is not selected.
  32103. for (var i = 0; i < legendModels.length; i++) {
  32104. if (!legendModels[i].isSelected(name)) {
  32105. return false;
  32106. }
  32107. }
  32108. return true;
  32109. }, this);
  32110. }
  32111. };
  32112. };
  32113. createDataSelectAction('pie', [{
  32114. type: 'pieToggleSelect',
  32115. event: 'pieselectchanged',
  32116. method: 'toggleSelected'
  32117. }, {
  32118. type: 'pieSelect',
  32119. event: 'pieselected',
  32120. method: 'select'
  32121. }, {
  32122. type: 'pieUnSelect',
  32123. event: 'pieunselected',
  32124. method: 'unSelect'
  32125. }]);
  32126. registerVisual(dataColor('pie'));
  32127. registerLayout(curry(pieLayout, 'pie'));
  32128. registerProcessor(dataFilter('pie'));
  32129. SeriesModel.extend({
  32130. type: 'series.scatter',
  32131. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32132. getInitialData: function (option, ecModel) {
  32133. return createListFromArray(this.getSource(), this);
  32134. },
  32135. brushSelector: 'point',
  32136. getProgressive: function () {
  32137. var progressive = this.option.progressive;
  32138. if (progressive == null) {
  32139. // PENDING
  32140. return this.option.large ? 5e3 : this.get('progressive');
  32141. }
  32142. return progressive;
  32143. },
  32144. getProgressiveThreshold: function () {
  32145. var progressiveThreshold = this.option.progressiveThreshold;
  32146. if (progressiveThreshold == null) {
  32147. // PENDING
  32148. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32149. }
  32150. return progressiveThreshold;
  32151. },
  32152. defaultOption: {
  32153. coordinateSystem: 'cartesian2d',
  32154. zlevel: 0,
  32155. z: 2,
  32156. legendHoverLink: true,
  32157. hoverAnimation: true,
  32158. // Cartesian coordinate system
  32159. // xAxisIndex: 0,
  32160. // yAxisIndex: 0,
  32161. // Polar coordinate system
  32162. // polarIndex: 0,
  32163. // Geo coordinate system
  32164. // geoIndex: 0,
  32165. // symbol: null, // 图形类型
  32166. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32167. // symbolRotate: null, // 图形旋转控制
  32168. large: false,
  32169. // Available when large is true
  32170. largeThreshold: 2000,
  32171. // cursor: null,
  32172. // label: {
  32173. // show: false
  32174. // distance: 5,
  32175. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32176. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32177. // 'inside'|'left'|'right'|'top'|'bottom'
  32178. // 默认使用全局文本样式,详见TEXTSTYLE
  32179. // },
  32180. itemStyle: {
  32181. opacity: 0.8
  32182. // color: 各异
  32183. },
  32184. progressive: null
  32185. }
  32186. });
  32187. // TODO Batch by color
  32188. var BOOST_SIZE_THRESHOLD = 4;
  32189. var LargeSymbolPath = extendShape({
  32190. shape: {
  32191. points: null
  32192. },
  32193. symbolProxy: null,
  32194. buildPath: function (path, shape) {
  32195. var points = shape.points;
  32196. var size = shape.size;
  32197. var symbolProxy = this.symbolProxy;
  32198. var symbolProxyShape = symbolProxy.shape;
  32199. var ctx = path.getContext ? path.getContext() : path;
  32200. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32201. // Do draw in afterBrush.
  32202. if (canBoost) {
  32203. return;
  32204. }
  32205. for (var i = 0; i < points.length;) {
  32206. var x = points[i++];
  32207. var y = points[i++];
  32208. if (isNaN(x) || isNaN(y)) {
  32209. continue;
  32210. }
  32211. symbolProxyShape.x = x - size[0] / 2;
  32212. symbolProxyShape.y = y - size[1] / 2;
  32213. symbolProxyShape.width = size[0];
  32214. symbolProxyShape.height = size[1];
  32215. symbolProxy.buildPath(path, symbolProxyShape, true);
  32216. }
  32217. },
  32218. afterBrush: function (ctx) {
  32219. var shape = this.shape;
  32220. var points = shape.points;
  32221. var size = shape.size;
  32222. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32223. if (!canBoost) {
  32224. return;
  32225. }
  32226. this.setTransform(ctx);
  32227. // PENDING If style or other canvas status changed?
  32228. for (var i = 0; i < points.length;) {
  32229. var x = points[i++];
  32230. var y = points[i++];
  32231. if (isNaN(x) || isNaN(y)) {
  32232. continue;
  32233. }
  32234. // fillRect is faster than building a rect path and draw.
  32235. // And it support light globalCompositeOperation.
  32236. ctx.fillRect(
  32237. x - size[0] / 2, y - size[1] / 2,
  32238. size[0], size[1]
  32239. );
  32240. }
  32241. this.restoreTransform(ctx);
  32242. },
  32243. findDataIndex: function (x, y) {
  32244. // TODO ???
  32245. // Consider transform
  32246. var shape = this.shape;
  32247. var points = shape.points;
  32248. var size = shape.size;
  32249. var w = Math.max(size[0], 4);
  32250. var h = Math.max(size[1], 4);
  32251. // Not consider transform
  32252. // Treat each element as a rect
  32253. // top down traverse
  32254. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32255. var i = idx * 2;
  32256. var x0 = points[i] - w / 2;
  32257. var y0 = points[i + 1] - h / 2;
  32258. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32259. return idx;
  32260. }
  32261. }
  32262. return -1;
  32263. }
  32264. });
  32265. function LargeSymbolDraw() {
  32266. this.group = new Group();
  32267. }
  32268. var largeSymbolProto = LargeSymbolDraw.prototype;
  32269. largeSymbolProto.isPersistent = function () {
  32270. return !this._incremental;
  32271. };
  32272. /**
  32273. * Update symbols draw by new data
  32274. * @param {module:echarts/data/List} data
  32275. */
  32276. largeSymbolProto.updateData = function (data) {
  32277. this.group.removeAll();
  32278. var symbolEl = new LargeSymbolPath({
  32279. rectHover: true,
  32280. cursor: 'default'
  32281. });
  32282. symbolEl.setShape({
  32283. points: data.getLayout('symbolPoints')
  32284. });
  32285. this._setCommon(symbolEl, data);
  32286. this.group.add(symbolEl);
  32287. this._incremental = null;
  32288. };
  32289. largeSymbolProto.updateLayout = function (data) {
  32290. if (this._incremental) {
  32291. return;
  32292. }
  32293. var points = data.getLayout('symbolPoints');
  32294. this.group.eachChild(function (child) {
  32295. if (child.startIndex != null) {
  32296. var len = (child.endIndex - child.startIndex) * 2;
  32297. var byteOffset = child.startIndex * 4 * 2;
  32298. points = new Float32Array(points.buffer, byteOffset, len);
  32299. }
  32300. child.setShape('points', points);
  32301. });
  32302. };
  32303. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  32304. this.group.removeAll();
  32305. this._clearIncremental();
  32306. // Only use incremental displayables when data amount is larger than 2 million.
  32307. // PENDING Incremental data?
  32308. if (data.count() > 2e6) {
  32309. if (!this._incremental) {
  32310. this._incremental = new IncrementalDisplayble({
  32311. silent: true
  32312. });
  32313. }
  32314. this.group.add(this._incremental);
  32315. }
  32316. else {
  32317. this._incremental = null;
  32318. }
  32319. };
  32320. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  32321. var symbolEl;
  32322. if (this._incremental) {
  32323. symbolEl = new LargeSymbolPath();
  32324. this._incremental.addDisplayable(symbolEl, true);
  32325. }
  32326. else {
  32327. symbolEl = new LargeSymbolPath({
  32328. rectHover: true,
  32329. cursor: 'default',
  32330. startIndex: taskParams.start,
  32331. endIndex: taskParams.end
  32332. });
  32333. symbolEl.incremental = true;
  32334. this.group.add(symbolEl);
  32335. }
  32336. symbolEl.setShape({
  32337. points: data.getLayout('symbolPoints')
  32338. });
  32339. this._setCommon(symbolEl, data, !!this._incremental);
  32340. };
  32341. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  32342. var hostModel = data.hostModel;
  32343. // TODO
  32344. // if (data.hasItemVisual.symbolSize) {
  32345. // // TODO typed array?
  32346. // symbolEl.setShape('sizes', data.mapArray(
  32347. // function (idx) {
  32348. // var size = data.getItemVisual(idx, 'symbolSize');
  32349. // return (size instanceof Array) ? size : [size, size];
  32350. // }
  32351. // ));
  32352. // }
  32353. // else {
  32354. var size = data.getVisual('symbolSize');
  32355. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  32356. // }
  32357. // Create symbolProxy to build path for each data
  32358. symbolEl.symbolProxy = createSymbol(
  32359. data.getVisual('symbol'), 0, 0, 0, 0
  32360. );
  32361. // Use symbolProxy setColor method
  32362. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  32363. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  32364. symbolEl.useStyle(
  32365. // Draw shadow when doing fillRect is extremely slow.
  32366. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  32367. );
  32368. var visualColor = data.getVisual('color');
  32369. if (visualColor) {
  32370. symbolEl.setColor(visualColor);
  32371. }
  32372. if (!isIncremental) {
  32373. // Enable tooltip
  32374. // PENDING May have performance issue when path is extremely large
  32375. symbolEl.seriesIndex = hostModel.seriesIndex;
  32376. symbolEl.on('mousemove', function (e) {
  32377. symbolEl.dataIndex = null;
  32378. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  32379. if (dataIndex >= 0) {
  32380. // Provide dataIndex for tooltip
  32381. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  32382. }
  32383. });
  32384. }
  32385. };
  32386. largeSymbolProto.remove = function () {
  32387. this._clearIncremental();
  32388. this._incremental = null;
  32389. this.group.removeAll();
  32390. };
  32391. largeSymbolProto._clearIncremental = function () {
  32392. var incremental = this._incremental;
  32393. if (incremental) {
  32394. incremental.clearDisplaybles();
  32395. }
  32396. };
  32397. extendChartView({
  32398. type: 'scatter',
  32399. render: function (seriesModel, ecModel, api) {
  32400. var data = seriesModel.getData();
  32401. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32402. symbolDraw.updateData(data);
  32403. this._finished = true;
  32404. },
  32405. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  32406. var data = seriesModel.getData();
  32407. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32408. symbolDraw.incrementalPrepareUpdate(data);
  32409. this._finished = false;
  32410. },
  32411. incrementalRender: function (taskParams, seriesModel, ecModel) {
  32412. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  32413. this._finished = taskParams.end === seriesModel.getData().count();
  32414. },
  32415. updateTransform: function (seriesModel, ecModel, api) {
  32416. var data = seriesModel.getData();
  32417. // Must mark group dirty and make sure the incremental layer will be cleared
  32418. // PENDING
  32419. this.group.dirty();
  32420. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  32421. return {
  32422. update: true
  32423. };
  32424. }
  32425. else {
  32426. var res = pointsLayout().reset(seriesModel);
  32427. if (res.progress) {
  32428. res.progress({ start: 0, end: data.count() }, data);
  32429. }
  32430. this._symbolDraw.updateLayout(data);
  32431. }
  32432. },
  32433. _updateSymbolDraw: function (data, seriesModel) {
  32434. var symbolDraw = this._symbolDraw;
  32435. var pipelineContext = seriesModel.pipelineContext;
  32436. var isLargeDraw = pipelineContext.large;
  32437. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  32438. symbolDraw && symbolDraw.remove();
  32439. symbolDraw = this._symbolDraw = isLargeDraw
  32440. ? new LargeSymbolDraw()
  32441. : new SymbolDraw();
  32442. this._isLargeDraw = isLargeDraw;
  32443. this.group.removeAll();
  32444. }
  32445. this.group.add(symbolDraw.group);
  32446. return symbolDraw;
  32447. },
  32448. remove: function (ecModel, api) {
  32449. this._symbolDraw && this._symbolDraw.remove(true);
  32450. this._symbolDraw = null;
  32451. },
  32452. dispose: function () {}
  32453. });
  32454. // import * as zrUtil from 'zrender/src/core/util';
  32455. // In case developer forget to include grid component
  32456. registerVisual(visualSymbol('scatter', 'circle'));
  32457. registerLayout(pointsLayout('scatter'));
  32458. // echarts.registerProcessor(function (ecModel, api) {
  32459. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  32460. // var data = seriesModel.getData();
  32461. // var coordSys = seriesModel.coordinateSystem;
  32462. // if (coordSys.type !== 'geo') {
  32463. // return;
  32464. // }
  32465. // var startPt = coordSys.pointToData([0, 0]);
  32466. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  32467. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  32468. // return data.mapDimension(dim);
  32469. // });
  32470. // var range = {};
  32471. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  32472. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  32473. // data.selectRange(range);
  32474. // });
  32475. // });
  32476. // -------------
  32477. // Preprocessor
  32478. // -------------
  32479. registerPreprocessor(function (option) {
  32480. var graphicOption = option.graphic;
  32481. // Convert
  32482. // {graphic: [{left: 10, type: 'circle'}, ...]}
  32483. // or
  32484. // {graphic: {left: 10, type: 'circle'}}
  32485. // to
  32486. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  32487. if (isArray(graphicOption)) {
  32488. if (!graphicOption[0] || !graphicOption[0].elements) {
  32489. option.graphic = [{elements: graphicOption}];
  32490. }
  32491. else {
  32492. // Only one graphic instance can be instantiated. (We dont
  32493. // want that too many views are created in echarts._viewMap)
  32494. option.graphic = [option.graphic[0]];
  32495. }
  32496. }
  32497. else if (graphicOption && !graphicOption.elements) {
  32498. option.graphic = [{elements: [graphicOption]}];
  32499. }
  32500. });
  32501. // ------
  32502. // Model
  32503. // ------
  32504. var GraphicModel = extendComponentModel({
  32505. type: 'graphic',
  32506. defaultOption: {
  32507. // Extra properties for each elements:
  32508. //
  32509. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  32510. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  32511. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  32512. // This mechanism is useful when you want to position a group/element
  32513. // against the right side or the center of this container.
  32514. //
  32515. // width/height: (can only be pixel value, default 0)
  32516. // Only be used to specify contianer(group) size, if needed. And
  32517. // can not be percentage value (like '33%'). See the reason in the
  32518. // layout algorithm below.
  32519. //
  32520. // bounding: (enum: 'all' (default) | 'raw')
  32521. // Specify how to calculate boundingRect when locating.
  32522. // 'all': Get uioned and transformed boundingRect
  32523. // from both itself and its descendants.
  32524. // This mode simplies confining a group of elements in the bounding
  32525. // of their ancester container (e.g., using 'right: 0').
  32526. // 'raw': Only use the boundingRect of itself and before transformed.
  32527. // This mode is similar to css behavior, which is useful when you
  32528. // want an element to be able to overflow its container. (Consider
  32529. // a rotated circle needs to be located in a corner.)
  32530. // Note: elements is always behind its ancestors in this elements array.
  32531. elements: [],
  32532. parentId: null
  32533. },
  32534. /**
  32535. * Save el options for the sake of the performance (only update modified graphics).
  32536. * The order is the same as those in option. (ancesters -> descendants)
  32537. *
  32538. * @private
  32539. * @type {Array.<Object>}
  32540. */
  32541. _elOptionsToUpdate: null,
  32542. /**
  32543. * @override
  32544. */
  32545. mergeOption: function (option) {
  32546. // Prevent default merge to elements
  32547. var elements = this.option.elements;
  32548. this.option.elements = null;
  32549. GraphicModel.superApply(this, 'mergeOption', arguments);
  32550. this.option.elements = elements;
  32551. },
  32552. /**
  32553. * @override
  32554. */
  32555. optionUpdated: function (newOption, isInit) {
  32556. var thisOption = this.option;
  32557. var newList = (isInit ? thisOption : newOption).elements;
  32558. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  32559. var flattenedList = [];
  32560. this._flatten(newList, flattenedList);
  32561. var mappingResult = mappingToExists(existList, flattenedList);
  32562. makeIdAndName(mappingResult);
  32563. // Clear elOptionsToUpdate
  32564. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  32565. each$1(mappingResult, function (resultItem, index) {
  32566. var newElOption = resultItem.option;
  32567. if (__DEV__) {
  32568. assert$1(
  32569. isObject$1(newElOption) || resultItem.exist,
  32570. 'Empty graphic option definition'
  32571. );
  32572. }
  32573. if (!newElOption) {
  32574. return;
  32575. }
  32576. elOptionsToUpdate.push(newElOption);
  32577. setKeyInfoToNewElOption(resultItem, newElOption);
  32578. mergeNewElOptionToExist(existList, index, newElOption);
  32579. setLayoutInfoToExist(existList[index], newElOption);
  32580. }, this);
  32581. // Clean
  32582. for (var i = existList.length - 1; i >= 0; i--) {
  32583. if (existList[i] == null) {
  32584. existList.splice(i, 1);
  32585. }
  32586. else {
  32587. // $action should be volatile, otherwise option gotten from
  32588. // `getOption` will contain unexpected $action.
  32589. delete existList[i].$action;
  32590. }
  32591. }
  32592. },
  32593. /**
  32594. * Convert
  32595. * [{
  32596. * type: 'group',
  32597. * id: 'xx',
  32598. * children: [{type: 'circle'}, {type: 'polygon'}]
  32599. * }]
  32600. * to
  32601. * [
  32602. * {type: 'group', id: 'xx'},
  32603. * {type: 'circle', parentId: 'xx'},
  32604. * {type: 'polygon', parentId: 'xx'}
  32605. * ]
  32606. *
  32607. * @private
  32608. * @param {Array.<Object>} optionList option list
  32609. * @param {Array.<Object>} result result of flatten
  32610. * @param {Object} parentOption parent option
  32611. */
  32612. _flatten: function (optionList, result, parentOption) {
  32613. each$1(optionList, function (option) {
  32614. if (!option) {
  32615. return;
  32616. }
  32617. if (parentOption) {
  32618. option.parentOption = parentOption;
  32619. }
  32620. result.push(option);
  32621. var children = option.children;
  32622. if (option.type === 'group' && children) {
  32623. this._flatten(children, result, option);
  32624. }
  32625. // Deleting for JSON output, and for not affecting group creation.
  32626. delete option.children;
  32627. }, this);
  32628. },
  32629. // FIXME
  32630. // Pass to view using payload? setOption has a payload?
  32631. useElOptionsToUpdate: function () {
  32632. var els = this._elOptionsToUpdate;
  32633. // Clear to avoid render duplicately when zooming.
  32634. this._elOptionsToUpdate = null;
  32635. return els;
  32636. }
  32637. });
  32638. // -----
  32639. // View
  32640. // -----
  32641. extendComponentView({
  32642. type: 'graphic',
  32643. /**
  32644. * @override
  32645. */
  32646. init: function (ecModel, api) {
  32647. /**
  32648. * @private
  32649. * @type {module:zrender/core/util.HashMap}
  32650. */
  32651. this._elMap = createHashMap();
  32652. /**
  32653. * @private
  32654. * @type {module:echarts/graphic/GraphicModel}
  32655. */
  32656. this._lastGraphicModel;
  32657. },
  32658. /**
  32659. * @override
  32660. */
  32661. render: function (graphicModel, ecModel, api) {
  32662. // Having leveraged between use cases and algorithm complexity, a very
  32663. // simple layout mechanism is used:
  32664. // The size(width/height) can be determined by itself or its parent (not
  32665. // implemented yet), but can not by its children. (Top-down travel)
  32666. // The location(x/y) can be determined by the bounding rect of itself
  32667. // (can including its descendants or not) and the size of its parent.
  32668. // (Bottom-up travel)
  32669. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  32670. // view will be reused.
  32671. if (graphicModel !== this._lastGraphicModel) {
  32672. this._clear();
  32673. }
  32674. this._lastGraphicModel = graphicModel;
  32675. this._updateElements(graphicModel, api);
  32676. this._relocate(graphicModel, api);
  32677. },
  32678. /**
  32679. * Update graphic elements.
  32680. *
  32681. * @private
  32682. * @param {Object} graphicModel graphic model
  32683. * @param {module:echarts/ExtensionAPI} api extension API
  32684. */
  32685. _updateElements: function (graphicModel, api) {
  32686. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  32687. if (!elOptionsToUpdate) {
  32688. return;
  32689. }
  32690. var elMap = this._elMap;
  32691. var rootGroup = this.group;
  32692. // Top-down tranverse to assign graphic settings to each elements.
  32693. each$1(elOptionsToUpdate, function (elOption) {
  32694. var $action = elOption.$action;
  32695. var id = elOption.id;
  32696. var existEl = elMap.get(id);
  32697. var parentId = elOption.parentId;
  32698. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  32699. if (elOption.type === 'text') {
  32700. var elOptionStyle = elOption.style;
  32701. // In top/bottom mode, textVerticalAlign should not be used, which cause
  32702. // inaccurately locating.
  32703. if (elOption.hv && elOption.hv[1]) {
  32704. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  32705. }
  32706. // Compatible with previous setting: both support fill and textFill,
  32707. // stroke and textStroke.
  32708. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  32709. elOptionStyle.textFill = elOptionStyle.fill
  32710. );
  32711. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  32712. elOptionStyle.textStroke = elOptionStyle.stroke
  32713. );
  32714. }
  32715. // Remove unnecessary props to avoid potential problems.
  32716. var elOptionCleaned = getCleanedElOption(elOption);
  32717. // For simple, do not support parent change, otherwise reorder is needed.
  32718. if (__DEV__) {
  32719. existEl && assert$1(
  32720. targetElParent === existEl.parent,
  32721. 'Changing parent is not supported.'
  32722. );
  32723. }
  32724. if (!$action || $action === 'merge') {
  32725. existEl
  32726. ? existEl.attr(elOptionCleaned)
  32727. : createEl(id, targetElParent, elOptionCleaned, elMap);
  32728. }
  32729. else if ($action === 'replace') {
  32730. removeEl(existEl, elMap);
  32731. createEl(id, targetElParent, elOptionCleaned, elMap);
  32732. }
  32733. else if ($action === 'remove') {
  32734. removeEl(existEl, elMap);
  32735. }
  32736. var el = elMap.get(id);
  32737. if (el) {
  32738. el.__ecGraphicWidth = elOption.width;
  32739. el.__ecGraphicHeight = elOption.height;
  32740. }
  32741. });
  32742. },
  32743. /**
  32744. * Locate graphic elements.
  32745. *
  32746. * @private
  32747. * @param {Object} graphicModel graphic model
  32748. * @param {module:echarts/ExtensionAPI} api extension API
  32749. */
  32750. _relocate: function (graphicModel, api) {
  32751. var elOptions = graphicModel.option.elements;
  32752. var rootGroup = this.group;
  32753. var elMap = this._elMap;
  32754. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  32755. for (var i = elOptions.length - 1; i >= 0; i--) {
  32756. var elOption = elOptions[i];
  32757. var el = elMap.get(elOption.id);
  32758. if (!el) {
  32759. continue;
  32760. }
  32761. var parentEl = el.parent;
  32762. var containerInfo = parentEl === rootGroup
  32763. ? {
  32764. width: api.getWidth(),
  32765. height: api.getHeight()
  32766. }
  32767. : { // Like 'position:absolut' in css, default 0.
  32768. width: parentEl.__ecGraphicWidth || 0,
  32769. height: parentEl.__ecGraphicHeight || 0
  32770. };
  32771. positionElement(
  32772. el, elOption, containerInfo, null,
  32773. {hv: elOption.hv, boundingMode: elOption.bounding}
  32774. );
  32775. }
  32776. },
  32777. /**
  32778. * Clear all elements.
  32779. *
  32780. * @private
  32781. */
  32782. _clear: function () {
  32783. var elMap = this._elMap;
  32784. elMap.each(function (el) {
  32785. removeEl(el, elMap);
  32786. });
  32787. this._elMap = createHashMap();
  32788. },
  32789. /**
  32790. * @override
  32791. */
  32792. dispose: function () {
  32793. this._clear();
  32794. }
  32795. });
  32796. function createEl(id, targetElParent, elOption, elMap) {
  32797. var graphicType = elOption.type;
  32798. if (__DEV__) {
  32799. assert$1(graphicType, 'graphic type MUST be set');
  32800. }
  32801. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  32802. if (__DEV__) {
  32803. assert$1(Clz, 'graphic type can not be found');
  32804. }
  32805. var el = new Clz(elOption);
  32806. targetElParent.add(el);
  32807. elMap.set(id, el);
  32808. el.__ecGraphicId = id;
  32809. }
  32810. function removeEl(existEl, elMap) {
  32811. var existElParent = existEl && existEl.parent;
  32812. if (existElParent) {
  32813. existEl.type === 'group' && existEl.traverse(function (el) {
  32814. removeEl(el, elMap);
  32815. });
  32816. elMap.removeKey(existEl.__ecGraphicId);
  32817. existElParent.remove(existEl);
  32818. }
  32819. }
  32820. // Remove unnecessary props to avoid potential problems.
  32821. function getCleanedElOption(elOption) {
  32822. elOption = extend({}, elOption);
  32823. each$1(
  32824. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  32825. function (name) {
  32826. delete elOption[name];
  32827. }
  32828. );
  32829. return elOption;
  32830. }
  32831. function isSetLoc(obj, props) {
  32832. var isSet;
  32833. each$1(props, function (prop) {
  32834. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  32835. });
  32836. return isSet;
  32837. }
  32838. function setKeyInfoToNewElOption(resultItem, newElOption) {
  32839. var existElOption = resultItem.exist;
  32840. // Set id and type after id assigned.
  32841. newElOption.id = resultItem.keyInfo.id;
  32842. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  32843. // Set parent id if not specified
  32844. if (newElOption.parentId == null) {
  32845. var newElParentOption = newElOption.parentOption;
  32846. if (newElParentOption) {
  32847. newElOption.parentId = newElParentOption.id;
  32848. }
  32849. else if (existElOption) {
  32850. newElOption.parentId = existElOption.parentId;
  32851. }
  32852. }
  32853. // Clear
  32854. newElOption.parentOption = null;
  32855. }
  32856. function mergeNewElOptionToExist(existList, index, newElOption) {
  32857. // Update existing options, for `getOption` feature.
  32858. var newElOptCopy = extend({}, newElOption);
  32859. var existElOption = existList[index];
  32860. var $action = newElOption.$action || 'merge';
  32861. if ($action === 'merge') {
  32862. if (existElOption) {
  32863. if (__DEV__) {
  32864. var newType = newElOption.type;
  32865. assert$1(
  32866. !newType || existElOption.type === newType,
  32867. 'Please set $action: "replace" to change `type`'
  32868. );
  32869. }
  32870. // We can ensure that newElOptCopy and existElOption are not
  32871. // the same object, so `merge` will not change newElOptCopy.
  32872. merge(existElOption, newElOptCopy, true);
  32873. // Rigid body, use ignoreSize.
  32874. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  32875. // Will be used in render.
  32876. copyLayoutParams(newElOption, existElOption);
  32877. }
  32878. else {
  32879. existList[index] = newElOptCopy;
  32880. }
  32881. }
  32882. else if ($action === 'replace') {
  32883. existList[index] = newElOptCopy;
  32884. }
  32885. else if ($action === 'remove') {
  32886. // null will be cleaned later.
  32887. existElOption && (existList[index] = null);
  32888. }
  32889. }
  32890. function setLayoutInfoToExist(existItem, newElOption) {
  32891. if (!existItem) {
  32892. return;
  32893. }
  32894. existItem.hv = newElOption.hv = [
  32895. // Rigid body, dont care `width`.
  32896. isSetLoc(newElOption, ['left', 'right']),
  32897. // Rigid body, dont care `height`.
  32898. isSetLoc(newElOption, ['top', 'bottom'])
  32899. ];
  32900. // Give default group size. Otherwise layout error may occur.
  32901. if (existItem.type === 'group') {
  32902. existItem.width == null && (existItem.width = newElOption.width = 0);
  32903. existItem.height == null && (existItem.height = newElOption.height = 0);
  32904. }
  32905. }
  32906. /**
  32907. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  32908. * @param {module:echarts/model/Global} ecModel
  32909. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  32910. */
  32911. var findPointFromSeries = function (finder, ecModel) {
  32912. var point = [];
  32913. var seriesIndex = finder.seriesIndex;
  32914. var seriesModel;
  32915. if (seriesIndex == null || !(
  32916. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  32917. )) {
  32918. return {point: []};
  32919. }
  32920. var data = seriesModel.getData();
  32921. var dataIndex = queryDataIndex(data, finder);
  32922. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  32923. return {point: []};
  32924. }
  32925. var el = data.getItemGraphicEl(dataIndex);
  32926. var coordSys = seriesModel.coordinateSystem;
  32927. if (seriesModel.getTooltipPosition) {
  32928. point = seriesModel.getTooltipPosition(dataIndex) || [];
  32929. }
  32930. else if (coordSys && coordSys.dataToPoint) {
  32931. point = coordSys.dataToPoint(
  32932. data.getValues(
  32933. map(coordSys.dimensions, function (dim) {
  32934. return data.mapDimension(dim);
  32935. }), dataIndex, true
  32936. )
  32937. ) || [];
  32938. }
  32939. else if (el) {
  32940. // Use graphic bounding rect
  32941. var rect = el.getBoundingRect().clone();
  32942. rect.applyTransform(el.transform);
  32943. point = [
  32944. rect.x + rect.width / 2,
  32945. rect.y + rect.height / 2
  32946. ];
  32947. }
  32948. return {point: point, el: el};
  32949. };
  32950. var each$8 = each$1;
  32951. var curry$2 = curry;
  32952. var inner$6 = makeInner();
  32953. /**
  32954. * Basic logic: check all axis, if they do not demand show/highlight,
  32955. * then hide/downplay them.
  32956. *
  32957. * @param {Object} coordSysAxesInfo
  32958. * @param {Object} payload
  32959. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  32960. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  32961. * trigger axisPointer and tooltip.
  32962. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  32963. * trigger axisPointer and tooltip.
  32964. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  32965. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  32966. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  32967. * [{
  32968. * axisDim: 'x'|'y'|'angle'|...,
  32969. * axisIndex: ...,
  32970. * value: ...
  32971. * }, ...]
  32972. * @param {Function} [payload.dispatchAction]
  32973. * @param {Object} [payload.tooltipOption]
  32974. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  32975. * which can be specified in dispatchAction
  32976. * @param {module:echarts/model/Global} ecModel
  32977. * @param {module:echarts/ExtensionAPI} api
  32978. * @return {Object} content of event obj for echarts.connect.
  32979. */
  32980. var axisTrigger = function (payload, ecModel, api) {
  32981. var currTrigger = payload.currTrigger;
  32982. var point = [payload.x, payload.y];
  32983. var finder = payload;
  32984. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  32985. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  32986. // Pending
  32987. // See #6121. But we are not able to reproduce it yet.
  32988. if (!coordSysAxesInfo) {
  32989. return;
  32990. }
  32991. if (illegalPoint(point)) {
  32992. // Used in the default behavior of `connection`: use the sample seriesIndex
  32993. // and dataIndex. And also used in the tooltipView trigger.
  32994. point = findPointFromSeries({
  32995. seriesIndex: finder.seriesIndex,
  32996. // Do not use dataIndexInside from other ec instance.
  32997. // FIXME: auto detect it?
  32998. dataIndex: finder.dataIndex
  32999. }, ecModel).point;
  33000. }
  33001. var isIllegalPoint = illegalPoint(point);
  33002. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  33003. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  33004. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  33005. // and dataIndex.
  33006. var inputAxesInfo = finder.axesInfo;
  33007. var axesInfo = coordSysAxesInfo.axesInfo;
  33008. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  33009. var outputFinder = {};
  33010. var showValueMap = {};
  33011. var dataByCoordSys = {list: [], map: {}};
  33012. var updaters = {
  33013. showPointer: curry$2(showPointer, showValueMap),
  33014. showTooltip: curry$2(showTooltip, dataByCoordSys)
  33015. };
  33016. // Process for triggered axes.
  33017. each$8(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  33018. // If a point given, it must be contained by the coordinate system.
  33019. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  33020. each$8(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  33021. var axis = axisInfo.axis;
  33022. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  33023. // If no inputAxesInfo, no axis is restricted.
  33024. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  33025. var val = inputAxisInfo && inputAxisInfo.value;
  33026. if (val == null && !isIllegalPoint) {
  33027. val = axis.pointToData(point);
  33028. }
  33029. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  33030. }
  33031. });
  33032. });
  33033. // Process for linked axes.
  33034. var linkTriggers = {};
  33035. each$8(axesInfo, function (tarAxisInfo, tarKey) {
  33036. var linkGroup = tarAxisInfo.linkGroup;
  33037. // If axis has been triggered in the previous stage, it should not be triggered by link.
  33038. if (linkGroup && !showValueMap[tarKey]) {
  33039. each$8(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  33040. var srcValItem = showValueMap[srcKey];
  33041. // If srcValItem exist, source axis is triggered, so link to target axis.
  33042. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  33043. var val = srcValItem.value;
  33044. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  33045. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  33046. )));
  33047. linkTriggers[tarAxisInfo.key] = val;
  33048. }
  33049. });
  33050. }
  33051. });
  33052. each$8(linkTriggers, function (val, tarKey) {
  33053. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  33054. });
  33055. updateModelActually(showValueMap, axesInfo, outputFinder);
  33056. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  33057. dispatchHighDownActually(axesInfo, dispatchAction, api);
  33058. return outputFinder;
  33059. };
  33060. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  33061. var axis = axisInfo.axis;
  33062. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  33063. return;
  33064. }
  33065. if (!axisInfo.involveSeries) {
  33066. updaters.showPointer(axisInfo, newValue);
  33067. return;
  33068. }
  33069. // Heavy calculation. So put it after axis.containData checking.
  33070. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  33071. var payloadBatch = payloadInfo.payloadBatch;
  33072. var snapToValue = payloadInfo.snapToValue;
  33073. // Fill content of event obj for echarts.connect.
  33074. // By defualt use the first involved series data as a sample to connect.
  33075. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  33076. extend(outputFinder, payloadBatch[0]);
  33077. }
  33078. // If no linkSource input, this process is for collecting link
  33079. // target, where snap should not be accepted.
  33080. if (!dontSnap && axisInfo.snap) {
  33081. if (axis.containData(snapToValue) && snapToValue != null) {
  33082. newValue = snapToValue;
  33083. }
  33084. }
  33085. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  33086. // Tooltip should always be snapToValue, otherwise there will be
  33087. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  33088. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  33089. }
  33090. function buildPayloadsBySeries(value, axisInfo) {
  33091. var axis = axisInfo.axis;
  33092. var dim = axis.dim;
  33093. var snapToValue = value;
  33094. var payloadBatch = [];
  33095. var minDist = Number.MAX_VALUE;
  33096. var minDiff = -1;
  33097. each$8(axisInfo.seriesModels, function (series, idx) {
  33098. var dataDim = series.getData().mapDimension(dim, true);
  33099. var seriesNestestValue;
  33100. var dataIndices;
  33101. if (series.getAxisTooltipData) {
  33102. var result = series.getAxisTooltipData(dataDim, value, axis);
  33103. dataIndices = result.dataIndices;
  33104. seriesNestestValue = result.nestestValue;
  33105. }
  33106. else {
  33107. dataIndices = series.getData().indicesOfNearest(
  33108. dataDim[0],
  33109. value,
  33110. // Add a threshold to avoid find the wrong dataIndex
  33111. // when data length is not same.
  33112. false, axis.type === 'category' ? 0.5 : null
  33113. );
  33114. if (!dataIndices.length) {
  33115. return;
  33116. }
  33117. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  33118. }
  33119. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  33120. return;
  33121. }
  33122. var diff = value - seriesNestestValue;
  33123. var dist = Math.abs(diff);
  33124. // Consider category case
  33125. if (dist <= minDist) {
  33126. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  33127. minDist = dist;
  33128. minDiff = diff;
  33129. snapToValue = seriesNestestValue;
  33130. payloadBatch.length = 0;
  33131. }
  33132. each$8(dataIndices, function (dataIndex) {
  33133. payloadBatch.push({
  33134. seriesIndex: series.seriesIndex,
  33135. dataIndexInside: dataIndex,
  33136. dataIndex: series.getData().getRawIndex(dataIndex)
  33137. });
  33138. });
  33139. }
  33140. });
  33141. return {
  33142. payloadBatch: payloadBatch,
  33143. snapToValue: snapToValue
  33144. };
  33145. }
  33146. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  33147. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  33148. }
  33149. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  33150. var payloadBatch = payloadInfo.payloadBatch;
  33151. var axis = axisInfo.axis;
  33152. var axisModel = axis.model;
  33153. var axisPointerModel = axisInfo.axisPointerModel;
  33154. // If no data, do not create anything in dataByCoordSys,
  33155. // whose length will be used to judge whether dispatch action.
  33156. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  33157. return;
  33158. }
  33159. var coordSysModel = axisInfo.coordSys.model;
  33160. var coordSysKey = makeKey(coordSysModel);
  33161. var coordSysItem = dataByCoordSys.map[coordSysKey];
  33162. if (!coordSysItem) {
  33163. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  33164. coordSysId: coordSysModel.id,
  33165. coordSysIndex: coordSysModel.componentIndex,
  33166. coordSysType: coordSysModel.type,
  33167. coordSysMainType: coordSysModel.mainType,
  33168. dataByAxis: []
  33169. };
  33170. dataByCoordSys.list.push(coordSysItem);
  33171. }
  33172. coordSysItem.dataByAxis.push({
  33173. axisDim: axis.dim,
  33174. axisIndex: axisModel.componentIndex,
  33175. axisType: axisModel.type,
  33176. axisId: axisModel.id,
  33177. value: value,
  33178. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  33179. // depends that all models have been updated. So it should not be performed
  33180. // here. Considering axisPointerModel used here is volatile, which is hard
  33181. // to be retrieve in TooltipView, we prepare parameters here.
  33182. valueLabelOpt: {
  33183. precision: axisPointerModel.get('label.precision'),
  33184. formatter: axisPointerModel.get('label.formatter')
  33185. },
  33186. seriesDataIndices: payloadBatch.slice()
  33187. });
  33188. }
  33189. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  33190. var outputAxesInfo = outputFinder.axesInfo = [];
  33191. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  33192. each$8(axesInfo, function (axisInfo, key) {
  33193. var option = axisInfo.axisPointerModel.option;
  33194. var valItem = showValueMap[key];
  33195. if (valItem) {
  33196. !axisInfo.useHandle && (option.status = 'show');
  33197. option.value = valItem.value;
  33198. // For label formatter param and highlight.
  33199. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  33200. }
  33201. // When always show (e.g., handle used), remain
  33202. // original value and status.
  33203. else {
  33204. // If hide, value still need to be set, consider
  33205. // click legend to toggle axis blank.
  33206. !axisInfo.useHandle && (option.status = 'hide');
  33207. }
  33208. // If status is 'hide', should be no info in payload.
  33209. option.status === 'show' && outputAxesInfo.push({
  33210. axisDim: axisInfo.axis.dim,
  33211. axisIndex: axisInfo.axis.model.componentIndex,
  33212. value: option.value
  33213. });
  33214. });
  33215. }
  33216. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  33217. // Basic logic: If no showTip required, hideTip will be dispatched.
  33218. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  33219. dispatchAction({type: 'hideTip'});
  33220. return;
  33221. }
  33222. // In most case only one axis (or event one series is used). It is
  33223. // convinient to fetch payload.seriesIndex and payload.dataIndex
  33224. // dirtectly. So put the first seriesIndex and dataIndex of the first
  33225. // axis on the payload.
  33226. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  33227. dispatchAction({
  33228. type: 'showTip',
  33229. escapeConnect: true,
  33230. x: point[0],
  33231. y: point[1],
  33232. tooltipOption: payload.tooltipOption,
  33233. position: payload.position,
  33234. dataIndexInside: sampleItem.dataIndexInside,
  33235. dataIndex: sampleItem.dataIndex,
  33236. seriesIndex: sampleItem.seriesIndex,
  33237. dataByCoordSys: dataByCoordSys.list
  33238. });
  33239. }
  33240. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  33241. // FIXME
  33242. // highlight status modification shoule be a stage of main process?
  33243. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  33244. var zr = api.getZr();
  33245. var highDownKey = 'axisPointerLastHighlights';
  33246. var lastHighlights = inner$6(zr)[highDownKey] || {};
  33247. var newHighlights = inner$6(zr)[highDownKey] = {};
  33248. // Update highlight/downplay status according to axisPointer model.
  33249. // Build hash map and remove duplicate incidentally.
  33250. each$8(axesInfo, function (axisInfo, key) {
  33251. var option = axisInfo.axisPointerModel.option;
  33252. option.status === 'show' && each$8(option.seriesDataIndices, function (batchItem) {
  33253. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  33254. newHighlights[key] = batchItem;
  33255. });
  33256. });
  33257. // Diff.
  33258. var toHighlight = [];
  33259. var toDownplay = [];
  33260. each$1(lastHighlights, function (batchItem, key) {
  33261. !newHighlights[key] && toDownplay.push(batchItem);
  33262. });
  33263. each$1(newHighlights, function (batchItem, key) {
  33264. !lastHighlights[key] && toHighlight.push(batchItem);
  33265. });
  33266. toDownplay.length && api.dispatchAction({
  33267. type: 'downplay', escapeConnect: true, batch: toDownplay
  33268. });
  33269. toHighlight.length && api.dispatchAction({
  33270. type: 'highlight', escapeConnect: true, batch: toHighlight
  33271. });
  33272. }
  33273. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  33274. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  33275. var inputAxisInfo = inputAxesInfo[i];
  33276. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  33277. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  33278. ) {
  33279. return inputAxisInfo;
  33280. }
  33281. }
  33282. }
  33283. function makeMapperParam(axisInfo) {
  33284. var axisModel = axisInfo.axis.model;
  33285. var item = {};
  33286. var dim = item.axisDim = axisInfo.axis.dim;
  33287. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  33288. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  33289. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  33290. return item;
  33291. }
  33292. function illegalPoint(point) {
  33293. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  33294. }
  33295. var AxisPointerModel = extendComponentModel({
  33296. type: 'axisPointer',
  33297. coordSysAxesInfo: null,
  33298. defaultOption: {
  33299. // 'auto' means that show when triggered by tooltip or handle.
  33300. show: 'auto',
  33301. // 'click' | 'mousemove' | 'none'
  33302. triggerOn: null, // set default in AxisPonterView.js
  33303. zlevel: 0,
  33304. z: 50,
  33305. type: 'line',
  33306. // axispointer triggered by tootip determine snap automatically,
  33307. // see `modelHelper`.
  33308. snap: false,
  33309. triggerTooltip: true,
  33310. value: null,
  33311. status: null, // Init value depends on whether handle is used.
  33312. // [group0, group1, ...]
  33313. // Each group can be: {
  33314. // mapper: function () {},
  33315. // singleTooltip: 'multiple', // 'multiple' or 'single'
  33316. // xAxisId: ...,
  33317. // yAxisName: ...,
  33318. // angleAxisIndex: ...
  33319. // }
  33320. // mapper: can be ignored.
  33321. // input: {axisInfo, value}
  33322. // output: {axisInfo, value}
  33323. link: [],
  33324. // Do not set 'auto' here, otherwise global animation: false
  33325. // will not effect at this axispointer.
  33326. animation: null,
  33327. animationDurationUpdate: 200,
  33328. lineStyle: {
  33329. color: '#aaa',
  33330. width: 1,
  33331. type: 'solid'
  33332. },
  33333. shadowStyle: {
  33334. color: 'rgba(150,150,150,0.3)'
  33335. },
  33336. label: {
  33337. show: true,
  33338. formatter: null, // string | Function
  33339. precision: 'auto', // Or a number like 0, 1, 2 ...
  33340. margin: 3,
  33341. color: '#fff',
  33342. padding: [5, 7, 5, 7],
  33343. backgroundColor: 'auto', // default: axis line color
  33344. borderColor: null,
  33345. borderWidth: 0,
  33346. shadowBlur: 3,
  33347. shadowColor: '#aaa'
  33348. // Considering applicability, common style should
  33349. // better not have shadowOffset.
  33350. // shadowOffsetX: 0,
  33351. // shadowOffsetY: 2
  33352. },
  33353. handle: {
  33354. show: false,
  33355. 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
  33356. size: 45,
  33357. // handle margin is from symbol center to axis, which is stable when circular move.
  33358. margin: 50,
  33359. // color: '#1b8bbd'
  33360. // color: '#2f4554'
  33361. color: '#333',
  33362. shadowBlur: 3,
  33363. shadowColor: '#aaa',
  33364. shadowOffsetX: 0,
  33365. shadowOffsetY: 2,
  33366. // For mobile performance
  33367. throttle: 40
  33368. }
  33369. }
  33370. });
  33371. var inner$7 = makeInner();
  33372. var each$9 = each$1;
  33373. /**
  33374. * @param {string} key
  33375. * @param {module:echarts/ExtensionAPI} api
  33376. * @param {Function} handler
  33377. * param: {string} currTrigger
  33378. * param: {Array.<number>} point
  33379. */
  33380. function register(key, api, handler) {
  33381. if (env$1.node) {
  33382. return;
  33383. }
  33384. var zr = api.getZr();
  33385. inner$7(zr).records || (inner$7(zr).records = {});
  33386. initGlobalListeners(zr, api);
  33387. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  33388. record.handler = handler;
  33389. }
  33390. function initGlobalListeners(zr, api) {
  33391. if (inner$7(zr).initialized) {
  33392. return;
  33393. }
  33394. inner$7(zr).initialized = true;
  33395. useHandler('click', curry(doEnter, 'click'));
  33396. useHandler('mousemove', curry(doEnter, 'mousemove'));
  33397. // useHandler('mouseout', onLeave);
  33398. useHandler('globalout', onLeave);
  33399. function useHandler(eventType, cb) {
  33400. zr.on(eventType, function (e) {
  33401. var dis = makeDispatchAction(api);
  33402. each$9(inner$7(zr).records, function (record) {
  33403. record && cb(record, e, dis.dispatchAction);
  33404. });
  33405. dispatchTooltipFinally(dis.pendings, api);
  33406. });
  33407. }
  33408. }
  33409. function dispatchTooltipFinally(pendings, api) {
  33410. var showLen = pendings.showTip.length;
  33411. var hideLen = pendings.hideTip.length;
  33412. var actuallyPayload;
  33413. if (showLen) {
  33414. actuallyPayload = pendings.showTip[showLen - 1];
  33415. }
  33416. else if (hideLen) {
  33417. actuallyPayload = pendings.hideTip[hideLen - 1];
  33418. }
  33419. if (actuallyPayload) {
  33420. actuallyPayload.dispatchAction = null;
  33421. api.dispatchAction(actuallyPayload);
  33422. }
  33423. }
  33424. function onLeave(record, e, dispatchAction) {
  33425. record.handler('leave', null, dispatchAction);
  33426. }
  33427. function doEnter(currTrigger, record, e, dispatchAction) {
  33428. record.handler(currTrigger, e, dispatchAction);
  33429. }
  33430. function makeDispatchAction(api) {
  33431. var pendings = {
  33432. showTip: [],
  33433. hideTip: []
  33434. };
  33435. // FIXME
  33436. // better approach?
  33437. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  33438. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  33439. // So we have to add "final stage" to merge those dispatched actions.
  33440. var dispatchAction = function (payload) {
  33441. var pendingList = pendings[payload.type];
  33442. if (pendingList) {
  33443. pendingList.push(payload);
  33444. }
  33445. else {
  33446. payload.dispatchAction = dispatchAction;
  33447. api.dispatchAction(payload);
  33448. }
  33449. };
  33450. return {
  33451. dispatchAction: dispatchAction,
  33452. pendings: pendings
  33453. };
  33454. }
  33455. /**
  33456. * @param {string} key
  33457. * @param {module:echarts/ExtensionAPI} api
  33458. */
  33459. function unregister(key, api) {
  33460. if (env$1.node) {
  33461. return;
  33462. }
  33463. var zr = api.getZr();
  33464. var record = (inner$7(zr).records || {})[key];
  33465. if (record) {
  33466. inner$7(zr).records[key] = null;
  33467. }
  33468. }
  33469. var AxisPointerView = extendComponentView({
  33470. type: 'axisPointer',
  33471. render: function (globalAxisPointerModel, ecModel, api) {
  33472. var globalTooltipModel = ecModel.getComponent('tooltip');
  33473. var triggerOn = globalAxisPointerModel.get('triggerOn')
  33474. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  33475. // Register global listener in AxisPointerView to enable
  33476. // AxisPointerView to be independent to Tooltip.
  33477. register(
  33478. 'axisPointer',
  33479. api,
  33480. function (currTrigger, e, dispatchAction) {
  33481. // If 'none', it is not controlled by mouse totally.
  33482. if (triggerOn !== 'none'
  33483. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  33484. ) {
  33485. dispatchAction({
  33486. type: 'updateAxisPointer',
  33487. currTrigger: currTrigger,
  33488. x: e && e.offsetX,
  33489. y: e && e.offsetY
  33490. });
  33491. }
  33492. }
  33493. );
  33494. },
  33495. /**
  33496. * @override
  33497. */
  33498. remove: function (ecModel, api) {
  33499. unregister(api.getZr(), 'axisPointer');
  33500. AxisPointerView.superApply(this._model, 'remove', arguments);
  33501. },
  33502. /**
  33503. * @override
  33504. */
  33505. dispose: function (ecModel, api) {
  33506. unregister('axisPointer', api);
  33507. AxisPointerView.superApply(this._model, 'dispose', arguments);
  33508. }
  33509. });
  33510. var inner$8 = makeInner();
  33511. var clone$4 = clone;
  33512. var bind$1 = bind;
  33513. /**
  33514. * Base axis pointer class in 2D.
  33515. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  33516. */
  33517. function BaseAxisPointer () {
  33518. }
  33519. BaseAxisPointer.prototype = {
  33520. /**
  33521. * @private
  33522. */
  33523. _group: null,
  33524. /**
  33525. * @private
  33526. */
  33527. _lastGraphicKey: null,
  33528. /**
  33529. * @private
  33530. */
  33531. _handle: null,
  33532. /**
  33533. * @private
  33534. */
  33535. _dragging: false,
  33536. /**
  33537. * @private
  33538. */
  33539. _lastValue: null,
  33540. /**
  33541. * @private
  33542. */
  33543. _lastStatus: null,
  33544. /**
  33545. * @private
  33546. */
  33547. _payloadInfo: null,
  33548. /**
  33549. * In px, arbitrary value. Do not set too small,
  33550. * no animation is ok for most cases.
  33551. * @protected
  33552. */
  33553. animationThreshold: 15,
  33554. /**
  33555. * @implement
  33556. */
  33557. render: function (axisModel, axisPointerModel, api, forceRender) {
  33558. var value = axisPointerModel.get('value');
  33559. var status = axisPointerModel.get('status');
  33560. // Bind them to `this`, not in closure, otherwise they will not
  33561. // be replaced when user calling setOption in not merge mode.
  33562. this._axisModel = axisModel;
  33563. this._axisPointerModel = axisPointerModel;
  33564. this._api = api;
  33565. // Optimize: `render` will be called repeatly during mouse move.
  33566. // So it is power consuming if performing `render` each time,
  33567. // especially on mobile device.
  33568. if (!forceRender
  33569. && this._lastValue === value
  33570. && this._lastStatus === status
  33571. ) {
  33572. return;
  33573. }
  33574. this._lastValue = value;
  33575. this._lastStatus = status;
  33576. var group = this._group;
  33577. var handle = this._handle;
  33578. if (!status || status === 'hide') {
  33579. // Do not clear here, for animation better.
  33580. group && group.hide();
  33581. handle && handle.hide();
  33582. return;
  33583. }
  33584. group && group.show();
  33585. handle && handle.show();
  33586. // Otherwise status is 'show'
  33587. var elOption = {};
  33588. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  33589. // Enable change axis pointer type.
  33590. var graphicKey = elOption.graphicKey;
  33591. if (graphicKey !== this._lastGraphicKey) {
  33592. this.clear(api);
  33593. }
  33594. this._lastGraphicKey = graphicKey;
  33595. var moveAnimation = this._moveAnimation =
  33596. this.determineAnimation(axisModel, axisPointerModel);
  33597. if (!group) {
  33598. group = this._group = new Group();
  33599. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  33600. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  33601. api.getZr().add(group);
  33602. }
  33603. else {
  33604. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  33605. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  33606. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  33607. }
  33608. updateMandatoryProps(group, axisPointerModel, true);
  33609. this._renderHandle(value);
  33610. },
  33611. /**
  33612. * @implement
  33613. */
  33614. remove: function (api) {
  33615. this.clear(api);
  33616. },
  33617. /**
  33618. * @implement
  33619. */
  33620. dispose: function (api) {
  33621. this.clear(api);
  33622. },
  33623. /**
  33624. * @protected
  33625. */
  33626. determineAnimation: function (axisModel, axisPointerModel) {
  33627. var animation = axisPointerModel.get('animation');
  33628. var axis = axisModel.axis;
  33629. var isCategoryAxis = axis.type === 'category';
  33630. var useSnap = axisPointerModel.get('snap');
  33631. // Value axis without snap always do not snap.
  33632. if (!useSnap && !isCategoryAxis) {
  33633. return false;
  33634. }
  33635. if (animation === 'auto' || animation == null) {
  33636. var animationThreshold = this.animationThreshold;
  33637. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  33638. return true;
  33639. }
  33640. // It is important to auto animation when snap used. Consider if there is
  33641. // a dataZoom, animation will be disabled when too many points exist, while
  33642. // it will be enabled for better visual effect when little points exist.
  33643. if (useSnap) {
  33644. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  33645. var axisExtent = axis.getExtent();
  33646. // Approximate band width
  33647. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  33648. }
  33649. return false;
  33650. }
  33651. return animation === true;
  33652. },
  33653. /**
  33654. * add {pointer, label, graphicKey} to elOption
  33655. * @protected
  33656. */
  33657. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  33658. // Shoule be implemenented by sub-class.
  33659. },
  33660. /**
  33661. * @protected
  33662. */
  33663. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  33664. var pointerOption = elOption.pointer;
  33665. if (pointerOption) {
  33666. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  33667. clone$4(elOption.pointer)
  33668. );
  33669. group.add(pointerEl);
  33670. }
  33671. },
  33672. /**
  33673. * @protected
  33674. */
  33675. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  33676. if (elOption.label) {
  33677. var labelEl = inner$8(group).labelEl = new Rect(
  33678. clone$4(elOption.label)
  33679. );
  33680. group.add(labelEl);
  33681. updateLabelShowHide(labelEl, axisPointerModel);
  33682. }
  33683. },
  33684. /**
  33685. * @protected
  33686. */
  33687. updatePointerEl: function (group, elOption, updateProps$$1) {
  33688. var pointerEl = inner$8(group).pointerEl;
  33689. if (pointerEl) {
  33690. pointerEl.setStyle(elOption.pointer.style);
  33691. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  33692. }
  33693. },
  33694. /**
  33695. * @protected
  33696. */
  33697. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  33698. var labelEl = inner$8(group).labelEl;
  33699. if (labelEl) {
  33700. labelEl.setStyle(elOption.label.style);
  33701. updateProps$$1(labelEl, {
  33702. // Consider text length change in vertical axis, animation should
  33703. // be used on shape, otherwise the effect will be weird.
  33704. shape: elOption.label.shape,
  33705. position: elOption.label.position
  33706. });
  33707. updateLabelShowHide(labelEl, axisPointerModel);
  33708. }
  33709. },
  33710. /**
  33711. * @private
  33712. */
  33713. _renderHandle: function (value) {
  33714. if (this._dragging || !this.updateHandleTransform) {
  33715. return;
  33716. }
  33717. var axisPointerModel = this._axisPointerModel;
  33718. var zr = this._api.getZr();
  33719. var handle = this._handle;
  33720. var handleModel = axisPointerModel.getModel('handle');
  33721. var status = axisPointerModel.get('status');
  33722. if (!handleModel.get('show') || !status || status === 'hide') {
  33723. handle && zr.remove(handle);
  33724. this._handle = null;
  33725. return;
  33726. }
  33727. var isInit;
  33728. if (!this._handle) {
  33729. isInit = true;
  33730. handle = this._handle = createIcon(
  33731. handleModel.get('icon'),
  33732. {
  33733. cursor: 'move',
  33734. draggable: true,
  33735. onmousemove: function (e) {
  33736. // Fot mobile devicem, prevent screen slider on the button.
  33737. stop(e.event);
  33738. },
  33739. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  33740. drift: bind$1(this._onHandleDragMove, this),
  33741. ondragend: bind$1(this._onHandleDragEnd, this)
  33742. }
  33743. );
  33744. zr.add(handle);
  33745. }
  33746. updateMandatoryProps(handle, axisPointerModel, false);
  33747. // update style
  33748. var includeStyles = [
  33749. 'color', 'borderColor', 'borderWidth', 'opacity',
  33750. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  33751. ];
  33752. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  33753. // update position
  33754. var handleSize = handleModel.get('size');
  33755. if (!isArray(handleSize)) {
  33756. handleSize = [handleSize, handleSize];
  33757. }
  33758. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  33759. createOrUpdate(
  33760. this,
  33761. '_doDispatchAxisPointer',
  33762. handleModel.get('throttle') || 0,
  33763. 'fixRate'
  33764. );
  33765. this._moveHandleToValue(value, isInit);
  33766. },
  33767. /**
  33768. * @private
  33769. */
  33770. _moveHandleToValue: function (value, isInit) {
  33771. updateProps$1(
  33772. this._axisPointerModel,
  33773. !isInit && this._moveAnimation,
  33774. this._handle,
  33775. getHandleTransProps(this.getHandleTransform(
  33776. value, this._axisModel, this._axisPointerModel
  33777. ))
  33778. );
  33779. },
  33780. /**
  33781. * @private
  33782. */
  33783. _onHandleDragMove: function (dx, dy) {
  33784. var handle = this._handle;
  33785. if (!handle) {
  33786. return;
  33787. }
  33788. this._dragging = true;
  33789. // Persistent for throttle.
  33790. var trans = this.updateHandleTransform(
  33791. getHandleTransProps(handle),
  33792. [dx, dy],
  33793. this._axisModel,
  33794. this._axisPointerModel
  33795. );
  33796. this._payloadInfo = trans;
  33797. handle.stopAnimation();
  33798. handle.attr(getHandleTransProps(trans));
  33799. inner$8(handle).lastProp = null;
  33800. this._doDispatchAxisPointer();
  33801. },
  33802. /**
  33803. * Throttled method.
  33804. * @private
  33805. */
  33806. _doDispatchAxisPointer: function () {
  33807. var handle = this._handle;
  33808. if (!handle) {
  33809. return;
  33810. }
  33811. var payloadInfo = this._payloadInfo;
  33812. var axisModel = this._axisModel;
  33813. this._api.dispatchAction({
  33814. type: 'updateAxisPointer',
  33815. x: payloadInfo.cursorPoint[0],
  33816. y: payloadInfo.cursorPoint[1],
  33817. tooltipOption: payloadInfo.tooltipOption,
  33818. axesInfo: [{
  33819. axisDim: axisModel.axis.dim,
  33820. axisIndex: axisModel.componentIndex
  33821. }]
  33822. });
  33823. },
  33824. /**
  33825. * @private
  33826. */
  33827. _onHandleDragEnd: function (moveAnimation) {
  33828. this._dragging = false;
  33829. var handle = this._handle;
  33830. if (!handle) {
  33831. return;
  33832. }
  33833. var value = this._axisPointerModel.get('value');
  33834. // Consider snap or categroy axis, handle may be not consistent with
  33835. // axisPointer. So move handle to align the exact value position when
  33836. // drag ended.
  33837. this._moveHandleToValue(value);
  33838. // For the effect: tooltip will be shown when finger holding on handle
  33839. // button, and will be hidden after finger left handle button.
  33840. this._api.dispatchAction({
  33841. type: 'hideTip'
  33842. });
  33843. },
  33844. /**
  33845. * Should be implemenented by sub-class if support `handle`.
  33846. * @protected
  33847. * @param {number} value
  33848. * @param {module:echarts/model/Model} axisModel
  33849. * @param {module:echarts/model/Model} axisPointerModel
  33850. * @return {Object} {position: [x, y], rotation: 0}
  33851. */
  33852. getHandleTransform: null,
  33853. /**
  33854. * * Should be implemenented by sub-class if support `handle`.
  33855. * @protected
  33856. * @param {Object} transform {position, rotation}
  33857. * @param {Array.<number>} delta [dx, dy]
  33858. * @param {module:echarts/model/Model} axisModel
  33859. * @param {module:echarts/model/Model} axisPointerModel
  33860. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  33861. */
  33862. updateHandleTransform: null,
  33863. /**
  33864. * @private
  33865. */
  33866. clear: function (api) {
  33867. this._lastValue = null;
  33868. this._lastStatus = null;
  33869. var zr = api.getZr();
  33870. var group = this._group;
  33871. var handle = this._handle;
  33872. if (zr && group) {
  33873. this._lastGraphicKey = null;
  33874. group && zr.remove(group);
  33875. handle && zr.remove(handle);
  33876. this._group = null;
  33877. this._handle = null;
  33878. this._payloadInfo = null;
  33879. }
  33880. },
  33881. /**
  33882. * @protected
  33883. */
  33884. doClear: function () {
  33885. // Implemented by sub-class if necessary.
  33886. },
  33887. /**
  33888. * @protected
  33889. * @param {Array.<number>} xy
  33890. * @param {Array.<number>} wh
  33891. * @param {number} [xDimIndex=0] or 1
  33892. */
  33893. buildLabel: function (xy, wh, xDimIndex) {
  33894. xDimIndex = xDimIndex || 0;
  33895. return {
  33896. x: xy[xDimIndex],
  33897. y: xy[1 - xDimIndex],
  33898. width: wh[xDimIndex],
  33899. height: wh[1 - xDimIndex]
  33900. };
  33901. }
  33902. };
  33903. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  33904. function updateProps$1(animationModel, moveAnimation, el, props) {
  33905. // Animation optimize.
  33906. if (!propsEqual(inner$8(el).lastProp, props)) {
  33907. inner$8(el).lastProp = props;
  33908. moveAnimation
  33909. ? updateProps(el, props, animationModel)
  33910. : (el.stopAnimation(), el.attr(props));
  33911. }
  33912. }
  33913. function propsEqual(lastProps, newProps) {
  33914. if (isObject$1(lastProps) && isObject$1(newProps)) {
  33915. var equals = true;
  33916. each$1(newProps, function (item, key) {
  33917. equals = equals && propsEqual(lastProps[key], item);
  33918. });
  33919. return !!equals;
  33920. }
  33921. else {
  33922. return lastProps === newProps;
  33923. }
  33924. }
  33925. function updateLabelShowHide(labelEl, axisPointerModel) {
  33926. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  33927. }
  33928. function getHandleTransProps(trans) {
  33929. return {
  33930. position: trans.position.slice(),
  33931. rotation: trans.rotation || 0
  33932. };
  33933. }
  33934. function updateMandatoryProps(group, axisPointerModel, silent) {
  33935. var z = axisPointerModel.get('z');
  33936. var zlevel = axisPointerModel.get('zlevel');
  33937. group && group.traverse(function (el) {
  33938. if (el.type !== 'group') {
  33939. z != null && (el.z = z);
  33940. zlevel != null && (el.zlevel = zlevel);
  33941. el.silent = silent;
  33942. }
  33943. });
  33944. }
  33945. enableClassExtend(BaseAxisPointer);
  33946. /**
  33947. * @param {module:echarts/model/Model} axisPointerModel
  33948. */
  33949. function buildElStyle(axisPointerModel) {
  33950. var axisPointerType = axisPointerModel.get('type');
  33951. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  33952. var style;
  33953. if (axisPointerType === 'line') {
  33954. style = styleModel.getLineStyle();
  33955. style.fill = null;
  33956. }
  33957. else if (axisPointerType === 'shadow') {
  33958. style = styleModel.getAreaStyle();
  33959. style.stroke = null;
  33960. }
  33961. return style;
  33962. }
  33963. /**
  33964. * @param {Function} labelPos {align, verticalAlign, position}
  33965. */
  33966. function buildLabelElOption(
  33967. elOption, axisModel, axisPointerModel, api, labelPos
  33968. ) {
  33969. var value = axisPointerModel.get('value');
  33970. var text = getValueLabel(
  33971. value, axisModel.axis, axisModel.ecModel,
  33972. axisPointerModel.get('seriesDataIndices'),
  33973. {
  33974. precision: axisPointerModel.get('label.precision'),
  33975. formatter: axisPointerModel.get('label.formatter')
  33976. }
  33977. );
  33978. var labelModel = axisPointerModel.getModel('label');
  33979. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  33980. var font = labelModel.getFont();
  33981. var textRect = getBoundingRect(text, font);
  33982. var position = labelPos.position;
  33983. var width = textRect.width + paddings[1] + paddings[3];
  33984. var height = textRect.height + paddings[0] + paddings[2];
  33985. // Adjust by align.
  33986. var align = labelPos.align;
  33987. align === 'right' && (position[0] -= width);
  33988. align === 'center' && (position[0] -= width / 2);
  33989. var verticalAlign = labelPos.verticalAlign;
  33990. verticalAlign === 'bottom' && (position[1] -= height);
  33991. verticalAlign === 'middle' && (position[1] -= height / 2);
  33992. // Not overflow ec container
  33993. confineInContainer(position, width, height, api);
  33994. var bgColor = labelModel.get('backgroundColor');
  33995. if (!bgColor || bgColor === 'auto') {
  33996. bgColor = axisModel.get('axisLine.lineStyle.color');
  33997. }
  33998. elOption.label = {
  33999. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  34000. position: position.slice(),
  34001. // TODO: rich
  34002. style: {
  34003. text: text,
  34004. textFont: font,
  34005. textFill: labelModel.getTextColor(),
  34006. textPosition: 'inside',
  34007. fill: bgColor,
  34008. stroke: labelModel.get('borderColor') || 'transparent',
  34009. lineWidth: labelModel.get('borderWidth') || 0,
  34010. shadowBlur: labelModel.get('shadowBlur'),
  34011. shadowColor: labelModel.get('shadowColor'),
  34012. shadowOffsetX: labelModel.get('shadowOffsetX'),
  34013. shadowOffsetY: labelModel.get('shadowOffsetY')
  34014. },
  34015. // Lable should be over axisPointer.
  34016. z2: 10
  34017. };
  34018. }
  34019. // Do not overflow ec container
  34020. function confineInContainer(position, width, height, api) {
  34021. var viewWidth = api.getWidth();
  34022. var viewHeight = api.getHeight();
  34023. position[0] = Math.min(position[0] + width, viewWidth) - width;
  34024. position[1] = Math.min(position[1] + height, viewHeight) - height;
  34025. position[0] = Math.max(position[0], 0);
  34026. position[1] = Math.max(position[1], 0);
  34027. }
  34028. /**
  34029. * @param {number} value
  34030. * @param {module:echarts/coord/Axis} axis
  34031. * @param {module:echarts/model/Global} ecModel
  34032. * @param {Object} opt
  34033. * @param {Array.<Object>} seriesDataIndices
  34034. * @param {number|string} opt.precision 'auto' or a number
  34035. * @param {string|Function} opt.formatter label formatter
  34036. */
  34037. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  34038. var text = axis.scale.getLabel(
  34039. // If `precision` is set, width can be fixed (like '12.00500'), which
  34040. // helps to debounce when when moving label.
  34041. value, {precision: opt.precision}
  34042. );
  34043. var formatter = opt.formatter;
  34044. if (formatter) {
  34045. var params = {
  34046. value: getAxisRawValue(axis, value),
  34047. seriesData: []
  34048. };
  34049. each$1(seriesDataIndices, function (idxItem) {
  34050. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  34051. var dataIndex = idxItem.dataIndexInside;
  34052. var dataParams = series && series.getDataParams(dataIndex);
  34053. dataParams && params.seriesData.push(dataParams);
  34054. });
  34055. if (isString(formatter)) {
  34056. text = formatter.replace('{value}', text);
  34057. }
  34058. else if (isFunction$1(formatter)) {
  34059. text = formatter(params);
  34060. }
  34061. }
  34062. return text;
  34063. }
  34064. /**
  34065. * @param {module:echarts/coord/Axis} axis
  34066. * @param {number} value
  34067. * @param {Object} layoutInfo {
  34068. * rotation, position, labelOffset, labelDirection, labelMargin
  34069. * }
  34070. */
  34071. function getTransformedPosition (axis, value, layoutInfo) {
  34072. var transform = create$1();
  34073. rotate(transform, transform, layoutInfo.rotation);
  34074. translate(transform, transform, layoutInfo.position);
  34075. return applyTransform$1([
  34076. axis.dataToCoord(value),
  34077. (layoutInfo.labelOffset || 0)
  34078. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  34079. ], transform);
  34080. }
  34081. function buildCartesianSingleLabelElOption(
  34082. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34083. ) {
  34084. var textLayout = AxisBuilder.innerTextLayout(
  34085. layoutInfo.rotation, 0, layoutInfo.labelDirection
  34086. );
  34087. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  34088. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  34089. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34090. align: textLayout.textAlign,
  34091. verticalAlign: textLayout.textVerticalAlign
  34092. });
  34093. }
  34094. /**
  34095. * @param {Array.<number>} p1
  34096. * @param {Array.<number>} p2
  34097. * @param {number} [xDimIndex=0] or 1
  34098. */
  34099. function makeLineShape(p1, p2, xDimIndex) {
  34100. xDimIndex = xDimIndex || 0;
  34101. return {
  34102. x1: p1[xDimIndex],
  34103. y1: p1[1 - xDimIndex],
  34104. x2: p2[xDimIndex],
  34105. y2: p2[1 - xDimIndex]
  34106. };
  34107. }
  34108. /**
  34109. * @param {Array.<number>} xy
  34110. * @param {Array.<number>} wh
  34111. * @param {number} [xDimIndex=0] or 1
  34112. */
  34113. function makeRectShape(xy, wh, xDimIndex) {
  34114. xDimIndex = xDimIndex || 0;
  34115. return {
  34116. x: xy[xDimIndex],
  34117. y: xy[1 - xDimIndex],
  34118. width: wh[xDimIndex],
  34119. height: wh[1 - xDimIndex]
  34120. };
  34121. }
  34122. var CartesianAxisPointer = BaseAxisPointer.extend({
  34123. /**
  34124. * @override
  34125. */
  34126. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34127. var axis = axisModel.axis;
  34128. var grid = axis.grid;
  34129. var axisPointerType = axisPointerModel.get('type');
  34130. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34131. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  34132. if (axisPointerType && axisPointerType !== 'none') {
  34133. var elStyle = buildElStyle(axisPointerModel);
  34134. var pointerOption = pointerShapeBuilder[axisPointerType](
  34135. axis, pixelValue, otherExtent, elStyle
  34136. );
  34137. pointerOption.style = elStyle;
  34138. elOption.graphicKey = pointerOption.type;
  34139. elOption.pointer = pointerOption;
  34140. }
  34141. var layoutInfo = layout$1(grid.model, axisModel);
  34142. buildCartesianSingleLabelElOption(
  34143. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34144. );
  34145. },
  34146. /**
  34147. * @override
  34148. */
  34149. getHandleTransform: function (value, axisModel, axisPointerModel) {
  34150. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  34151. labelInside: false
  34152. });
  34153. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  34154. return {
  34155. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34156. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  34157. };
  34158. },
  34159. /**
  34160. * @override
  34161. */
  34162. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  34163. var axis = axisModel.axis;
  34164. var grid = axis.grid;
  34165. var axisExtent = axis.getGlobalExtent(true);
  34166. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34167. var dimIndex = axis.dim === 'x' ? 0 : 1;
  34168. var currPosition = transform.position;
  34169. currPosition[dimIndex] += delta[dimIndex];
  34170. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  34171. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  34172. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  34173. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  34174. cursorPoint[dimIndex] = currPosition[dimIndex];
  34175. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  34176. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  34177. return {
  34178. position: currPosition,
  34179. rotation: transform.rotation,
  34180. cursorPoint: cursorPoint,
  34181. tooltipOption: tooltipOptions[dimIndex]
  34182. };
  34183. }
  34184. });
  34185. function getCartesian(grid, axis) {
  34186. var opt = {};
  34187. opt[axis.dim + 'AxisIndex'] = axis.index;
  34188. return grid.getCartesian(opt);
  34189. }
  34190. var pointerShapeBuilder = {
  34191. line: function (axis, pixelValue, otherExtent, elStyle) {
  34192. var targetShape = makeLineShape(
  34193. [pixelValue, otherExtent[0]],
  34194. [pixelValue, otherExtent[1]],
  34195. getAxisDimIndex(axis)
  34196. );
  34197. subPixelOptimizeLine({
  34198. shape: targetShape,
  34199. style: elStyle
  34200. });
  34201. return {
  34202. type: 'Line',
  34203. shape: targetShape
  34204. };
  34205. },
  34206. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  34207. var bandWidth = axis.getBandWidth();
  34208. var span = otherExtent[1] - otherExtent[0];
  34209. return {
  34210. type: 'Rect',
  34211. shape: makeRectShape(
  34212. [pixelValue - bandWidth / 2, otherExtent[0]],
  34213. [bandWidth, span],
  34214. getAxisDimIndex(axis)
  34215. )
  34216. };
  34217. }
  34218. };
  34219. function getAxisDimIndex(axis) {
  34220. return axis.dim === 'x' ? 0 : 1;
  34221. }
  34222. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  34223. // CartesianAxisPointer is not supposed to be required here. But consider
  34224. // echarts.simple.js and online build tooltip, which only require gridSimple,
  34225. // CartesianAxisPointer should be able to required somewhere.
  34226. registerPreprocessor(function (option) {
  34227. // Always has a global axisPointerModel for default setting.
  34228. if (option) {
  34229. (!option.axisPointer || option.axisPointer.length === 0)
  34230. && (option.axisPointer = {});
  34231. var link = option.axisPointer.link;
  34232. // Normalize to array to avoid object mergin. But if link
  34233. // is not set, remain null/undefined, otherwise it will
  34234. // override existent link setting.
  34235. if (link && !isArray(link)) {
  34236. option.axisPointer.link = [link];
  34237. }
  34238. }
  34239. });
  34240. // This process should proformed after coordinate systems created
  34241. // and series data processed. So put it on statistic processing stage.
  34242. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  34243. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34244. // allAxesInfo should be updated when setOption performed.
  34245. ecModel.getComponent('axisPointer').coordSysAxesInfo
  34246. = collect(ecModel, api);
  34247. });
  34248. // Broadcast to all views.
  34249. registerAction({
  34250. type: 'updateAxisPointer',
  34251. event: 'updateAxisPointer',
  34252. update: ':updateAxisPointer'
  34253. }, axisTrigger);
  34254. extendComponentModel({
  34255. type: 'tooltip',
  34256. dependencies: ['axisPointer'],
  34257. defaultOption: {
  34258. zlevel: 0,
  34259. z: 8,
  34260. show: true,
  34261. // tooltip主体内容
  34262. showContent: true,
  34263. // 'trigger' only works on coordinate system.
  34264. // 'item' | 'axis' | 'none'
  34265. trigger: 'item',
  34266. // 'click' | 'mousemove' | 'none'
  34267. triggerOn: 'mousemove|click',
  34268. alwaysShowContent: false,
  34269. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  34270. // 位置 {Array} | {Function}
  34271. // position: null
  34272. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  34273. // align: null,
  34274. // verticalAlign: null,
  34275. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  34276. confine: false,
  34277. // 内容格式器:{string}(Template) ¦ {Function}
  34278. // formatter: null
  34279. showDelay: 0,
  34280. // 隐藏延迟,单位ms
  34281. hideDelay: 100,
  34282. // 动画变换时间,单位s
  34283. transitionDuration: 0.4,
  34284. enterable: false,
  34285. // 提示背景颜色,默认为透明度为0.7的黑色
  34286. backgroundColor: 'rgba(50,50,50,0.7)',
  34287. // 提示边框颜色
  34288. borderColor: '#333',
  34289. // 提示边框圆角,单位px,默认为4
  34290. borderRadius: 4,
  34291. // 提示边框线宽,单位px,默认为0(无边框)
  34292. borderWidth: 0,
  34293. // 提示内边距,单位px,默认各方向内边距为5,
  34294. // 接受数组分别设定上右下左边距,同css
  34295. padding: 5,
  34296. // Extra css text
  34297. extraCssText: '',
  34298. // 坐标轴指示器,坐标轴触发有效
  34299. axisPointer: {
  34300. // 默认为直线
  34301. // 可选为:'line' | 'shadow' | 'cross'
  34302. type: 'line',
  34303. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  34304. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  34305. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  34306. // 极坐标系会默认选择 angle 轴
  34307. axis: 'auto',
  34308. animation: 'auto',
  34309. animationDurationUpdate: 200,
  34310. animationEasingUpdate: 'exponentialOut',
  34311. crossStyle: {
  34312. color: '#999',
  34313. width: 1,
  34314. type: 'dashed',
  34315. // TODO formatter
  34316. textStyle: {}
  34317. }
  34318. // lineStyle and shadowStyle should not be specified here,
  34319. // otherwise it will always override those styles on option.axisPointer.
  34320. },
  34321. textStyle: {
  34322. color: '#fff',
  34323. fontSize: 14
  34324. }
  34325. }
  34326. });
  34327. var each$11 = each$1;
  34328. var toCamelCase$1 = toCamelCase;
  34329. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  34330. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  34331. /**
  34332. * @param {number} duration
  34333. * @return {string}
  34334. * @inner
  34335. */
  34336. function assembleTransition(duration) {
  34337. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  34338. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  34339. + 'top ' + duration + 's ' + transitionCurve;
  34340. return map(vendors, function (vendorPrefix) {
  34341. return vendorPrefix + 'transition:' + transitionText;
  34342. }).join(';');
  34343. }
  34344. /**
  34345. * @param {Object} textStyle
  34346. * @return {string}
  34347. * @inner
  34348. */
  34349. function assembleFont(textStyleModel) {
  34350. var cssText = [];
  34351. var fontSize = textStyleModel.get('fontSize');
  34352. var color = textStyleModel.getTextColor();
  34353. color && cssText.push('color:' + color);
  34354. cssText.push('font:' + textStyleModel.getFont());
  34355. fontSize &&
  34356. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  34357. each$11(['decoration', 'align'], function (name) {
  34358. var val = textStyleModel.get(name);
  34359. val && cssText.push('text-' + name + ':' + val);
  34360. });
  34361. return cssText.join(';');
  34362. }
  34363. /**
  34364. * @param {Object} tooltipModel
  34365. * @return {string}
  34366. * @inner
  34367. */
  34368. function assembleCssText(tooltipModel) {
  34369. var cssText = [];
  34370. var transitionDuration = tooltipModel.get('transitionDuration');
  34371. var backgroundColor = tooltipModel.get('backgroundColor');
  34372. var textStyleModel = tooltipModel.getModel('textStyle');
  34373. var padding = tooltipModel.get('padding');
  34374. // Animation transition. Do not animate when transitionDuration is 0.
  34375. transitionDuration &&
  34376. cssText.push(assembleTransition(transitionDuration));
  34377. if (backgroundColor) {
  34378. if (env$1.canvasSupported) {
  34379. cssText.push('background-Color:' + backgroundColor);
  34380. }
  34381. else {
  34382. // for ie
  34383. cssText.push(
  34384. 'background-Color:#' + toHex(backgroundColor)
  34385. );
  34386. cssText.push('filter:alpha(opacity=70)');
  34387. }
  34388. }
  34389. // Border style
  34390. each$11(['width', 'color', 'radius'], function (name) {
  34391. var borderName = 'border-' + name;
  34392. var camelCase = toCamelCase$1(borderName);
  34393. var val = tooltipModel.get(camelCase);
  34394. val != null &&
  34395. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  34396. });
  34397. // Text style
  34398. cssText.push(assembleFont(textStyleModel));
  34399. // Padding
  34400. if (padding != null) {
  34401. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  34402. }
  34403. return cssText.join(';') + ';';
  34404. }
  34405. /**
  34406. * @alias module:echarts/component/tooltip/TooltipContent
  34407. * @constructor
  34408. */
  34409. function TooltipContent(container, api) {
  34410. if (env$1.wxa) {
  34411. return null;
  34412. }
  34413. var el = document.createElement('div');
  34414. var zr = this._zr = api.getZr();
  34415. this.el = el;
  34416. this._x = api.getWidth() / 2;
  34417. this._y = api.getHeight() / 2;
  34418. container.appendChild(el);
  34419. this._container = container;
  34420. this._show = false;
  34421. /**
  34422. * @private
  34423. */
  34424. this._hideTimeout;
  34425. var self = this;
  34426. el.onmouseenter = function () {
  34427. // clear the timeout in hideLater and keep showing tooltip
  34428. if (self._enterable) {
  34429. clearTimeout(self._hideTimeout);
  34430. self._show = true;
  34431. }
  34432. self._inContent = true;
  34433. };
  34434. el.onmousemove = function (e) {
  34435. e = e || window.event;
  34436. if (!self._enterable) {
  34437. // Try trigger zrender event to avoid mouse
  34438. // in and out shape too frequently
  34439. var handler = zr.handler;
  34440. normalizeEvent(container, e, true);
  34441. handler.dispatch('mousemove', e);
  34442. }
  34443. };
  34444. el.onmouseleave = function () {
  34445. if (self._enterable) {
  34446. if (self._show) {
  34447. self.hideLater(self._hideDelay);
  34448. }
  34449. }
  34450. self._inContent = false;
  34451. };
  34452. }
  34453. TooltipContent.prototype = {
  34454. constructor: TooltipContent,
  34455. /**
  34456. * @private
  34457. * @type {boolean}
  34458. */
  34459. _enterable: true,
  34460. /**
  34461. * Update when tooltip is rendered
  34462. */
  34463. update: function () {
  34464. // FIXME
  34465. // Move this logic to ec main?
  34466. var container = this._container;
  34467. var stl = container.currentStyle
  34468. || document.defaultView.getComputedStyle(container);
  34469. var domStyle = container.style;
  34470. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  34471. domStyle.position = 'relative';
  34472. }
  34473. // Hide the tooltip
  34474. // PENDING
  34475. // this.hide();
  34476. },
  34477. show: function (tooltipModel) {
  34478. clearTimeout(this._hideTimeout);
  34479. var el = this.el;
  34480. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  34481. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  34482. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  34483. + (tooltipModel.get('extraCssText') || '');
  34484. el.style.display = el.innerHTML ? 'block' : 'none';
  34485. this._show = true;
  34486. },
  34487. setContent: function (content) {
  34488. this.el.innerHTML = content == null ? '' : content;
  34489. },
  34490. setEnterable: function (enterable) {
  34491. this._enterable = enterable;
  34492. },
  34493. getSize: function () {
  34494. var el = this.el;
  34495. return [el.clientWidth, el.clientHeight];
  34496. },
  34497. moveTo: function (x, y) {
  34498. // xy should be based on canvas root. But tooltipContent is
  34499. // the sibling of canvas root. So padding of ec container
  34500. // should be considered here.
  34501. var zr = this._zr;
  34502. var viewportRootOffset;
  34503. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  34504. x += viewportRootOffset.offsetLeft;
  34505. y += viewportRootOffset.offsetTop;
  34506. }
  34507. var style = this.el.style;
  34508. style.left = x + 'px';
  34509. style.top = y + 'px';
  34510. this._x = x;
  34511. this._y = y;
  34512. },
  34513. hide: function () {
  34514. this.el.style.display = 'none';
  34515. this._show = false;
  34516. },
  34517. hideLater: function (time) {
  34518. if (this._show && !(this._inContent && this._enterable)) {
  34519. if (time) {
  34520. this._hideDelay = time;
  34521. // Set show false to avoid invoke hideLater mutiple times
  34522. this._show = false;
  34523. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  34524. }
  34525. else {
  34526. this.hide();
  34527. }
  34528. }
  34529. },
  34530. isShow: function () {
  34531. return this._show;
  34532. }
  34533. };
  34534. var bind$2 = bind;
  34535. var each$10 = each$1;
  34536. var parsePercent$2 = parsePercent$1;
  34537. var proxyRect = new Rect({
  34538. shape: {x: -1, y: -1, width: 2, height: 2}
  34539. });
  34540. extendComponentView({
  34541. type: 'tooltip',
  34542. init: function (ecModel, api) {
  34543. if (env$1.node) {
  34544. return;
  34545. }
  34546. var tooltipContent = new TooltipContent(api.getDom(), api);
  34547. this._tooltipContent = tooltipContent;
  34548. },
  34549. render: function (tooltipModel, ecModel, api) {
  34550. if (env$1.node || env$1.wxa) {
  34551. return;
  34552. }
  34553. // Reset
  34554. this.group.removeAll();
  34555. /**
  34556. * @private
  34557. * @type {module:echarts/component/tooltip/TooltipModel}
  34558. */
  34559. this._tooltipModel = tooltipModel;
  34560. /**
  34561. * @private
  34562. * @type {module:echarts/model/Global}
  34563. */
  34564. this._ecModel = ecModel;
  34565. /**
  34566. * @private
  34567. * @type {module:echarts/ExtensionAPI}
  34568. */
  34569. this._api = api;
  34570. /**
  34571. * Should be cleaned when render.
  34572. * @private
  34573. * @type {Array.<Array.<Object>>}
  34574. */
  34575. this._lastDataByCoordSys = null;
  34576. /**
  34577. * @private
  34578. * @type {boolean}
  34579. */
  34580. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  34581. var tooltipContent = this._tooltipContent;
  34582. tooltipContent.update();
  34583. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  34584. this._initGlobalListener();
  34585. this._keepShow();
  34586. },
  34587. _initGlobalListener: function () {
  34588. var tooltipModel = this._tooltipModel;
  34589. var triggerOn = tooltipModel.get('triggerOn');
  34590. register(
  34591. 'itemTooltip',
  34592. this._api,
  34593. bind$2(function (currTrigger, e, dispatchAction) {
  34594. // If 'none', it is not controlled by mouse totally.
  34595. if (triggerOn !== 'none') {
  34596. if (triggerOn.indexOf(currTrigger) >= 0) {
  34597. this._tryShow(e, dispatchAction);
  34598. }
  34599. else if (currTrigger === 'leave') {
  34600. this._hide(dispatchAction);
  34601. }
  34602. }
  34603. }, this)
  34604. );
  34605. },
  34606. _keepShow: function () {
  34607. var tooltipModel = this._tooltipModel;
  34608. var ecModel = this._ecModel;
  34609. var api = this._api;
  34610. // Try to keep the tooltip show when refreshing
  34611. if (this._lastX != null
  34612. && this._lastY != null
  34613. // When user is willing to control tooltip totally using API,
  34614. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  34615. // which is not expected.
  34616. && tooltipModel.get('triggerOn') !== 'none'
  34617. ) {
  34618. var self = this;
  34619. clearTimeout(this._refreshUpdateTimeout);
  34620. this._refreshUpdateTimeout = setTimeout(function () {
  34621. // Show tip next tick after other charts are rendered
  34622. // In case highlight action has wrong result
  34623. // FIXME
  34624. self.manuallyShowTip(tooltipModel, ecModel, api, {
  34625. x: self._lastX,
  34626. y: self._lastY
  34627. });
  34628. });
  34629. }
  34630. },
  34631. /**
  34632. * Show tip manually by
  34633. * dispatchAction({
  34634. * type: 'showTip',
  34635. * x: 10,
  34636. * y: 10
  34637. * });
  34638. * Or
  34639. * dispatchAction({
  34640. * type: 'showTip',
  34641. * seriesIndex: 0,
  34642. * dataIndex or dataIndexInside or name
  34643. * });
  34644. *
  34645. * TODO Batch
  34646. */
  34647. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  34648. if (payload.from === this.uid || env$1.node) {
  34649. return;
  34650. }
  34651. var dispatchAction = makeDispatchAction$1(payload, api);
  34652. // Reset ticket
  34653. this._ticket = '';
  34654. // When triggered from axisPointer.
  34655. var dataByCoordSys = payload.dataByCoordSys;
  34656. if (payload.tooltip && payload.x != null && payload.y != null) {
  34657. var el = proxyRect;
  34658. el.position = [payload.x, payload.y];
  34659. el.update();
  34660. el.tooltip = payload.tooltip;
  34661. // Manually show tooltip while view is not using zrender elements.
  34662. this._tryShow({
  34663. offsetX: payload.x,
  34664. offsetY: payload.y,
  34665. target: el
  34666. }, dispatchAction);
  34667. }
  34668. else if (dataByCoordSys) {
  34669. this._tryShow({
  34670. offsetX: payload.x,
  34671. offsetY: payload.y,
  34672. position: payload.position,
  34673. event: {},
  34674. dataByCoordSys: payload.dataByCoordSys,
  34675. tooltipOption: payload.tooltipOption
  34676. }, dispatchAction);
  34677. }
  34678. else if (payload.seriesIndex != null) {
  34679. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  34680. return;
  34681. }
  34682. var pointInfo = findPointFromSeries(payload, ecModel);
  34683. var cx = pointInfo.point[0];
  34684. var cy = pointInfo.point[1];
  34685. if (cx != null && cy != null) {
  34686. this._tryShow({
  34687. offsetX: cx,
  34688. offsetY: cy,
  34689. position: payload.position,
  34690. target: pointInfo.el,
  34691. event: {}
  34692. }, dispatchAction);
  34693. }
  34694. }
  34695. else if (payload.x != null && payload.y != null) {
  34696. // FIXME
  34697. // should wrap dispatchAction like `axisPointer/globalListener` ?
  34698. api.dispatchAction({
  34699. type: 'updateAxisPointer',
  34700. x: payload.x,
  34701. y: payload.y
  34702. });
  34703. this._tryShow({
  34704. offsetX: payload.x,
  34705. offsetY: payload.y,
  34706. position: payload.position,
  34707. target: api.getZr().findHover(payload.x, payload.y).target,
  34708. event: {}
  34709. }, dispatchAction);
  34710. }
  34711. },
  34712. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  34713. var tooltipContent = this._tooltipContent;
  34714. if (!this._alwaysShowContent && this._tooltipModel) {
  34715. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  34716. }
  34717. this._lastX = this._lastY = null;
  34718. if (payload.from !== this.uid) {
  34719. this._hide(makeDispatchAction$1(payload, api));
  34720. }
  34721. },
  34722. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  34723. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  34724. // and tooltip.
  34725. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  34726. var seriesIndex = payload.seriesIndex;
  34727. var dataIndex = payload.dataIndex;
  34728. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  34729. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  34730. return;
  34731. }
  34732. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  34733. if (!seriesModel) {
  34734. return;
  34735. }
  34736. var data = seriesModel.getData();
  34737. var tooltipModel = buildTooltipModel([
  34738. data.getItemModel(dataIndex),
  34739. seriesModel,
  34740. (seriesModel.coordinateSystem || {}).model,
  34741. tooltipModel
  34742. ]);
  34743. if (tooltipModel.get('trigger') !== 'axis') {
  34744. return;
  34745. }
  34746. api.dispatchAction({
  34747. type: 'updateAxisPointer',
  34748. seriesIndex: seriesIndex,
  34749. dataIndex: dataIndex,
  34750. position: payload.position
  34751. });
  34752. return true;
  34753. },
  34754. _tryShow: function (e, dispatchAction) {
  34755. var el = e.target;
  34756. var tooltipModel = this._tooltipModel;
  34757. if (!tooltipModel) {
  34758. return;
  34759. }
  34760. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  34761. this._lastX = e.offsetX;
  34762. this._lastY = e.offsetY;
  34763. var dataByCoordSys = e.dataByCoordSys;
  34764. if (dataByCoordSys && dataByCoordSys.length) {
  34765. this._showAxisTooltip(dataByCoordSys, e);
  34766. }
  34767. // Always show item tooltip if mouse is on the element with dataIndex
  34768. else if (el && el.dataIndex != null) {
  34769. this._lastDataByCoordSys = null;
  34770. this._showSeriesItemTooltip(e, el, dispatchAction);
  34771. }
  34772. // Tooltip provided directly. Like legend.
  34773. else if (el && el.tooltip) {
  34774. this._lastDataByCoordSys = null;
  34775. this._showComponentItemTooltip(e, el, dispatchAction);
  34776. }
  34777. else {
  34778. this._lastDataByCoordSys = null;
  34779. this._hide(dispatchAction);
  34780. }
  34781. },
  34782. _showOrMove: function (tooltipModel, cb) {
  34783. // showDelay is used in this case: tooltip.enterable is set
  34784. // as true. User intent to move mouse into tooltip and click
  34785. // something. `showDelay` makes it easyer to enter the content
  34786. // but tooltip do not move immediately.
  34787. var delay = tooltipModel.get('showDelay');
  34788. cb = bind(cb, this);
  34789. clearTimeout(this._showTimout);
  34790. delay > 0
  34791. ? (this._showTimout = setTimeout(cb, delay))
  34792. : cb();
  34793. },
  34794. _showAxisTooltip: function (dataByCoordSys, e) {
  34795. var ecModel = this._ecModel;
  34796. var globalTooltipModel = this._tooltipModel;
  34797. var point = [e.offsetX, e.offsetY];
  34798. var singleDefaultHTML = [];
  34799. var singleParamsList = [];
  34800. var singleTooltipModel = buildTooltipModel([
  34801. e.tooltipOption,
  34802. globalTooltipModel
  34803. ]);
  34804. each$10(dataByCoordSys, function (itemCoordSys) {
  34805. // var coordParamList = [];
  34806. // var coordDefaultHTML = [];
  34807. // var coordTooltipModel = buildTooltipModel([
  34808. // e.tooltipOption,
  34809. // itemCoordSys.tooltipOption,
  34810. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  34811. // globalTooltipModel
  34812. // ]);
  34813. // var displayMode = coordTooltipModel.get('displayMode');
  34814. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  34815. each$10(itemCoordSys.dataByAxis, function (item) {
  34816. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  34817. var axisValue = item.value;
  34818. var seriesDefaultHTML = [];
  34819. if (!axisModel || axisValue == null) {
  34820. return;
  34821. }
  34822. var valueLabel = getValueLabel(
  34823. axisValue, axisModel.axis, ecModel,
  34824. item.seriesDataIndices,
  34825. item.valueLabelOpt
  34826. );
  34827. each$1(item.seriesDataIndices, function (idxItem) {
  34828. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  34829. var dataIndex = idxItem.dataIndexInside;
  34830. var dataParams = series && series.getDataParams(dataIndex);
  34831. dataParams.axisDim = item.axisDim;
  34832. dataParams.axisIndex = item.axisIndex;
  34833. dataParams.axisType = item.axisType;
  34834. dataParams.axisId = item.axisId;
  34835. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  34836. dataParams.axisValueLabel = valueLabel;
  34837. if (dataParams) {
  34838. singleParamsList.push(dataParams);
  34839. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  34840. }
  34841. });
  34842. // Default tooltip content
  34843. // FIXME
  34844. // (1) shold be the first data which has name?
  34845. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  34846. var firstLine = valueLabel;
  34847. singleDefaultHTML.push(
  34848. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  34849. + seriesDefaultHTML.join('<br />')
  34850. );
  34851. });
  34852. }, this);
  34853. // In most case, the second axis is shown upper than the first one.
  34854. singleDefaultHTML.reverse();
  34855. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  34856. var positionExpr = e.position;
  34857. this._showOrMove(singleTooltipModel, function () {
  34858. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  34859. this._updatePosition(
  34860. singleTooltipModel,
  34861. positionExpr,
  34862. point[0], point[1],
  34863. this._tooltipContent,
  34864. singleParamsList
  34865. );
  34866. }
  34867. else {
  34868. this._showTooltipContent(
  34869. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  34870. point[0], point[1], positionExpr
  34871. );
  34872. }
  34873. });
  34874. // Do not trigger events here, because this branch only be entered
  34875. // from dispatchAction.
  34876. },
  34877. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  34878. var ecModel = this._ecModel;
  34879. // Use dataModel in element if possible
  34880. // Used when mouseover on a element like markPoint or edge
  34881. // In which case, the data is not main data in series.
  34882. var seriesIndex = el.seriesIndex;
  34883. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  34884. // For example, graph link.
  34885. var dataModel = el.dataModel || seriesModel;
  34886. var dataIndex = el.dataIndex;
  34887. var dataType = el.dataType;
  34888. var data = dataModel.getData();
  34889. var tooltipModel = buildTooltipModel([
  34890. data.getItemModel(dataIndex),
  34891. dataModel,
  34892. seriesModel && (seriesModel.coordinateSystem || {}).model,
  34893. this._tooltipModel
  34894. ]);
  34895. var tooltipTrigger = tooltipModel.get('trigger');
  34896. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  34897. return;
  34898. }
  34899. var params = dataModel.getDataParams(dataIndex, dataType);
  34900. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  34901. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  34902. this._showOrMove(tooltipModel, function () {
  34903. this._showTooltipContent(
  34904. tooltipModel, defaultHtml, params, asyncTicket,
  34905. e.offsetX, e.offsetY, e.position, e.target
  34906. );
  34907. });
  34908. // FIXME
  34909. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  34910. dispatchAction({
  34911. type: 'showTip',
  34912. dataIndexInside: dataIndex,
  34913. dataIndex: data.getRawIndex(dataIndex),
  34914. seriesIndex: seriesIndex,
  34915. from: this.uid
  34916. });
  34917. },
  34918. _showComponentItemTooltip: function (e, el, dispatchAction) {
  34919. var tooltipOpt = el.tooltip;
  34920. if (typeof tooltipOpt === 'string') {
  34921. var content = tooltipOpt;
  34922. tooltipOpt = {
  34923. content: content,
  34924. // Fixed formatter
  34925. formatter: content
  34926. };
  34927. }
  34928. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  34929. var defaultHtml = subTooltipModel.get('content');
  34930. var asyncTicket = Math.random();
  34931. // Do not check whether `trigger` is 'none' here, because `trigger`
  34932. // only works on cooridinate system. In fact, we have not found case
  34933. // that requires setting `trigger` nothing on component yet.
  34934. this._showOrMove(subTooltipModel, function () {
  34935. this._showTooltipContent(
  34936. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  34937. asyncTicket, e.offsetX, e.offsetY, e.position, el
  34938. );
  34939. });
  34940. // If not dispatch showTip, tip may be hide triggered by axis.
  34941. dispatchAction({
  34942. type: 'showTip',
  34943. from: this.uid
  34944. });
  34945. },
  34946. _showTooltipContent: function (
  34947. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  34948. ) {
  34949. // Reset ticket
  34950. this._ticket = '';
  34951. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  34952. return;
  34953. }
  34954. var tooltipContent = this._tooltipContent;
  34955. var formatter = tooltipModel.get('formatter');
  34956. positionExpr = positionExpr || tooltipModel.get('position');
  34957. var html = defaultHtml;
  34958. if (formatter && typeof formatter === 'string') {
  34959. html = formatTpl(formatter, params, true);
  34960. }
  34961. else if (typeof formatter === 'function') {
  34962. var callback = bind$2(function (cbTicket, html) {
  34963. if (cbTicket === this._ticket) {
  34964. tooltipContent.setContent(html);
  34965. this._updatePosition(
  34966. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  34967. );
  34968. }
  34969. }, this);
  34970. this._ticket = asyncTicket;
  34971. html = formatter(params, asyncTicket, callback);
  34972. }
  34973. tooltipContent.setContent(html);
  34974. tooltipContent.show(tooltipModel);
  34975. this._updatePosition(
  34976. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  34977. );
  34978. },
  34979. /**
  34980. * @param {string|Function|Array.<number>|Object} positionExpr
  34981. * @param {number} x Mouse x
  34982. * @param {number} y Mouse y
  34983. * @param {boolean} confine Whether confine tooltip content in view rect.
  34984. * @param {Object|<Array.<Object>} params
  34985. * @param {module:zrender/Element} el target element
  34986. * @param {module:echarts/ExtensionAPI} api
  34987. * @return {Array.<number>}
  34988. */
  34989. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  34990. var viewWidth = this._api.getWidth();
  34991. var viewHeight = this._api.getHeight();
  34992. positionExpr = positionExpr || tooltipModel.get('position');
  34993. var contentSize = content.getSize();
  34994. var align = tooltipModel.get('align');
  34995. var vAlign = tooltipModel.get('verticalAlign');
  34996. var rect = el && el.getBoundingRect().clone();
  34997. el && rect.applyTransform(el.transform);
  34998. if (typeof positionExpr === 'function') {
  34999. // Callback of position can be an array or a string specify the position
  35000. positionExpr = positionExpr([x, y], params, content.el, rect, {
  35001. viewSize: [viewWidth, viewHeight],
  35002. contentSize: contentSize.slice()
  35003. });
  35004. }
  35005. if (isArray(positionExpr)) {
  35006. x = parsePercent$2(positionExpr[0], viewWidth);
  35007. y = parsePercent$2(positionExpr[1], viewHeight);
  35008. }
  35009. else if (isObject$1(positionExpr)) {
  35010. positionExpr.width = contentSize[0];
  35011. positionExpr.height = contentSize[1];
  35012. var layoutRect = getLayoutRect(
  35013. positionExpr, {width: viewWidth, height: viewHeight}
  35014. );
  35015. x = layoutRect.x;
  35016. y = layoutRect.y;
  35017. align = null;
  35018. // When positionExpr is left/top/right/bottom,
  35019. // align and verticalAlign will not work.
  35020. vAlign = null;
  35021. }
  35022. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  35023. else if (typeof positionExpr === 'string' && el) {
  35024. var pos = calcTooltipPosition(
  35025. positionExpr, rect, contentSize
  35026. );
  35027. x = pos[0];
  35028. y = pos[1];
  35029. }
  35030. else {
  35031. var pos = refixTooltipPosition(
  35032. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  35033. );
  35034. x = pos[0];
  35035. y = pos[1];
  35036. }
  35037. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  35038. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  35039. if (tooltipModel.get('confine')) {
  35040. var pos = confineTooltipPosition(
  35041. x, y, content.el, viewWidth, viewHeight
  35042. );
  35043. x = pos[0];
  35044. y = pos[1];
  35045. }
  35046. content.moveTo(x, y);
  35047. },
  35048. // FIXME
  35049. // Should we remove this but leave this to user?
  35050. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  35051. var lastCoordSys = this._lastDataByCoordSys;
  35052. var contentNotChanged = !!lastCoordSys
  35053. && lastCoordSys.length === dataByCoordSys.length;
  35054. contentNotChanged && each$10(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  35055. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  35056. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  35057. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  35058. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  35059. contentNotChanged && each$10(lastDataByAxis, function (lastItem, indexAxis) {
  35060. var thisItem = thisDataByAxis[indexAxis] || {};
  35061. var lastIndices = lastItem.seriesDataIndices || [];
  35062. var newIndices = thisItem.seriesDataIndices || [];
  35063. contentNotChanged &=
  35064. lastItem.value === thisItem.value
  35065. && lastItem.axisType === thisItem.axisType
  35066. && lastItem.axisId === thisItem.axisId
  35067. && lastIndices.length === newIndices.length;
  35068. contentNotChanged && each$10(lastIndices, function (lastIdxItem, j) {
  35069. var newIdxItem = newIndices[j];
  35070. contentNotChanged &=
  35071. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  35072. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  35073. });
  35074. });
  35075. });
  35076. this._lastDataByCoordSys = dataByCoordSys;
  35077. return !!contentNotChanged;
  35078. },
  35079. _hide: function (dispatchAction) {
  35080. // Do not directly hideLater here, because this behavior may be prevented
  35081. // in dispatchAction when showTip is dispatched.
  35082. // FIXME
  35083. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  35084. this._lastDataByCoordSys = null;
  35085. dispatchAction({
  35086. type: 'hideTip',
  35087. from: this.uid
  35088. });
  35089. },
  35090. dispose: function (ecModel, api) {
  35091. if (env$1.node) {
  35092. return;
  35093. }
  35094. this._tooltipContent.hide();
  35095. unregister('itemTooltip', api);
  35096. }
  35097. });
  35098. /**
  35099. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  35100. * From top to bottom. (the last one should be globalTooltipModel);
  35101. */
  35102. function buildTooltipModel(modelCascade) {
  35103. var resultModel = modelCascade.pop();
  35104. while (modelCascade.length) {
  35105. var tooltipOpt = modelCascade.pop();
  35106. if (tooltipOpt) {
  35107. if (Model.isInstance(tooltipOpt)) {
  35108. tooltipOpt = tooltipOpt.get('tooltip', true);
  35109. }
  35110. // In each data item tooltip can be simply write:
  35111. // {
  35112. // value: 10,
  35113. // tooltip: 'Something you need to know'
  35114. // }
  35115. if (typeof tooltipOpt === 'string') {
  35116. tooltipOpt = {formatter: tooltipOpt};
  35117. }
  35118. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  35119. }
  35120. }
  35121. return resultModel;
  35122. }
  35123. function makeDispatchAction$1(payload, api) {
  35124. return payload.dispatchAction || bind(api.dispatchAction, api);
  35125. }
  35126. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  35127. var size = getOuterSize(el);
  35128. var width = size.width;
  35129. var height = size.height;
  35130. if (gapH != null) {
  35131. if (x + width + gapH > viewWidth) {
  35132. x -= width + gapH;
  35133. }
  35134. else {
  35135. x += gapH;
  35136. }
  35137. }
  35138. if (gapV != null) {
  35139. if (y + height + gapV > viewHeight) {
  35140. y -= height + gapV;
  35141. }
  35142. else {
  35143. y += gapV;
  35144. }
  35145. }
  35146. return [x, y];
  35147. }
  35148. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  35149. var size = getOuterSize(el);
  35150. var width = size.width;
  35151. var height = size.height;
  35152. x = Math.min(x + width, viewWidth) - width;
  35153. y = Math.min(y + height, viewHeight) - height;
  35154. x = Math.max(x, 0);
  35155. y = Math.max(y, 0);
  35156. return [x, y];
  35157. }
  35158. function getOuterSize(el) {
  35159. var width = el.clientWidth;
  35160. var height = el.clientHeight;
  35161. // Consider browser compatibility.
  35162. // IE8 does not support getComputedStyle.
  35163. if (document.defaultView && document.defaultView.getComputedStyle) {
  35164. var stl = document.defaultView.getComputedStyle(el);
  35165. if (stl) {
  35166. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  35167. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  35168. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  35169. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  35170. }
  35171. }
  35172. return {width: width, height: height};
  35173. }
  35174. function calcTooltipPosition(position, rect, contentSize) {
  35175. var domWidth = contentSize[0];
  35176. var domHeight = contentSize[1];
  35177. var gap = 5;
  35178. var x = 0;
  35179. var y = 0;
  35180. var rectWidth = rect.width;
  35181. var rectHeight = rect.height;
  35182. switch (position) {
  35183. case 'inside':
  35184. x = rect.x + rectWidth / 2 - domWidth / 2;
  35185. y = rect.y + rectHeight / 2 - domHeight / 2;
  35186. break;
  35187. case 'top':
  35188. x = rect.x + rectWidth / 2 - domWidth / 2;
  35189. y = rect.y - domHeight - gap;
  35190. break;
  35191. case 'bottom':
  35192. x = rect.x + rectWidth / 2 - domWidth / 2;
  35193. y = rect.y + rectHeight + gap;
  35194. break;
  35195. case 'left':
  35196. x = rect.x - domWidth - gap;
  35197. y = rect.y + rectHeight / 2 - domHeight / 2;
  35198. break;
  35199. case 'right':
  35200. x = rect.x + rectWidth + gap;
  35201. y = rect.y + rectHeight / 2 - domHeight / 2;
  35202. }
  35203. return [x, y];
  35204. }
  35205. function isCenterAlign(align) {
  35206. return align === 'center' || align === 'middle';
  35207. }
  35208. // FIXME Better way to pack data in graphic element
  35209. /**
  35210. * @action
  35211. * @property {string} type
  35212. * @property {number} seriesIndex
  35213. * @property {number} dataIndex
  35214. * @property {number} [x]
  35215. * @property {number} [y]
  35216. */
  35217. registerAction(
  35218. {
  35219. type: 'showTip',
  35220. event: 'showTip',
  35221. update: 'tooltip:manuallyShowTip'
  35222. },
  35223. // noop
  35224. function () {}
  35225. );
  35226. registerAction(
  35227. {
  35228. type: 'hideTip',
  35229. event: 'hideTip',
  35230. update: 'tooltip:manuallyHideTip'
  35231. },
  35232. // noop
  35233. function () {}
  35234. );
  35235. var LegendModel = extendComponentModel({
  35236. type: 'legend.plain',
  35237. dependencies: ['series'],
  35238. layoutMode: {
  35239. type: 'box',
  35240. // legend.width/height are maxWidth/maxHeight actually,
  35241. // whereas realy width/height is calculated by its content.
  35242. // (Setting {left: 10, right: 10} does not make sense).
  35243. // So consider the case:
  35244. // `setOption({legend: {left: 10});`
  35245. // then `setOption({legend: {right: 10});`
  35246. // The previous `left` should be cleared by setting `ignoreSize`.
  35247. ignoreSize: true
  35248. },
  35249. init: function (option, parentModel, ecModel) {
  35250. this.mergeDefaultAndTheme(option, ecModel);
  35251. option.selected = option.selected || {};
  35252. },
  35253. mergeOption: function (option) {
  35254. LegendModel.superCall(this, 'mergeOption', option);
  35255. },
  35256. optionUpdated: function () {
  35257. this._updateData(this.ecModel);
  35258. var legendData = this._data;
  35259. // If selectedMode is single, try to select one
  35260. if (legendData[0] && this.get('selectedMode') === 'single') {
  35261. var hasSelected = false;
  35262. // If has any selected in option.selected
  35263. for (var i = 0; i < legendData.length; i++) {
  35264. var name = legendData[i].get('name');
  35265. if (this.isSelected(name)) {
  35266. // Force to unselect others
  35267. this.select(name);
  35268. hasSelected = true;
  35269. break;
  35270. }
  35271. }
  35272. // Try select the first if selectedMode is single
  35273. !hasSelected && this.select(legendData[0].get('name'));
  35274. }
  35275. },
  35276. _updateData: function (ecModel) {
  35277. var potentialData = [];
  35278. var availableNames = [];
  35279. ecModel.eachRawSeries(function (seriesModel) {
  35280. var seriesName = seriesModel.name;
  35281. availableNames.push(seriesName);
  35282. var potentialSeriesName;
  35283. if (seriesModel.legendDataProvider) {
  35284. var data = seriesModel.legendDataProvider();
  35285. var names = data.mapArray(data.getName);
  35286. if (!ecModel.isSeriesFiltered(seriesModel)) {
  35287. availableNames = availableNames.concat(names);
  35288. }
  35289. if (names.length) {
  35290. potentialData = potentialData.concat(names);
  35291. }
  35292. else {
  35293. potentialSeriesName = seriesName;
  35294. }
  35295. }
  35296. else {
  35297. potentialSeriesName = seriesName;
  35298. }
  35299. if (potentialSeriesName && potentialSeriesName !== DEFAULT_COMPONENT_NAME) {
  35300. potentialData.push(potentialSeriesName);
  35301. }
  35302. });
  35303. /**
  35304. * @type {Array.<string>}
  35305. * @private
  35306. */
  35307. this._availableNames = availableNames;
  35308. // If legend.data not specified in option, use availableNames as data,
  35309. // which is convinient for user preparing option.
  35310. var rawData = this.get('data') || potentialData;
  35311. var legendData = map(rawData, function (dataItem) {
  35312. // Can be string or number
  35313. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  35314. dataItem = {
  35315. name: dataItem
  35316. };
  35317. }
  35318. return new Model(dataItem, this, this.ecModel);
  35319. }, this);
  35320. /**
  35321. * @type {Array.<module:echarts/model/Model>}
  35322. * @private
  35323. */
  35324. this._data = legendData;
  35325. },
  35326. /**
  35327. * @return {Array.<module:echarts/model/Model>}
  35328. */
  35329. getData: function () {
  35330. return this._data;
  35331. },
  35332. /**
  35333. * @param {string} name
  35334. */
  35335. select: function (name) {
  35336. var selected = this.option.selected;
  35337. var selectedMode = this.get('selectedMode');
  35338. if (selectedMode === 'single') {
  35339. var data = this._data;
  35340. each$1(data, function (dataItem) {
  35341. selected[dataItem.get('name')] = false;
  35342. });
  35343. }
  35344. selected[name] = true;
  35345. },
  35346. /**
  35347. * @param {string} name
  35348. */
  35349. unSelect: function (name) {
  35350. if (this.get('selectedMode') !== 'single') {
  35351. this.option.selected[name] = false;
  35352. }
  35353. },
  35354. /**
  35355. * @param {string} name
  35356. */
  35357. toggleSelected: function (name) {
  35358. var selected = this.option.selected;
  35359. // Default is true
  35360. if (!selected.hasOwnProperty(name)) {
  35361. selected[name] = true;
  35362. }
  35363. this[selected[name] ? 'unSelect' : 'select'](name);
  35364. },
  35365. /**
  35366. * @param {string} name
  35367. */
  35368. isSelected: function (name) {
  35369. var selected = this.option.selected;
  35370. return !(selected.hasOwnProperty(name) && !selected[name])
  35371. && indexOf(this._availableNames, name) >= 0;
  35372. },
  35373. defaultOption: {
  35374. // 一级层叠
  35375. zlevel: 0,
  35376. // 二级层叠
  35377. z: 4,
  35378. show: true,
  35379. // 布局方式,默认为水平布局,可选为:
  35380. // 'horizontal' | 'vertical'
  35381. orient: 'horizontal',
  35382. left: 'center',
  35383. // right: 'center',
  35384. top: 0,
  35385. // bottom: null,
  35386. // 水平对齐
  35387. // 'auto' | 'left' | 'right'
  35388. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  35389. align: 'auto',
  35390. backgroundColor: 'rgba(0,0,0,0)',
  35391. // 图例边框颜色
  35392. borderColor: '#ccc',
  35393. borderRadius: 0,
  35394. // 图例边框线宽,单位px,默认为0(无边框)
  35395. borderWidth: 0,
  35396. // 图例内边距,单位px,默认各方向内边距为5,
  35397. // 接受数组分别设定上右下左边距,同css
  35398. padding: 5,
  35399. // 各个item之间的间隔,单位px,默认为10,
  35400. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  35401. itemGap: 10,
  35402. // 图例图形宽度
  35403. itemWidth: 25,
  35404. // 图例图形高度
  35405. itemHeight: 14,
  35406. // 图例关闭时候的颜色
  35407. inactiveColor: '#ccc',
  35408. textStyle: {
  35409. // 图例文字颜色
  35410. color: '#333'
  35411. },
  35412. // formatter: '',
  35413. // 选择模式,默认开启图例开关
  35414. selectedMode: true,
  35415. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  35416. // selected: null,
  35417. // 图例内容(详见legend.data,数组中每一项代表一个item
  35418. // data: [],
  35419. // Tooltip 相关配置
  35420. tooltip: {
  35421. show: false
  35422. }
  35423. }
  35424. });
  35425. function legendSelectActionHandler(methodName, payload, ecModel) {
  35426. var selectedMap = {};
  35427. var isToggleSelect = methodName === 'toggleSelected';
  35428. var isSelected;
  35429. // Update all legend components
  35430. ecModel.eachComponent('legend', function (legendModel) {
  35431. if (isToggleSelect && isSelected != null) {
  35432. // Force other legend has same selected status
  35433. // Or the first is toggled to true and other are toggled to false
  35434. // In the case one legend has some item unSelected in option. And if other legend
  35435. // doesn't has the item, they will assume it is selected.
  35436. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  35437. }
  35438. else {
  35439. legendModel[methodName](payload.name);
  35440. isSelected = legendModel.isSelected(payload.name);
  35441. }
  35442. var legendData = legendModel.getData();
  35443. each$1(legendData, function (model) {
  35444. var name = model.get('name');
  35445. // Wrap element
  35446. if (name === '\n' || name === '') {
  35447. return;
  35448. }
  35449. var isItemSelected = legendModel.isSelected(name);
  35450. if (selectedMap.hasOwnProperty(name)) {
  35451. // Unselected if any legend is unselected
  35452. selectedMap[name] = selectedMap[name] && isItemSelected;
  35453. }
  35454. else {
  35455. selectedMap[name] = isItemSelected;
  35456. }
  35457. });
  35458. });
  35459. // Return the event explicitly
  35460. return {
  35461. name: payload.name,
  35462. selected: selectedMap
  35463. };
  35464. }
  35465. /**
  35466. * @event legendToggleSelect
  35467. * @type {Object}
  35468. * @property {string} type 'legendToggleSelect'
  35469. * @property {string} [from]
  35470. * @property {string} name Series name or data item name
  35471. */
  35472. registerAction(
  35473. 'legendToggleSelect', 'legendselectchanged',
  35474. curry(legendSelectActionHandler, 'toggleSelected')
  35475. );
  35476. /**
  35477. * @event legendSelect
  35478. * @type {Object}
  35479. * @property {string} type 'legendSelect'
  35480. * @property {string} name Series name or data item name
  35481. */
  35482. registerAction(
  35483. 'legendSelect', 'legendselected',
  35484. curry(legendSelectActionHandler, 'select')
  35485. );
  35486. /**
  35487. * @event legendUnSelect
  35488. * @type {Object}
  35489. * @property {string} type 'legendUnSelect'
  35490. * @property {string} name Series name or data item name
  35491. */
  35492. registerAction(
  35493. 'legendUnSelect', 'legendunselected',
  35494. curry(legendSelectActionHandler, 'unSelect')
  35495. );
  35496. /**
  35497. * Layout list like component.
  35498. * It will box layout each items in group of component and then position the whole group in the viewport
  35499. * @param {module:zrender/group/Group} group
  35500. * @param {module:echarts/model/Component} componentModel
  35501. * @param {module:echarts/ExtensionAPI}
  35502. */
  35503. function layout$2(group, componentModel, api) {
  35504. var boxLayoutParams = componentModel.getBoxLayoutParams();
  35505. var padding = componentModel.get('padding');
  35506. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  35507. var rect = getLayoutRect(
  35508. boxLayoutParams,
  35509. viewportSize,
  35510. padding
  35511. );
  35512. box(
  35513. componentModel.get('orient'),
  35514. group,
  35515. componentModel.get('itemGap'),
  35516. rect.width,
  35517. rect.height
  35518. );
  35519. positionElement(
  35520. group,
  35521. boxLayoutParams,
  35522. viewportSize,
  35523. padding
  35524. );
  35525. }
  35526. function makeBackground(rect, componentModel) {
  35527. var padding = normalizeCssArray$1(
  35528. componentModel.get('padding')
  35529. );
  35530. var style = componentModel.getItemStyle(['color', 'opacity']);
  35531. style.fill = componentModel.get('backgroundColor');
  35532. var rect = new Rect({
  35533. shape: {
  35534. x: rect.x - padding[3],
  35535. y: rect.y - padding[0],
  35536. width: rect.width + padding[1] + padding[3],
  35537. height: rect.height + padding[0] + padding[2],
  35538. r: componentModel.get('borderRadius')
  35539. },
  35540. style: style,
  35541. silent: true,
  35542. z2: -1
  35543. });
  35544. // FIXME
  35545. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  35546. // and background rect when setting like `left: 0`, `top: 0`.
  35547. // graphic.subPixelOptimizeRect(rect);
  35548. return rect;
  35549. }
  35550. var curry$3 = curry;
  35551. var each$12 = each$1;
  35552. var Group$2 = Group;
  35553. var LegendView = extendComponentView({
  35554. type: 'legend.plain',
  35555. newlineDisabled: false,
  35556. /**
  35557. * @override
  35558. */
  35559. init: function () {
  35560. /**
  35561. * @private
  35562. * @type {module:zrender/container/Group}
  35563. */
  35564. this.group.add(this._contentGroup = new Group$2());
  35565. /**
  35566. * @private
  35567. * @type {module:zrender/Element}
  35568. */
  35569. this._backgroundEl;
  35570. },
  35571. /**
  35572. * @protected
  35573. */
  35574. getContentGroup: function () {
  35575. return this._contentGroup;
  35576. },
  35577. /**
  35578. * @override
  35579. */
  35580. render: function (legendModel, ecModel, api) {
  35581. this.resetInner();
  35582. if (!legendModel.get('show', true)) {
  35583. return;
  35584. }
  35585. var itemAlign = legendModel.get('align');
  35586. if (!itemAlign || itemAlign === 'auto') {
  35587. itemAlign = (
  35588. legendModel.get('left') === 'right'
  35589. && legendModel.get('orient') === 'vertical'
  35590. ) ? 'right' : 'left';
  35591. }
  35592. this.renderInner(itemAlign, legendModel, ecModel, api);
  35593. // Perform layout.
  35594. var positionInfo = legendModel.getBoxLayoutParams();
  35595. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  35596. var padding = legendModel.get('padding');
  35597. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  35598. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  35599. // Place mainGroup, based on the calculated `mainRect`.
  35600. var layoutRect = getLayoutRect(
  35601. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  35602. viewportSize,
  35603. padding
  35604. );
  35605. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  35606. // Render background after group is layout.
  35607. this.group.add(
  35608. this._backgroundEl = makeBackground(mainRect, legendModel)
  35609. );
  35610. },
  35611. /**
  35612. * @protected
  35613. */
  35614. resetInner: function () {
  35615. this.getContentGroup().removeAll();
  35616. this._backgroundEl && this.group.remove(this._backgroundEl);
  35617. },
  35618. /**
  35619. * @protected
  35620. */
  35621. renderInner: function (itemAlign, legendModel, ecModel, api) {
  35622. var contentGroup = this.getContentGroup();
  35623. var legendDrawnMap = createHashMap();
  35624. var selectMode = legendModel.get('selectedMode');
  35625. each$12(legendModel.getData(), function (itemModel, dataIndex) {
  35626. var name = itemModel.get('name');
  35627. // Use empty string or \n as a newline string
  35628. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  35629. contentGroup.add(new Group$2({
  35630. newline: true
  35631. }));
  35632. return;
  35633. }
  35634. var seriesModel = ecModel.getSeriesByName(name)[0];
  35635. if (legendDrawnMap.get(name)) {
  35636. // Have been drawed
  35637. return;
  35638. }
  35639. // Series legend
  35640. if (seriesModel) {
  35641. var data = seriesModel.getData();
  35642. var color = data.getVisual('color');
  35643. // If color is a callback function
  35644. if (typeof color === 'function') {
  35645. // Use the first data
  35646. color = color(seriesModel.getDataParams(0));
  35647. }
  35648. // Using rect symbol defaultly
  35649. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  35650. var symbolType = data.getVisual('symbol');
  35651. var itemGroup = this._createItem(
  35652. name, dataIndex, itemModel, legendModel,
  35653. legendSymbolType, symbolType,
  35654. itemAlign, color,
  35655. selectMode
  35656. );
  35657. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  35658. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, null, api))
  35659. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, null, api));
  35660. legendDrawnMap.set(name, true);
  35661. }
  35662. else {
  35663. // Data legend of pie, funnel
  35664. ecModel.eachRawSeries(function (seriesModel) {
  35665. // In case multiple series has same data name
  35666. if (legendDrawnMap.get(name)) {
  35667. return;
  35668. }
  35669. if (seriesModel.legendDataProvider) {
  35670. var data = seriesModel.legendDataProvider();
  35671. var idx = data.indexOfName(name);
  35672. if (idx < 0) {
  35673. return;
  35674. }
  35675. var color = data.getItemVisual(idx, 'color');
  35676. var legendSymbolType = 'roundRect';
  35677. var itemGroup = this._createItem(
  35678. name, dataIndex, itemModel, legendModel,
  35679. legendSymbolType, null,
  35680. itemAlign, color,
  35681. selectMode
  35682. );
  35683. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  35684. // FIXME Should not specify the series name
  35685. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, name, api))
  35686. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, name, api));
  35687. legendDrawnMap.set(name, true);
  35688. }
  35689. }, this);
  35690. }
  35691. if (__DEV__) {
  35692. if (!legendDrawnMap.get(name)) {
  35693. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  35694. }
  35695. }
  35696. }, this);
  35697. },
  35698. _createItem: function (
  35699. name, dataIndex, itemModel, legendModel,
  35700. legendSymbolType, symbolType,
  35701. itemAlign, color, selectMode
  35702. ) {
  35703. var itemWidth = legendModel.get('itemWidth');
  35704. var itemHeight = legendModel.get('itemHeight');
  35705. var inactiveColor = legendModel.get('inactiveColor');
  35706. var isSelected = legendModel.isSelected(name);
  35707. var itemGroup = new Group$2();
  35708. var textStyleModel = itemModel.getModel('textStyle');
  35709. var itemIcon = itemModel.get('icon');
  35710. var tooltipModel = itemModel.getModel('tooltip');
  35711. var legendGlobalTooltipModel = tooltipModel.parentModel;
  35712. // Use user given icon first
  35713. legendSymbolType = itemIcon || legendSymbolType;
  35714. itemGroup.add(createSymbol(
  35715. legendSymbolType,
  35716. 0,
  35717. 0,
  35718. itemWidth,
  35719. itemHeight,
  35720. isSelected ? color : inactiveColor,
  35721. true
  35722. ));
  35723. // Compose symbols
  35724. // PENDING
  35725. if (!itemIcon && symbolType
  35726. // At least show one symbol, can't be all none
  35727. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  35728. ) {
  35729. var size = itemHeight * 0.8;
  35730. if (symbolType === 'none') {
  35731. symbolType = 'circle';
  35732. }
  35733. // Put symbol in the center
  35734. itemGroup.add(createSymbol(
  35735. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  35736. isSelected ? color : inactiveColor
  35737. ));
  35738. }
  35739. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  35740. var textAlign = itemAlign;
  35741. var formatter = legendModel.get('formatter');
  35742. var content = name;
  35743. if (typeof formatter === 'string' && formatter) {
  35744. content = formatter.replace('{name}', name != null ? name : '');
  35745. }
  35746. else if (typeof formatter === 'function') {
  35747. content = formatter(name);
  35748. }
  35749. itemGroup.add(new Text({
  35750. style: setTextStyle({}, textStyleModel, {
  35751. text: content,
  35752. x: textX,
  35753. y: itemHeight / 2,
  35754. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  35755. textAlign: textAlign,
  35756. textVerticalAlign: 'middle'
  35757. })
  35758. }));
  35759. // Add a invisible rect to increase the area of mouse hover
  35760. var hitRect = new Rect({
  35761. shape: itemGroup.getBoundingRect(),
  35762. invisible: true,
  35763. tooltip: tooltipModel.get('show') ? extend({
  35764. content: name,
  35765. // Defaul formatter
  35766. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  35767. return name;
  35768. },
  35769. formatterParams: {
  35770. componentType: 'legend',
  35771. legendIndex: legendModel.componentIndex,
  35772. name: name,
  35773. $vars: ['name']
  35774. }
  35775. }, tooltipModel.option) : null
  35776. });
  35777. itemGroup.add(hitRect);
  35778. itemGroup.eachChild(function (child) {
  35779. child.silent = true;
  35780. });
  35781. hitRect.silent = !selectMode;
  35782. this.getContentGroup().add(itemGroup);
  35783. setHoverStyle(itemGroup);
  35784. itemGroup.__legendDataIndex = dataIndex;
  35785. return itemGroup;
  35786. },
  35787. /**
  35788. * @protected
  35789. */
  35790. layoutInner: function (legendModel, itemAlign, maxSize) {
  35791. var contentGroup = this.getContentGroup();
  35792. // Place items in contentGroup.
  35793. box(
  35794. legendModel.get('orient'),
  35795. contentGroup,
  35796. legendModel.get('itemGap'),
  35797. maxSize.width,
  35798. maxSize.height
  35799. );
  35800. var contentRect = contentGroup.getBoundingRect();
  35801. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  35802. return this.group.getBoundingRect();
  35803. }
  35804. });
  35805. function dispatchSelectAction(name, api) {
  35806. api.dispatchAction({
  35807. type: 'legendToggleSelect',
  35808. name: name
  35809. });
  35810. }
  35811. function dispatchHighlightAction(seriesModel, dataName, api) {
  35812. // If element hover will move to a hoverLayer.
  35813. var el = api.getZr().storage.getDisplayList()[0];
  35814. if (!(el && el.useHoverLayer)) {
  35815. seriesModel.get('legendHoverLink') && api.dispatchAction({
  35816. type: 'highlight',
  35817. seriesName: seriesModel.name,
  35818. name: dataName
  35819. });
  35820. }
  35821. }
  35822. function dispatchDownplayAction(seriesModel, dataName, api) {
  35823. // If element hover will move to a hoverLayer.
  35824. var el = api.getZr().storage.getDisplayList()[0];
  35825. if (!(el && el.useHoverLayer)) {
  35826. seriesModel.get('legendHoverLink') && api.dispatchAction({
  35827. type: 'downplay',
  35828. seriesName: seriesModel.name,
  35829. name: dataName
  35830. });
  35831. }
  35832. }
  35833. var legendFilter = function (ecModel) {
  35834. var legendModels = ecModel.findComponents({
  35835. mainType: 'legend'
  35836. });
  35837. if (legendModels && legendModels.length) {
  35838. ecModel.filterSeries(function (series) {
  35839. // If in any legend component the status is not selected.
  35840. // Because in legend series is assumed selected when it is not in the legend data.
  35841. for (var i = 0; i < legendModels.length; i++) {
  35842. if (!legendModels[i].isSelected(series.name)) {
  35843. return false;
  35844. }
  35845. }
  35846. return true;
  35847. });
  35848. }
  35849. };
  35850. // Do not contain scrollable legend, for sake of file size.
  35851. // Series Filter
  35852. registerProcessor(legendFilter);
  35853. ComponentModel.registerSubTypeDefaulter('legend', function () {
  35854. // Default 'plain' when no type specified.
  35855. return 'plain';
  35856. });
  35857. var ScrollableLegendModel = LegendModel.extend({
  35858. type: 'legend.scroll',
  35859. /**
  35860. * @param {number} scrollDataIndex
  35861. */
  35862. setScrollDataIndex: function (scrollDataIndex) {
  35863. this.option.scrollDataIndex = scrollDataIndex;
  35864. },
  35865. defaultOption: {
  35866. scrollDataIndex: 0,
  35867. pageButtonItemGap: 5,
  35868. pageButtonGap: null,
  35869. pageButtonPosition: 'end', // 'start' or 'end'
  35870. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  35871. pageIcons: {
  35872. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  35873. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  35874. },
  35875. pageIconColor: '#2f4554',
  35876. pageIconInactiveColor: '#aaa',
  35877. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  35878. pageTextStyle: {
  35879. color: '#333'
  35880. },
  35881. animationDurationUpdate: 800
  35882. },
  35883. /**
  35884. * @override
  35885. */
  35886. init: function (option, parentModel, ecModel, extraOpt) {
  35887. var inputPositionParams = getLayoutParams(option);
  35888. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  35889. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  35890. },
  35891. /**
  35892. * @override
  35893. */
  35894. mergeOption: function (option, extraOpt) {
  35895. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  35896. mergeAndNormalizeLayoutParams(this, this.option, option);
  35897. },
  35898. getOrient: function () {
  35899. return this.get('orient') === 'vertical'
  35900. ? {index: 1, name: 'vertical'}
  35901. : {index: 0, name: 'horizontal'};
  35902. }
  35903. });
  35904. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  35905. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  35906. var orient = legendModel.getOrient();
  35907. var ignoreSize = [1, 1];
  35908. ignoreSize[orient.index] = 0;
  35909. mergeLayoutParam(target, raw, {
  35910. type: 'box', ignoreSize: ignoreSize
  35911. });
  35912. }
  35913. /**
  35914. * Separate legend and scrollable legend to reduce package size.
  35915. */
  35916. var Group$3 = Group;
  35917. var WH = ['width', 'height'];
  35918. var XY = ['x', 'y'];
  35919. var ScrollableLegendView = LegendView.extend({
  35920. type: 'legend.scroll',
  35921. newlineDisabled: true,
  35922. init: function () {
  35923. ScrollableLegendView.superCall(this, 'init');
  35924. /**
  35925. * @private
  35926. * @type {number} For `scroll`.
  35927. */
  35928. this._currentIndex = 0;
  35929. /**
  35930. * @private
  35931. * @type {module:zrender/container/Group}
  35932. */
  35933. this.group.add(this._containerGroup = new Group$3());
  35934. this._containerGroup.add(this.getContentGroup());
  35935. /**
  35936. * @private
  35937. * @type {module:zrender/container/Group}
  35938. */
  35939. this.group.add(this._controllerGroup = new Group$3());
  35940. /**
  35941. *
  35942. * @private
  35943. */
  35944. this._showController;
  35945. },
  35946. /**
  35947. * @override
  35948. */
  35949. resetInner: function () {
  35950. ScrollableLegendView.superCall(this, 'resetInner');
  35951. this._controllerGroup.removeAll();
  35952. this._containerGroup.removeClipPath();
  35953. this._containerGroup.__rectSize = null;
  35954. },
  35955. /**
  35956. * @override
  35957. */
  35958. renderInner: function (itemAlign, legendModel, ecModel, api) {
  35959. var me = this;
  35960. // Render content items.
  35961. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  35962. var controllerGroup = this._controllerGroup;
  35963. var pageIconSize = legendModel.get('pageIconSize', true);
  35964. if (!isArray(pageIconSize)) {
  35965. pageIconSize = [pageIconSize, pageIconSize];
  35966. }
  35967. createPageButton('pagePrev', 0);
  35968. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  35969. controllerGroup.add(new Text({
  35970. name: 'pageText',
  35971. style: {
  35972. textFill: pageTextStyleModel.getTextColor(),
  35973. font: pageTextStyleModel.getFont(),
  35974. textVerticalAlign: 'middle',
  35975. textAlign: 'center'
  35976. },
  35977. silent: true
  35978. }));
  35979. createPageButton('pageNext', 1);
  35980. function createPageButton(name, iconIdx) {
  35981. var pageDataIndexName = name + 'DataIndex';
  35982. var icon = createIcon(
  35983. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  35984. {
  35985. // Buttons will be created in each render, so we do not need
  35986. // to worry about avoiding using legendModel kept in scope.
  35987. onclick: bind(
  35988. me._pageGo, me, pageDataIndexName, legendModel, api
  35989. )
  35990. },
  35991. {
  35992. x: -pageIconSize[0] / 2,
  35993. y: -pageIconSize[1] / 2,
  35994. width: pageIconSize[0],
  35995. height: pageIconSize[1]
  35996. }
  35997. );
  35998. icon.name = name;
  35999. controllerGroup.add(icon);
  36000. }
  36001. },
  36002. /**
  36003. * @override
  36004. */
  36005. layoutInner: function (legendModel, itemAlign, maxSize) {
  36006. var contentGroup = this.getContentGroup();
  36007. var containerGroup = this._containerGroup;
  36008. var controllerGroup = this._controllerGroup;
  36009. var orientIdx = legendModel.getOrient().index;
  36010. var wh = WH[orientIdx];
  36011. var hw = WH[1 - orientIdx];
  36012. var yx = XY[1 - orientIdx];
  36013. // Place items in contentGroup.
  36014. box(
  36015. legendModel.get('orient'),
  36016. contentGroup,
  36017. legendModel.get('itemGap'),
  36018. !orientIdx ? null : maxSize.width,
  36019. orientIdx ? null : maxSize.height
  36020. );
  36021. box(
  36022. // Buttons in controller are layout always horizontally.
  36023. 'horizontal',
  36024. controllerGroup,
  36025. legendModel.get('pageButtonItemGap', true)
  36026. );
  36027. var contentRect = contentGroup.getBoundingRect();
  36028. var controllerRect = controllerGroup.getBoundingRect();
  36029. var showController = this._showController = contentRect[wh] > maxSize[wh];
  36030. var contentPos = [-contentRect.x, -contentRect.y];
  36031. // Remain contentPos when scroll animation perfroming.
  36032. contentPos[orientIdx] = contentGroup.position[orientIdx];
  36033. // Layout container group based on 0.
  36034. var containerPos = [0, 0];
  36035. var controllerPos = [-controllerRect.x, -controllerRect.y];
  36036. var pageButtonGap = retrieve2(
  36037. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  36038. );
  36039. // Place containerGroup and controllerGroup and contentGroup.
  36040. if (showController) {
  36041. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  36042. // controller is on the right / bottom.
  36043. if (pageButtonPosition === 'end') {
  36044. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  36045. }
  36046. // controller is on the left / top.
  36047. else {
  36048. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  36049. }
  36050. }
  36051. // Always align controller to content as 'middle'.
  36052. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  36053. contentGroup.attr('position', contentPos);
  36054. containerGroup.attr('position', containerPos);
  36055. controllerGroup.attr('position', controllerPos);
  36056. // Calculate `mainRect` and set `clipPath`.
  36057. // mainRect should not be calculated by `this.group.getBoundingRect()`
  36058. // for sake of the overflow.
  36059. var mainRect = this.group.getBoundingRect();
  36060. var mainRect = {x: 0, y: 0};
  36061. // Consider content may be overflow (should be clipped).
  36062. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  36063. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  36064. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  36065. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  36066. containerGroup.__rectSize = maxSize[wh];
  36067. if (showController) {
  36068. var clipShape = {x: 0, y: 0};
  36069. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  36070. clipShape[hw] = mainRect[hw];
  36071. containerGroup.setClipPath(new Rect({shape: clipShape}));
  36072. // Consider content may be larger than container, container rect
  36073. // can not be obtained from `containerGroup.getBoundingRect()`.
  36074. containerGroup.__rectSize = clipShape[wh];
  36075. }
  36076. else {
  36077. // Do not remove or ignore controller. Keep them set as place holders.
  36078. controllerGroup.eachChild(function (child) {
  36079. child.attr({invisible: true, silent: true});
  36080. });
  36081. }
  36082. // Content translate animation.
  36083. var pageInfo = this._getPageInfo(legendModel);
  36084. pageInfo.pageIndex != null && updateProps(
  36085. contentGroup,
  36086. {position: pageInfo.contentPosition},
  36087. // When switch from "show controller" to "not show controller", view should be
  36088. // updated immediately without animation, otherwise causes weird efffect.
  36089. showController ? legendModel : false
  36090. );
  36091. this._updatePageInfoView(legendModel, pageInfo);
  36092. return mainRect;
  36093. },
  36094. _pageGo: function (to, legendModel, api) {
  36095. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  36096. scrollDataIndex != null && api.dispatchAction({
  36097. type: 'legendScroll',
  36098. scrollDataIndex: scrollDataIndex,
  36099. legendId: legendModel.id
  36100. });
  36101. },
  36102. _updatePageInfoView: function (legendModel, pageInfo) {
  36103. var controllerGroup = this._controllerGroup;
  36104. each$1(['pagePrev', 'pageNext'], function (name) {
  36105. var canJump = pageInfo[name + 'DataIndex'] != null;
  36106. var icon = controllerGroup.childOfName(name);
  36107. if (icon) {
  36108. icon.setStyle(
  36109. 'fill',
  36110. canJump
  36111. ? legendModel.get('pageIconColor', true)
  36112. : legendModel.get('pageIconInactiveColor', true)
  36113. );
  36114. icon.cursor = canJump ? 'pointer' : 'default';
  36115. }
  36116. });
  36117. var pageText = controllerGroup.childOfName('pageText');
  36118. var pageFormatter = legendModel.get('pageFormatter');
  36119. var pageIndex = pageInfo.pageIndex;
  36120. var current = pageIndex != null ? pageIndex + 1 : 0;
  36121. var total = pageInfo.pageCount;
  36122. pageText && pageFormatter && pageText.setStyle(
  36123. 'text',
  36124. isString(pageFormatter)
  36125. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  36126. : pageFormatter({current: current, total: total})
  36127. );
  36128. },
  36129. /**
  36130. * @param {module:echarts/model/Model} legendModel
  36131. * @return {Object} {
  36132. * contentPosition: Array.<number>, null when data item not found.
  36133. * pageIndex: number, null when data item not found.
  36134. * pageCount: number, always be a number, can be 0.
  36135. * pagePrevDataIndex: number, null when no next page.
  36136. * pageNextDataIndex: number, null when no previous page.
  36137. * }
  36138. */
  36139. _getPageInfo: function (legendModel) {
  36140. // Align left or top by the current dataIndex.
  36141. var currDataIndex = legendModel.get('scrollDataIndex', true);
  36142. var contentGroup = this.getContentGroup();
  36143. var contentRect = contentGroup.getBoundingRect();
  36144. var containerRectSize = this._containerGroup.__rectSize;
  36145. var orientIdx = legendModel.getOrient().index;
  36146. var wh = WH[orientIdx];
  36147. var hw = WH[1 - orientIdx];
  36148. var xy = XY[orientIdx];
  36149. var contentPos = contentGroup.position.slice();
  36150. var pageIndex;
  36151. var pagePrevDataIndex;
  36152. var pageNextDataIndex;
  36153. var targetItemGroup;
  36154. if (this._showController) {
  36155. contentGroup.eachChild(function (child) {
  36156. if (child.__legendDataIndex === currDataIndex) {
  36157. targetItemGroup = child;
  36158. }
  36159. });
  36160. }
  36161. else {
  36162. targetItemGroup = contentGroup.childAt(0);
  36163. }
  36164. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  36165. if (targetItemGroup) {
  36166. var itemRect = targetItemGroup.getBoundingRect();
  36167. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  36168. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  36169. pageIndex = Math.floor(
  36170. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  36171. );
  36172. pageIndex = (contentRect[wh] && pageCount)
  36173. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  36174. : -1;
  36175. var winRect = {x: 0, y: 0};
  36176. winRect[wh] = containerRectSize;
  36177. winRect[hw] = contentRect[hw];
  36178. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  36179. var startIdx;
  36180. var children = contentGroup.children();
  36181. contentGroup.eachChild(function (child, index) {
  36182. var itemRect = getItemRect(child);
  36183. if (itemRect.intersect(winRect)) {
  36184. startIdx == null && (startIdx = index);
  36185. // It is user-friendly that the last item shown in the
  36186. // current window is shown at the begining of next window.
  36187. pageNextDataIndex = child.__legendDataIndex;
  36188. }
  36189. // If the last item is shown entirely, no next page.
  36190. if (index === children.length - 1
  36191. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  36192. ) {
  36193. pageNextDataIndex = null;
  36194. }
  36195. });
  36196. // Always align based on the left/top most item, so the left/top most
  36197. // item in the previous window is needed to be found here.
  36198. if (startIdx != null) {
  36199. var startItem = children[startIdx];
  36200. var startRect = getItemRect(startItem);
  36201. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  36202. // If the first item is shown entirely, no previous page.
  36203. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  36204. pagePrevDataIndex = null;
  36205. }
  36206. else {
  36207. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  36208. startIdx--;
  36209. }
  36210. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  36211. }
  36212. }
  36213. }
  36214. return {
  36215. contentPosition: contentPos,
  36216. pageIndex: pageIndex,
  36217. pageCount: pageCount,
  36218. pagePrevDataIndex: pagePrevDataIndex,
  36219. pageNextDataIndex: pageNextDataIndex
  36220. };
  36221. function getItemRect(el) {
  36222. var itemRect = el.getBoundingRect().clone();
  36223. itemRect[xy] += el.position[orientIdx];
  36224. return itemRect;
  36225. }
  36226. }
  36227. });
  36228. /**
  36229. * @event legendScroll
  36230. * @type {Object}
  36231. * @property {string} type 'legendScroll'
  36232. * @property {string} scrollDataIndex
  36233. */
  36234. registerAction(
  36235. 'legendScroll', 'legendscroll',
  36236. function (payload, ecModel) {
  36237. var scrollDataIndex = payload.scrollDataIndex;
  36238. scrollDataIndex != null && ecModel.eachComponent(
  36239. {mainType: 'legend', subType: 'scroll', query: payload},
  36240. function (legendModel) {
  36241. legendModel.setScrollDataIndex(scrollDataIndex);
  36242. }
  36243. );
  36244. }
  36245. );
  36246. /**
  36247. * Legend component entry file8
  36248. */
  36249. // Model
  36250. extendComponentModel({
  36251. type: 'title',
  36252. layoutMode: {type: 'box', ignoreSize: true},
  36253. defaultOption: {
  36254. // 一级层叠
  36255. zlevel: 0,
  36256. // 二级层叠
  36257. z: 6,
  36258. show: true,
  36259. text: '',
  36260. // 超链接跳转
  36261. // link: null,
  36262. // 仅支持self | blank
  36263. target: 'blank',
  36264. subtext: '',
  36265. // 超链接跳转
  36266. // sublink: null,
  36267. // 仅支持self | blank
  36268. subtarget: 'blank',
  36269. // 'center' ¦ 'left' ¦ 'right'
  36270. // ¦ {number}(x坐标,单位px)
  36271. left: 0,
  36272. // 'top' ¦ 'bottom' ¦ 'center'
  36273. // ¦ {number}(y坐标,单位px)
  36274. top: 0,
  36275. // 水平对齐
  36276. // 'auto' | 'left' | 'right' | 'center'
  36277. // 默认根据 left 的位置判断是左对齐还是右对齐
  36278. // textAlign: null
  36279. //
  36280. // 垂直对齐
  36281. // 'auto' | 'top' | 'bottom' | 'middle'
  36282. // 默认根据 top 位置判断是上对齐还是下对齐
  36283. // textBaseline: null
  36284. backgroundColor: 'rgba(0,0,0,0)',
  36285. // 标题边框颜色
  36286. borderColor: '#ccc',
  36287. // 标题边框线宽,单位px,默认为0(无边框)
  36288. borderWidth: 0,
  36289. // 标题内边距,单位px,默认各方向内边距为5,
  36290. // 接受数组分别设定上右下左边距,同css
  36291. padding: 5,
  36292. // 主副标题纵向间隔,单位px,默认为10,
  36293. itemGap: 10,
  36294. textStyle: {
  36295. fontSize: 18,
  36296. fontWeight: 'bolder',
  36297. color: '#333'
  36298. },
  36299. subtextStyle: {
  36300. color: '#aaa'
  36301. }
  36302. }
  36303. });
  36304. // View
  36305. extendComponentView({
  36306. type: 'title',
  36307. render: function (titleModel, ecModel, api) {
  36308. this.group.removeAll();
  36309. if (!titleModel.get('show')) {
  36310. return;
  36311. }
  36312. var group = this.group;
  36313. var textStyleModel = titleModel.getModel('textStyle');
  36314. var subtextStyleModel = titleModel.getModel('subtextStyle');
  36315. var textAlign = titleModel.get('textAlign');
  36316. var textBaseline = titleModel.get('textBaseline');
  36317. var textEl = new Text({
  36318. style: setTextStyle({}, textStyleModel, {
  36319. text: titleModel.get('text'),
  36320. textFill: textStyleModel.getTextColor()
  36321. }, {disableBox: true}),
  36322. z2: 10
  36323. });
  36324. var textRect = textEl.getBoundingRect();
  36325. var subText = titleModel.get('subtext');
  36326. var subTextEl = new Text({
  36327. style: setTextStyle({}, subtextStyleModel, {
  36328. text: subText,
  36329. textFill: subtextStyleModel.getTextColor(),
  36330. y: textRect.height + titleModel.get('itemGap'),
  36331. textVerticalAlign: 'top'
  36332. }, {disableBox: true}),
  36333. z2: 10
  36334. });
  36335. var link = titleModel.get('link');
  36336. var sublink = titleModel.get('sublink');
  36337. textEl.silent = !link;
  36338. subTextEl.silent = !sublink;
  36339. if (link) {
  36340. textEl.on('click', function () {
  36341. window.open(link, '_' + titleModel.get('target'));
  36342. });
  36343. }
  36344. if (sublink) {
  36345. subTextEl.on('click', function () {
  36346. window.open(sublink, '_' + titleModel.get('subtarget'));
  36347. });
  36348. }
  36349. group.add(textEl);
  36350. subText && group.add(subTextEl);
  36351. // If no subText, but add subTextEl, there will be an empty line.
  36352. var groupRect = group.getBoundingRect();
  36353. var layoutOption = titleModel.getBoxLayoutParams();
  36354. layoutOption.width = groupRect.width;
  36355. layoutOption.height = groupRect.height;
  36356. var layoutRect = getLayoutRect(
  36357. layoutOption, {
  36358. width: api.getWidth(),
  36359. height: api.getHeight()
  36360. }, titleModel.get('padding')
  36361. );
  36362. // Adjust text align based on position
  36363. if (!textAlign) {
  36364. // Align left if title is on the left. center and right is same
  36365. textAlign = titleModel.get('left') || titleModel.get('right');
  36366. if (textAlign === 'middle') {
  36367. textAlign = 'center';
  36368. }
  36369. // Adjust layout by text align
  36370. if (textAlign === 'right') {
  36371. layoutRect.x += layoutRect.width;
  36372. }
  36373. else if (textAlign === 'center') {
  36374. layoutRect.x += layoutRect.width / 2;
  36375. }
  36376. }
  36377. if (!textBaseline) {
  36378. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  36379. if (textBaseline === 'center') {
  36380. textBaseline = 'middle';
  36381. }
  36382. if (textBaseline === 'bottom') {
  36383. layoutRect.y += layoutRect.height;
  36384. }
  36385. else if (textBaseline === 'middle') {
  36386. layoutRect.y += layoutRect.height / 2;
  36387. }
  36388. textBaseline = textBaseline || 'top';
  36389. }
  36390. group.attr('position', [layoutRect.x, layoutRect.y]);
  36391. var alignStyle = {
  36392. textAlign: textAlign,
  36393. textVerticalAlign: textBaseline
  36394. };
  36395. textEl.setStyle(alignStyle);
  36396. subTextEl.setStyle(alignStyle);
  36397. // Render background
  36398. // Get groupRect again because textAlign has been changed
  36399. groupRect = group.getBoundingRect();
  36400. var padding = layoutRect.margin;
  36401. var style = titleModel.getItemStyle(['color', 'opacity']);
  36402. style.fill = titleModel.get('backgroundColor');
  36403. var rect = new Rect({
  36404. shape: {
  36405. x: groupRect.x - padding[3],
  36406. y: groupRect.y - padding[0],
  36407. width: groupRect.width + padding[1] + padding[3],
  36408. height: groupRect.height + padding[0] + padding[2],
  36409. r: titleModel.get('borderRadius')
  36410. },
  36411. style: style,
  36412. silent: true
  36413. });
  36414. subPixelOptimizeRect(rect);
  36415. group.add(rect);
  36416. }
  36417. });
  36418. var addCommas$1 = addCommas;
  36419. var encodeHTML$1 = encodeHTML;
  36420. function fillLabel(opt) {
  36421. defaultEmphasis(opt, 'label', ['show']);
  36422. }
  36423. var MarkerModel = extendComponentModel({
  36424. type: 'marker',
  36425. dependencies: ['series', 'grid', 'polar', 'geo'],
  36426. /**
  36427. * @overrite
  36428. */
  36429. init: function (option, parentModel, ecModel, extraOpt) {
  36430. if (__DEV__) {
  36431. if (this.type === 'marker') {
  36432. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  36433. }
  36434. }
  36435. this.mergeDefaultAndTheme(option, ecModel);
  36436. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  36437. },
  36438. /**
  36439. * @return {boolean}
  36440. */
  36441. isAnimationEnabled: function () {
  36442. if (env$1.node) {
  36443. return false;
  36444. }
  36445. var hostSeries = this.__hostSeries;
  36446. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  36447. },
  36448. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  36449. var MarkerModel = this.constructor;
  36450. var modelPropName = this.mainType + 'Model';
  36451. if (!createdBySelf) {
  36452. ecModel.eachSeries(function (seriesModel) {
  36453. var markerOpt = seriesModel.get(this.mainType);
  36454. var markerModel = seriesModel[modelPropName];
  36455. if (!markerOpt || !markerOpt.data) {
  36456. seriesModel[modelPropName] = null;
  36457. return;
  36458. }
  36459. if (!markerModel) {
  36460. if (isInit) {
  36461. // Default label emphasis `position` and `show`
  36462. fillLabel(markerOpt);
  36463. }
  36464. each$1(markerOpt.data, function (item) {
  36465. // FIXME Overwrite fillLabel method ?
  36466. if (item instanceof Array) {
  36467. fillLabel(item[0]);
  36468. fillLabel(item[1]);
  36469. }
  36470. else {
  36471. fillLabel(item);
  36472. }
  36473. });
  36474. markerModel = new MarkerModel(
  36475. markerOpt, this, ecModel
  36476. );
  36477. extend(markerModel, {
  36478. mainType: this.mainType,
  36479. // Use the same series index and name
  36480. seriesIndex: seriesModel.seriesIndex,
  36481. name: seriesModel.name,
  36482. createdBySelf: true
  36483. });
  36484. markerModel.__hostSeries = seriesModel;
  36485. }
  36486. else {
  36487. markerModel.mergeOption(markerOpt, ecModel, true);
  36488. }
  36489. seriesModel[modelPropName] = markerModel;
  36490. }, this);
  36491. }
  36492. },
  36493. formatTooltip: function (dataIndex) {
  36494. var data = this.getData();
  36495. var value = this.getRawValue(dataIndex);
  36496. var formattedValue = isArray(value)
  36497. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  36498. var name = data.getName(dataIndex);
  36499. var html = encodeHTML$1(this.name);
  36500. if (value != null || name) {
  36501. html += '<br />';
  36502. }
  36503. if (name) {
  36504. html += encodeHTML$1(name);
  36505. if (value != null) {
  36506. html += ' : ';
  36507. }
  36508. }
  36509. if (value != null) {
  36510. html += encodeHTML$1(formattedValue);
  36511. }
  36512. return html;
  36513. },
  36514. getData: function () {
  36515. return this._data;
  36516. },
  36517. setData: function (data) {
  36518. this._data = data;
  36519. }
  36520. });
  36521. mixin(MarkerModel, dataFormatMixin);
  36522. MarkerModel.extend({
  36523. type: 'markPoint',
  36524. defaultOption: {
  36525. zlevel: 0,
  36526. z: 5,
  36527. symbol: 'pin',
  36528. symbolSize: 50,
  36529. //symbolRotate: 0,
  36530. //symbolOffset: [0, 0]
  36531. tooltip: {
  36532. trigger: 'item'
  36533. },
  36534. label: {
  36535. show: true,
  36536. position: 'inside'
  36537. },
  36538. itemStyle: {
  36539. borderWidth: 2
  36540. },
  36541. emphasis: {
  36542. label: {
  36543. show: true
  36544. }
  36545. }
  36546. }
  36547. });
  36548. var indexOf$1 = indexOf;
  36549. function hasXOrY(item) {
  36550. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  36551. }
  36552. function hasXAndY(item) {
  36553. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  36554. }
  36555. function getPrecision$1(data, valueAxisDim, dataIndex) {
  36556. var precision = -1;
  36557. do {
  36558. precision = Math.max(
  36559. getPrecision(data.get(
  36560. valueAxisDim, dataIndex
  36561. )),
  36562. precision
  36563. );
  36564. data = data.stackedOn;
  36565. } while (data);
  36566. return precision;
  36567. }
  36568. function markerTypeCalculatorWithExtent(
  36569. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  36570. ) {
  36571. var coordArr = [];
  36572. var value = numCalculate(data, targetDataDim, mlType);
  36573. var dataIndex = data.indicesOfNearest(targetDataDim, value, true)[0];
  36574. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex, true);
  36575. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex, true);
  36576. var precision = getPrecision$1(data, targetDataDim, dataIndex);
  36577. precision = Math.min(precision, 20);
  36578. if (precision >= 0) {
  36579. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  36580. }
  36581. return coordArr;
  36582. }
  36583. var curry$4 = curry;
  36584. // TODO Specified percent
  36585. var markerTypeCalculator = {
  36586. /**
  36587. * @method
  36588. * @param {module:echarts/data/List} data
  36589. * @param {string} baseAxisDim
  36590. * @param {string} valueAxisDim
  36591. */
  36592. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  36593. /**
  36594. * @method
  36595. * @param {module:echarts/data/List} data
  36596. * @param {string} baseAxisDim
  36597. * @param {string} valueAxisDim
  36598. */
  36599. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  36600. /**
  36601. * @method
  36602. * @param {module:echarts/data/List} data
  36603. * @param {string} baseAxisDim
  36604. * @param {string} valueAxisDim
  36605. */
  36606. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  36607. };
  36608. /**
  36609. * Transform markPoint data item to format used in List by do the following
  36610. * 1. Calculate statistic like `max`, `min`, `average`
  36611. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  36612. * @param {module:echarts/model/Series} seriesModel
  36613. * @param {module:echarts/coord/*} [coordSys]
  36614. * @param {Object} item
  36615. * @return {Object}
  36616. */
  36617. function dataTransform(seriesModel, item) {
  36618. var data = seriesModel.getData();
  36619. var coordSys = seriesModel.coordinateSystem;
  36620. // 1. If not specify the position with pixel directly
  36621. // 2. If `coord` is not a data array. Which uses `xAxis`,
  36622. // `yAxis` to specify the coord on each dimension
  36623. // parseFloat first because item.x and item.y can be percent string like '20%'
  36624. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  36625. var dims = coordSys.dimensions;
  36626. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  36627. // Clone the option
  36628. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  36629. item = clone(item);
  36630. if (item.type
  36631. && markerTypeCalculator[item.type]
  36632. && axisInfo.baseAxis && axisInfo.valueAxis
  36633. ) {
  36634. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  36635. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  36636. item.coord = markerTypeCalculator[item.type](
  36637. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  36638. otherCoordIndex, targetCoordIndex
  36639. );
  36640. // Force to use the value of calculated value.
  36641. item.value = item.coord[targetCoordIndex];
  36642. }
  36643. else {
  36644. // FIXME Only has one of xAxis and yAxis.
  36645. var coord = [
  36646. item.xAxis != null ? item.xAxis : item.radiusAxis,
  36647. item.yAxis != null ? item.yAxis : item.angleAxis
  36648. ];
  36649. // Each coord support max, min, average
  36650. for (var i = 0; i < 2; i++) {
  36651. if (markerTypeCalculator[coord[i]]) {
  36652. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  36653. }
  36654. }
  36655. item.coord = coord;
  36656. }
  36657. }
  36658. return item;
  36659. }
  36660. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  36661. var ret = {};
  36662. if (item.valueIndex != null || item.valueDim != null) {
  36663. ret.valueDataDim = item.valueIndex != null
  36664. ? data.getDimension(item.valueIndex) : item.valueDim;
  36665. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  36666. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  36667. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  36668. }
  36669. else {
  36670. ret.baseAxis = seriesModel.getBaseAxis();
  36671. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  36672. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  36673. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  36674. }
  36675. return ret;
  36676. }
  36677. function dataDimToCoordDim(seriesModel, dataDim) {
  36678. var data = seriesModel.getData();
  36679. var dimensions = data.dimensions;
  36680. dataDim = data.getDimension(dataDim);
  36681. for (var i = 0; i < dimensions.length; i++) {
  36682. var dimItem = data.getDimensionInfo(dimensions[i]);
  36683. if (dimItem.name === dataDim) {
  36684. return dimItem.coordDim;
  36685. }
  36686. }
  36687. }
  36688. /**
  36689. * Filter data which is out of coordinateSystem range
  36690. * [dataFilter description]
  36691. * @param {module:echarts/coord/*} [coordSys]
  36692. * @param {Object} item
  36693. * @return {boolean}
  36694. */
  36695. function dataFilter$1(coordSys, item) {
  36696. // Alwalys return true if there is no coordSys
  36697. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  36698. ? coordSys.containData(item.coord) : true;
  36699. }
  36700. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  36701. // x, y, radius, angle
  36702. if (dimIndex < 2) {
  36703. return item.coord && item.coord[dimIndex];
  36704. }
  36705. return item.value;
  36706. }
  36707. function numCalculate(data, valueDataDim, type) {
  36708. if (type === 'average') {
  36709. var sum = 0;
  36710. var count = 0;
  36711. data.each(valueDataDim, function (val, idx) {
  36712. if (!isNaN(val)) {
  36713. sum += val;
  36714. count++;
  36715. }
  36716. }, true);
  36717. return sum / count;
  36718. }
  36719. else {
  36720. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  36721. }
  36722. }
  36723. var MarkerView = extendComponentView({
  36724. type: 'marker',
  36725. init: function () {
  36726. /**
  36727. * Markline grouped by series
  36728. * @private
  36729. * @type {module:zrender/core/util.HashMap}
  36730. */
  36731. this.markerGroupMap = createHashMap();
  36732. },
  36733. render: function (markerModel, ecModel, api) {
  36734. var markerGroupMap = this.markerGroupMap;
  36735. markerGroupMap.each(function (item) {
  36736. item.__keep = false;
  36737. });
  36738. var markerModelKey = this.type + 'Model';
  36739. ecModel.eachSeries(function (seriesModel) {
  36740. var markerModel = seriesModel[markerModelKey];
  36741. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  36742. }, this);
  36743. markerGroupMap.each(function (item) {
  36744. !item.__keep && this.group.remove(item.group);
  36745. }, this);
  36746. },
  36747. renderSeries: function () {}
  36748. });
  36749. function updateMarkerLayout(mpData, seriesModel, api) {
  36750. var coordSys = seriesModel.coordinateSystem;
  36751. mpData.each(function (idx) {
  36752. var itemModel = mpData.getItemModel(idx);
  36753. var point;
  36754. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  36755. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  36756. if (!isNaN(xPx) && !isNaN(yPx)) {
  36757. point = [xPx, yPx];
  36758. }
  36759. // Chart like bar may have there own marker positioning logic
  36760. else if (seriesModel.getMarkerPosition) {
  36761. // Use the getMarkerPoisition
  36762. point = seriesModel.getMarkerPosition(
  36763. mpData.getValues(mpData.dimensions, idx)
  36764. );
  36765. }
  36766. else if (coordSys) {
  36767. var x = mpData.get(coordSys.dimensions[0], idx);
  36768. var y = mpData.get(coordSys.dimensions[1], idx);
  36769. point = coordSys.dataToPoint([x, y]);
  36770. }
  36771. // Use x, y if has any
  36772. if (!isNaN(xPx)) {
  36773. point[0] = xPx;
  36774. }
  36775. if (!isNaN(yPx)) {
  36776. point[1] = yPx;
  36777. }
  36778. mpData.setItemLayout(idx, point);
  36779. });
  36780. }
  36781. MarkerView.extend({
  36782. type: 'markPoint',
  36783. // updateLayout: function (markPointModel, ecModel, api) {
  36784. // ecModel.eachSeries(function (seriesModel) {
  36785. // var mpModel = seriesModel.markPointModel;
  36786. // if (mpModel) {
  36787. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36788. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  36789. // }
  36790. // }, this);
  36791. // },
  36792. updateTransform: function (markPointModel, ecModel, api) {
  36793. ecModel.eachSeries(function (seriesModel) {
  36794. var mpModel = seriesModel.markPointModel;
  36795. if (mpModel) {
  36796. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36797. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  36798. }
  36799. }, this);
  36800. },
  36801. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  36802. var coordSys = seriesModel.coordinateSystem;
  36803. var seriesId = seriesModel.id;
  36804. var seriesData = seriesModel.getData();
  36805. var symbolDrawMap = this.markerGroupMap;
  36806. var symbolDraw = symbolDrawMap.get(seriesId)
  36807. || symbolDrawMap.set(seriesId, new SymbolDraw());
  36808. var mpData = createList$1(coordSys, seriesModel, mpModel);
  36809. // FIXME
  36810. mpModel.setData(mpData);
  36811. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36812. mpData.each(function (idx) {
  36813. var itemModel = mpData.getItemModel(idx);
  36814. var symbolSize = itemModel.getShallow('symbolSize');
  36815. if (typeof symbolSize === 'function') {
  36816. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  36817. symbolSize = symbolSize(
  36818. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  36819. );
  36820. }
  36821. mpData.setItemVisual(idx, {
  36822. symbolSize: symbolSize,
  36823. color: itemModel.get('itemStyle.color')
  36824. || seriesData.getVisual('color'),
  36825. symbol: itemModel.getShallow('symbol')
  36826. });
  36827. });
  36828. // TODO Text are wrong
  36829. symbolDraw.updateData(mpData);
  36830. this.group.add(symbolDraw.group);
  36831. // Set host model for tooltip
  36832. // FIXME
  36833. mpData.eachItemGraphicEl(function (el) {
  36834. el.traverse(function (child) {
  36835. child.dataModel = mpModel;
  36836. });
  36837. });
  36838. symbolDraw.__keep = true;
  36839. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  36840. }
  36841. });
  36842. /**
  36843. * @inner
  36844. * @param {module:echarts/coord/*} [coordSys]
  36845. * @param {module:echarts/model/Series} seriesModel
  36846. * @param {module:echarts/model/Model} mpModel
  36847. */
  36848. function createList$1(coordSys, seriesModel, mpModel) {
  36849. var coordDimsInfos;
  36850. if (coordSys) {
  36851. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  36852. var info = seriesModel.getData().getDimensionInfo(
  36853. seriesModel.getData().mapDimension(coordDim)
  36854. ) || {};
  36855. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  36856. return defaults({name: coordDim, isSysCoord: true}, info);
  36857. });
  36858. }
  36859. else {
  36860. coordDimsInfos =[{
  36861. name: 'value',
  36862. type: 'float',
  36863. isSysCoord: true
  36864. }];
  36865. }
  36866. var mpData = new List(coordDimsInfos, mpModel);
  36867. var dataOpt = map(mpModel.get('data'), curry(
  36868. dataTransform, seriesModel
  36869. ));
  36870. if (coordSys) {
  36871. dataOpt = filter(
  36872. dataOpt, curry(dataFilter$1, coordSys)
  36873. );
  36874. }
  36875. mpData.initData(dataOpt, null,
  36876. coordSys ? dimValueGetter : function (item) {
  36877. return item.value;
  36878. }
  36879. );
  36880. return mpData;
  36881. }
  36882. // HINT Markpoint can't be used too much
  36883. registerPreprocessor(function (opt) {
  36884. // Make sure markPoint component is enabled
  36885. opt.markPoint = opt.markPoint || {};
  36886. });
  36887. MarkerModel.extend({
  36888. type: 'markLine',
  36889. defaultOption: {
  36890. zlevel: 0,
  36891. z: 5,
  36892. symbol: ['circle', 'arrow'],
  36893. symbolSize: [8, 16],
  36894. //symbolRotate: 0,
  36895. precision: 2,
  36896. tooltip: {
  36897. trigger: 'item'
  36898. },
  36899. label: {
  36900. show: true,
  36901. position: 'end'
  36902. },
  36903. lineStyle: {
  36904. type: 'dashed'
  36905. },
  36906. emphasis: {
  36907. label: {
  36908. show: true
  36909. },
  36910. lineStyle: {
  36911. width: 3
  36912. }
  36913. },
  36914. animationEasing: 'linear'
  36915. }
  36916. });
  36917. /**
  36918. * Line path for bezier and straight line draw
  36919. */
  36920. var straightLineProto = Line.prototype;
  36921. var bezierCurveProto = BezierCurve.prototype;
  36922. function isLine(shape) {
  36923. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  36924. }
  36925. var LinePath = extendShape({
  36926. type: 'ec-line',
  36927. style: {
  36928. stroke: '#000',
  36929. fill: null
  36930. },
  36931. shape: {
  36932. x1: 0,
  36933. y1: 0,
  36934. x2: 0,
  36935. y2: 0,
  36936. percent: 1,
  36937. cpx1: null,
  36938. cpy1: null
  36939. },
  36940. buildPath: function (ctx, shape) {
  36941. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  36942. },
  36943. pointAt: function (t) {
  36944. return isLine(this.shape)
  36945. ? straightLineProto.pointAt.call(this, t)
  36946. : bezierCurveProto.pointAt.call(this, t);
  36947. },
  36948. tangentAt: function (t) {
  36949. var shape = this.shape;
  36950. var p = isLine(shape)
  36951. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  36952. : bezierCurveProto.tangentAt.call(this, t);
  36953. return normalize(p, p);
  36954. }
  36955. });
  36956. /**
  36957. * @module echarts/chart/helper/Line
  36958. */
  36959. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  36960. function makeSymbolTypeKey(symbolCategory) {
  36961. return '_' + symbolCategory + 'Type';
  36962. }
  36963. /**
  36964. * @inner
  36965. */
  36966. function createSymbol$1(name, lineData, idx) {
  36967. var color = lineData.getItemVisual(idx, 'color');
  36968. var symbolType = lineData.getItemVisual(idx, name);
  36969. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  36970. if (!symbolType || symbolType === 'none') {
  36971. return;
  36972. }
  36973. if (!isArray(symbolSize)) {
  36974. symbolSize = [symbolSize, symbolSize];
  36975. }
  36976. var symbolPath = createSymbol(
  36977. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  36978. symbolSize[0], symbolSize[1], color
  36979. );
  36980. symbolPath.name = name;
  36981. return symbolPath;
  36982. }
  36983. function createLine(points) {
  36984. var line = new LinePath({
  36985. name: 'line'
  36986. });
  36987. setLinePoints(line.shape, points);
  36988. return line;
  36989. }
  36990. function setLinePoints(targetShape, points) {
  36991. var p1 = points[0];
  36992. var p2 = points[1];
  36993. var cp1 = points[2];
  36994. targetShape.x1 = p1[0];
  36995. targetShape.y1 = p1[1];
  36996. targetShape.x2 = p2[0];
  36997. targetShape.y2 = p2[1];
  36998. targetShape.percent = 1;
  36999. if (cp1) {
  37000. targetShape.cpx1 = cp1[0];
  37001. targetShape.cpy1 = cp1[1];
  37002. }
  37003. else {
  37004. targetShape.cpx1 = NaN;
  37005. targetShape.cpy1 = NaN;
  37006. }
  37007. }
  37008. function updateSymbolAndLabelBeforeLineUpdate () {
  37009. var lineGroup = this;
  37010. var symbolFrom = lineGroup.childOfName('fromSymbol');
  37011. var symbolTo = lineGroup.childOfName('toSymbol');
  37012. var label = lineGroup.childOfName('label');
  37013. // Quick reject
  37014. if (!symbolFrom && !symbolTo && label.ignore) {
  37015. return;
  37016. }
  37017. var invScale = 1;
  37018. var parentNode = this.parent;
  37019. while (parentNode) {
  37020. if (parentNode.scale) {
  37021. invScale /= parentNode.scale[0];
  37022. }
  37023. parentNode = parentNode.parent;
  37024. }
  37025. var line = lineGroup.childOfName('line');
  37026. // If line not changed
  37027. // FIXME Parent scale changed
  37028. if (!this.__dirty && !line.__dirty) {
  37029. return;
  37030. }
  37031. var percent = line.shape.percent;
  37032. var fromPos = line.pointAt(0);
  37033. var toPos = line.pointAt(percent);
  37034. var d = sub([], toPos, fromPos);
  37035. normalize(d, d);
  37036. if (symbolFrom) {
  37037. symbolFrom.attr('position', fromPos);
  37038. var tangent = line.tangentAt(0);
  37039. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  37040. tangent[1], tangent[0]
  37041. ));
  37042. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  37043. }
  37044. if (symbolTo) {
  37045. symbolTo.attr('position', toPos);
  37046. var tangent = line.tangentAt(1);
  37047. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  37048. tangent[1], tangent[0]
  37049. ));
  37050. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  37051. }
  37052. if (!label.ignore) {
  37053. label.attr('position', toPos);
  37054. var textPosition;
  37055. var textAlign;
  37056. var textVerticalAlign;
  37057. var distance$$1 = 5 * invScale;
  37058. // End
  37059. if (label.__position === 'end') {
  37060. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  37061. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  37062. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  37063. }
  37064. // Middle
  37065. else if (label.__position === 'middle') {
  37066. var halfPercent = percent / 2;
  37067. var tangent = line.tangentAt(halfPercent);
  37068. var n = [tangent[1], -tangent[0]];
  37069. var cp = line.pointAt(halfPercent);
  37070. if (n[1] > 0) {
  37071. n[0] = -n[0];
  37072. n[1] = -n[1];
  37073. }
  37074. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  37075. textAlign = 'center';
  37076. textVerticalAlign = 'bottom';
  37077. var rotation = -Math.atan2(tangent[1], tangent[0]);
  37078. if (toPos[0] < fromPos[0]) {
  37079. rotation = Math.PI + rotation;
  37080. }
  37081. label.attr('rotation', rotation);
  37082. }
  37083. // Start
  37084. else {
  37085. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  37086. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  37087. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  37088. }
  37089. label.attr({
  37090. style: {
  37091. // Use the user specified text align and baseline first
  37092. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  37093. textAlign: label.__textAlign || textAlign
  37094. },
  37095. position: textPosition,
  37096. scale: [invScale, invScale]
  37097. });
  37098. }
  37099. }
  37100. /**
  37101. * @constructor
  37102. * @extends {module:zrender/graphic/Group}
  37103. * @alias {module:echarts/chart/helper/Line}
  37104. */
  37105. function Line$1(lineData, idx, seriesScope) {
  37106. Group.call(this);
  37107. this._createLine(lineData, idx, seriesScope);
  37108. }
  37109. var lineProto = Line$1.prototype;
  37110. // Update symbol position and rotation
  37111. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  37112. lineProto._createLine = function (lineData, idx, seriesScope) {
  37113. var seriesModel = lineData.hostModel;
  37114. var linePoints = lineData.getItemLayout(idx);
  37115. var line = createLine(linePoints);
  37116. line.shape.percent = 0;
  37117. initProps(line, {
  37118. shape: {
  37119. percent: 1
  37120. }
  37121. }, seriesModel, idx);
  37122. this.add(line);
  37123. var label = new Text({
  37124. name: 'label'
  37125. });
  37126. this.add(label);
  37127. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37128. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37129. // symbols must added after line to make sure
  37130. // it will be updated after line#update.
  37131. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  37132. this.add(symbol);
  37133. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  37134. }, this);
  37135. this._updateCommonStl(lineData, idx, seriesScope);
  37136. };
  37137. lineProto.updateData = function (lineData, idx, seriesScope) {
  37138. var seriesModel = lineData.hostModel;
  37139. var line = this.childOfName('line');
  37140. var linePoints = lineData.getItemLayout(idx);
  37141. var target = {
  37142. shape: {}
  37143. };
  37144. setLinePoints(target.shape, linePoints);
  37145. updateProps(line, target, seriesModel, idx);
  37146. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37147. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  37148. var key = makeSymbolTypeKey(symbolCategory);
  37149. // Symbol changed
  37150. if (this[key] !== symbolType) {
  37151. this.remove(this.childOfName(symbolCategory));
  37152. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37153. this.add(symbol);
  37154. }
  37155. this[key] = symbolType;
  37156. }, this);
  37157. this._updateCommonStl(lineData, idx, seriesScope);
  37158. };
  37159. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  37160. var seriesModel = lineData.hostModel;
  37161. var line = this.childOfName('line');
  37162. var lineStyle = seriesScope && seriesScope.lineStyle;
  37163. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  37164. var labelModel = seriesScope && seriesScope.labelModel;
  37165. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  37166. // Optimization for large dataset
  37167. if (!seriesScope || lineData.hasItemOption) {
  37168. var itemModel = lineData.getItemModel(idx);
  37169. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  37170. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  37171. labelModel = itemModel.getModel('label');
  37172. hoverLabelModel = itemModel.getModel('emphasis.label');
  37173. }
  37174. var visualColor = lineData.getItemVisual(idx, 'color');
  37175. var visualOpacity = retrieve3(
  37176. lineData.getItemVisual(idx, 'opacity'),
  37177. lineStyle.opacity,
  37178. 1
  37179. );
  37180. line.useStyle(defaults(
  37181. {
  37182. strokeNoScale: true,
  37183. fill: 'none',
  37184. stroke: visualColor,
  37185. opacity: visualOpacity
  37186. },
  37187. lineStyle
  37188. ));
  37189. line.hoverStyle = hoverLineStyle;
  37190. // Update symbol
  37191. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37192. var symbol = this.childOfName(symbolCategory);
  37193. if (symbol) {
  37194. symbol.setColor(visualColor);
  37195. symbol.setStyle({
  37196. opacity: visualOpacity
  37197. });
  37198. }
  37199. }, this);
  37200. var showLabel = labelModel.getShallow('show');
  37201. var hoverShowLabel = hoverLabelModel.getShallow('show');
  37202. var label = this.childOfName('label');
  37203. var defaultLabelColor;
  37204. var normalText;
  37205. var emphasisText;
  37206. if (showLabel || hoverShowLabel) {
  37207. defaultLabelColor = visualColor || '#000';
  37208. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  37209. if (normalText == null) {
  37210. var rawVal = seriesModel.getRawValue(idx);
  37211. normalText = rawVal == null
  37212. ? lineData.getName(idx)
  37213. : isFinite(rawVal)
  37214. ? round$1(rawVal)
  37215. : rawVal;
  37216. }
  37217. emphasisText = retrieve2(
  37218. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  37219. normalText
  37220. );
  37221. }
  37222. // label.afterUpdate = lineAfterUpdate;
  37223. if (showLabel) {
  37224. var labelStyle = setTextStyle(label.style, labelModel, {
  37225. text: normalText
  37226. }, {
  37227. autoColor: defaultLabelColor
  37228. });
  37229. label.__textAlign = labelStyle.textAlign;
  37230. label.__verticalAlign = labelStyle.textVerticalAlign;
  37231. // 'start', 'middle', 'end'
  37232. label.__position = labelModel.get('position') || 'middle';
  37233. }
  37234. else {
  37235. label.setStyle('text', null);
  37236. }
  37237. if (hoverShowLabel) {
  37238. // Only these properties supported in this emphasis style here.
  37239. label.hoverStyle = {
  37240. text: emphasisText,
  37241. textFill: hoverLabelModel.getTextColor(true),
  37242. // For merging hover style to normal style, do not use
  37243. // `hoverLabelModel.getFont()` here.
  37244. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  37245. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  37246. fontSize: hoverLabelModel.getShallow('fontSize'),
  37247. fontFamily: hoverLabelModel.getShallow('fontFamily')
  37248. };
  37249. }
  37250. else {
  37251. label.hoverStyle = {
  37252. text: null
  37253. };
  37254. }
  37255. label.ignore = !showLabel && !hoverShowLabel;
  37256. setHoverStyle(this);
  37257. };
  37258. lineProto.highlight = function () {
  37259. this.trigger('emphasis');
  37260. };
  37261. lineProto.downplay = function () {
  37262. this.trigger('normal');
  37263. };
  37264. lineProto.updateLayout = function (lineData, idx) {
  37265. this.setLinePoints(lineData.getItemLayout(idx));
  37266. };
  37267. lineProto.setLinePoints = function (points) {
  37268. var linePath = this.childOfName('line');
  37269. setLinePoints(linePath.shape, points);
  37270. linePath.dirty();
  37271. };
  37272. inherits(Line$1, Group);
  37273. /**
  37274. * @module echarts/chart/helper/LineDraw
  37275. */
  37276. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  37277. /**
  37278. * @alias module:echarts/component/marker/LineDraw
  37279. * @constructor
  37280. */
  37281. function LineDraw(ctor) {
  37282. this._ctor = ctor || Line$1;
  37283. this.group = new Group();
  37284. }
  37285. var lineDrawProto = LineDraw.prototype;
  37286. lineDrawProto.isPersistent = function () {
  37287. return true;
  37288. };
  37289. /**
  37290. * @param {module:echarts/data/List} lineData
  37291. */
  37292. lineDrawProto.updateData = function (lineData) {
  37293. var lineDraw = this;
  37294. var group = lineDraw.group;
  37295. var oldLineData = lineDraw._lineData;
  37296. lineDraw._lineData = lineData;
  37297. // There is no oldLineData only when first rendering or switching from
  37298. // stream mode to normal mode, where previous elements should be removed.
  37299. if (!oldLineData) {
  37300. group.removeAll();
  37301. }
  37302. var seriesScope = makeSeriesScope$1(lineData);
  37303. lineData.diff(oldLineData)
  37304. .add(function (idx) {
  37305. doAdd(lineDraw, lineData, idx, seriesScope);
  37306. })
  37307. .update(function (newIdx, oldIdx) {
  37308. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  37309. })
  37310. .remove(function (idx) {
  37311. group.remove(oldLineData.getItemGraphicEl(idx));
  37312. })
  37313. .execute();
  37314. };
  37315. function doAdd(lineDraw, lineData, idx, seriesScope) {
  37316. var itemLayout = lineData.getItemLayout(idx);
  37317. if (!lineNeedsDraw(itemLayout)) {
  37318. return;
  37319. }
  37320. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  37321. lineData.setItemGraphicEl(idx, el);
  37322. lineDraw.group.add(el);
  37323. }
  37324. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  37325. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  37326. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  37327. lineDraw.group.remove(itemEl);
  37328. return;
  37329. }
  37330. if (!itemEl) {
  37331. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  37332. }
  37333. else {
  37334. itemEl.updateData(newLineData, newIdx, seriesScope);
  37335. }
  37336. newLineData.setItemGraphicEl(newIdx, itemEl);
  37337. lineDraw.group.add(itemEl);
  37338. }
  37339. lineDrawProto.updateLayout = function () {
  37340. var lineData = this._lineData;
  37341. lineData.eachItemGraphicEl(function (el, idx) {
  37342. el.updateLayout(lineData, idx);
  37343. }, this);
  37344. };
  37345. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  37346. this._seriesScope = makeSeriesScope$1(lineData);
  37347. this._lineData = null;
  37348. this.group.removeAll();
  37349. };
  37350. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  37351. function updateIncrementalAndHover(el) {
  37352. if (!el.isGroup) {
  37353. el.incremental = el.useHoverLayer = true;
  37354. }
  37355. }
  37356. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  37357. var itemLayout = lineData.getItemLayout(idx);
  37358. if (lineNeedsDraw(itemLayout)) {
  37359. var el = new this._ctor(lineData, idx, this._seriesScope);
  37360. el.traverse(updateIncrementalAndHover);
  37361. this.group.add(el);
  37362. }
  37363. }
  37364. };
  37365. function makeSeriesScope$1(lineData) {
  37366. var hostModel = lineData.hostModel;
  37367. return {
  37368. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  37369. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  37370. labelModel: hostModel.getModel('label'),
  37371. hoverLabelModel: hostModel.getModel('emphasis.label')
  37372. };
  37373. }
  37374. lineDrawProto.remove = function () {
  37375. this._clearIncremental();
  37376. this._incremental = null;
  37377. this.group.removeAll();
  37378. };
  37379. lineDrawProto._clearIncremental = function () {
  37380. var incremental = this._incremental;
  37381. if (incremental) {
  37382. incremental.clearDisplaybles();
  37383. }
  37384. };
  37385. function isPointNaN(pt) {
  37386. return isNaN(pt[0]) || isNaN(pt[1]);
  37387. }
  37388. function lineNeedsDraw(pts) {
  37389. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  37390. }
  37391. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  37392. var data = seriesModel.getData();
  37393. // Special type markLine like 'min', 'max', 'average'
  37394. var mlType = item.type;
  37395. if (!isArray(item)
  37396. && (
  37397. mlType === 'min' || mlType === 'max' || mlType === 'average'
  37398. // In case
  37399. // data: [{
  37400. // yAxis: 10
  37401. // }]
  37402. || (item.xAxis != null || item.yAxis != null)
  37403. )
  37404. ) {
  37405. var valueAxis;
  37406. var valueDataDim;
  37407. var value;
  37408. if (item.yAxis != null || item.xAxis != null) {
  37409. valueDataDim = item.yAxis != null ? 'y' : 'x';
  37410. valueAxis = coordSys.getAxis(valueDataDim);
  37411. value = retrieve(item.yAxis, item.xAxis);
  37412. }
  37413. else {
  37414. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  37415. valueDataDim = axisInfo.valueDataDim;
  37416. valueAxis = axisInfo.valueAxis;
  37417. value = numCalculate(data, valueDataDim, mlType);
  37418. }
  37419. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  37420. var baseIndex = 1 - valueIndex;
  37421. var mlFrom = clone(item);
  37422. var mlTo = {};
  37423. mlFrom.type = null;
  37424. mlFrom.coord = [];
  37425. mlTo.coord = [];
  37426. mlFrom.coord[baseIndex] = -Infinity;
  37427. mlTo.coord[baseIndex] = Infinity;
  37428. var precision = mlModel.get('precision');
  37429. if (precision >= 0 && typeof value === 'number') {
  37430. value = +value.toFixed(Math.min(precision, 20));
  37431. }
  37432. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  37433. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  37434. type: mlType,
  37435. valueIndex: item.valueIndex,
  37436. // Force to use the value of calculated value.
  37437. value: value
  37438. }];
  37439. }
  37440. item = [
  37441. dataTransform(seriesModel, item[0]),
  37442. dataTransform(seriesModel, item[1]),
  37443. extend({}, item[2])
  37444. ];
  37445. // Avoid line data type is extended by from(to) data type
  37446. item[2].type = item[2].type || '';
  37447. // Merge from option and to option into line option
  37448. merge(item[2], item[0]);
  37449. merge(item[2], item[1]);
  37450. return item;
  37451. };
  37452. function isInifinity(val) {
  37453. return !isNaN(val) && !isFinite(val);
  37454. }
  37455. // If a markLine has one dim
  37456. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  37457. var otherDimIndex = 1 - dimIndex;
  37458. var dimName = coordSys.dimensions[dimIndex];
  37459. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  37460. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  37461. }
  37462. function markLineFilter(coordSys, item) {
  37463. if (coordSys.type === 'cartesian2d') {
  37464. var fromCoord = item[0].coord;
  37465. var toCoord = item[1].coord;
  37466. // In case
  37467. // {
  37468. // markLine: {
  37469. // data: [{ yAxis: 2 }]
  37470. // }
  37471. // }
  37472. if (
  37473. fromCoord && toCoord &&
  37474. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  37475. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  37476. ) {
  37477. return true;
  37478. }
  37479. }
  37480. return dataFilter$1(coordSys, item[0])
  37481. && dataFilter$1(coordSys, item[1]);
  37482. }
  37483. function updateSingleMarkerEndLayout(
  37484. data, idx, isFrom, seriesModel, api
  37485. ) {
  37486. var coordSys = seriesModel.coordinateSystem;
  37487. var itemModel = data.getItemModel(idx);
  37488. var point;
  37489. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  37490. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  37491. if (!isNaN(xPx) && !isNaN(yPx)) {
  37492. point = [xPx, yPx];
  37493. }
  37494. else {
  37495. // Chart like bar may have there own marker positioning logic
  37496. if (seriesModel.getMarkerPosition) {
  37497. // Use the getMarkerPoisition
  37498. point = seriesModel.getMarkerPosition(
  37499. data.getValues(data.dimensions, idx)
  37500. );
  37501. }
  37502. else {
  37503. var dims = coordSys.dimensions;
  37504. var x = data.get(dims[0], idx);
  37505. var y = data.get(dims[1], idx);
  37506. point = coordSys.dataToPoint([x, y]);
  37507. }
  37508. // Expand line to the edge of grid if value on one axis is Inifnity
  37509. // In case
  37510. // markLine: {
  37511. // data: [{
  37512. // yAxis: 2
  37513. // // or
  37514. // type: 'average'
  37515. // }]
  37516. // }
  37517. if (coordSys.type === 'cartesian2d') {
  37518. var xAxis = coordSys.getAxis('x');
  37519. var yAxis = coordSys.getAxis('y');
  37520. var dims = coordSys.dimensions;
  37521. if (isInifinity(data.get(dims[0], idx))) {
  37522. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  37523. }
  37524. else if (isInifinity(data.get(dims[1], idx))) {
  37525. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  37526. }
  37527. }
  37528. // Use x, y if has any
  37529. if (!isNaN(xPx)) {
  37530. point[0] = xPx;
  37531. }
  37532. if (!isNaN(yPx)) {
  37533. point[1] = yPx;
  37534. }
  37535. }
  37536. data.setItemLayout(idx, point);
  37537. }
  37538. MarkerView.extend({
  37539. type: 'markLine',
  37540. // updateLayout: function (markLineModel, ecModel, api) {
  37541. // ecModel.eachSeries(function (seriesModel) {
  37542. // var mlModel = seriesModel.markLineModel;
  37543. // if (mlModel) {
  37544. // var mlData = mlModel.getData();
  37545. // var fromData = mlModel.__from;
  37546. // var toData = mlModel.__to;
  37547. // // Update visual and layout of from symbol and to symbol
  37548. // fromData.each(function (idx) {
  37549. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  37550. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  37551. // });
  37552. // // Update layout of line
  37553. // mlData.each(function (idx) {
  37554. // mlData.setItemLayout(idx, [
  37555. // fromData.getItemLayout(idx),
  37556. // toData.getItemLayout(idx)
  37557. // ]);
  37558. // });
  37559. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  37560. // }
  37561. // }, this);
  37562. // },
  37563. updateTransform: function (markLineModel, ecModel, api) {
  37564. ecModel.eachSeries(function (seriesModel) {
  37565. var mlModel = seriesModel.markLineModel;
  37566. if (mlModel) {
  37567. var mlData = mlModel.getData();
  37568. var fromData = mlModel.__from;
  37569. var toData = mlModel.__to;
  37570. // Update visual and layout of from symbol and to symbol
  37571. fromData.each(function (idx) {
  37572. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  37573. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  37574. });
  37575. // Update layout of line
  37576. mlData.each(function (idx) {
  37577. mlData.setItemLayout(idx, [
  37578. fromData.getItemLayout(idx),
  37579. toData.getItemLayout(idx)
  37580. ]);
  37581. });
  37582. this.markerGroupMap.get(seriesModel.id).updateLayout();
  37583. }
  37584. }, this);
  37585. },
  37586. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  37587. var coordSys = seriesModel.coordinateSystem;
  37588. var seriesId = seriesModel.id;
  37589. var seriesData = seriesModel.getData();
  37590. var lineDrawMap = this.markerGroupMap;
  37591. var lineDraw = lineDrawMap.get(seriesId)
  37592. || lineDrawMap.set(seriesId, new LineDraw());
  37593. this.group.add(lineDraw.group);
  37594. var mlData = createList$2(coordSys, seriesModel, mlModel);
  37595. var fromData = mlData.from;
  37596. var toData = mlData.to;
  37597. var lineData = mlData.line;
  37598. mlModel.__from = fromData;
  37599. mlModel.__to = toData;
  37600. // Line data for tooltip and formatter
  37601. mlModel.setData(lineData);
  37602. var symbolType = mlModel.get('symbol');
  37603. var symbolSize = mlModel.get('symbolSize');
  37604. if (!isArray(symbolType)) {
  37605. symbolType = [symbolType, symbolType];
  37606. }
  37607. if (typeof symbolSize === 'number') {
  37608. symbolSize = [symbolSize, symbolSize];
  37609. }
  37610. // Update visual and layout of from symbol and to symbol
  37611. mlData.from.each(function (idx) {
  37612. updateDataVisualAndLayout(fromData, idx, true);
  37613. updateDataVisualAndLayout(toData, idx, false);
  37614. });
  37615. // Update visual and layout of line
  37616. lineData.each(function (idx) {
  37617. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  37618. lineData.setItemVisual(idx, {
  37619. color: lineColor || fromData.getItemVisual(idx, 'color')
  37620. });
  37621. lineData.setItemLayout(idx, [
  37622. fromData.getItemLayout(idx),
  37623. toData.getItemLayout(idx)
  37624. ]);
  37625. lineData.setItemVisual(idx, {
  37626. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  37627. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  37628. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  37629. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  37630. });
  37631. });
  37632. lineDraw.updateData(lineData);
  37633. // Set host model for tooltip
  37634. // FIXME
  37635. mlData.line.eachItemGraphicEl(function (el, idx) {
  37636. el.traverse(function (child) {
  37637. child.dataModel = mlModel;
  37638. });
  37639. });
  37640. function updateDataVisualAndLayout(data, idx, isFrom) {
  37641. var itemModel = data.getItemModel(idx);
  37642. updateSingleMarkerEndLayout(
  37643. data, idx, isFrom, seriesModel, api
  37644. );
  37645. data.setItemVisual(idx, {
  37646. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  37647. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  37648. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  37649. });
  37650. }
  37651. lineDraw.__keep = true;
  37652. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  37653. }
  37654. });
  37655. /**
  37656. * @inner
  37657. * @param {module:echarts/coord/*} coordSys
  37658. * @param {module:echarts/model/Series} seriesModel
  37659. * @param {module:echarts/model/Model} mpModel
  37660. */
  37661. function createList$2(coordSys, seriesModel, mlModel) {
  37662. var coordDimsInfos;
  37663. if (coordSys) {
  37664. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37665. var info = seriesModel.getData().getDimensionInfo(
  37666. seriesModel.getData().mapDimension(coordDim)
  37667. ) || {};
  37668. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37669. return defaults({name: coordDim}, info);
  37670. });
  37671. }
  37672. else {
  37673. coordDimsInfos =[{
  37674. name: 'value',
  37675. type: 'float'
  37676. }];
  37677. }
  37678. var fromData = new List(coordDimsInfos, mlModel);
  37679. var toData = new List(coordDimsInfos, mlModel);
  37680. // No dimensions
  37681. var lineData = new List([], mlModel);
  37682. var optData = map(mlModel.get('data'), curry(
  37683. markLineTransform, seriesModel, coordSys, mlModel
  37684. ));
  37685. if (coordSys) {
  37686. optData = filter(
  37687. optData, curry(markLineFilter, coordSys)
  37688. );
  37689. }
  37690. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  37691. return item.value;
  37692. };
  37693. fromData.initData(
  37694. map(optData, function (item) { return item[0]; }),
  37695. null, dimValueGetter$$1
  37696. );
  37697. toData.initData(
  37698. map(optData, function (item) { return item[1]; }),
  37699. null, dimValueGetter$$1
  37700. );
  37701. lineData.initData(
  37702. map(optData, function (item) { return item[2]; })
  37703. );
  37704. lineData.hasItemOption = true;
  37705. return {
  37706. from: fromData,
  37707. to: toData,
  37708. line: lineData
  37709. };
  37710. }
  37711. registerPreprocessor(function (opt) {
  37712. // Make sure markLine component is enabled
  37713. opt.markLine = opt.markLine || {};
  37714. });
  37715. MarkerModel.extend({
  37716. type: 'markArea',
  37717. defaultOption: {
  37718. zlevel: 0,
  37719. // PENDING
  37720. z: 1,
  37721. tooltip: {
  37722. trigger: 'item'
  37723. },
  37724. // markArea should fixed on the coordinate system
  37725. animation: false,
  37726. label: {
  37727. show: true,
  37728. position: 'top'
  37729. },
  37730. itemStyle: {
  37731. // color and borderColor default to use color from series
  37732. // color: 'auto'
  37733. // borderColor: 'auto'
  37734. borderWidth: 0
  37735. },
  37736. emphasis: {
  37737. label: {
  37738. show: true,
  37739. position: 'top'
  37740. }
  37741. }
  37742. }
  37743. });
  37744. // TODO Better on polar
  37745. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  37746. var lt = dataTransform(seriesModel, item[0]);
  37747. var rb = dataTransform(seriesModel, item[1]);
  37748. var retrieve$$1 = retrieve;
  37749. // FIXME make sure lt is less than rb
  37750. var ltCoord = lt.coord;
  37751. var rbCoord = rb.coord;
  37752. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  37753. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  37754. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  37755. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  37756. // Merge option into one
  37757. var result = mergeAll([{}, lt, rb]);
  37758. result.coord = [
  37759. lt.coord, rb.coord
  37760. ];
  37761. result.x0 = lt.x;
  37762. result.y0 = lt.y;
  37763. result.x1 = rb.x;
  37764. result.y1 = rb.y;
  37765. return result;
  37766. };
  37767. function isInifinity$1(val) {
  37768. return !isNaN(val) && !isFinite(val);
  37769. }
  37770. // If a markArea has one dim
  37771. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  37772. var otherDimIndex = 1 - dimIndex;
  37773. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  37774. }
  37775. function markAreaFilter(coordSys, item) {
  37776. var fromCoord = item.coord[0];
  37777. var toCoord = item.coord[1];
  37778. if (coordSys.type === 'cartesian2d') {
  37779. // In case
  37780. // {
  37781. // markArea: {
  37782. // data: [{ yAxis: 2 }]
  37783. // }
  37784. // }
  37785. if (
  37786. fromCoord && toCoord &&
  37787. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  37788. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  37789. ) {
  37790. return true;
  37791. }
  37792. }
  37793. return dataFilter$1(coordSys, {
  37794. coord: fromCoord,
  37795. x: item.x0,
  37796. y: item.y0
  37797. })
  37798. || dataFilter$1(coordSys, {
  37799. coord: toCoord,
  37800. x: item.x1,
  37801. y: item.y1
  37802. });
  37803. }
  37804. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  37805. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  37806. var coordSys = seriesModel.coordinateSystem;
  37807. var itemModel = data.getItemModel(idx);
  37808. var point;
  37809. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  37810. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  37811. if (!isNaN(xPx) && !isNaN(yPx)) {
  37812. point = [xPx, yPx];
  37813. }
  37814. else {
  37815. // Chart like bar may have there own marker positioning logic
  37816. if (seriesModel.getMarkerPosition) {
  37817. // Use the getMarkerPoisition
  37818. point = seriesModel.getMarkerPosition(
  37819. data.getValues(dims, idx)
  37820. );
  37821. }
  37822. else {
  37823. var x = data.get(dims[0], idx);
  37824. var y = data.get(dims[1], idx);
  37825. var pt = [x, y];
  37826. coordSys.clampData && coordSys.clampData(pt, pt);
  37827. point = coordSys.dataToPoint(pt, true);
  37828. }
  37829. if (coordSys.type === 'cartesian2d') {
  37830. var xAxis = coordSys.getAxis('x');
  37831. var yAxis = coordSys.getAxis('y');
  37832. var x = data.get(dims[0], idx);
  37833. var y = data.get(dims[1], idx);
  37834. if (isInifinity$1(x)) {
  37835. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  37836. }
  37837. else if (isInifinity$1(y)) {
  37838. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  37839. }
  37840. }
  37841. // Use x, y if has any
  37842. if (!isNaN(xPx)) {
  37843. point[0] = xPx;
  37844. }
  37845. if (!isNaN(yPx)) {
  37846. point[1] = yPx;
  37847. }
  37848. }
  37849. return point;
  37850. }
  37851. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  37852. MarkerView.extend({
  37853. type: 'markArea',
  37854. // updateLayout: function (markAreaModel, ecModel, api) {
  37855. // ecModel.eachSeries(function (seriesModel) {
  37856. // var maModel = seriesModel.markAreaModel;
  37857. // if (maModel) {
  37858. // var areaData = maModel.getData();
  37859. // areaData.each(function (idx) {
  37860. // var points = zrUtil.map(dimPermutations, function (dim) {
  37861. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37862. // });
  37863. // // Layout
  37864. // areaData.setItemLayout(idx, points);
  37865. // var el = areaData.getItemGraphicEl(idx);
  37866. // el.setShape('points', points);
  37867. // });
  37868. // }
  37869. // }, this);
  37870. // },
  37871. updateTransform: function (markAreaModel, ecModel, api) {
  37872. ecModel.eachSeries(function (seriesModel) {
  37873. var maModel = seriesModel.markAreaModel;
  37874. if (maModel) {
  37875. var areaData = maModel.getData();
  37876. areaData.each(function (idx) {
  37877. var points = map(dimPermutations, function (dim) {
  37878. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37879. });
  37880. // Layout
  37881. areaData.setItemLayout(idx, points);
  37882. var el = areaData.getItemGraphicEl(idx);
  37883. el.setShape('points', points);
  37884. });
  37885. }
  37886. }, this);
  37887. },
  37888. renderSeries: function (seriesModel, maModel, ecModel, api) {
  37889. var coordSys = seriesModel.coordinateSystem;
  37890. var seriesName = seriesModel.name;
  37891. var seriesData = seriesModel.getData();
  37892. var areaGroupMap = this.markerGroupMap;
  37893. var polygonGroup = areaGroupMap.get(seriesName)
  37894. || areaGroupMap.set(seriesName, {group: new Group()});
  37895. this.group.add(polygonGroup.group);
  37896. polygonGroup.__keep = true;
  37897. var areaData = createList$3(coordSys, seriesModel, maModel);
  37898. // Line data for tooltip and formatter
  37899. maModel.setData(areaData);
  37900. // Update visual and layout of line
  37901. areaData.each(function (idx) {
  37902. // Layout
  37903. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  37904. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37905. }));
  37906. // Visual
  37907. areaData.setItemVisual(idx, {
  37908. color: seriesData.getVisual('color')
  37909. });
  37910. });
  37911. areaData.diff(polygonGroup.__data)
  37912. .add(function (idx) {
  37913. var polygon = new Polygon({
  37914. shape: {
  37915. points: areaData.getItemLayout(idx)
  37916. }
  37917. });
  37918. areaData.setItemGraphicEl(idx, polygon);
  37919. polygonGroup.group.add(polygon);
  37920. })
  37921. .update(function (newIdx, oldIdx) {
  37922. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  37923. updateProps(polygon, {
  37924. shape: {
  37925. points: areaData.getItemLayout(newIdx)
  37926. }
  37927. }, maModel, newIdx);
  37928. polygonGroup.group.add(polygon);
  37929. areaData.setItemGraphicEl(newIdx, polygon);
  37930. })
  37931. .remove(function (idx) {
  37932. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  37933. polygonGroup.group.remove(polygon);
  37934. })
  37935. .execute();
  37936. areaData.eachItemGraphicEl(function (polygon, idx) {
  37937. var itemModel = areaData.getItemModel(idx);
  37938. var labelModel = itemModel.getModel('label');
  37939. var labelHoverModel = itemModel.getModel('emphasis.label');
  37940. var color = areaData.getItemVisual(idx, 'color');
  37941. polygon.useStyle(
  37942. defaults(
  37943. itemModel.getModel('itemStyle').getItemStyle(),
  37944. {
  37945. fill: modifyAlpha(color, 0.4),
  37946. stroke: color
  37947. }
  37948. )
  37949. );
  37950. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  37951. setLabelStyle(
  37952. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  37953. {
  37954. labelFetcher: maModel,
  37955. labelDataIndex: idx,
  37956. defaultText: areaData.getName(idx) || '',
  37957. isRectText: true,
  37958. autoColor: color
  37959. }
  37960. );
  37961. setHoverStyle(polygon, {});
  37962. polygon.dataModel = maModel;
  37963. });
  37964. polygonGroup.__data = areaData;
  37965. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  37966. }
  37967. });
  37968. /**
  37969. * @inner
  37970. * @param {module:echarts/coord/*} coordSys
  37971. * @param {module:echarts/model/Series} seriesModel
  37972. * @param {module:echarts/model/Model} mpModel
  37973. */
  37974. function createList$3(coordSys, seriesModel, maModel) {
  37975. var coordDimsInfos;
  37976. var areaData;
  37977. var dims = ['x0', 'y0', 'x1', 'y1'];
  37978. if (coordSys) {
  37979. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37980. var data = seriesModel.getData();
  37981. var info = data.getDimensionInfo(
  37982. data.mapDimension(coordDim)
  37983. ) || {};
  37984. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37985. return defaults({name: coordDim}, info);
  37986. });
  37987. areaData = new List(map(dims, function (dim, idx) {
  37988. return {
  37989. name: dim,
  37990. type: coordDimsInfos[idx % 2].type
  37991. };
  37992. }), maModel);
  37993. }
  37994. else {
  37995. coordDimsInfos =[{
  37996. name: 'value',
  37997. type: 'float'
  37998. }];
  37999. areaData = new List(coordDimsInfos, maModel);
  38000. }
  38001. var optData = map(maModel.get('data'), curry(
  38002. markAreaTransform, seriesModel, coordSys, maModel
  38003. ));
  38004. if (coordSys) {
  38005. optData = filter(
  38006. optData, curry(markAreaFilter, coordSys)
  38007. );
  38008. }
  38009. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  38010. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  38011. } : function (item) {
  38012. return item.value;
  38013. };
  38014. areaData.initData(optData, null, dimValueGetter$$1);
  38015. areaData.hasItemOption = true;
  38016. return areaData;
  38017. }
  38018. registerPreprocessor(function (opt) {
  38019. // Make sure markArea component is enabled
  38020. opt.markArea = opt.markArea || {};
  38021. });
  38022. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  38023. // Default 'slider' when no type specified.
  38024. return 'slider';
  38025. });
  38026. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  38027. // Supported coords.
  38028. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  38029. /**
  38030. * @param {string} coordType
  38031. * @return {boolean}
  38032. */
  38033. function isCoordSupported(coordType) {
  38034. return indexOf(COORDS, coordType) >= 0;
  38035. }
  38036. /**
  38037. * Create "each" method to iterate names.
  38038. *
  38039. * @pubilc
  38040. * @param {Array.<string>} names
  38041. * @param {Array.<string>=} attrs
  38042. * @return {Function}
  38043. */
  38044. function createNameEach(names, attrs) {
  38045. names = names.slice();
  38046. var capitalNames = map(names, capitalFirst);
  38047. attrs = (attrs || []).slice();
  38048. var capitalAttrs = map(attrs, capitalFirst);
  38049. return function (callback, context) {
  38050. each$1(names, function (name, index) {
  38051. var nameObj = {name: name, capital: capitalNames[index]};
  38052. for (var j = 0; j < attrs.length; j++) {
  38053. nameObj[attrs[j]] = name + capitalAttrs[j];
  38054. }
  38055. callback.call(context, nameObj);
  38056. });
  38057. };
  38058. }
  38059. /**
  38060. * Iterate each dimension name.
  38061. *
  38062. * @public
  38063. * @param {Function} callback The parameter is like:
  38064. * {
  38065. * name: 'angle',
  38066. * capital: 'Angle',
  38067. * axis: 'angleAxis',
  38068. * axisIndex: 'angleAixs',
  38069. * index: 'angleIndex'
  38070. * }
  38071. * @param {Object} context
  38072. */
  38073. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  38074. /**
  38075. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  38076. * dataZoomModels and 'links' make up one or more graphics.
  38077. * This function finds the graphic where the source dataZoomModel is in.
  38078. *
  38079. * @public
  38080. * @param {Function} forEachNode Node iterator.
  38081. * @param {Function} forEachEdgeType edgeType iterator
  38082. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  38083. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  38084. */
  38085. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  38086. return function (sourceNode) {
  38087. var result = {
  38088. nodes: [],
  38089. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  38090. };
  38091. forEachEdgeType(function (edgeType) {
  38092. result.records[edgeType.name] = {};
  38093. });
  38094. if (!sourceNode) {
  38095. return result;
  38096. }
  38097. absorb(sourceNode, result);
  38098. var existsLink;
  38099. do {
  38100. existsLink = false;
  38101. forEachNode(processSingleNode);
  38102. }
  38103. while (existsLink);
  38104. function processSingleNode(node) {
  38105. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  38106. absorb(node, result);
  38107. existsLink = true;
  38108. }
  38109. }
  38110. return result;
  38111. };
  38112. function isNodeAbsorded(node, result) {
  38113. return indexOf(result.nodes, node) >= 0;
  38114. }
  38115. function isLinked(node, result) {
  38116. var hasLink = false;
  38117. forEachEdgeType(function (edgeType) {
  38118. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38119. result.records[edgeType.name][edgeId] && (hasLink = true);
  38120. });
  38121. });
  38122. return hasLink;
  38123. }
  38124. function absorb(node, result) {
  38125. result.nodes.push(node);
  38126. forEachEdgeType(function (edgeType) {
  38127. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38128. result.records[edgeType.name][edgeId] = true;
  38129. });
  38130. });
  38131. }
  38132. }
  38133. var each$14 = each$1;
  38134. var asc$1 = asc;
  38135. /**
  38136. * Operate single axis.
  38137. * One axis can only operated by one axis operator.
  38138. * Different dataZoomModels may be defined to operate the same axis.
  38139. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  38140. * So dataZoomModels share one axisProxy in that case.
  38141. *
  38142. * @class
  38143. */
  38144. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  38145. /**
  38146. * @private
  38147. * @type {string}
  38148. */
  38149. this._dimName = dimName;
  38150. /**
  38151. * @private
  38152. */
  38153. this._axisIndex = axisIndex;
  38154. /**
  38155. * @private
  38156. * @type {Array.<number>}
  38157. */
  38158. this._valueWindow;
  38159. /**
  38160. * @private
  38161. * @type {Array.<number>}
  38162. */
  38163. this._percentWindow;
  38164. /**
  38165. * @private
  38166. * @type {Array.<number>}
  38167. */
  38168. this._dataExtent;
  38169. /**
  38170. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  38171. * @private
  38172. * @type {Object}
  38173. */
  38174. this._minMaxSpan;
  38175. /**
  38176. * @readOnly
  38177. * @type {module: echarts/model/Global}
  38178. */
  38179. this.ecModel = ecModel;
  38180. /**
  38181. * @private
  38182. * @type {module: echarts/component/dataZoom/DataZoomModel}
  38183. */
  38184. this._dataZoomModel = dataZoomModel;
  38185. /**
  38186. * @readOnly
  38187. * @private
  38188. */
  38189. this.hasSeriesStacked;
  38190. };
  38191. AxisProxy.prototype = {
  38192. constructor: AxisProxy,
  38193. /**
  38194. * Whether the axisProxy is hosted by dataZoomModel.
  38195. *
  38196. * @public
  38197. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38198. * @return {boolean}
  38199. */
  38200. hostedBy: function (dataZoomModel) {
  38201. return this._dataZoomModel === dataZoomModel;
  38202. },
  38203. /**
  38204. * @return {Array.<number>} Value can only be NaN or finite value.
  38205. */
  38206. getDataValueWindow: function () {
  38207. return this._valueWindow.slice();
  38208. },
  38209. /**
  38210. * @return {Array.<number>}
  38211. */
  38212. getDataPercentWindow: function () {
  38213. return this._percentWindow.slice();
  38214. },
  38215. /**
  38216. * @public
  38217. * @param {number} axisIndex
  38218. * @return {Array} seriesModels
  38219. */
  38220. getTargetSeriesModels: function () {
  38221. var seriesModels = [];
  38222. var ecModel = this.ecModel;
  38223. ecModel.eachSeries(function (seriesModel) {
  38224. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  38225. var dimName = this._dimName;
  38226. var axisModel = ecModel.queryComponents({
  38227. mainType: dimName + 'Axis',
  38228. index: seriesModel.get(dimName + 'AxisIndex'),
  38229. id: seriesModel.get(dimName + 'AxisId')
  38230. })[0];
  38231. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  38232. seriesModels.push(seriesModel);
  38233. }
  38234. }
  38235. }, this);
  38236. return seriesModels;
  38237. },
  38238. getAxisModel: function () {
  38239. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  38240. },
  38241. getOtherAxisModel: function () {
  38242. var axisDim = this._dimName;
  38243. var ecModel = this.ecModel;
  38244. var axisModel = this.getAxisModel();
  38245. var isCartesian = axisDim === 'x' || axisDim === 'y';
  38246. var otherAxisDim;
  38247. var coordSysIndexName;
  38248. if (isCartesian) {
  38249. coordSysIndexName = 'gridIndex';
  38250. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  38251. }
  38252. else {
  38253. coordSysIndexName = 'polarIndex';
  38254. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  38255. }
  38256. var foundOtherAxisModel;
  38257. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  38258. if ((otherAxisModel.get(coordSysIndexName) || 0)
  38259. === (axisModel.get(coordSysIndexName) || 0)
  38260. ) {
  38261. foundOtherAxisModel = otherAxisModel;
  38262. }
  38263. });
  38264. return foundOtherAxisModel;
  38265. },
  38266. getMinMaxSpan: function () {
  38267. return clone(this._minMaxSpan);
  38268. },
  38269. /**
  38270. * Only calculate by given range and this._dataExtent, do not change anything.
  38271. *
  38272. * @param {Object} opt
  38273. * @param {number} [opt.start]
  38274. * @param {number} [opt.end]
  38275. * @param {number} [opt.startValue]
  38276. * @param {number} [opt.endValue]
  38277. */
  38278. calculateDataWindow: function (opt) {
  38279. var dataExtent = this._dataExtent;
  38280. var axisModel = this.getAxisModel();
  38281. var scale = axisModel.axis.scale;
  38282. var rangePropMode = this._dataZoomModel.getRangePropMode();
  38283. var percentExtent = [0, 100];
  38284. var percentWindow = [
  38285. opt.start,
  38286. opt.end
  38287. ];
  38288. var valueWindow = [];
  38289. each$14(['startValue', 'endValue'], function (prop) {
  38290. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  38291. });
  38292. // Normalize bound.
  38293. each$14([0, 1], function (idx) {
  38294. var boundValue = valueWindow[idx];
  38295. var boundPercent = percentWindow[idx];
  38296. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  38297. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  38298. // for cases that a dataZoom component controls multiple axes with different
  38299. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  38300. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  38301. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  38302. // accurately (because all of values that are overflow the `dataExtent` will
  38303. // be calculated to percent '100%'). So we have to use
  38304. // `dataZoom.getRangePropMode()` to mark which prop is used.
  38305. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  38306. // it remains its original value.
  38307. if (rangePropMode[idx] === 'percent') {
  38308. if (boundPercent == null) {
  38309. boundPercent = percentExtent[idx];
  38310. }
  38311. // Use scale.parse to math round for category or time axis.
  38312. boundValue = scale.parse(linearMap(
  38313. boundPercent, percentExtent, dataExtent, true
  38314. ));
  38315. }
  38316. else {
  38317. // Calculating `percent` from `value` may be not accurate, because
  38318. // This calculation can not be inversed, because all of values that
  38319. // are overflow the `dataExtent` will be calculated to percent '100%'
  38320. boundPercent = linearMap(
  38321. boundValue, dataExtent, percentExtent, true
  38322. );
  38323. }
  38324. // valueWindow[idx] = round(boundValue);
  38325. // percentWindow[idx] = round(boundPercent);
  38326. valueWindow[idx] = boundValue;
  38327. percentWindow[idx] = boundPercent;
  38328. });
  38329. return {
  38330. valueWindow: asc$1(valueWindow),
  38331. percentWindow: asc$1(percentWindow)
  38332. };
  38333. },
  38334. /**
  38335. * Notice: reset should not be called before series.restoreData() called,
  38336. * so it is recommanded to be called in "process stage" but not "model init
  38337. * stage".
  38338. *
  38339. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38340. */
  38341. reset: function (dataZoomModel) {
  38342. if (dataZoomModel !== this._dataZoomModel) {
  38343. return;
  38344. }
  38345. var targetSeries = this.getTargetSeriesModels();
  38346. // Culculate data window and data extent, and record them.
  38347. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  38348. this.hasSeriesStacked = false;
  38349. each$14(targetSeries, function (series) {
  38350. var data = series.getData();
  38351. var dataDim = data.mapDimension(this._dimName);
  38352. if (data.isStacked(dataDim)) {
  38353. this.hasSeriesStacked = true;
  38354. }
  38355. }, this);
  38356. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  38357. this._valueWindow = dataWindow.valueWindow;
  38358. this._percentWindow = dataWindow.percentWindow;
  38359. setMinMaxSpan(this);
  38360. // Update axis setting then.
  38361. setAxisModel(this);
  38362. },
  38363. /**
  38364. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38365. */
  38366. restore: function (dataZoomModel) {
  38367. if (dataZoomModel !== this._dataZoomModel) {
  38368. return;
  38369. }
  38370. this._valueWindow = this._percentWindow = null;
  38371. setAxisModel(this, true);
  38372. },
  38373. /**
  38374. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38375. */
  38376. filterData: function (dataZoomModel, api) {
  38377. if (dataZoomModel !== this._dataZoomModel) {
  38378. return;
  38379. }
  38380. var axisDim = this._dimName;
  38381. var seriesModels = this.getTargetSeriesModels();
  38382. var filterMode = dataZoomModel.get('filterMode');
  38383. var valueWindow = this._valueWindow;
  38384. if (filterMode === 'none') {
  38385. return;
  38386. }
  38387. // FIXME
  38388. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  38389. // with NaN data, NaN will be filtered and stack will be wrong.
  38390. // So we need to force the mode to be set empty.
  38391. // In fect, it is not a big deal that do not support filterMode-'filter'
  38392. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  38393. // selection" some day, which might need "adapt to data extent on the
  38394. // otherAxis", which is disabled by filterMode-'empty'.
  38395. var otherAxisModel = this.getOtherAxisModel();
  38396. if (dataZoomModel.get('$fromToolbox')
  38397. && otherAxisModel
  38398. && otherAxisModel.hasSeriesStacked
  38399. ) {
  38400. filterMode = 'empty';
  38401. }
  38402. // TODO
  38403. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  38404. // Process series data
  38405. each$14(seriesModels, function (seriesModel) {
  38406. var seriesData = seriesModel.getData();
  38407. var dataDims = seriesData.mapDimension(axisDim, true);
  38408. if (filterMode === 'weakFilter') {
  38409. seriesData.filterSelf(function (dataIndex) {
  38410. var leftOut;
  38411. var rightOut;
  38412. var hasValue;
  38413. for (var i = 0; i < dataDims.length; i++) {
  38414. var value = seriesData.get(dataDims[i], dataIndex);
  38415. var thisHasValue = !isNaN(value);
  38416. var thisLeftOut = value < valueWindow[0];
  38417. var thisRightOut = value > valueWindow[1];
  38418. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  38419. return true;
  38420. }
  38421. thisHasValue && (hasValue = true);
  38422. thisLeftOut && (leftOut = true);
  38423. thisRightOut && (rightOut = true);
  38424. }
  38425. // If both left out and right out, do not filter.
  38426. return hasValue && leftOut && rightOut;
  38427. });
  38428. }
  38429. else {
  38430. each$14(dataDims, function (dim) {
  38431. if (filterMode === 'empty') {
  38432. seriesModel.setData(
  38433. seriesData.map(dim, function (value) {
  38434. return !isInWindow(value) ? NaN : value;
  38435. })
  38436. );
  38437. }
  38438. else {
  38439. var range = {};
  38440. range[dim] = valueWindow;
  38441. // console.time('select');
  38442. seriesData.selectRange(range);
  38443. // console.timeEnd('select');
  38444. }
  38445. });
  38446. }
  38447. each$14(dataDims, function (dim) {
  38448. seriesData.setApproximateExtent(valueWindow, dim);
  38449. });
  38450. });
  38451. function isInWindow(value) {
  38452. return value >= valueWindow[0] && value <= valueWindow[1];
  38453. }
  38454. }
  38455. };
  38456. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  38457. var dataExtent = [Infinity, -Infinity];
  38458. each$14(seriesModels, function (seriesModel) {
  38459. var seriesData = seriesModel.getData();
  38460. if (seriesData) {
  38461. each$14(seriesData.mapDimension(axisDim, true), function (dim) {
  38462. var seriesExtent = seriesData.getApproximateExtent(dim);
  38463. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  38464. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  38465. });
  38466. }
  38467. });
  38468. if (dataExtent[1] < dataExtent[0]) {
  38469. dataExtent = [NaN, NaN];
  38470. }
  38471. // It is important to get "consistent" extent when more then one axes is
  38472. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  38473. // when zooming. But it is difficult to know what is "consistent", considering
  38474. // axes have different type or even different meanings (For example, two
  38475. // time axes are used to compare data of the same date in different years).
  38476. // So basically dataZoom just obtains extent by series.data (in category axis
  38477. // extent can be obtained from axis.data).
  38478. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  38479. // consistent.
  38480. fixExtentByAxis(axisProxy, dataExtent);
  38481. return dataExtent;
  38482. }
  38483. function fixExtentByAxis(axisProxy, dataExtent) {
  38484. var axisModel = axisProxy.getAxisModel();
  38485. var min = axisModel.getMin(true);
  38486. // For category axis, if min/max/scale are not set, extent is determined
  38487. // by axis.data by default.
  38488. var isCategoryAxis = axisModel.get('type') === 'category';
  38489. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  38490. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  38491. dataExtent[0] = min;
  38492. }
  38493. else if (isCategoryAxis) {
  38494. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  38495. }
  38496. var max = axisModel.getMax(true);
  38497. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  38498. dataExtent[1] = max;
  38499. }
  38500. else if (isCategoryAxis) {
  38501. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  38502. }
  38503. if (!axisModel.get('scale', true)) {
  38504. dataExtent[0] > 0 && (dataExtent[0] = 0);
  38505. dataExtent[1] < 0 && (dataExtent[1] = 0);
  38506. }
  38507. // For value axis, if min/max/scale are not set, we just use the extent obtained
  38508. // by series data, which may be a little different from the extent calculated by
  38509. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  38510. // little when zooming. So it will not be fixed until some users require it strongly.
  38511. return dataExtent;
  38512. }
  38513. function setAxisModel(axisProxy, isRestore) {
  38514. var axisModel = axisProxy.getAxisModel();
  38515. var percentWindow = axisProxy._percentWindow;
  38516. var valueWindow = axisProxy._valueWindow;
  38517. if (!percentWindow) {
  38518. return;
  38519. }
  38520. // [0, 500]: arbitrary value, guess axis extent.
  38521. var precision = getPixelPrecision(valueWindow, [0, 500]);
  38522. precision = Math.min(precision, 20);
  38523. // isRestore or isFull
  38524. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  38525. axisModel.setRange(
  38526. useOrigin ? null : +valueWindow[0].toFixed(precision),
  38527. useOrigin ? null : +valueWindow[1].toFixed(precision)
  38528. );
  38529. }
  38530. function setMinMaxSpan(axisProxy) {
  38531. var minMaxSpan = axisProxy._minMaxSpan = {};
  38532. var dataZoomModel = axisProxy._dataZoomModel;
  38533. each$14(['min', 'max'], function (minMax) {
  38534. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  38535. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  38536. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  38537. if (valueSpan != null) {
  38538. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  38539. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  38540. if (valueSpan != null) {
  38541. var dataExtent = axisProxy._dataExtent;
  38542. minMaxSpan[minMax + 'Span'] = linearMap(
  38543. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  38544. );
  38545. }
  38546. }
  38547. });
  38548. }
  38549. var each$13 = each$1;
  38550. var eachAxisDim = eachAxisDim$1;
  38551. var DataZoomModel = extendComponentModel({
  38552. type: 'dataZoom',
  38553. dependencies: [
  38554. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  38555. ],
  38556. /**
  38557. * @protected
  38558. */
  38559. defaultOption: {
  38560. zlevel: 0,
  38561. z: 4, // Higher than normal component (z: 2).
  38562. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  38563. xAxisIndex: null, // Default the first horizontal category axis.
  38564. yAxisIndex: null, // Default the first vertical category axis.
  38565. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  38566. // 'filter': data items which are out of window will be removed. This option is
  38567. // applicable when filtering outliers. For each data item, it will be
  38568. // filtered if one of the relevant dimensions is out of the window.
  38569. // 'weakFilter': data items which are out of window will be removed. This option
  38570. // is applicable when filtering outliers. For each data item, it will be
  38571. // filtered only if all of the relevant dimensions are out of the same
  38572. // side of the window.
  38573. // 'empty': data items which are out of window will be set to empty.
  38574. // This option is applicable when user should not neglect
  38575. // that there are some data items out of window.
  38576. // 'none': Do not filter.
  38577. // Taking line chart as an example, line will be broken in
  38578. // the filtered points when filterModel is set to 'empty', but
  38579. // be connected when set to 'filter'.
  38580. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  38581. // default 100. Do not throttle when use null/undefined.
  38582. // If animation === true and animationDurationUpdate > 0,
  38583. // default value is 100, otherwise 20.
  38584. start: 0, // Start percent. 0 ~ 100
  38585. end: 100, // End percent. 0 ~ 100
  38586. startValue: null, // Start value. If startValue specified, start is ignored.
  38587. endValue: null, // End value. If endValue specified, end is ignored.
  38588. minSpan: null, // 0 ~ 100
  38589. maxSpan: null, // 0 ~ 100
  38590. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  38591. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  38592. rangeMode: null // Array, can be 'value' or 'percent'.
  38593. },
  38594. /**
  38595. * @override
  38596. */
  38597. init: function (option, parentModel, ecModel) {
  38598. /**
  38599. * key like x_0, y_1
  38600. * @private
  38601. * @type {Object}
  38602. */
  38603. this._dataIntervalByAxis = {};
  38604. /**
  38605. * @private
  38606. */
  38607. this._dataInfo = {};
  38608. /**
  38609. * key like x_0, y_1
  38610. * @private
  38611. */
  38612. this._axisProxies = {};
  38613. /**
  38614. * @readOnly
  38615. */
  38616. this.textStyleModel;
  38617. /**
  38618. * @private
  38619. */
  38620. this._autoThrottle = true;
  38621. /**
  38622. * 'percent' or 'value'
  38623. * @private
  38624. */
  38625. this._rangePropMode = ['percent', 'percent'];
  38626. var rawOption = retrieveRaw(option);
  38627. this.mergeDefaultAndTheme(option, ecModel);
  38628. this.doInit(rawOption);
  38629. },
  38630. /**
  38631. * @override
  38632. */
  38633. mergeOption: function (newOption) {
  38634. var rawOption = retrieveRaw(newOption);
  38635. //FIX #2591
  38636. merge(this.option, newOption, true);
  38637. this.doInit(rawOption);
  38638. },
  38639. /**
  38640. * @protected
  38641. */
  38642. doInit: function (rawOption) {
  38643. var thisOption = this.option;
  38644. // Disable realtime view update if canvas is not supported.
  38645. if (!env$1.canvasSupported) {
  38646. thisOption.realtime = false;
  38647. }
  38648. this._setDefaultThrottle(rawOption);
  38649. updateRangeUse(this, rawOption);
  38650. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  38651. // start/end has higher priority over startValue/endValue if they
  38652. // both set, but we should make chart.setOption({endValue: 1000})
  38653. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  38654. if (this._rangePropMode[index] === 'value') {
  38655. thisOption[names[0]] = null;
  38656. }
  38657. // Otherwise do nothing and use the merge result.
  38658. }, this);
  38659. this.textStyleModel = this.getModel('textStyle');
  38660. this._resetTarget();
  38661. this._giveAxisProxies();
  38662. },
  38663. /**
  38664. * @private
  38665. */
  38666. _giveAxisProxies: function () {
  38667. var axisProxies = this._axisProxies;
  38668. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  38669. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  38670. // If exists, share axisProxy with other dataZoomModels.
  38671. var axisProxy = axisModel.__dzAxisProxy || (
  38672. // Use the first dataZoomModel as the main model of axisProxy.
  38673. axisModel.__dzAxisProxy = new AxisProxy(
  38674. dimNames.name, axisIndex, this, ecModel
  38675. )
  38676. );
  38677. // FIXME
  38678. // dispose __dzAxisProxy
  38679. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  38680. }, this);
  38681. },
  38682. /**
  38683. * @private
  38684. */
  38685. _resetTarget: function () {
  38686. var thisOption = this.option;
  38687. var autoMode = this._judgeAutoMode();
  38688. eachAxisDim(function (dimNames) {
  38689. var axisIndexName = dimNames.axisIndex;
  38690. thisOption[axisIndexName] = normalizeToArray(
  38691. thisOption[axisIndexName]
  38692. );
  38693. }, this);
  38694. if (autoMode === 'axisIndex') {
  38695. this._autoSetAxisIndex();
  38696. }
  38697. else if (autoMode === 'orient') {
  38698. this._autoSetOrient();
  38699. }
  38700. },
  38701. /**
  38702. * @private
  38703. */
  38704. _judgeAutoMode: function () {
  38705. // Auto set only works for setOption at the first time.
  38706. // The following is user's reponsibility. So using merged
  38707. // option is OK.
  38708. var thisOption = this.option;
  38709. var hasIndexSpecified = false;
  38710. eachAxisDim(function (dimNames) {
  38711. // When user set axisIndex as a empty array, we think that user specify axisIndex
  38712. // but do not want use auto mode. Because empty array may be encountered when
  38713. // some error occured.
  38714. if (thisOption[dimNames.axisIndex] != null) {
  38715. hasIndexSpecified = true;
  38716. }
  38717. }, this);
  38718. var orient = thisOption.orient;
  38719. if (orient == null && hasIndexSpecified) {
  38720. return 'orient';
  38721. }
  38722. else if (!hasIndexSpecified) {
  38723. if (orient == null) {
  38724. thisOption.orient = 'horizontal';
  38725. }
  38726. return 'axisIndex';
  38727. }
  38728. },
  38729. /**
  38730. * @private
  38731. */
  38732. _autoSetAxisIndex: function () {
  38733. var autoAxisIndex = true;
  38734. var orient = this.get('orient', true);
  38735. var thisOption = this.option;
  38736. var dependentModels = this.dependentModels;
  38737. if (autoAxisIndex) {
  38738. // Find axis that parallel to dataZoom as default.
  38739. var dimName = orient === 'vertical' ? 'y' : 'x';
  38740. if (dependentModels[dimName + 'Axis'].length) {
  38741. thisOption[dimName + 'AxisIndex'] = [0];
  38742. autoAxisIndex = false;
  38743. }
  38744. else {
  38745. each$13(dependentModels.singleAxis, function (singleAxisModel) {
  38746. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  38747. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  38748. autoAxisIndex = false;
  38749. }
  38750. });
  38751. }
  38752. }
  38753. if (autoAxisIndex) {
  38754. // Find the first category axis as default. (consider polar)
  38755. eachAxisDim(function (dimNames) {
  38756. if (!autoAxisIndex) {
  38757. return;
  38758. }
  38759. var axisIndices = [];
  38760. var axisModels = this.dependentModels[dimNames.axis];
  38761. if (axisModels.length && !axisIndices.length) {
  38762. for (var i = 0, len = axisModels.length; i < len; i++) {
  38763. if (axisModels[i].get('type') === 'category') {
  38764. axisIndices.push(i);
  38765. }
  38766. }
  38767. }
  38768. thisOption[dimNames.axisIndex] = axisIndices;
  38769. if (axisIndices.length) {
  38770. autoAxisIndex = false;
  38771. }
  38772. }, this);
  38773. }
  38774. if (autoAxisIndex) {
  38775. // FIXME
  38776. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  38777. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  38778. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  38779. // dataZoom component auto adopts series that reference to
  38780. // both xAxis and yAxis which type is 'value'.
  38781. this.ecModel.eachSeries(function (seriesModel) {
  38782. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  38783. eachAxisDim(function (dimNames) {
  38784. var axisIndices = thisOption[dimNames.axisIndex];
  38785. var axisIndex = seriesModel.get(dimNames.axisIndex);
  38786. var axisId = seriesModel.get(dimNames.axisId);
  38787. var axisModel = seriesModel.ecModel.queryComponents({
  38788. mainType: dimNames.axis,
  38789. index: axisIndex,
  38790. id: axisId
  38791. })[0];
  38792. if (__DEV__) {
  38793. if (!axisModel) {
  38794. throw new Error(
  38795. dimNames.axis + ' "' + retrieve(
  38796. axisIndex,
  38797. axisId,
  38798. 0
  38799. ) + '" not found'
  38800. );
  38801. }
  38802. }
  38803. axisIndex = axisModel.componentIndex;
  38804. if (indexOf(axisIndices, axisIndex) < 0) {
  38805. axisIndices.push(axisIndex);
  38806. }
  38807. });
  38808. }
  38809. }, this);
  38810. }
  38811. },
  38812. /**
  38813. * @private
  38814. */
  38815. _autoSetOrient: function () {
  38816. var dim;
  38817. // Find the first axis
  38818. this.eachTargetAxis(function (dimNames) {
  38819. !dim && (dim = dimNames.name);
  38820. }, this);
  38821. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  38822. },
  38823. /**
  38824. * @private
  38825. */
  38826. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  38827. // FIXME
  38828. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  38829. // 例如series.type === scatter时。
  38830. var is = true;
  38831. eachAxisDim(function (dimNames) {
  38832. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  38833. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  38834. if (!axisModel || axisModel.get('type') !== axisType) {
  38835. is = false;
  38836. }
  38837. }, this);
  38838. return is;
  38839. },
  38840. /**
  38841. * @private
  38842. */
  38843. _setDefaultThrottle: function (rawOption) {
  38844. // When first time user set throttle, auto throttle ends.
  38845. if (rawOption.hasOwnProperty('throttle')) {
  38846. this._autoThrottle = false;
  38847. }
  38848. if (this._autoThrottle) {
  38849. var globalOption = this.ecModel.option;
  38850. this.option.throttle =
  38851. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  38852. ? 100 : 20;
  38853. }
  38854. },
  38855. /**
  38856. * @public
  38857. */
  38858. getFirstTargetAxisModel: function () {
  38859. var firstAxisModel;
  38860. eachAxisDim(function (dimNames) {
  38861. if (firstAxisModel == null) {
  38862. var indices = this.get(dimNames.axisIndex);
  38863. if (indices.length) {
  38864. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  38865. }
  38866. }
  38867. }, this);
  38868. return firstAxisModel;
  38869. },
  38870. /**
  38871. * @public
  38872. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  38873. */
  38874. eachTargetAxis: function (callback, context) {
  38875. var ecModel = this.ecModel;
  38876. eachAxisDim(function (dimNames) {
  38877. each$13(
  38878. this.get(dimNames.axisIndex),
  38879. function (axisIndex) {
  38880. callback.call(context, dimNames, axisIndex, this, ecModel);
  38881. },
  38882. this
  38883. );
  38884. }, this);
  38885. },
  38886. /**
  38887. * @param {string} dimName
  38888. * @param {number} axisIndex
  38889. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  38890. */
  38891. getAxisProxy: function (dimName, axisIndex) {
  38892. return this._axisProxies[dimName + '_' + axisIndex];
  38893. },
  38894. /**
  38895. * @param {string} dimName
  38896. * @param {number} axisIndex
  38897. * @return {module:echarts/model/Model} If not found, return null/undefined.
  38898. */
  38899. getAxisModel: function (dimName, axisIndex) {
  38900. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  38901. return axisProxy && axisProxy.getAxisModel();
  38902. },
  38903. /**
  38904. * If not specified, set to undefined.
  38905. *
  38906. * @public
  38907. * @param {Object} opt
  38908. * @param {number} [opt.start]
  38909. * @param {number} [opt.end]
  38910. * @param {number} [opt.startValue]
  38911. * @param {number} [opt.endValue]
  38912. * @param {boolean} [ignoreUpdateRangeUsg=false]
  38913. */
  38914. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  38915. var option = this.option;
  38916. each$13([['start', 'startValue'], ['end', 'endValue']], function (names) {
  38917. // If only one of 'start' and 'startValue' is not null/undefined, the other
  38918. // should be cleared, which enable clear the option.
  38919. // If both of them are not set, keep option with the original value, which
  38920. // enable use only set start but not set end when calling `dispatchAction`.
  38921. // The same as 'end' and 'endValue'.
  38922. if (opt[names[0]] != null || opt[names[1]] != null) {
  38923. option[names[0]] = opt[names[0]];
  38924. option[names[1]] = opt[names[1]];
  38925. }
  38926. }, this);
  38927. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  38928. },
  38929. /**
  38930. * @public
  38931. * @return {Array.<number>} [startPercent, endPercent]
  38932. */
  38933. getPercentRange: function () {
  38934. var axisProxy = this.findRepresentativeAxisProxy();
  38935. if (axisProxy) {
  38936. return axisProxy.getDataPercentWindow();
  38937. }
  38938. },
  38939. /**
  38940. * @public
  38941. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  38942. *
  38943. * @param {string} [axisDimName]
  38944. * @param {number} [axisIndex]
  38945. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  38946. */
  38947. getValueRange: function (axisDimName, axisIndex) {
  38948. if (axisDimName == null && axisIndex == null) {
  38949. var axisProxy = this.findRepresentativeAxisProxy();
  38950. if (axisProxy) {
  38951. return axisProxy.getDataValueWindow();
  38952. }
  38953. }
  38954. else {
  38955. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  38956. }
  38957. },
  38958. /**
  38959. * @public
  38960. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  38961. * corresponding to the axisModel
  38962. * @return {module:echarts/component/dataZoom/AxisProxy}
  38963. */
  38964. findRepresentativeAxisProxy: function (axisModel) {
  38965. if (axisModel) {
  38966. return axisModel.__dzAxisProxy;
  38967. }
  38968. // Find the first hosted axisProxy
  38969. var axisProxies = this._axisProxies;
  38970. for (var key in axisProxies) {
  38971. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  38972. return axisProxies[key];
  38973. }
  38974. }
  38975. // If no hosted axis find not hosted axisProxy.
  38976. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  38977. // and the option.start or option.end settings are different. The percentRange
  38978. // should follow axisProxy.
  38979. // (We encounter this problem in toolbox data zoom.)
  38980. for (var key in axisProxies) {
  38981. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  38982. return axisProxies[key];
  38983. }
  38984. }
  38985. },
  38986. /**
  38987. * @return {Array.<string>}
  38988. */
  38989. getRangePropMode: function () {
  38990. return this._rangePropMode.slice();
  38991. }
  38992. });
  38993. function retrieveRaw(option) {
  38994. var ret = {};
  38995. each$13(
  38996. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  38997. function (name) {
  38998. option.hasOwnProperty(name) && (ret[name] = option[name]);
  38999. }
  39000. );
  39001. return ret;
  39002. }
  39003. function updateRangeUse(dataZoomModel, rawOption) {
  39004. var rangePropMode = dataZoomModel._rangePropMode;
  39005. var rangeModeInOption = dataZoomModel.get('rangeMode');
  39006. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  39007. var percentSpecified = rawOption[names[0]] != null;
  39008. var valueSpecified = rawOption[names[1]] != null;
  39009. if (percentSpecified && !valueSpecified) {
  39010. rangePropMode[index] = 'percent';
  39011. }
  39012. else if (!percentSpecified && valueSpecified) {
  39013. rangePropMode[index] = 'value';
  39014. }
  39015. else if (rangeModeInOption) {
  39016. rangePropMode[index] = rangeModeInOption[index];
  39017. }
  39018. else if (percentSpecified) { // percentSpecified && valueSpecified
  39019. rangePropMode[index] = 'percent';
  39020. }
  39021. // else remain its original setting.
  39022. });
  39023. }
  39024. var DataZoomView = Component$1.extend({
  39025. type: 'dataZoom',
  39026. render: function (dataZoomModel, ecModel, api, payload) {
  39027. this.dataZoomModel = dataZoomModel;
  39028. this.ecModel = ecModel;
  39029. this.api = api;
  39030. },
  39031. /**
  39032. * Find the first target coordinate system.
  39033. *
  39034. * @protected
  39035. * @return {Object} {
  39036. * grid: [
  39037. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  39038. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  39039. * ...
  39040. * ], // cartesians must not be null/undefined.
  39041. * polar: [
  39042. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  39043. * ...
  39044. * ], // polars must not be null/undefined.
  39045. * singleAxis: [
  39046. * {model: coord0, axisModels: [], coordIndex: 0}
  39047. * ]
  39048. */
  39049. getTargetCoordInfo: function () {
  39050. var dataZoomModel = this.dataZoomModel;
  39051. var ecModel = this.ecModel;
  39052. var coordSysLists = {};
  39053. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  39054. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  39055. if (axisModel) {
  39056. var coordModel = axisModel.getCoordSysModel();
  39057. coordModel && save(
  39058. coordModel,
  39059. axisModel,
  39060. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  39061. coordModel.componentIndex
  39062. );
  39063. }
  39064. }, this);
  39065. function save(coordModel, axisModel, store, coordIndex) {
  39066. var item;
  39067. for (var i = 0; i < store.length; i++) {
  39068. if (store[i].model === coordModel) {
  39069. item = store[i];
  39070. break;
  39071. }
  39072. }
  39073. if (!item) {
  39074. store.push(item = {
  39075. model: coordModel, axisModels: [], coordIndex: coordIndex
  39076. });
  39077. }
  39078. item.axisModels.push(axisModel);
  39079. }
  39080. return coordSysLists;
  39081. }
  39082. });
  39083. var SliderZoomModel = DataZoomModel.extend({
  39084. type: 'dataZoom.slider',
  39085. layoutMode: 'box',
  39086. /**
  39087. * @protected
  39088. */
  39089. defaultOption: {
  39090. show: true,
  39091. // ph => placeholder. Using placehoder here because
  39092. // deault value can only be drived in view stage.
  39093. right: 'ph', // Default align to grid rect.
  39094. top: 'ph', // Default align to grid rect.
  39095. width: 'ph', // Default align to grid rect.
  39096. height: 'ph', // Default align to grid rect.
  39097. left: null, // Default align to grid rect.
  39098. bottom: null, // Default align to grid rect.
  39099. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  39100. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  39101. // highest priority, remain for compatibility of
  39102. // previous version, but not recommended any more.
  39103. dataBackground: {
  39104. lineStyle: {
  39105. color: '#2f4554',
  39106. width: 0.5,
  39107. opacity: 0.3
  39108. },
  39109. areaStyle: {
  39110. color: 'rgba(47,69,84,0.3)',
  39111. opacity: 0.3
  39112. }
  39113. },
  39114. borderColor: '#ddd', // border color of the box. For compatibility,
  39115. // if dataBackgroundColor is set, borderColor
  39116. // is ignored.
  39117. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  39118. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  39119. // 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',
  39120. 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',
  39121. // Percent of the slider height
  39122. handleSize: '100%',
  39123. handleStyle: {
  39124. color: '#a7b7cc'
  39125. },
  39126. labelPrecision: null,
  39127. labelFormatter: null,
  39128. showDetail: true,
  39129. showDataShadow: 'auto', // Default auto decision.
  39130. realtime: true,
  39131. zoomLock: false, // Whether disable zoom.
  39132. textStyle: {
  39133. color: '#333'
  39134. }
  39135. }
  39136. });
  39137. /**
  39138. * Calculate slider move result.
  39139. * Usage:
  39140. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  39141. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  39142. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  39143. *
  39144. * @param {number} delta Move length.
  39145. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  39146. * handleEnds will be modified in this method.
  39147. * @param {Array.<number>} extent handleEnds is restricted by extent.
  39148. * extent[0] should less or equals than extent[1].
  39149. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  39150. * where the input minSpan and maxSpan will not work.
  39151. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  39152. * If not set, handle0 and cross handle1. If set as a non-negative
  39153. * number (including `0`), handles will push each other when reaching
  39154. * the minSpan.
  39155. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  39156. * @return {Array.<number>} The input handleEnds.
  39157. */
  39158. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  39159. // Normalize firstly.
  39160. handleEnds[0] = restrict(handleEnds[0], extent);
  39161. handleEnds[1] = restrict(handleEnds[1], extent);
  39162. delta = delta || 0;
  39163. var extentSpan = extent[1] - extent[0];
  39164. // Notice maxSpan and minSpan can be null/undefined.
  39165. if (minSpan != null) {
  39166. minSpan = restrict(minSpan, [0, extentSpan]);
  39167. }
  39168. if (maxSpan != null) {
  39169. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  39170. }
  39171. if (handleIndex === 'all') {
  39172. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  39173. handleIndex = 0;
  39174. }
  39175. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  39176. handleEnds[handleIndex] += delta;
  39177. // Restrict in extent.
  39178. var extentMinSpan = minSpan || 0;
  39179. var realExtent = extent.slice();
  39180. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  39181. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  39182. // Expand span.
  39183. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39184. if (minSpan != null && (
  39185. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  39186. )) {
  39187. // If minSpan exists, 'cross' is forbinden.
  39188. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  39189. }
  39190. // Shrink span.
  39191. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39192. if (maxSpan != null && currDistSign.span > maxSpan) {
  39193. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  39194. }
  39195. return handleEnds;
  39196. };
  39197. function getSpanSign(handleEnds, handleIndex) {
  39198. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  39199. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  39200. // is at left of handleEnds[1] for non-cross case.
  39201. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  39202. }
  39203. function restrict(value, extend) {
  39204. return Math.min(extend[1], Math.max(extend[0], value));
  39205. }
  39206. var Rect$1 = Rect;
  39207. var linearMap$2 = linearMap;
  39208. var asc$2 = asc;
  39209. var bind$3 = bind;
  39210. var each$15 = each$1;
  39211. // Constants
  39212. var DEFAULT_LOCATION_EDGE_GAP = 7;
  39213. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  39214. var DEFAULT_FILLER_SIZE = 30;
  39215. var HORIZONTAL = 'horizontal';
  39216. var VERTICAL = 'vertical';
  39217. var LABEL_GAP = 5;
  39218. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  39219. var SliderZoomView = DataZoomView.extend({
  39220. type: 'dataZoom.slider',
  39221. init: function (ecModel, api) {
  39222. /**
  39223. * @private
  39224. * @type {Object}
  39225. */
  39226. this._displayables = {};
  39227. /**
  39228. * @private
  39229. * @type {string}
  39230. */
  39231. this._orient;
  39232. /**
  39233. * [0, 100]
  39234. * @private
  39235. */
  39236. this._range;
  39237. /**
  39238. * [coord of the first handle, coord of the second handle]
  39239. * @private
  39240. */
  39241. this._handleEnds;
  39242. /**
  39243. * [length, thick]
  39244. * @private
  39245. * @type {Array.<number>}
  39246. */
  39247. this._size;
  39248. /**
  39249. * @private
  39250. * @type {number}
  39251. */
  39252. this._handleWidth;
  39253. /**
  39254. * @private
  39255. * @type {number}
  39256. */
  39257. this._handleHeight;
  39258. /**
  39259. * @private
  39260. */
  39261. this._location;
  39262. /**
  39263. * @private
  39264. */
  39265. this._dragging;
  39266. /**
  39267. * @private
  39268. */
  39269. this._dataShadowInfo;
  39270. this.api = api;
  39271. },
  39272. /**
  39273. * @override
  39274. */
  39275. render: function (dataZoomModel, ecModel, api, payload) {
  39276. SliderZoomView.superApply(this, 'render', arguments);
  39277. createOrUpdate(
  39278. this,
  39279. '_dispatchZoomAction',
  39280. this.dataZoomModel.get('throttle'),
  39281. 'fixRate'
  39282. );
  39283. this._orient = dataZoomModel.get('orient');
  39284. if (this.dataZoomModel.get('show') === false) {
  39285. this.group.removeAll();
  39286. return;
  39287. }
  39288. // Notice: this._resetInterval() should not be executed when payload.type
  39289. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  39290. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  39291. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  39292. this._buildView();
  39293. }
  39294. this._updateView();
  39295. },
  39296. /**
  39297. * @override
  39298. */
  39299. remove: function () {
  39300. SliderZoomView.superApply(this, 'remove', arguments);
  39301. clear(this, '_dispatchZoomAction');
  39302. },
  39303. /**
  39304. * @override
  39305. */
  39306. dispose: function () {
  39307. SliderZoomView.superApply(this, 'dispose', arguments);
  39308. clear(this, '_dispatchZoomAction');
  39309. },
  39310. _buildView: function () {
  39311. var thisGroup = this.group;
  39312. thisGroup.removeAll();
  39313. this._resetLocation();
  39314. this._resetInterval();
  39315. var barGroup = this._displayables.barGroup = new Group();
  39316. this._renderBackground();
  39317. this._renderHandle();
  39318. this._renderDataShadow();
  39319. thisGroup.add(barGroup);
  39320. this._positionGroup();
  39321. },
  39322. /**
  39323. * @private
  39324. */
  39325. _resetLocation: function () {
  39326. var dataZoomModel = this.dataZoomModel;
  39327. var api = this.api;
  39328. // If some of x/y/width/height are not specified,
  39329. // auto-adapt according to target grid.
  39330. var coordRect = this._findCoordRect();
  39331. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  39332. // Default align by coordinate system rect.
  39333. var positionInfo = this._orient === HORIZONTAL
  39334. ? {
  39335. // Why using 'right', because right should be used in vertical,
  39336. // and it is better to be consistent for dealing with position param merge.
  39337. right: ecSize.width - coordRect.x - coordRect.width,
  39338. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  39339. width: coordRect.width,
  39340. height: DEFAULT_FILLER_SIZE
  39341. }
  39342. : { // vertical
  39343. right: DEFAULT_LOCATION_EDGE_GAP,
  39344. top: coordRect.y,
  39345. width: DEFAULT_FILLER_SIZE,
  39346. height: coordRect.height
  39347. };
  39348. // Do not write back to option and replace value 'ph', because
  39349. // the 'ph' value should be recalculated when resize.
  39350. var layoutParams = getLayoutParams(dataZoomModel.option);
  39351. // Replace the placeholder value.
  39352. each$1(['right', 'top', 'width', 'height'], function (name) {
  39353. if (layoutParams[name] === 'ph') {
  39354. layoutParams[name] = positionInfo[name];
  39355. }
  39356. });
  39357. var layoutRect = getLayoutRect(
  39358. layoutParams,
  39359. ecSize,
  39360. dataZoomModel.padding
  39361. );
  39362. this._location = {x: layoutRect.x, y: layoutRect.y};
  39363. this._size = [layoutRect.width, layoutRect.height];
  39364. this._orient === VERTICAL && this._size.reverse();
  39365. },
  39366. /**
  39367. * @private
  39368. */
  39369. _positionGroup: function () {
  39370. var thisGroup = this.group;
  39371. var location = this._location;
  39372. var orient = this._orient;
  39373. // Just use the first axis to determine mapping.
  39374. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  39375. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  39376. var barGroup = this._displayables.barGroup;
  39377. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  39378. // Transform barGroup.
  39379. barGroup.attr(
  39380. (orient === HORIZONTAL && !inverse)
  39381. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  39382. : (orient === HORIZONTAL && inverse)
  39383. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  39384. : (orient === VERTICAL && !inverse)
  39385. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  39386. // Dont use Math.PI, considering shadow direction.
  39387. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  39388. );
  39389. // Position barGroup
  39390. var rect = thisGroup.getBoundingRect([barGroup]);
  39391. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  39392. },
  39393. /**
  39394. * @private
  39395. */
  39396. _getViewExtent: function () {
  39397. return [0, this._size[0]];
  39398. },
  39399. _renderBackground: function () {
  39400. var dataZoomModel = this.dataZoomModel;
  39401. var size = this._size;
  39402. var barGroup = this._displayables.barGroup;
  39403. barGroup.add(new Rect$1({
  39404. silent: true,
  39405. shape: {
  39406. x: 0, y: 0, width: size[0], height: size[1]
  39407. },
  39408. style: {
  39409. fill: dataZoomModel.get('backgroundColor')
  39410. },
  39411. z2: -40
  39412. }));
  39413. // Click panel, over shadow, below handles.
  39414. barGroup.add(new Rect$1({
  39415. shape: {
  39416. x: 0, y: 0, width: size[0], height: size[1]
  39417. },
  39418. style: {
  39419. fill: 'transparent'
  39420. },
  39421. z2: 0,
  39422. onclick: bind(this._onClickPanelClick, this)
  39423. }));
  39424. },
  39425. _renderDataShadow: function () {
  39426. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  39427. if (!info) {
  39428. return;
  39429. }
  39430. var size = this._size;
  39431. var seriesModel = info.series;
  39432. var data = seriesModel.getRawData();
  39433. var otherDim = seriesModel.getShadowDim
  39434. ? seriesModel.getShadowDim() // @see candlestick
  39435. : info.otherDim;
  39436. if (otherDim == null) {
  39437. return;
  39438. }
  39439. var otherDataExtent = data.getDataExtent(otherDim);
  39440. // Nice extent.
  39441. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  39442. otherDataExtent = [
  39443. otherDataExtent[0] - otherOffset,
  39444. otherDataExtent[1] + otherOffset
  39445. ];
  39446. var otherShadowExtent = [0, size[1]];
  39447. var thisShadowExtent = [0, size[0]];
  39448. var areaPoints = [[size[0], 0], [0, 0]];
  39449. var linePoints = [];
  39450. var step = thisShadowExtent[1] / (data.count() - 1);
  39451. var thisCoord = 0;
  39452. // Optimize for large data shadow
  39453. var stride = Math.round(data.count() / size[0]);
  39454. var lastIsEmpty;
  39455. data.each([otherDim], function (value, index) {
  39456. if (stride > 0 && (index % stride)) {
  39457. thisCoord += step;
  39458. return;
  39459. }
  39460. // FIXME
  39461. // Should consider axis.min/axis.max when drawing dataShadow.
  39462. // FIXME
  39463. // 应该使用统一的空判断?还是在list里进行空判断?
  39464. var isEmpty = value == null || isNaN(value) || value === '';
  39465. // See #4235.
  39466. var otherCoord = isEmpty
  39467. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  39468. // Attempt to draw data shadow precisely when there are empty value.
  39469. if (isEmpty && !lastIsEmpty && index) {
  39470. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  39471. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  39472. }
  39473. else if (!isEmpty && lastIsEmpty) {
  39474. areaPoints.push([thisCoord, 0]);
  39475. linePoints.push([thisCoord, 0]);
  39476. }
  39477. areaPoints.push([thisCoord, otherCoord]);
  39478. linePoints.push([thisCoord, otherCoord]);
  39479. thisCoord += step;
  39480. lastIsEmpty = isEmpty;
  39481. });
  39482. var dataZoomModel = this.dataZoomModel;
  39483. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  39484. this._displayables.barGroup.add(new Polygon({
  39485. shape: {points: areaPoints},
  39486. style: defaults(
  39487. {fill: dataZoomModel.get('dataBackgroundColor')},
  39488. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  39489. ),
  39490. silent: true,
  39491. z2: -20
  39492. }));
  39493. this._displayables.barGroup.add(new Polyline({
  39494. shape: {points: linePoints},
  39495. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  39496. silent: true,
  39497. z2: -19
  39498. }));
  39499. },
  39500. _prepareDataShadowInfo: function () {
  39501. var dataZoomModel = this.dataZoomModel;
  39502. var showDataShadow = dataZoomModel.get('showDataShadow');
  39503. if (showDataShadow === false) {
  39504. return;
  39505. }
  39506. // Find a representative series.
  39507. var result;
  39508. var ecModel = this.ecModel;
  39509. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  39510. var seriesModels = dataZoomModel
  39511. .getAxisProxy(dimNames.name, axisIndex)
  39512. .getTargetSeriesModels();
  39513. each$1(seriesModels, function (seriesModel) {
  39514. if (result) {
  39515. return;
  39516. }
  39517. if (showDataShadow !== true && indexOf(
  39518. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  39519. ) < 0
  39520. ) {
  39521. return;
  39522. }
  39523. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  39524. var otherDim = getOtherDim(dimNames.name);
  39525. var otherAxisInverse;
  39526. var coordSys = seriesModel.coordinateSystem;
  39527. if (otherDim != null && coordSys.getOtherAxis) {
  39528. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  39529. }
  39530. otherDim = seriesModel.getData().mapDimension(otherDim);
  39531. result = {
  39532. thisAxis: thisAxis,
  39533. series: seriesModel,
  39534. thisDim: dimNames.name,
  39535. otherDim: otherDim,
  39536. otherAxisInverse: otherAxisInverse
  39537. };
  39538. }, this);
  39539. }, this);
  39540. return result;
  39541. },
  39542. _renderHandle: function () {
  39543. var displaybles = this._displayables;
  39544. var handles = displaybles.handles = [];
  39545. var handleLabels = displaybles.handleLabels = [];
  39546. var barGroup = this._displayables.barGroup;
  39547. var size = this._size;
  39548. var dataZoomModel = this.dataZoomModel;
  39549. barGroup.add(displaybles.filler = new Rect$1({
  39550. draggable: true,
  39551. cursor: getCursor(this._orient),
  39552. drift: bind$3(this._onDragMove, this, 'all'),
  39553. onmousemove: function (e) {
  39554. // Fot mobile devicem, prevent screen slider on the button.
  39555. stop(e.event);
  39556. },
  39557. ondragstart: bind$3(this._showDataInfo, this, true),
  39558. ondragend: bind$3(this._onDragEnd, this),
  39559. onmouseover: bind$3(this._showDataInfo, this, true),
  39560. onmouseout: bind$3(this._showDataInfo, this, false),
  39561. style: {
  39562. fill: dataZoomModel.get('fillerColor'),
  39563. textPosition : 'inside'
  39564. }
  39565. }));
  39566. // Frame border.
  39567. barGroup.add(new Rect$1(subPixelOptimizeRect({
  39568. silent: true,
  39569. shape: {
  39570. x: 0,
  39571. y: 0,
  39572. width: size[0],
  39573. height: size[1]
  39574. },
  39575. style: {
  39576. stroke: dataZoomModel.get('dataBackgroundColor')
  39577. || dataZoomModel.get('borderColor'),
  39578. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  39579. fill: 'rgba(0,0,0,0)'
  39580. }
  39581. })));
  39582. each$15([0, 1], function (handleIndex) {
  39583. var path = createIcon(
  39584. dataZoomModel.get('handleIcon'),
  39585. {
  39586. cursor: getCursor(this._orient),
  39587. draggable: true,
  39588. drift: bind$3(this._onDragMove, this, handleIndex),
  39589. onmousemove: function (e) {
  39590. // Fot mobile devicem, prevent screen slider on the button.
  39591. stop(e.event);
  39592. },
  39593. ondragend: bind$3(this._onDragEnd, this),
  39594. onmouseover: bind$3(this._showDataInfo, this, true),
  39595. onmouseout: bind$3(this._showDataInfo, this, false)
  39596. },
  39597. {x: -1, y: 0, width: 2, height: 2}
  39598. );
  39599. var bRect = path.getBoundingRect();
  39600. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  39601. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  39602. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  39603. var handleColor = dataZoomModel.get('handleColor');
  39604. // Compatitable with previous version
  39605. if (handleColor != null) {
  39606. path.style.fill = handleColor;
  39607. }
  39608. barGroup.add(handles[handleIndex] = path);
  39609. var textStyleModel = dataZoomModel.textStyleModel;
  39610. this.group.add(
  39611. handleLabels[handleIndex] = new Text({
  39612. silent: true,
  39613. invisible: true,
  39614. style: {
  39615. x: 0, y: 0, text: '',
  39616. textVerticalAlign: 'middle',
  39617. textAlign: 'center',
  39618. textFill: textStyleModel.getTextColor(),
  39619. textFont: textStyleModel.getFont()
  39620. },
  39621. z2: 10
  39622. }));
  39623. }, this);
  39624. },
  39625. /**
  39626. * @private
  39627. */
  39628. _resetInterval: function () {
  39629. var range = this._range = this.dataZoomModel.getPercentRange();
  39630. var viewExtent = this._getViewExtent();
  39631. this._handleEnds = [
  39632. linearMap$2(range[0], [0, 100], viewExtent, true),
  39633. linearMap$2(range[1], [0, 100], viewExtent, true)
  39634. ];
  39635. },
  39636. /**
  39637. * @private
  39638. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  39639. * @param {number} delta
  39640. */
  39641. _updateInterval: function (handleIndex, delta) {
  39642. var dataZoomModel = this.dataZoomModel;
  39643. var handleEnds = this._handleEnds;
  39644. var viewExtend = this._getViewExtent();
  39645. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  39646. var percentExtent = [0, 100];
  39647. sliderMove(
  39648. delta,
  39649. handleEnds,
  39650. viewExtend,
  39651. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  39652. minMaxSpan.minSpan != null
  39653. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  39654. minMaxSpan.maxSpan != null
  39655. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  39656. );
  39657. this._range = asc$2([
  39658. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  39659. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  39660. ]);
  39661. },
  39662. /**
  39663. * @private
  39664. */
  39665. _updateView: function (nonRealtime) {
  39666. var displaybles = this._displayables;
  39667. var handleEnds = this._handleEnds;
  39668. var handleInterval = asc$2(handleEnds.slice());
  39669. var size = this._size;
  39670. each$15([0, 1], function (handleIndex) {
  39671. // Handles
  39672. var handle = displaybles.handles[handleIndex];
  39673. var handleHeight = this._handleHeight;
  39674. handle.attr({
  39675. scale: [handleHeight / 2, handleHeight / 2],
  39676. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  39677. });
  39678. }, this);
  39679. // Filler
  39680. displaybles.filler.setShape({
  39681. x: handleInterval[0],
  39682. y: 0,
  39683. width: handleInterval[1] - handleInterval[0],
  39684. height: size[1]
  39685. });
  39686. this._updateDataInfo(nonRealtime);
  39687. },
  39688. /**
  39689. * @private
  39690. */
  39691. _updateDataInfo: function (nonRealtime) {
  39692. var dataZoomModel = this.dataZoomModel;
  39693. var displaybles = this._displayables;
  39694. var handleLabels = displaybles.handleLabels;
  39695. var orient = this._orient;
  39696. var labelTexts = ['', ''];
  39697. // FIXME
  39698. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  39699. if (dataZoomModel.get('showDetail')) {
  39700. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  39701. if (axisProxy) {
  39702. var axis = axisProxy.getAxisModel().axis;
  39703. var range = this._range;
  39704. var dataInterval = nonRealtime
  39705. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  39706. ? axisProxy.calculateDataWindow({
  39707. start: range[0], end: range[1]
  39708. }).valueWindow
  39709. : axisProxy.getDataValueWindow();
  39710. labelTexts = [
  39711. this._formatLabel(dataInterval[0], axis),
  39712. this._formatLabel(dataInterval[1], axis)
  39713. ];
  39714. }
  39715. }
  39716. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  39717. setLabel.call(this, 0);
  39718. setLabel.call(this, 1);
  39719. function setLabel(handleIndex) {
  39720. // Label
  39721. // Text should not transform by barGroup.
  39722. // Ignore handlers transform
  39723. var barTransform = getTransform(
  39724. displaybles.handles[handleIndex].parent, this.group
  39725. );
  39726. var direction = transformDirection(
  39727. handleIndex === 0 ? 'right' : 'left', barTransform
  39728. );
  39729. var offset = this._handleWidth / 2 + LABEL_GAP;
  39730. var textPoint = applyTransform$1(
  39731. [
  39732. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  39733. this._size[1] / 2
  39734. ],
  39735. barTransform
  39736. );
  39737. handleLabels[handleIndex].setStyle({
  39738. x: textPoint[0],
  39739. y: textPoint[1],
  39740. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  39741. textAlign: orient === HORIZONTAL ? direction : 'center',
  39742. text: labelTexts[handleIndex]
  39743. });
  39744. }
  39745. },
  39746. /**
  39747. * @private
  39748. */
  39749. _formatLabel: function (value, axis) {
  39750. var dataZoomModel = this.dataZoomModel;
  39751. var labelFormatter = dataZoomModel.get('labelFormatter');
  39752. var labelPrecision = dataZoomModel.get('labelPrecision');
  39753. if (labelPrecision == null || labelPrecision === 'auto') {
  39754. labelPrecision = axis.getPixelPrecision();
  39755. }
  39756. var valueStr = (value == null || isNaN(value))
  39757. ? ''
  39758. // FIXME Glue code
  39759. : (axis.type === 'category' || axis.type === 'time')
  39760. ? axis.scale.getLabel(Math.round(value))
  39761. // param of toFixed should less then 20.
  39762. : value.toFixed(Math.min(labelPrecision, 20));
  39763. return isFunction$1(labelFormatter)
  39764. ? labelFormatter(value, valueStr)
  39765. : isString(labelFormatter)
  39766. ? labelFormatter.replace('{value}', valueStr)
  39767. : valueStr;
  39768. },
  39769. /**
  39770. * @private
  39771. * @param {boolean} showOrHide true: show, false: hide
  39772. */
  39773. _showDataInfo: function (showOrHide) {
  39774. // Always show when drgging.
  39775. showOrHide = this._dragging || showOrHide;
  39776. var handleLabels = this._displayables.handleLabels;
  39777. handleLabels[0].attr('invisible', !showOrHide);
  39778. handleLabels[1].attr('invisible', !showOrHide);
  39779. },
  39780. _onDragMove: function (handleIndex, dx, dy) {
  39781. this._dragging = true;
  39782. // Transform dx, dy to bar coordination.
  39783. var barTransform = this._displayables.barGroup.getLocalTransform();
  39784. var vertex = applyTransform$1([dx, dy], barTransform, true);
  39785. this._updateInterval(handleIndex, vertex[0]);
  39786. var realtime = this.dataZoomModel.get('realtime');
  39787. this._updateView(!realtime);
  39788. realtime && this._dispatchZoomAction();
  39789. },
  39790. _onDragEnd: function () {
  39791. this._dragging = false;
  39792. this._showDataInfo(false);
  39793. // While in realtime mode and stream mode, dispatch action when
  39794. // drag end will cause the whole view rerender, which is unnecessary.
  39795. var realtime = this.dataZoomModel.get('realtime');
  39796. !realtime && this._dispatchZoomAction();
  39797. },
  39798. _onClickPanelClick: function (e) {
  39799. var size = this._size;
  39800. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  39801. if (localPoint[0] < 0 || localPoint[0] > size[0]
  39802. || localPoint[1] < 0 || localPoint[1] > size[1]
  39803. ) {
  39804. return;
  39805. }
  39806. var handleEnds = this._handleEnds;
  39807. var center = (handleEnds[0] + handleEnds[1]) / 2;
  39808. this._updateInterval('all', localPoint[0] - center);
  39809. this._updateView();
  39810. this._dispatchZoomAction();
  39811. },
  39812. /**
  39813. * This action will be throttled.
  39814. * @private
  39815. */
  39816. _dispatchZoomAction: function () {
  39817. var range = this._range;
  39818. this.api.dispatchAction({
  39819. type: 'dataZoom',
  39820. from: this.uid,
  39821. dataZoomId: this.dataZoomModel.id,
  39822. start: range[0],
  39823. end: range[1]
  39824. });
  39825. },
  39826. /**
  39827. * @private
  39828. */
  39829. _findCoordRect: function () {
  39830. // Find the grid coresponding to the first axis referred by dataZoom.
  39831. var rect;
  39832. each$15(this.getTargetCoordInfo(), function (coordInfoList) {
  39833. if (!rect && coordInfoList.length) {
  39834. var coordSys = coordInfoList[0].model.coordinateSystem;
  39835. rect = coordSys.getRect && coordSys.getRect();
  39836. }
  39837. });
  39838. if (!rect) {
  39839. var width = this.api.getWidth();
  39840. var height = this.api.getHeight();
  39841. rect = {
  39842. x: width * 0.2,
  39843. y: height * 0.2,
  39844. width: width * 0.6,
  39845. height: height * 0.6
  39846. };
  39847. }
  39848. return rect;
  39849. }
  39850. });
  39851. function getOtherDim(thisDim) {
  39852. // FIXME
  39853. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  39854. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  39855. return map$$1[thisDim];
  39856. }
  39857. function getCursor(orient) {
  39858. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  39859. }
  39860. DataZoomModel.extend({
  39861. type: 'dataZoom.inside',
  39862. /**
  39863. * @protected
  39864. */
  39865. defaultOption: {
  39866. disabled: false, // Whether disable this inside zoom.
  39867. zoomLock: false, // Whether disable zoom but only pan.
  39868. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39869. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39870. preventDefaultMouseMove: true
  39871. }
  39872. });
  39873. var ATTR$1 = '\0_ec_interaction_mutex';
  39874. function take(zr, resourceKey, userKey) {
  39875. var store = getStore(zr);
  39876. store[resourceKey] = userKey;
  39877. }
  39878. function release(zr, resourceKey, userKey) {
  39879. var store = getStore(zr);
  39880. var uKey = store[resourceKey];
  39881. if (uKey === userKey) {
  39882. store[resourceKey] = null;
  39883. }
  39884. }
  39885. function isTaken(zr, resourceKey) {
  39886. return !!getStore(zr)[resourceKey];
  39887. }
  39888. function getStore(zr) {
  39889. return zr[ATTR$1] || (zr[ATTR$1] = {});
  39890. }
  39891. /**
  39892. * payload: {
  39893. * type: 'takeGlobalCursor',
  39894. * key: 'dataZoomSelect', or 'brush', or ...,
  39895. * If no userKey, release global cursor.
  39896. * }
  39897. */
  39898. registerAction(
  39899. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  39900. function () {}
  39901. );
  39902. /**
  39903. * @alias module:echarts/component/helper/RoamController
  39904. * @constructor
  39905. * @mixin {module:zrender/mixin/Eventful}
  39906. *
  39907. * @param {module:zrender/zrender~ZRender} zr
  39908. */
  39909. function RoamController(zr) {
  39910. /**
  39911. * @type {Function}
  39912. */
  39913. this.pointerChecker;
  39914. /**
  39915. * @type {module:zrender}
  39916. */
  39917. this._zr = zr;
  39918. /**
  39919. * @type {Object}
  39920. */
  39921. this._opt = {};
  39922. // Avoid two roamController bind the same handler
  39923. var bind$$1 = bind;
  39924. var mousedownHandler = bind$$1(mousedown, this);
  39925. var mousemoveHandler = bind$$1(mousemove, this);
  39926. var mouseupHandler = bind$$1(mouseup, this);
  39927. var mousewheelHandler = bind$$1(mousewheel, this);
  39928. var pinchHandler = bind$$1(pinch, this);
  39929. Eventful.call(this);
  39930. /**
  39931. * @param {Function} pointerChecker
  39932. * input: x, y
  39933. * output: boolean
  39934. */
  39935. this.setPointerChecker = function (pointerChecker) {
  39936. this.pointerChecker = pointerChecker;
  39937. };
  39938. /**
  39939. * Notice: only enable needed types. For example, if 'zoom'
  39940. * is not needed, 'zoom' should not be enabled, otherwise
  39941. * default mousewheel behaviour (scroll page) will be disabled.
  39942. *
  39943. * @param {boolean|string} [controlType=true] Specify the control type,
  39944. * which can be null/undefined or true/false
  39945. * or 'pan/move' or 'zoom'/'scale'
  39946. * @param {Object} [opt]
  39947. * @param {Object} [opt.zoomOnMouseWheel=true]
  39948. * @param {Object} [opt.moveOnMouseMove=true]
  39949. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  39950. */
  39951. this.enable = function (controlType, opt) {
  39952. // Disable previous first
  39953. this.disable();
  39954. this._opt = defaults(clone(opt) || {}, {
  39955. zoomOnMouseWheel: true,
  39956. moveOnMouseMove: true,
  39957. preventDefaultMouseMove: true
  39958. });
  39959. if (controlType == null) {
  39960. controlType = true;
  39961. }
  39962. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  39963. zr.on('mousedown', mousedownHandler);
  39964. zr.on('mousemove', mousemoveHandler);
  39965. zr.on('mouseup', mouseupHandler);
  39966. }
  39967. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  39968. zr.on('mousewheel', mousewheelHandler);
  39969. zr.on('pinch', pinchHandler);
  39970. }
  39971. };
  39972. this.disable = function () {
  39973. zr.off('mousedown', mousedownHandler);
  39974. zr.off('mousemove', mousemoveHandler);
  39975. zr.off('mouseup', mouseupHandler);
  39976. zr.off('mousewheel', mousewheelHandler);
  39977. zr.off('pinch', pinchHandler);
  39978. };
  39979. this.dispose = this.disable;
  39980. this.isDragging = function () {
  39981. return this._dragging;
  39982. };
  39983. this.isPinching = function () {
  39984. return this._pinching;
  39985. };
  39986. }
  39987. mixin(RoamController, Eventful);
  39988. function mousedown(e) {
  39989. if (notLeftMouse(e)
  39990. || (e.target && e.target.draggable)
  39991. ) {
  39992. return;
  39993. }
  39994. var x = e.offsetX;
  39995. var y = e.offsetY;
  39996. // Only check on mosedown, but not mousemove.
  39997. // Mouse can be out of target when mouse moving.
  39998. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  39999. this._x = x;
  40000. this._y = y;
  40001. this._dragging = true;
  40002. }
  40003. }
  40004. function mousemove(e) {
  40005. if (notLeftMouse(e)
  40006. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  40007. || !this._dragging
  40008. || e.gestureEvent === 'pinch'
  40009. || isTaken(this._zr, 'globalPan')
  40010. ) {
  40011. return;
  40012. }
  40013. var x = e.offsetX;
  40014. var y = e.offsetY;
  40015. var oldX = this._x;
  40016. var oldY = this._y;
  40017. var dx = x - oldX;
  40018. var dy = y - oldY;
  40019. this._x = x;
  40020. this._y = y;
  40021. this._opt.preventDefaultMouseMove && stop(e.event);
  40022. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  40023. }
  40024. function mouseup(e) {
  40025. if (!notLeftMouse(e)) {
  40026. this._dragging = false;
  40027. }
  40028. }
  40029. function mousewheel(e) {
  40030. // wheelDelta maybe -0 in chrome mac.
  40031. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  40032. return;
  40033. }
  40034. // Convenience:
  40035. // Mac and VM Windows on Mac: scroll up: zoom out.
  40036. // Windows: scroll up: zoom in.
  40037. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  40038. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  40039. }
  40040. function pinch(e) {
  40041. if (isTaken(this._zr, 'globalPan')) {
  40042. return;
  40043. }
  40044. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  40045. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  40046. }
  40047. function zoom(e, zoomDelta, zoomX, zoomY) {
  40048. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  40049. // When mouse is out of roamController rect,
  40050. // default befavoius should not be be disabled, otherwise
  40051. // page sliding is disabled, contrary to expectation.
  40052. stop(e.event);
  40053. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  40054. }
  40055. }
  40056. function checkKeyBinding(roamController, prop, e) {
  40057. var setting = roamController._opt[prop];
  40058. return setting
  40059. && (!isString(setting) || e.event[setting + 'Key']);
  40060. }
  40061. // Only create one roam controller for each coordinate system.
  40062. // one roam controller might be refered by two inside data zoom
  40063. // components (for example, one for x and one for y). When user
  40064. // pan or zoom, only dispatch one action for those data zoom
  40065. // components.
  40066. var curry$5 = curry;
  40067. var ATTR = '\0_ec_dataZoom_roams';
  40068. /**
  40069. * @public
  40070. * @param {module:echarts/ExtensionAPI} api
  40071. * @param {Object} dataZoomInfo
  40072. * @param {string} dataZoomInfo.coordId
  40073. * @param {Function} dataZoomInfo.containsPoint
  40074. * @param {Array.<string>} dataZoomInfo.allCoordIds
  40075. * @param {string} dataZoomInfo.dataZoomId
  40076. * @param {number} dataZoomInfo.throttleRate
  40077. * @param {Function} dataZoomInfo.panGetRange
  40078. * @param {Function} dataZoomInfo.zoomGetRange
  40079. * @param {boolean} [dataZoomInfo.zoomLock]
  40080. * @param {boolean} [dataZoomInfo.disabled]
  40081. */
  40082. function register$1(api, dataZoomInfo) {
  40083. var store = giveStore(api);
  40084. var theDataZoomId = dataZoomInfo.dataZoomId;
  40085. var theCoordId = dataZoomInfo.coordId;
  40086. // Do clean when a dataZoom changes its target coordnate system.
  40087. // Avoid memory leak, dispose all not-used-registered.
  40088. each$1(store, function (record, coordId) {
  40089. var dataZoomInfos = record.dataZoomInfos;
  40090. if (dataZoomInfos[theDataZoomId]
  40091. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  40092. ) {
  40093. delete dataZoomInfos[theDataZoomId];
  40094. record.count--;
  40095. }
  40096. });
  40097. cleanStore(store);
  40098. var record = store[theCoordId];
  40099. // Create if needed.
  40100. if (!record) {
  40101. record = store[theCoordId] = {
  40102. coordId: theCoordId,
  40103. dataZoomInfos: {},
  40104. count: 0
  40105. };
  40106. record.controller = createController(api, record);
  40107. record.dispatchAction = curry(dispatchAction, api);
  40108. }
  40109. // Update reference of dataZoom.
  40110. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  40111. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  40112. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  40113. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  40114. // Consider resize, area should be always updated.
  40115. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  40116. // Update throttle.
  40117. createOrUpdate(
  40118. record,
  40119. 'dispatchAction',
  40120. dataZoomInfo.throttleRate,
  40121. 'fixRate'
  40122. );
  40123. }
  40124. /**
  40125. * @public
  40126. * @param {module:echarts/ExtensionAPI} api
  40127. * @param {string} dataZoomId
  40128. */
  40129. function unregister$1(api, dataZoomId) {
  40130. var store = giveStore(api);
  40131. each$1(store, function (record) {
  40132. record.controller.dispose();
  40133. var dataZoomInfos = record.dataZoomInfos;
  40134. if (dataZoomInfos[dataZoomId]) {
  40135. delete dataZoomInfos[dataZoomId];
  40136. record.count--;
  40137. }
  40138. });
  40139. cleanStore(store);
  40140. }
  40141. /**
  40142. * @public
  40143. */
  40144. function shouldRecordRange(payload, dataZoomId) {
  40145. if (payload && payload.type === 'dataZoom' && payload.batch) {
  40146. for (var i = 0, len = payload.batch.length; i < len; i++) {
  40147. if (payload.batch[i].dataZoomId === dataZoomId) {
  40148. return false;
  40149. }
  40150. }
  40151. }
  40152. return true;
  40153. }
  40154. /**
  40155. * @public
  40156. */
  40157. function generateCoordId(coordModel) {
  40158. return coordModel.type + '\0_' + coordModel.id;
  40159. }
  40160. /**
  40161. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  40162. * @type {Array.<Object>}
  40163. */
  40164. function giveStore(api) {
  40165. // Mount store on zrender instance, so that we do not
  40166. // need to worry about dispose.
  40167. var zr = api.getZr();
  40168. return zr[ATTR] || (zr[ATTR] = {});
  40169. }
  40170. function createController(api, newRecord) {
  40171. var controller = new RoamController(api.getZr());
  40172. controller.on('pan', curry$5(onPan, newRecord));
  40173. controller.on('zoom', curry$5(onZoom, newRecord));
  40174. return controller;
  40175. }
  40176. function cleanStore(store) {
  40177. each$1(store, function (record, coordId) {
  40178. if (!record.count) {
  40179. record.controller.dispose();
  40180. delete store[coordId];
  40181. }
  40182. });
  40183. }
  40184. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  40185. wrapAndDispatch(record, function (info) {
  40186. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  40187. });
  40188. }
  40189. function onZoom(record, scale, mouseX, mouseY) {
  40190. wrapAndDispatch(record, function (info) {
  40191. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  40192. });
  40193. }
  40194. function wrapAndDispatch(record, getRange) {
  40195. var batch = [];
  40196. each$1(record.dataZoomInfos, function (info) {
  40197. var range = getRange(info);
  40198. !info.disabled && range && batch.push({
  40199. dataZoomId: info.dataZoomId,
  40200. start: range[0],
  40201. end: range[1]
  40202. });
  40203. });
  40204. record.dispatchAction(batch);
  40205. }
  40206. /**
  40207. * This action will be throttled.
  40208. */
  40209. function dispatchAction(api, batch) {
  40210. api.dispatchAction({
  40211. type: 'dataZoom',
  40212. batch: batch
  40213. });
  40214. }
  40215. /**
  40216. * Merge roamController settings when multiple dataZooms share one roamController.
  40217. */
  40218. function mergeControllerParams(dataZoomInfos) {
  40219. var controlType;
  40220. var opt = {};
  40221. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  40222. // as string, it is probably revert to reserved word by compress tool. See #7411.
  40223. var prefix = 'type_';
  40224. var typePriority = {
  40225. 'type_true': 2,
  40226. 'type_move': 1,
  40227. 'type_false': 0,
  40228. 'type_undefined': -1
  40229. };
  40230. each$1(dataZoomInfos, function (dataZoomInfo) {
  40231. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  40232. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  40233. controlType = oneType;
  40234. }
  40235. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  40236. extend(opt, dataZoomInfo.roamControllerOpt);
  40237. });
  40238. return {
  40239. controlType: controlType,
  40240. opt: opt
  40241. };
  40242. }
  40243. var bind$4 = bind;
  40244. var InsideZoomView = DataZoomView.extend({
  40245. type: 'dataZoom.inside',
  40246. /**
  40247. * @override
  40248. */
  40249. init: function (ecModel, api) {
  40250. /**
  40251. * 'throttle' is used in this.dispatchAction, so we save range
  40252. * to avoid missing some 'pan' info.
  40253. * @private
  40254. * @type {Array.<number>}
  40255. */
  40256. this._range;
  40257. },
  40258. /**
  40259. * @override
  40260. */
  40261. render: function (dataZoomModel, ecModel, api, payload) {
  40262. InsideZoomView.superApply(this, 'render', arguments);
  40263. // Notice: origin this._range should be maintained, and should not be re-fetched
  40264. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  40265. // info will be missed because of 'throttle' of this.dispatchAction.
  40266. if (shouldRecordRange(payload, dataZoomModel.id)) {
  40267. this._range = dataZoomModel.getPercentRange();
  40268. }
  40269. // Reset controllers.
  40270. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  40271. var allCoordIds = map(coordInfoList, function (coordInfo) {
  40272. return generateCoordId(coordInfo.model);
  40273. });
  40274. each$1(coordInfoList, function (coordInfo) {
  40275. var coordModel = coordInfo.model;
  40276. var dataZoomOption = dataZoomModel.option;
  40277. register$1(
  40278. api,
  40279. {
  40280. coordId: generateCoordId(coordModel),
  40281. allCoordIds: allCoordIds,
  40282. containsPoint: function (e, x, y) {
  40283. return coordModel.coordinateSystem.containPoint([x, y]);
  40284. },
  40285. dataZoomId: dataZoomModel.id,
  40286. throttleRate: dataZoomModel.get('throttle', true),
  40287. panGetRange: bind$4(this._onPan, this, coordInfo, coordSysName),
  40288. zoomGetRange: bind$4(this._onZoom, this, coordInfo, coordSysName),
  40289. zoomLock: dataZoomOption.zoomLock,
  40290. disabled: dataZoomOption.disabled,
  40291. roamControllerOpt: {
  40292. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  40293. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  40294. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  40295. }
  40296. }
  40297. );
  40298. }, this);
  40299. }, this);
  40300. },
  40301. /**
  40302. * @override
  40303. */
  40304. dispose: function () {
  40305. unregister$1(this.api, this.dataZoomModel.id);
  40306. InsideZoomView.superApply(this, 'dispose', arguments);
  40307. this._range = null;
  40308. },
  40309. /**
  40310. * @private
  40311. */
  40312. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  40313. var range = this._range.slice();
  40314. // Calculate transform by the first axis.
  40315. var axisModel = coordInfo.axisModels[0];
  40316. if (!axisModel) {
  40317. return;
  40318. }
  40319. var directionInfo = getDirectionInfo[coordSysName](
  40320. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  40321. );
  40322. var percentDelta = directionInfo.signal
  40323. * (range[1] - range[0])
  40324. * directionInfo.pixel / directionInfo.pixelLength;
  40325. sliderMove(percentDelta, range, [0, 100], 'all');
  40326. return (this._range = range);
  40327. },
  40328. /**
  40329. * @private
  40330. */
  40331. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  40332. var range = this._range.slice();
  40333. // Calculate transform by the first axis.
  40334. var axisModel = coordInfo.axisModels[0];
  40335. if (!axisModel) {
  40336. return;
  40337. }
  40338. var directionInfo = getDirectionInfo[coordSysName](
  40339. null, [mouseX, mouseY], axisModel, controller, coordInfo
  40340. );
  40341. var percentPoint = (
  40342. directionInfo.signal > 0
  40343. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  40344. : (directionInfo.pixel - directionInfo.pixelStart)
  40345. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  40346. scale = Math.max(1 / scale, 0);
  40347. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  40348. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  40349. // Restrict range.
  40350. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  40351. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  40352. return (this._range = range);
  40353. }
  40354. });
  40355. var getDirectionInfo = {
  40356. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40357. var axis = axisModel.axis;
  40358. var ret = {};
  40359. var rect = coordInfo.model.coordinateSystem.getRect();
  40360. oldPoint = oldPoint || [0, 0];
  40361. if (axis.dim === 'x') {
  40362. ret.pixel = newPoint[0] - oldPoint[0];
  40363. ret.pixelLength = rect.width;
  40364. ret.pixelStart = rect.x;
  40365. ret.signal = axis.inverse ? 1 : -1;
  40366. }
  40367. else { // axis.dim === 'y'
  40368. ret.pixel = newPoint[1] - oldPoint[1];
  40369. ret.pixelLength = rect.height;
  40370. ret.pixelStart = rect.y;
  40371. ret.signal = axis.inverse ? -1 : 1;
  40372. }
  40373. return ret;
  40374. },
  40375. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40376. var axis = axisModel.axis;
  40377. var ret = {};
  40378. var polar = coordInfo.model.coordinateSystem;
  40379. var radiusExtent = polar.getRadiusAxis().getExtent();
  40380. var angleExtent = polar.getAngleAxis().getExtent();
  40381. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  40382. newPoint = polar.pointToCoord(newPoint);
  40383. if (axisModel.mainType === 'radiusAxis') {
  40384. ret.pixel = newPoint[0] - oldPoint[0];
  40385. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  40386. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  40387. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  40388. ret.pixelStart = radiusExtent[0];
  40389. ret.signal = axis.inverse ? 1 : -1;
  40390. }
  40391. else { // 'angleAxis'
  40392. ret.pixel = newPoint[1] - oldPoint[1];
  40393. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  40394. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  40395. ret.pixelLength = angleExtent[1] - angleExtent[0];
  40396. ret.pixelStart = angleExtent[0];
  40397. ret.signal = axis.inverse ? -1 : 1;
  40398. }
  40399. return ret;
  40400. },
  40401. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40402. var axis = axisModel.axis;
  40403. var rect = coordInfo.model.coordinateSystem.getRect();
  40404. var ret = {};
  40405. oldPoint = oldPoint || [0, 0];
  40406. if (axis.orient === 'horizontal') {
  40407. ret.pixel = newPoint[0] - oldPoint[0];
  40408. ret.pixelLength = rect.width;
  40409. ret.pixelStart = rect.x;
  40410. ret.signal = axis.inverse ? 1 : -1;
  40411. }
  40412. else { // 'vertical'
  40413. ret.pixel = newPoint[1] - oldPoint[1];
  40414. ret.pixelLength = rect.height;
  40415. ret.pixelStart = rect.y;
  40416. ret.signal = axis.inverse ? -1 : 1;
  40417. }
  40418. return ret;
  40419. }
  40420. };
  40421. registerProcessor({
  40422. getTargetSeries: function (ecModel) {
  40423. var seriesModelMap = createHashMap();
  40424. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40425. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40426. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  40427. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  40428. seriesModelMap.set(seriesModel.uid, seriesModel);
  40429. });
  40430. });
  40431. });
  40432. return seriesModelMap;
  40433. },
  40434. isOverallFilter: true,
  40435. // Consider appendData, where filter should be performed. Because data process is
  40436. // in block mode currently, it is not need to worry about that the overallProgress
  40437. // execute every frame.
  40438. overallReset: function (ecModel, api) {
  40439. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40440. // We calculate window and reset axis here but not in model
  40441. // init stage and not after action dispatch handler, because
  40442. // reset should be called after seriesData.restoreData.
  40443. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40444. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  40445. });
  40446. // Caution: data zoom filtering is order sensitive when using
  40447. // percent range and no min/max/scale set on axis.
  40448. // For example, we have dataZoom definition:
  40449. // [
  40450. // {xAxisIndex: 0, start: 30, end: 70},
  40451. // {yAxisIndex: 0, start: 20, end: 80}
  40452. // ]
  40453. // In this case, [20, 80] of y-dataZoom should be based on data
  40454. // that have filtered by x-dataZoom using range of [30, 70],
  40455. // but should not be based on full raw data. Thus sliding
  40456. // x-dataZoom will change both ranges of xAxis and yAxis,
  40457. // while sliding y-dataZoom will only change the range of yAxis.
  40458. // So we should filter x-axis after reset x-axis immediately,
  40459. // and then reset y-axis and filter y-axis.
  40460. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40461. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  40462. });
  40463. });
  40464. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40465. // Fullfill all of the range props so that user
  40466. // is able to get them from chart.getOption().
  40467. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  40468. var percentRange = axisProxy.getDataPercentWindow();
  40469. var valueRange = axisProxy.getDataValueWindow();
  40470. dataZoomModel.setRawRange({
  40471. start: percentRange[0],
  40472. end: percentRange[1],
  40473. startValue: valueRange[0],
  40474. endValue: valueRange[1]
  40475. }, true);
  40476. });
  40477. }
  40478. });
  40479. registerAction('dataZoom', function (payload, ecModel) {
  40480. var linkedNodesFinder = createLinkedNodesFinder(
  40481. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  40482. eachAxisDim$1,
  40483. function (model, dimNames) {
  40484. return model.get(dimNames.axisIndex);
  40485. }
  40486. );
  40487. var effectedModels = [];
  40488. ecModel.eachComponent(
  40489. {mainType: 'dataZoom', query: payload},
  40490. function (model, index) {
  40491. effectedModels.push.apply(
  40492. effectedModels, linkedNodesFinder(model).nodes
  40493. );
  40494. }
  40495. );
  40496. each$1(effectedModels, function (dataZoomModel, index) {
  40497. dataZoomModel.setRawRange({
  40498. start: payload.start,
  40499. end: payload.end,
  40500. startValue: payload.startValue,
  40501. endValue: payload.endValue
  40502. });
  40503. });
  40504. });
  40505. /**
  40506. * DataZoom component entry
  40507. */
  40508. var features = {};
  40509. function register$2(name, ctor) {
  40510. features[name] = ctor;
  40511. }
  40512. function get$1(name) {
  40513. return features[name];
  40514. }
  40515. var ToolboxModel = extendComponentModel({
  40516. type: 'toolbox',
  40517. layoutMode: {
  40518. type: 'box',
  40519. ignoreSize: true
  40520. },
  40521. mergeDefaultAndTheme: function (option) {
  40522. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  40523. each$1(this.option.feature, function (featureOpt, featureName) {
  40524. var Feature = get$1(featureName);
  40525. Feature && merge(featureOpt, Feature.defaultOption);
  40526. });
  40527. },
  40528. defaultOption: {
  40529. show: true,
  40530. z: 6,
  40531. zlevel: 0,
  40532. orient: 'horizontal',
  40533. left: 'right',
  40534. top: 'top',
  40535. // right
  40536. // bottom
  40537. backgroundColor: 'transparent',
  40538. borderColor: '#ccc',
  40539. borderRadius: 0,
  40540. borderWidth: 0,
  40541. padding: 5,
  40542. itemSize: 15,
  40543. itemGap: 8,
  40544. showTitle: true,
  40545. iconStyle: {
  40546. borderColor: '#666',
  40547. color: 'none'
  40548. },
  40549. emphasis: {
  40550. iconStyle: {
  40551. borderColor: '#3E98C5'
  40552. }
  40553. }
  40554. // textStyle: {},
  40555. // feature
  40556. }
  40557. });
  40558. extendComponentView({
  40559. type: 'toolbox',
  40560. render: function (toolboxModel, ecModel, api, payload) {
  40561. var group = this.group;
  40562. group.removeAll();
  40563. if (!toolboxModel.get('show')) {
  40564. return;
  40565. }
  40566. var itemSize = +toolboxModel.get('itemSize');
  40567. var featureOpts = toolboxModel.get('feature') || {};
  40568. var features = this._features || (this._features = {});
  40569. var featureNames = [];
  40570. each$1(featureOpts, function (opt, name) {
  40571. featureNames.push(name);
  40572. });
  40573. (new DataDiffer(this._featureNames || [], featureNames))
  40574. .add(processFeature)
  40575. .update(processFeature)
  40576. .remove(curry(processFeature, null))
  40577. .execute();
  40578. // Keep for diff.
  40579. this._featureNames = featureNames;
  40580. function processFeature(newIndex, oldIndex) {
  40581. var featureName = featureNames[newIndex];
  40582. var oldName = featureNames[oldIndex];
  40583. var featureOpt = featureOpts[featureName];
  40584. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  40585. var feature;
  40586. if (featureName && !oldName) { // Create
  40587. if (isUserFeatureName(featureName)) {
  40588. feature = {
  40589. model: featureModel,
  40590. onclick: featureModel.option.onclick,
  40591. featureName: featureName
  40592. };
  40593. }
  40594. else {
  40595. var Feature = get$1(featureName);
  40596. if (!Feature) {
  40597. return;
  40598. }
  40599. feature = new Feature(featureModel, ecModel, api);
  40600. }
  40601. features[featureName] = feature;
  40602. }
  40603. else {
  40604. feature = features[oldName];
  40605. // If feature does not exsit.
  40606. if (!feature) {
  40607. return;
  40608. }
  40609. feature.model = featureModel;
  40610. feature.ecModel = ecModel;
  40611. feature.api = api;
  40612. }
  40613. if (!featureName && oldName) {
  40614. feature.dispose && feature.dispose(ecModel, api);
  40615. return;
  40616. }
  40617. if (!featureModel.get('show') || feature.unusable) {
  40618. feature.remove && feature.remove(ecModel, api);
  40619. return;
  40620. }
  40621. createIconPaths(featureModel, feature, featureName);
  40622. featureModel.setIconStatus = function (iconName, status) {
  40623. var option = this.option;
  40624. var iconPaths = this.iconPaths;
  40625. option.iconStatus = option.iconStatus || {};
  40626. option.iconStatus[iconName] = status;
  40627. // FIXME
  40628. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  40629. };
  40630. if (feature.render) {
  40631. feature.render(featureModel, ecModel, api, payload);
  40632. }
  40633. }
  40634. function createIconPaths(featureModel, feature, featureName) {
  40635. var iconStyleModel = featureModel.getModel('iconStyle');
  40636. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  40637. // If one feature has mutiple icon. they are orginaized as
  40638. // {
  40639. // icon: {
  40640. // foo: '',
  40641. // bar: ''
  40642. // },
  40643. // title: {
  40644. // foo: '',
  40645. // bar: ''
  40646. // }
  40647. // }
  40648. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  40649. var titles = featureModel.get('title') || {};
  40650. if (typeof icons === 'string') {
  40651. var icon = icons;
  40652. var title = titles;
  40653. icons = {};
  40654. titles = {};
  40655. icons[featureName] = icon;
  40656. titles[featureName] = title;
  40657. }
  40658. var iconPaths = featureModel.iconPaths = {};
  40659. each$1(icons, function (iconStr, iconName) {
  40660. var path = createIcon(
  40661. iconStr,
  40662. {},
  40663. {
  40664. x: -itemSize / 2,
  40665. y: -itemSize / 2,
  40666. width: itemSize,
  40667. height: itemSize
  40668. }
  40669. );
  40670. path.setStyle(iconStyleModel.getItemStyle());
  40671. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  40672. setHoverStyle(path);
  40673. if (toolboxModel.get('showTitle')) {
  40674. path.__title = titles[iconName];
  40675. path.on('mouseover', function () {
  40676. // Should not reuse above hoverStyle, which might be modified.
  40677. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  40678. path.setStyle({
  40679. text: titles[iconName],
  40680. textPosition: hoverStyle.textPosition || 'bottom',
  40681. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  40682. textAlign: hoverStyle.textAlign || 'center'
  40683. });
  40684. })
  40685. .on('mouseout', function () {
  40686. path.setStyle({
  40687. textFill: null
  40688. });
  40689. });
  40690. }
  40691. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  40692. group.add(path);
  40693. path.on('click', bind(
  40694. feature.onclick, feature, ecModel, api, iconName
  40695. ));
  40696. iconPaths[iconName] = path;
  40697. });
  40698. }
  40699. layout$2(group, toolboxModel, api);
  40700. // Render background after group is layout
  40701. // FIXME
  40702. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  40703. // Adjust icon title positions to avoid them out of screen
  40704. group.eachChild(function (icon) {
  40705. var titleText = icon.__title;
  40706. var hoverStyle = icon.hoverStyle;
  40707. // May be background element
  40708. if (hoverStyle && titleText) {
  40709. var rect = getBoundingRect(
  40710. titleText, makeFont(hoverStyle)
  40711. );
  40712. var offsetX = icon.position[0] + group.position[0];
  40713. var offsetY = icon.position[1] + group.position[1] + itemSize;
  40714. var needPutOnTop = false;
  40715. if (offsetY + rect.height > api.getHeight()) {
  40716. hoverStyle.textPosition = 'top';
  40717. needPutOnTop = true;
  40718. }
  40719. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  40720. if (offsetX + rect.width / 2 > api.getWidth()) {
  40721. hoverStyle.textPosition = ['100%', topOffset];
  40722. hoverStyle.textAlign = 'right';
  40723. }
  40724. else if (offsetX - rect.width / 2 < 0) {
  40725. hoverStyle.textPosition = [0, topOffset];
  40726. hoverStyle.textAlign = 'left';
  40727. }
  40728. }
  40729. });
  40730. },
  40731. updateView: function (toolboxModel, ecModel, api, payload) {
  40732. each$1(this._features, function (feature) {
  40733. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  40734. });
  40735. },
  40736. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  40737. // zrUtil.each(this._features, function (feature) {
  40738. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  40739. // });
  40740. // },
  40741. remove: function (ecModel, api) {
  40742. each$1(this._features, function (feature) {
  40743. feature.remove && feature.remove(ecModel, api);
  40744. });
  40745. this.group.removeAll();
  40746. },
  40747. dispose: function (ecModel, api) {
  40748. each$1(this._features, function (feature) {
  40749. feature.dispose && feature.dispose(ecModel, api);
  40750. });
  40751. }
  40752. });
  40753. function isUserFeatureName(featureName) {
  40754. return featureName.indexOf('my') === 0;
  40755. }
  40756. var saveAsImageLang = lang.toolbox.saveAsImage;
  40757. function SaveAsImage(model) {
  40758. this.model = model;
  40759. }
  40760. SaveAsImage.defaultOption = {
  40761. show: true,
  40762. 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',
  40763. title: saveAsImageLang.title,
  40764. type: 'png',
  40765. // Default use option.backgroundColor
  40766. // backgroundColor: '#fff',
  40767. name: '',
  40768. excludeComponents: ['toolbox'],
  40769. pixelRatio: 1,
  40770. lang: saveAsImageLang.lang.slice()
  40771. };
  40772. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  40773. var proto$2 = SaveAsImage.prototype;
  40774. proto$2.onclick = function (ecModel, api) {
  40775. var model = this.model;
  40776. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  40777. var $a = document.createElement('a');
  40778. var type = model.get('type', true) || 'png';
  40779. $a.download = title + '.' + type;
  40780. $a.target = '_blank';
  40781. var url = api.getConnectedDataURL({
  40782. type: type,
  40783. backgroundColor: model.get('backgroundColor', true)
  40784. || ecModel.get('backgroundColor') || '#fff',
  40785. excludeComponents: model.get('excludeComponents'),
  40786. pixelRatio: model.get('pixelRatio')
  40787. });
  40788. $a.href = url;
  40789. // Chrome and Firefox
  40790. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  40791. var evt = new MouseEvent('click', {
  40792. view: window,
  40793. bubbles: true,
  40794. cancelable: false
  40795. });
  40796. $a.dispatchEvent(evt);
  40797. }
  40798. // IE
  40799. else {
  40800. if (window.navigator.msSaveOrOpenBlob) {
  40801. var bstr = atob(url.split(',')[1]);
  40802. var n = bstr.length;
  40803. var u8arr = new Uint8Array(n);
  40804. while(n--) {
  40805. u8arr[n] = bstr.charCodeAt(n);
  40806. }
  40807. var blob = new Blob([u8arr]);
  40808. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  40809. }
  40810. else {
  40811. var lang$$1 = model.get('lang');
  40812. var html = '' +
  40813. '<body style="margin:0;">' +
  40814. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  40815. '</body>';
  40816. var tab = window.open();
  40817. tab.document.write(html);
  40818. }
  40819. }
  40820. };
  40821. register$2(
  40822. 'saveAsImage', SaveAsImage
  40823. );
  40824. var magicTypeLang = lang.toolbox.magicType;
  40825. function MagicType(model) {
  40826. this.model = model;
  40827. }
  40828. MagicType.defaultOption = {
  40829. show: true,
  40830. type: [],
  40831. // Icon group
  40832. icon: {
  40833. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  40834. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  40835. 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
  40836. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  40837. },
  40838. // `line`, `bar`, `stack`, `tiled`
  40839. title: clone(magicTypeLang.title),
  40840. option: {},
  40841. seriesIndex: {}
  40842. };
  40843. var proto$3 = MagicType.prototype;
  40844. proto$3.getIcons = function () {
  40845. var model = this.model;
  40846. var availableIcons = model.get('icon');
  40847. var icons = {};
  40848. each$1(model.get('type'), function (type) {
  40849. if (availableIcons[type]) {
  40850. icons[type] = availableIcons[type];
  40851. }
  40852. });
  40853. return icons;
  40854. };
  40855. var seriesOptGenreator = {
  40856. 'line': function (seriesType, seriesId, seriesModel, model) {
  40857. if (seriesType === 'bar') {
  40858. return merge({
  40859. id: seriesId,
  40860. type: 'line',
  40861. // Preserve data related option
  40862. data: seriesModel.get('data'),
  40863. stack: seriesModel.get('stack'),
  40864. markPoint: seriesModel.get('markPoint'),
  40865. markLine: seriesModel.get('markLine')
  40866. }, model.get('option.line') || {}, true);
  40867. }
  40868. },
  40869. 'bar': function (seriesType, seriesId, seriesModel, model) {
  40870. if (seriesType === 'line') {
  40871. return merge({
  40872. id: seriesId,
  40873. type: 'bar',
  40874. // Preserve data related option
  40875. data: seriesModel.get('data'),
  40876. stack: seriesModel.get('stack'),
  40877. markPoint: seriesModel.get('markPoint'),
  40878. markLine: seriesModel.get('markLine')
  40879. }, model.get('option.bar') || {}, true);
  40880. }
  40881. },
  40882. 'stack': function (seriesType, seriesId, seriesModel, model) {
  40883. if (seriesType === 'line' || seriesType === 'bar') {
  40884. return merge({
  40885. id: seriesId,
  40886. stack: '__ec_magicType_stack__'
  40887. }, model.get('option.stack') || {}, true);
  40888. }
  40889. },
  40890. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  40891. if (seriesType === 'line' || seriesType === 'bar') {
  40892. return merge({
  40893. id: seriesId,
  40894. stack: ''
  40895. }, model.get('option.tiled') || {}, true);
  40896. }
  40897. }
  40898. };
  40899. var radioTypes = [
  40900. ['line', 'bar'],
  40901. ['stack', 'tiled']
  40902. ];
  40903. proto$3.onclick = function (ecModel, api, type) {
  40904. var model = this.model;
  40905. var seriesIndex = model.get('seriesIndex.' + type);
  40906. // Not supported magicType
  40907. if (!seriesOptGenreator[type]) {
  40908. return;
  40909. }
  40910. var newOption = {
  40911. series: []
  40912. };
  40913. var generateNewSeriesTypes = function (seriesModel) {
  40914. var seriesType = seriesModel.subType;
  40915. var seriesId = seriesModel.id;
  40916. var newSeriesOpt = seriesOptGenreator[type](
  40917. seriesType, seriesId, seriesModel, model
  40918. );
  40919. if (newSeriesOpt) {
  40920. // PENDING If merge original option?
  40921. defaults(newSeriesOpt, seriesModel.option);
  40922. newOption.series.push(newSeriesOpt);
  40923. }
  40924. // Modify boundaryGap
  40925. var coordSys = seriesModel.coordinateSystem;
  40926. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  40927. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  40928. if (categoryAxis) {
  40929. var axisDim = categoryAxis.dim;
  40930. var axisType = axisDim + 'Axis';
  40931. var axisModel = ecModel.queryComponents({
  40932. mainType: axisType,
  40933. index: seriesModel.get(name + 'Index'),
  40934. id: seriesModel.get(name + 'Id')
  40935. })[0];
  40936. var axisIndex = axisModel.componentIndex;
  40937. newOption[axisType] = newOption[axisType] || [];
  40938. for (var i = 0; i <= axisIndex; i++) {
  40939. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  40940. }
  40941. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  40942. }
  40943. }
  40944. };
  40945. each$1(radioTypes, function (radio) {
  40946. if (indexOf(radio, type) >= 0) {
  40947. each$1(radio, function (item) {
  40948. model.setIconStatus(item, 'normal');
  40949. });
  40950. }
  40951. });
  40952. model.setIconStatus(type, 'emphasis');
  40953. ecModel.eachComponent(
  40954. {
  40955. mainType: 'series',
  40956. query: seriesIndex == null ? null : {
  40957. seriesIndex: seriesIndex
  40958. }
  40959. }, generateNewSeriesTypes
  40960. );
  40961. api.dispatchAction({
  40962. type: 'changeMagicType',
  40963. currentType: type,
  40964. newOption: newOption
  40965. });
  40966. };
  40967. registerAction({
  40968. type: 'changeMagicType',
  40969. event: 'magicTypeChanged',
  40970. update: 'prepareAndUpdate'
  40971. }, function (payload, ecModel) {
  40972. ecModel.mergeOption(payload.newOption);
  40973. });
  40974. register$2('magicType', MagicType);
  40975. var dataViewLang = lang.toolbox.dataView;
  40976. var BLOCK_SPLITER = new Array(60).join('-');
  40977. var ITEM_SPLITER = '\t';
  40978. /**
  40979. * Group series into two types
  40980. * 1. on category axis, like line, bar
  40981. * 2. others, like scatter, pie
  40982. * @param {module:echarts/model/Global} ecModel
  40983. * @return {Object}
  40984. * @inner
  40985. */
  40986. function groupSeries(ecModel) {
  40987. var seriesGroupByCategoryAxis = {};
  40988. var otherSeries = [];
  40989. var meta = [];
  40990. ecModel.eachRawSeries(function (seriesModel) {
  40991. var coordSys = seriesModel.coordinateSystem;
  40992. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  40993. var baseAxis = coordSys.getBaseAxis();
  40994. if (baseAxis.type === 'category') {
  40995. var key = baseAxis.dim + '_' + baseAxis.index;
  40996. if (!seriesGroupByCategoryAxis[key]) {
  40997. seriesGroupByCategoryAxis[key] = {
  40998. categoryAxis: baseAxis,
  40999. valueAxis: coordSys.getOtherAxis(baseAxis),
  41000. series: []
  41001. };
  41002. meta.push({
  41003. axisDim: baseAxis.dim,
  41004. axisIndex: baseAxis.index
  41005. });
  41006. }
  41007. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  41008. }
  41009. else {
  41010. otherSeries.push(seriesModel);
  41011. }
  41012. }
  41013. else {
  41014. otherSeries.push(seriesModel);
  41015. }
  41016. });
  41017. return {
  41018. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  41019. other: otherSeries,
  41020. meta: meta
  41021. };
  41022. }
  41023. /**
  41024. * Assemble content of series on cateogory axis
  41025. * @param {Array.<module:echarts/model/Series>} series
  41026. * @return {string}
  41027. * @inner
  41028. */
  41029. function assembleSeriesWithCategoryAxis(series) {
  41030. var tables = [];
  41031. each$1(series, function (group, key) {
  41032. var categoryAxis = group.categoryAxis;
  41033. var valueAxis = group.valueAxis;
  41034. var valueAxisDim = valueAxis.dim;
  41035. var headers = [' '].concat(map(group.series, function (series) {
  41036. return series.name;
  41037. }));
  41038. var columns = [categoryAxis.model.getCategories()];
  41039. each$1(group.series, function (series) {
  41040. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  41041. return val;
  41042. }));
  41043. });
  41044. // Assemble table content
  41045. var lines = [headers.join(ITEM_SPLITER)];
  41046. for (var i = 0; i < columns[0].length; i++) {
  41047. var items = [];
  41048. for (var j = 0; j < columns.length; j++) {
  41049. items.push(columns[j][i]);
  41050. }
  41051. lines.push(items.join(ITEM_SPLITER));
  41052. }
  41053. tables.push(lines.join('\n'));
  41054. });
  41055. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  41056. }
  41057. /**
  41058. * Assemble content of other series
  41059. * @param {Array.<module:echarts/model/Series>} series
  41060. * @return {string}
  41061. * @inner
  41062. */
  41063. function assembleOtherSeries(series) {
  41064. return map(series, function (series) {
  41065. var data = series.getRawData();
  41066. var lines = [series.name];
  41067. var vals = [];
  41068. data.each(data.dimensions, function () {
  41069. var argLen = arguments.length;
  41070. var dataIndex = arguments[argLen - 1];
  41071. var name = data.getName(dataIndex);
  41072. for (var i = 0; i < argLen - 1; i++) {
  41073. vals[i] = arguments[i];
  41074. }
  41075. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  41076. });
  41077. return lines.join('\n');
  41078. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  41079. }
  41080. /**
  41081. * @param {module:echarts/model/Global}
  41082. * @return {Object}
  41083. * @inner
  41084. */
  41085. function getContentFromModel(ecModel) {
  41086. var result = groupSeries(ecModel);
  41087. return {
  41088. value: filter([
  41089. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  41090. assembleOtherSeries(result.other)
  41091. ], function (str) {
  41092. return str.replace(/[\n\t\s]/g, '');
  41093. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  41094. meta: result.meta
  41095. };
  41096. }
  41097. function trim$1(str) {
  41098. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  41099. }
  41100. /**
  41101. * If a block is tsv format
  41102. */
  41103. function isTSVFormat(block) {
  41104. // Simple method to find out if a block is tsv format
  41105. var firstLine = block.slice(0, block.indexOf('\n'));
  41106. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  41107. return true;
  41108. }
  41109. }
  41110. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  41111. /**
  41112. * @param {string} tsv
  41113. * @return {Object}
  41114. */
  41115. function parseTSVContents(tsv) {
  41116. var tsvLines = tsv.split(/\n+/g);
  41117. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  41118. var categories = [];
  41119. var series = map(headers, function (header) {
  41120. return {
  41121. name: header,
  41122. data: []
  41123. };
  41124. });
  41125. for (var i = 0; i < tsvLines.length; i++) {
  41126. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  41127. categories.push(items.shift());
  41128. for (var j = 0; j < items.length; j++) {
  41129. series[j] && (series[j].data[i] = items[j]);
  41130. }
  41131. }
  41132. return {
  41133. series: series,
  41134. categories: categories
  41135. };
  41136. }
  41137. /**
  41138. * @param {string} str
  41139. * @return {Array.<Object>}
  41140. * @inner
  41141. */
  41142. function parseListContents(str) {
  41143. var lines = str.split(/\n+/g);
  41144. var seriesName = trim$1(lines.shift());
  41145. var data = [];
  41146. for (var i = 0; i < lines.length; i++) {
  41147. var items = trim$1(lines[i]).split(itemSplitRegex);
  41148. var name = '';
  41149. var value;
  41150. var hasName = false;
  41151. if (isNaN(items[0])) { // First item is name
  41152. hasName = true;
  41153. name = items[0];
  41154. items = items.slice(1);
  41155. data[i] = {
  41156. name: name,
  41157. value: []
  41158. };
  41159. value = data[i].value;
  41160. }
  41161. else {
  41162. value = data[i] = [];
  41163. }
  41164. for (var j = 0; j < items.length; j++) {
  41165. value.push(+items[j]);
  41166. }
  41167. if (value.length === 1) {
  41168. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  41169. }
  41170. }
  41171. return {
  41172. name: seriesName,
  41173. data: data
  41174. };
  41175. }
  41176. /**
  41177. * @param {string} str
  41178. * @param {Array.<Object>} blockMetaList
  41179. * @return {Object}
  41180. * @inner
  41181. */
  41182. function parseContents(str, blockMetaList) {
  41183. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  41184. var newOption = {
  41185. series: []
  41186. };
  41187. each$1(blocks, function (block, idx) {
  41188. if (isTSVFormat(block)) {
  41189. var result = parseTSVContents(block);
  41190. var blockMeta = blockMetaList[idx];
  41191. var axisKey = blockMeta.axisDim + 'Axis';
  41192. if (blockMeta) {
  41193. newOption[axisKey] = newOption[axisKey] || [];
  41194. newOption[axisKey][blockMeta.axisIndex] = {
  41195. data: result.categories
  41196. };
  41197. newOption.series = newOption.series.concat(result.series);
  41198. }
  41199. }
  41200. else {
  41201. var result = parseListContents(block);
  41202. newOption.series.push(result);
  41203. }
  41204. });
  41205. return newOption;
  41206. }
  41207. /**
  41208. * @alias {module:echarts/component/toolbox/feature/DataView}
  41209. * @constructor
  41210. * @param {module:echarts/model/Model} model
  41211. */
  41212. function DataView(model) {
  41213. this._dom = null;
  41214. this.model = model;
  41215. }
  41216. DataView.defaultOption = {
  41217. show: true,
  41218. readOnly: false,
  41219. optionToContent: null,
  41220. contentToOption: null,
  41221. 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',
  41222. title: clone(dataViewLang.title),
  41223. lang: clone(dataViewLang.lang),
  41224. backgroundColor: '#fff',
  41225. textColor: '#000',
  41226. textareaColor: '#fff',
  41227. textareaBorderColor: '#333',
  41228. buttonColor: '#c23531',
  41229. buttonTextColor: '#fff'
  41230. };
  41231. DataView.prototype.onclick = function (ecModel, api) {
  41232. var container = api.getDom();
  41233. var model = this.model;
  41234. if (this._dom) {
  41235. container.removeChild(this._dom);
  41236. }
  41237. var root = document.createElement('div');
  41238. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  41239. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  41240. // Create elements
  41241. var header = document.createElement('h4');
  41242. var lang$$1 = model.get('lang') || [];
  41243. header.innerHTML = lang$$1[0] || model.get('title');
  41244. header.style.cssText = 'margin: 10px 20px;';
  41245. header.style.color = model.get('textColor');
  41246. var viewMain = document.createElement('div');
  41247. var textarea = document.createElement('textarea');
  41248. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  41249. var optionToContent = model.get('optionToContent');
  41250. var contentToOption = model.get('contentToOption');
  41251. var result = getContentFromModel(ecModel);
  41252. if (typeof optionToContent === 'function') {
  41253. var htmlOrDom = optionToContent(api.getOption());
  41254. if (typeof htmlOrDom === 'string') {
  41255. viewMain.innerHTML = htmlOrDom;
  41256. }
  41257. else if (isDom(htmlOrDom)) {
  41258. viewMain.appendChild(htmlOrDom);
  41259. }
  41260. }
  41261. else {
  41262. // Use default textarea
  41263. viewMain.appendChild(textarea);
  41264. textarea.readOnly = model.get('readOnly');
  41265. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  41266. textarea.style.color = model.get('textColor');
  41267. textarea.style.borderColor = model.get('textareaBorderColor');
  41268. textarea.style.backgroundColor = model.get('textareaColor');
  41269. textarea.value = result.value;
  41270. }
  41271. var blockMetaList = result.meta;
  41272. var buttonContainer = document.createElement('div');
  41273. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  41274. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  41275. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  41276. var closeButton = document.createElement('div');
  41277. var refreshButton = document.createElement('div');
  41278. buttonStyle += ';background-color:' + model.get('buttonColor');
  41279. buttonStyle += ';color:' + model.get('buttonTextColor');
  41280. var self = this;
  41281. function close() {
  41282. container.removeChild(root);
  41283. self._dom = null;
  41284. }
  41285. addEventListener(closeButton, 'click', close);
  41286. addEventListener(refreshButton, 'click', function () {
  41287. var newOption;
  41288. try {
  41289. if (typeof contentToOption === 'function') {
  41290. newOption = contentToOption(viewMain, api.getOption());
  41291. }
  41292. else {
  41293. newOption = parseContents(textarea.value, blockMetaList);
  41294. }
  41295. }
  41296. catch (e) {
  41297. close();
  41298. throw new Error('Data view format error ' + e);
  41299. }
  41300. if (newOption) {
  41301. api.dispatchAction({
  41302. type: 'changeDataView',
  41303. newOption: newOption
  41304. });
  41305. }
  41306. close();
  41307. });
  41308. closeButton.innerHTML = lang$$1[1];
  41309. refreshButton.innerHTML = lang$$1[2];
  41310. refreshButton.style.cssText = buttonStyle;
  41311. closeButton.style.cssText = buttonStyle;
  41312. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  41313. buttonContainer.appendChild(closeButton);
  41314. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  41315. addEventListener(textarea, 'keydown', function (e) {
  41316. if ((e.keyCode || e.which) === 9) {
  41317. // get caret position/selection
  41318. var val = this.value;
  41319. var start = this.selectionStart;
  41320. var end = this.selectionEnd;
  41321. // set textarea value to: text before caret + tab + text after caret
  41322. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  41323. // put caret at right position again
  41324. this.selectionStart = this.selectionEnd = start + 1;
  41325. // prevent the focus lose
  41326. stop(e);
  41327. }
  41328. });
  41329. root.appendChild(header);
  41330. root.appendChild(viewMain);
  41331. root.appendChild(buttonContainer);
  41332. viewMain.style.height = (container.clientHeight - 80) + 'px';
  41333. container.appendChild(root);
  41334. this._dom = root;
  41335. };
  41336. DataView.prototype.remove = function (ecModel, api) {
  41337. this._dom && api.getDom().removeChild(this._dom);
  41338. };
  41339. DataView.prototype.dispose = function (ecModel, api) {
  41340. this.remove(ecModel, api);
  41341. };
  41342. /**
  41343. * @inner
  41344. */
  41345. function tryMergeDataOption(newData, originalData) {
  41346. return map(newData, function (newVal, idx) {
  41347. var original = originalData && originalData[idx];
  41348. if (isObject$1(original) && !isArray(original)) {
  41349. if (isObject$1(newVal) && !isArray(newVal)) {
  41350. newVal = newVal.value;
  41351. }
  41352. // Original data has option
  41353. return defaults({
  41354. value: newVal
  41355. }, original);
  41356. }
  41357. else {
  41358. return newVal;
  41359. }
  41360. });
  41361. }
  41362. register$2('dataView', DataView);
  41363. registerAction({
  41364. type: 'changeDataView',
  41365. event: 'dataViewChanged',
  41366. update: 'prepareAndUpdate'
  41367. }, function (payload, ecModel) {
  41368. var newSeriesOptList = [];
  41369. each$1(payload.newOption.series, function (seriesOpt) {
  41370. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  41371. if (!seriesModel) {
  41372. // New created series
  41373. // Geuss the series type
  41374. newSeriesOptList.push(extend({
  41375. // Default is scatter
  41376. type: 'scatter'
  41377. }, seriesOpt));
  41378. }
  41379. else {
  41380. var originalData = seriesModel.get('data');
  41381. newSeriesOptList.push({
  41382. name: seriesOpt.name,
  41383. data: tryMergeDataOption(seriesOpt.data, originalData)
  41384. });
  41385. }
  41386. });
  41387. ecModel.mergeOption(defaults({
  41388. series: newSeriesOptList
  41389. }, payload.newOption));
  41390. });
  41391. var curry$6 = curry;
  41392. var each$17 = each$1;
  41393. var map$2 = map;
  41394. var mathMin$4 = Math.min;
  41395. var mathMax$4 = Math.max;
  41396. var mathPow$2 = Math.pow;
  41397. var COVER_Z = 10000;
  41398. var UNSELECT_THRESHOLD = 6;
  41399. var MIN_RESIZE_LINE_WIDTH = 6;
  41400. var MUTEX_RESOURCE_KEY = 'globalPan';
  41401. var DIRECTION_MAP = {
  41402. w: [0, 0],
  41403. e: [0, 1],
  41404. n: [1, 0],
  41405. s: [1, 1]
  41406. };
  41407. var CURSOR_MAP = {
  41408. w: 'ew',
  41409. e: 'ew',
  41410. n: 'ns',
  41411. s: 'ns',
  41412. ne: 'nesw',
  41413. sw: 'nesw',
  41414. nw: 'nwse',
  41415. se: 'nwse'
  41416. };
  41417. var DEFAULT_BRUSH_OPT = {
  41418. brushStyle: {
  41419. lineWidth: 2,
  41420. stroke: 'rgba(0,0,0,0.3)',
  41421. fill: 'rgba(0,0,0,0.1)'
  41422. },
  41423. transformable: true,
  41424. brushMode: 'single',
  41425. removeOnClick: false
  41426. };
  41427. var baseUID = 0;
  41428. /**
  41429. * @alias module:echarts/component/helper/BrushController
  41430. * @constructor
  41431. * @mixin {module:zrender/mixin/Eventful}
  41432. * @event module:echarts/component/helper/BrushController#brush
  41433. * params:
  41434. * areas: Array.<Array>, coord relates to container group,
  41435. * If no container specified, to global.
  41436. * opt {
  41437. * isEnd: boolean,
  41438. * removeOnClick: boolean
  41439. * }
  41440. *
  41441. * @param {module:zrender/zrender~ZRender} zr
  41442. */
  41443. function BrushController(zr) {
  41444. if (__DEV__) {
  41445. assert$1(zr);
  41446. }
  41447. Eventful.call(this);
  41448. /**
  41449. * @type {module:zrender/zrender~ZRender}
  41450. * @private
  41451. */
  41452. this._zr = zr;
  41453. /**
  41454. * @type {module:zrender/container/Group}
  41455. * @readOnly
  41456. */
  41457. this.group = new Group();
  41458. /**
  41459. * Only for drawing (after enabledBrush).
  41460. * 'line', 'rect', 'polygon' or false
  41461. * If passing false/null/undefined, disable brush.
  41462. * If passing 'auto', determined by panel.defaultBrushType
  41463. * @private
  41464. * @type {string}
  41465. */
  41466. this._brushType;
  41467. /**
  41468. * Only for drawing (after enabledBrush).
  41469. *
  41470. * @private
  41471. * @type {Object}
  41472. */
  41473. this._brushOption;
  41474. /**
  41475. * @private
  41476. * @type {Object}
  41477. */
  41478. this._panels;
  41479. /**
  41480. * @private
  41481. * @type {Array.<nubmer>}
  41482. */
  41483. this._track = [];
  41484. /**
  41485. * @private
  41486. * @type {boolean}
  41487. */
  41488. this._dragging;
  41489. /**
  41490. * @private
  41491. * @type {Array}
  41492. */
  41493. this._covers = [];
  41494. /**
  41495. * @private
  41496. * @type {moudule:zrender/container/Group}
  41497. */
  41498. this._creatingCover;
  41499. /**
  41500. * `true` means global panel
  41501. * @private
  41502. * @type {module:zrender/container/Group|boolean}
  41503. */
  41504. this._creatingPanel;
  41505. /**
  41506. * @private
  41507. * @type {boolean}
  41508. */
  41509. this._enableGlobalPan;
  41510. /**
  41511. * @private
  41512. * @type {boolean}
  41513. */
  41514. if (__DEV__) {
  41515. this._mounted;
  41516. }
  41517. /**
  41518. * @private
  41519. * @type {string}
  41520. */
  41521. this._uid = 'brushController_' + baseUID++;
  41522. /**
  41523. * @private
  41524. * @type {Object}
  41525. */
  41526. this._handlers = {};
  41527. each$17(mouseHandlers, function (handler, eventName) {
  41528. this._handlers[eventName] = bind(handler, this);
  41529. }, this);
  41530. }
  41531. BrushController.prototype = {
  41532. constructor: BrushController,
  41533. /**
  41534. * If set to null/undefined/false, select disabled.
  41535. * @param {Object} brushOption
  41536. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  41537. * If passing false/null/undefined, disable brush.
  41538. * If passing 'auto', determined by panel.defaultBrushType.
  41539. * ('auto' can not be used in global panel)
  41540. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  41541. * @param {boolean} [brushOption.transformable=true]
  41542. * @param {boolean} [brushOption.removeOnClick=false]
  41543. * @param {Object} [brushOption.brushStyle]
  41544. * @param {number} [brushOption.brushStyle.width]
  41545. * @param {number} [brushOption.brushStyle.lineWidth]
  41546. * @param {string} [brushOption.brushStyle.stroke]
  41547. * @param {string} [brushOption.brushStyle.fill]
  41548. * @param {number} [brushOption.z]
  41549. */
  41550. enableBrush: function (brushOption) {
  41551. if (__DEV__) {
  41552. assert$1(this._mounted);
  41553. }
  41554. this._brushType && doDisableBrush(this);
  41555. brushOption.brushType && doEnableBrush(this, brushOption);
  41556. return this;
  41557. },
  41558. /**
  41559. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  41560. * Each items: {
  41561. * panelId, // mandatory.
  41562. * clipPath, // mandatory. function.
  41563. * isTargetByCursor, // mandatory. function.
  41564. * defaultBrushType, // optional, only used when brushType is 'auto'.
  41565. * getLinearBrushOtherExtent, // optional. function.
  41566. * }
  41567. */
  41568. setPanels: function (panelOpts) {
  41569. if (panelOpts && panelOpts.length) {
  41570. var panels = this._panels = {};
  41571. each$1(panelOpts, function (panelOpts) {
  41572. panels[panelOpts.panelId] = clone(panelOpts);
  41573. });
  41574. }
  41575. else {
  41576. this._panels = null;
  41577. }
  41578. return this;
  41579. },
  41580. /**
  41581. * @param {Object} [opt]
  41582. * @return {boolean} [opt.enableGlobalPan=false]
  41583. */
  41584. mount: function (opt) {
  41585. opt = opt || {};
  41586. if (__DEV__) {
  41587. this._mounted = true; // should be at first.
  41588. }
  41589. this._enableGlobalPan = opt.enableGlobalPan;
  41590. var thisGroup = this.group;
  41591. this._zr.add(thisGroup);
  41592. thisGroup.attr({
  41593. position: opt.position || [0, 0],
  41594. rotation: opt.rotation || 0,
  41595. scale: opt.scale || [1, 1]
  41596. });
  41597. this._transform = thisGroup.getLocalTransform();
  41598. return this;
  41599. },
  41600. eachCover: function (cb, context) {
  41601. each$17(this._covers, cb, context);
  41602. },
  41603. /**
  41604. * Update covers.
  41605. * @param {Array.<Object>} brushOptionList Like:
  41606. * [
  41607. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  41608. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  41609. * ...
  41610. * ]
  41611. * `brushType` is required in each cover info. (can not be 'auto')
  41612. * `id` is not mandatory.
  41613. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  41614. * If brushOptionList is null/undefined, all covers removed.
  41615. */
  41616. updateCovers: function (brushOptionList) {
  41617. if (__DEV__) {
  41618. assert$1(this._mounted);
  41619. }
  41620. brushOptionList = map(brushOptionList, function (brushOption) {
  41621. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  41622. });
  41623. var tmpIdPrefix = '\0-brush-index-';
  41624. var oldCovers = this._covers;
  41625. var newCovers = this._covers = [];
  41626. var controller = this;
  41627. var creatingCover = this._creatingCover;
  41628. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  41629. .add(addOrUpdate)
  41630. .update(addOrUpdate)
  41631. .remove(remove)
  41632. .execute();
  41633. return this;
  41634. function getKey(brushOption, index) {
  41635. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  41636. + '-' + brushOption.brushType;
  41637. }
  41638. function oldGetKey(cover, index) {
  41639. return getKey(cover.__brushOption, index);
  41640. }
  41641. function addOrUpdate(newIndex, oldIndex) {
  41642. var newBrushOption = brushOptionList[newIndex];
  41643. // Consider setOption in event listener of brushSelect,
  41644. // where updating cover when creating should be forbiden.
  41645. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  41646. newCovers[newIndex] = oldCovers[oldIndex];
  41647. }
  41648. else {
  41649. var cover = newCovers[newIndex] = oldIndex != null
  41650. ? (
  41651. oldCovers[oldIndex].__brushOption = newBrushOption,
  41652. oldCovers[oldIndex]
  41653. )
  41654. : endCreating(controller, createCover(controller, newBrushOption));
  41655. updateCoverAfterCreation(controller, cover);
  41656. }
  41657. }
  41658. function remove(oldIndex) {
  41659. if (oldCovers[oldIndex] !== creatingCover) {
  41660. controller.group.remove(oldCovers[oldIndex]);
  41661. }
  41662. }
  41663. },
  41664. unmount: function () {
  41665. if (__DEV__) {
  41666. if (!this._mounted) {
  41667. return;
  41668. }
  41669. }
  41670. this.enableBrush(false);
  41671. // container may 'removeAll' outside.
  41672. clearCovers(this);
  41673. this._zr.remove(this.group);
  41674. if (__DEV__) {
  41675. this._mounted = false; // should be at last.
  41676. }
  41677. return this;
  41678. },
  41679. dispose: function () {
  41680. this.unmount();
  41681. this.off();
  41682. }
  41683. };
  41684. mixin(BrushController, Eventful);
  41685. function doEnableBrush(controller, brushOption) {
  41686. var zr = controller._zr;
  41687. // Consider roam, which takes globalPan too.
  41688. if (!controller._enableGlobalPan) {
  41689. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  41690. }
  41691. each$17(controller._handlers, function (handler, eventName) {
  41692. zr.on(eventName, handler);
  41693. });
  41694. controller._brushType = brushOption.brushType;
  41695. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  41696. }
  41697. function doDisableBrush(controller) {
  41698. var zr = controller._zr;
  41699. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  41700. each$17(controller._handlers, function (handler, eventName) {
  41701. zr.off(eventName, handler);
  41702. });
  41703. controller._brushType = controller._brushOption = null;
  41704. }
  41705. function createCover(controller, brushOption) {
  41706. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  41707. cover.__brushOption = brushOption;
  41708. updateZ$1(cover, brushOption);
  41709. controller.group.add(cover);
  41710. return cover;
  41711. }
  41712. function endCreating(controller, creatingCover) {
  41713. var coverRenderer = getCoverRenderer(creatingCover);
  41714. if (coverRenderer.endCreating) {
  41715. coverRenderer.endCreating(controller, creatingCover);
  41716. updateZ$1(creatingCover, creatingCover.__brushOption);
  41717. }
  41718. return creatingCover;
  41719. }
  41720. function updateCoverShape(controller, cover) {
  41721. var brushOption = cover.__brushOption;
  41722. getCoverRenderer(cover).updateCoverShape(
  41723. controller, cover, brushOption.range, brushOption
  41724. );
  41725. }
  41726. function updateZ$1(cover, brushOption) {
  41727. var z = brushOption.z;
  41728. z == null && (z = COVER_Z);
  41729. cover.traverse(function (el) {
  41730. el.z = z;
  41731. el.z2 = z; // Consider in given container.
  41732. });
  41733. }
  41734. function updateCoverAfterCreation(controller, cover) {
  41735. getCoverRenderer(cover).updateCommon(controller, cover);
  41736. updateCoverShape(controller, cover);
  41737. }
  41738. function getCoverRenderer(cover) {
  41739. return coverRenderers[cover.__brushOption.brushType];
  41740. }
  41741. // return target panel or `true` (means global panel)
  41742. function getPanelByPoint(controller, e, localCursorPoint) {
  41743. var panels = controller._panels;
  41744. if (!panels) {
  41745. return true; // Global panel
  41746. }
  41747. var panel;
  41748. var transform = controller._transform;
  41749. each$17(panels, function (pn) {
  41750. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  41751. });
  41752. return panel;
  41753. }
  41754. // Return a panel or true
  41755. function getPanelByCover(controller, cover) {
  41756. var panels = controller._panels;
  41757. if (!panels) {
  41758. return true; // Global panel
  41759. }
  41760. var panelId = cover.__brushOption.panelId;
  41761. // User may give cover without coord sys info,
  41762. // which is then treated as global panel.
  41763. return panelId != null ? panels[panelId] : true;
  41764. }
  41765. function clearCovers(controller) {
  41766. var covers = controller._covers;
  41767. var originalLength = covers.length;
  41768. each$17(covers, function (cover) {
  41769. controller.group.remove(cover);
  41770. }, controller);
  41771. covers.length = 0;
  41772. return !!originalLength;
  41773. }
  41774. function trigger(controller, opt) {
  41775. var areas = map$2(controller._covers, function (cover) {
  41776. var brushOption = cover.__brushOption;
  41777. var range = clone(brushOption.range);
  41778. return {
  41779. brushType: brushOption.brushType,
  41780. panelId: brushOption.panelId,
  41781. range: range
  41782. };
  41783. });
  41784. controller.trigger('brush', areas, {
  41785. isEnd: !!opt.isEnd,
  41786. removeOnClick: !!opt.removeOnClick
  41787. });
  41788. }
  41789. function shouldShowCover(controller) {
  41790. var track = controller._track;
  41791. if (!track.length) {
  41792. return false;
  41793. }
  41794. var p2 = track[track.length - 1];
  41795. var p1 = track[0];
  41796. var dx = p2[0] - p1[0];
  41797. var dy = p2[1] - p1[1];
  41798. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  41799. return dist > UNSELECT_THRESHOLD;
  41800. }
  41801. function getTrackEnds(track) {
  41802. var tail = track.length - 1;
  41803. tail < 0 && (tail = 0);
  41804. return [track[0], track[tail]];
  41805. }
  41806. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  41807. var cover = new Group();
  41808. cover.add(new Rect({
  41809. name: 'main',
  41810. style: makeStyle(brushOption),
  41811. silent: true,
  41812. draggable: true,
  41813. cursor: 'move',
  41814. drift: curry$6(doDrift, controller, cover, 'nswe'),
  41815. ondragend: curry$6(trigger, controller, {isEnd: true})
  41816. }));
  41817. each$17(
  41818. edgeNames,
  41819. function (name) {
  41820. cover.add(new Rect({
  41821. name: name,
  41822. style: {opacity: 0},
  41823. draggable: true,
  41824. silent: true,
  41825. invisible: true,
  41826. drift: curry$6(doDrift, controller, cover, name),
  41827. ondragend: curry$6(trigger, controller, {isEnd: true})
  41828. }));
  41829. }
  41830. );
  41831. return cover;
  41832. }
  41833. function updateBaseRect(controller, cover, localRange, brushOption) {
  41834. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  41835. var handleSize = mathMax$4(lineWidth, MIN_RESIZE_LINE_WIDTH);
  41836. var x = localRange[0][0];
  41837. var y = localRange[1][0];
  41838. var xa = x - lineWidth / 2;
  41839. var ya = y - lineWidth / 2;
  41840. var x2 = localRange[0][1];
  41841. var y2 = localRange[1][1];
  41842. var x2a = x2 - handleSize + lineWidth / 2;
  41843. var y2a = y2 - handleSize + lineWidth / 2;
  41844. var width = x2 - x;
  41845. var height = y2 - y;
  41846. var widtha = width + lineWidth;
  41847. var heighta = height + lineWidth;
  41848. updateRectShape(controller, cover, 'main', x, y, width, height);
  41849. if (brushOption.transformable) {
  41850. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  41851. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  41852. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  41853. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  41854. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  41855. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  41856. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  41857. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  41858. }
  41859. }
  41860. function updateCommon(controller, cover) {
  41861. var brushOption = cover.__brushOption;
  41862. var transformable = brushOption.transformable;
  41863. var mainEl = cover.childAt(0);
  41864. mainEl.useStyle(makeStyle(brushOption));
  41865. mainEl.attr({
  41866. silent: !transformable,
  41867. cursor: transformable ? 'move' : 'default'
  41868. });
  41869. each$17(
  41870. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  41871. function (name) {
  41872. var el = cover.childOfName(name);
  41873. var globalDir = getGlobalDirection(controller, name);
  41874. el && el.attr({
  41875. silent: !transformable,
  41876. invisible: !transformable,
  41877. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  41878. });
  41879. }
  41880. );
  41881. }
  41882. function updateRectShape(controller, cover, name, x, y, w, h) {
  41883. var el = cover.childOfName(name);
  41884. el && el.setShape(pointsToRect(
  41885. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  41886. ));
  41887. }
  41888. function makeStyle(brushOption) {
  41889. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  41890. }
  41891. function formatRectRange(x, y, x2, y2) {
  41892. var min = [mathMin$4(x, x2), mathMin$4(y, y2)];
  41893. var max = [mathMax$4(x, x2), mathMax$4(y, y2)];
  41894. return [
  41895. [min[0], max[0]], // x range
  41896. [min[1], max[1]] // y range
  41897. ];
  41898. }
  41899. function getTransform$1(controller) {
  41900. return getTransform(controller.group);
  41901. }
  41902. function getGlobalDirection(controller, localDirection) {
  41903. if (localDirection.length > 1) {
  41904. localDirection = localDirection.split('');
  41905. var globalDir = [
  41906. getGlobalDirection(controller, localDirection[0]),
  41907. getGlobalDirection(controller, localDirection[1])
  41908. ];
  41909. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  41910. return globalDir.join('');
  41911. }
  41912. else {
  41913. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  41914. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  41915. var globalDir = transformDirection(
  41916. map$$1[localDirection], getTransform$1(controller)
  41917. );
  41918. return inverseMap[globalDir];
  41919. }
  41920. }
  41921. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  41922. var brushOption = cover.__brushOption;
  41923. var rectRange = toRectRange(brushOption.range);
  41924. var localDelta = toLocalDelta(controller, dx, dy);
  41925. each$17(name.split(''), function (namePart) {
  41926. var ind = DIRECTION_MAP[namePart];
  41927. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  41928. });
  41929. brushOption.range = fromRectRange(formatRectRange(
  41930. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  41931. ));
  41932. updateCoverAfterCreation(controller, cover);
  41933. trigger(controller, {isEnd: false});
  41934. }
  41935. function driftPolygon(controller, cover, dx, dy, e) {
  41936. var range = cover.__brushOption.range;
  41937. var localDelta = toLocalDelta(controller, dx, dy);
  41938. each$17(range, function (point) {
  41939. point[0] += localDelta[0];
  41940. point[1] += localDelta[1];
  41941. });
  41942. updateCoverAfterCreation(controller, cover);
  41943. trigger(controller, {isEnd: false});
  41944. }
  41945. function toLocalDelta(controller, dx, dy) {
  41946. var thisGroup = controller.group;
  41947. var localD = thisGroup.transformCoordToLocal(dx, dy);
  41948. var localZero = thisGroup.transformCoordToLocal(0, 0);
  41949. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  41950. }
  41951. function clipByPanel(controller, cover, data) {
  41952. var panel = getPanelByCover(controller, cover);
  41953. return (panel && panel !== true)
  41954. ? panel.clipPath(data, controller._transform)
  41955. : clone(data);
  41956. }
  41957. function pointsToRect(points) {
  41958. var xmin = mathMin$4(points[0][0], points[1][0]);
  41959. var ymin = mathMin$4(points[0][1], points[1][1]);
  41960. var xmax = mathMax$4(points[0][0], points[1][0]);
  41961. var ymax = mathMax$4(points[0][1], points[1][1]);
  41962. return {
  41963. x: xmin,
  41964. y: ymin,
  41965. width: xmax - xmin,
  41966. height: ymax - ymin
  41967. };
  41968. }
  41969. function resetCursor(controller, e, localCursorPoint) {
  41970. // Check active
  41971. if (!controller._brushType) {
  41972. return;
  41973. }
  41974. var zr = controller._zr;
  41975. var covers = controller._covers;
  41976. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  41977. // Check whether in covers.
  41978. if (!controller._dragging) {
  41979. for (var i = 0; i < covers.length; i++) {
  41980. var brushOption = covers[i].__brushOption;
  41981. if (currPanel
  41982. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  41983. && coverRenderers[brushOption.brushType].contain(
  41984. covers[i], localCursorPoint[0], localCursorPoint[1]
  41985. )
  41986. ) {
  41987. // Use cursor style set on cover.
  41988. return;
  41989. }
  41990. }
  41991. }
  41992. currPanel && zr.setCursorStyle('crosshair');
  41993. }
  41994. function preventDefault(e) {
  41995. var rawE = e.event;
  41996. rawE.preventDefault && rawE.preventDefault();
  41997. }
  41998. function mainShapeContain(cover, x, y) {
  41999. return cover.childOfName('main').contain(x, y);
  42000. }
  42001. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  42002. var creatingCover = controller._creatingCover;
  42003. var panel = controller._creatingPanel;
  42004. var thisBrushOption = controller._brushOption;
  42005. var eventParams;
  42006. controller._track.push(localCursorPoint.slice());
  42007. if (shouldShowCover(controller) || creatingCover) {
  42008. if (panel && !creatingCover) {
  42009. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  42010. var brushOption = clone(thisBrushOption);
  42011. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  42012. brushOption.panelId = panel === true ? null : panel.panelId;
  42013. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  42014. controller._covers.push(creatingCover);
  42015. }
  42016. if (creatingCover) {
  42017. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  42018. var coverBrushOption = creatingCover.__brushOption;
  42019. coverBrushOption.range = coverRenderer.getCreatingRange(
  42020. clipByPanel(controller, creatingCover, controller._track)
  42021. );
  42022. if (isEnd) {
  42023. endCreating(controller, creatingCover);
  42024. coverRenderer.updateCommon(controller, creatingCover);
  42025. }
  42026. updateCoverShape(controller, creatingCover);
  42027. eventParams = {isEnd: isEnd};
  42028. }
  42029. }
  42030. else if (
  42031. isEnd
  42032. && thisBrushOption.brushMode === 'single'
  42033. && thisBrushOption.removeOnClick
  42034. ) {
  42035. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  42036. // But a single click do not clear covers, because user may have casual
  42037. // clicks (for example, click on other component and do not expect covers
  42038. // disappear).
  42039. // Only some cover removed, trigger action, but not every click trigger action.
  42040. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  42041. eventParams = {isEnd: isEnd, removeOnClick: true};
  42042. }
  42043. }
  42044. return eventParams;
  42045. }
  42046. function determineBrushType(brushType, panel) {
  42047. if (brushType === 'auto') {
  42048. if (__DEV__) {
  42049. assert$1(
  42050. panel && panel.defaultBrushType,
  42051. 'MUST have defaultBrushType when brushType is "atuo"'
  42052. );
  42053. }
  42054. return panel.defaultBrushType;
  42055. }
  42056. return brushType;
  42057. }
  42058. var mouseHandlers = {
  42059. mousedown: function (e) {
  42060. if (this._dragging) {
  42061. // In case some browser do not support globalOut,
  42062. // and release mose out side the browser.
  42063. handleDragEnd.call(this, e);
  42064. }
  42065. else if (!e.target || !e.target.draggable) {
  42066. preventDefault(e);
  42067. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42068. this._creatingCover = null;
  42069. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  42070. if (panel) {
  42071. this._dragging = true;
  42072. this._track = [localCursorPoint.slice()];
  42073. }
  42074. }
  42075. },
  42076. mousemove: function (e) {
  42077. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42078. resetCursor(this, e, localCursorPoint);
  42079. if (this._dragging) {
  42080. preventDefault(e);
  42081. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  42082. eventParams && trigger(this, eventParams);
  42083. }
  42084. },
  42085. mouseup: handleDragEnd //,
  42086. // FIXME
  42087. // in tooltip, globalout should not be triggered.
  42088. // globalout: handleDragEnd
  42089. };
  42090. function handleDragEnd(e) {
  42091. if (this._dragging) {
  42092. preventDefault(e);
  42093. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42094. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  42095. this._dragging = false;
  42096. this._track = [];
  42097. this._creatingCover = null;
  42098. // trigger event shoule be at final, after procedure will be nested.
  42099. eventParams && trigger(this, eventParams);
  42100. }
  42101. }
  42102. /**
  42103. * key: brushType
  42104. * @type {Object}
  42105. */
  42106. var coverRenderers = {
  42107. lineX: getLineRenderer(0),
  42108. lineY: getLineRenderer(1),
  42109. rect: {
  42110. createCover: function (controller, brushOption) {
  42111. return createBaseRectCover(
  42112. curry$6(
  42113. driftRect,
  42114. function (range) {
  42115. return range;
  42116. },
  42117. function (range) {
  42118. return range;
  42119. }
  42120. ),
  42121. controller,
  42122. brushOption,
  42123. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  42124. );
  42125. },
  42126. getCreatingRange: function (localTrack) {
  42127. var ends = getTrackEnds(localTrack);
  42128. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  42129. },
  42130. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42131. updateBaseRect(controller, cover, localRange, brushOption);
  42132. },
  42133. updateCommon: updateCommon,
  42134. contain: mainShapeContain
  42135. },
  42136. polygon: {
  42137. createCover: function (controller, brushOption) {
  42138. var cover = new Group();
  42139. // Do not use graphic.Polygon because graphic.Polyline do not close the
  42140. // border of the shape when drawing, which is a better experience for user.
  42141. cover.add(new Polyline({
  42142. name: 'main',
  42143. style: makeStyle(brushOption),
  42144. silent: true
  42145. }));
  42146. return cover;
  42147. },
  42148. getCreatingRange: function (localTrack) {
  42149. return localTrack;
  42150. },
  42151. endCreating: function (controller, cover) {
  42152. cover.remove(cover.childAt(0));
  42153. // Use graphic.Polygon close the shape.
  42154. cover.add(new Polygon({
  42155. name: 'main',
  42156. draggable: true,
  42157. drift: curry$6(driftPolygon, controller, cover),
  42158. ondragend: curry$6(trigger, controller, {isEnd: true})
  42159. }));
  42160. },
  42161. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42162. cover.childAt(0).setShape({
  42163. points: clipByPanel(controller, cover, localRange)
  42164. });
  42165. },
  42166. updateCommon: updateCommon,
  42167. contain: mainShapeContain
  42168. }
  42169. };
  42170. function getLineRenderer(xyIndex) {
  42171. return {
  42172. createCover: function (controller, brushOption) {
  42173. return createBaseRectCover(
  42174. curry$6(
  42175. driftRect,
  42176. function (range) {
  42177. var rectRange = [range, [0, 100]];
  42178. xyIndex && rectRange.reverse();
  42179. return rectRange;
  42180. },
  42181. function (rectRange) {
  42182. return rectRange[xyIndex];
  42183. }
  42184. ),
  42185. controller,
  42186. brushOption,
  42187. [['w', 'e'], ['n', 's']][xyIndex]
  42188. );
  42189. },
  42190. getCreatingRange: function (localTrack) {
  42191. var ends = getTrackEnds(localTrack);
  42192. var min = mathMin$4(ends[0][xyIndex], ends[1][xyIndex]);
  42193. var max = mathMax$4(ends[0][xyIndex], ends[1][xyIndex]);
  42194. return [min, max];
  42195. },
  42196. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42197. var otherExtent;
  42198. // If brushWidth not specified, fit the panel.
  42199. var panel = getPanelByCover(controller, cover);
  42200. if (panel !== true && panel.getLinearBrushOtherExtent) {
  42201. otherExtent = panel.getLinearBrushOtherExtent(
  42202. xyIndex, controller._transform
  42203. );
  42204. }
  42205. else {
  42206. var zr = controller._zr;
  42207. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  42208. }
  42209. var rectRange = [localRange, otherExtent];
  42210. xyIndex && rectRange.reverse();
  42211. updateBaseRect(controller, cover, rectRange, brushOption);
  42212. },
  42213. updateCommon: updateCommon,
  42214. contain: mainShapeContain
  42215. };
  42216. }
  42217. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  42218. /**
  42219. * Avoid that: mouse click on a elements that is over geo or graph,
  42220. * but roam is triggered.
  42221. */
  42222. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42223. var model = api.getComponentByElement(e.topTarget);
  42224. // If model is axisModel, it works only if it is injected with coordinateSystem.
  42225. var coordSys = model && model.coordinateSystem;
  42226. return model
  42227. && model !== targetCoordSysModel
  42228. && !IRRELEVANT_EXCLUDES[model.mainType]
  42229. && (coordSys && coordSys.model !== targetCoordSysModel);
  42230. }
  42231. function makeRectPanelClipPath(rect) {
  42232. rect = normalizeRect(rect);
  42233. return function (localPoints, transform) {
  42234. return clipPointsByRect(localPoints, rect);
  42235. };
  42236. }
  42237. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  42238. rect = normalizeRect(rect);
  42239. return function (xyIndex) {
  42240. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  42241. var brushWidth = idx ? rect.width : rect.height;
  42242. var base = idx ? rect.x : rect.y;
  42243. return [base, base + (brushWidth || 0)];
  42244. };
  42245. }
  42246. function makeRectIsTargetByCursor(rect, api, targetModel) {
  42247. rect = normalizeRect(rect);
  42248. return function (e, localCursorPoint, transform) {
  42249. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  42250. && !onIrrelevantElement(e, api, targetModel);
  42251. };
  42252. }
  42253. // Consider width/height is negative.
  42254. function normalizeRect(rect) {
  42255. return BoundingRect.create(rect);
  42256. }
  42257. var each$18 = each$1;
  42258. var indexOf$2 = indexOf;
  42259. var curry$7 = curry;
  42260. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  42261. // FIXME
  42262. // how to genarialize to more coordinate systems.
  42263. var INCLUDE_FINDER_MAIN_TYPES = [
  42264. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  42265. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  42266. ];
  42267. /**
  42268. * [option in constructor]:
  42269. * {
  42270. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42271. * }
  42272. *
  42273. *
  42274. * [targetInfo]:
  42275. *
  42276. * There can be multiple axes in a single targetInfo. Consider the case
  42277. * of `grid` component, a targetInfo represents a grid which contains one or more
  42278. * cartesian and one or more axes. And consider the case of parallel system,
  42279. * which has multiple axes in a coordinate system.
  42280. * Can be {
  42281. * panelId: ...,
  42282. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  42283. * coordSyses: all cartesians.
  42284. * gridModel: <grid component>
  42285. * xAxes: correspond to coordSyses on index
  42286. * yAxes: correspond to coordSyses on index
  42287. * }
  42288. * or {
  42289. * panelId: ...,
  42290. * coordSys: <geo coord sys>
  42291. * coordSyses: [<geo coord sys>]
  42292. * geoModel: <geo component>
  42293. * }
  42294. *
  42295. *
  42296. * [panelOpt]:
  42297. *
  42298. * Make from targetInfo. Input to BrushController.
  42299. * {
  42300. * panelId: ...,
  42301. * rect: ...
  42302. * }
  42303. *
  42304. *
  42305. * [area]:
  42306. *
  42307. * Generated by BrushController or user input.
  42308. * {
  42309. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  42310. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  42311. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42312. * range: pixel range.
  42313. * coordRange: representitive coord range (the first one of coordRanges).
  42314. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  42315. * }
  42316. */
  42317. /**
  42318. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  42319. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  42320. * @param {module:echarts/model/Global} ecModel
  42321. * @param {Object} [opt]
  42322. * @param {Array.<string>} [opt.include] include coordinate system types.
  42323. */
  42324. function BrushTargetManager(option, ecModel, opt) {
  42325. /**
  42326. * @private
  42327. * @type {Array.<Object>}
  42328. */
  42329. var targetInfoList = this._targetInfoList = [];
  42330. var info = {};
  42331. var foundCpts = parseFinder$1(ecModel, option);
  42332. each$18(targetInfoBuilders, function (builder, type) {
  42333. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  42334. builder(foundCpts, targetInfoList, info);
  42335. }
  42336. });
  42337. }
  42338. var proto$5 = BrushTargetManager.prototype;
  42339. proto$5.setOutputRanges = function (areas, ecModel) {
  42340. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  42341. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  42342. // area.coordRange is the first of area.coordRanges
  42343. if (!area.coordRange) {
  42344. area.coordRange = coordRange;
  42345. // In 'category' axis, coord to pixel is not reversible, so we can not
  42346. // rebuild range by coordRange accrately, which may bring trouble when
  42347. // brushing only one item. So we use __rangeOffset to rebuilding range
  42348. // by coordRange. And this it only used in brush component so it is no
  42349. // need to be adapted to coordRanges.
  42350. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  42351. area.__rangeOffset = {
  42352. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  42353. xyMinMax: result.xyMinMax
  42354. };
  42355. }
  42356. });
  42357. };
  42358. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  42359. each$18(areas, function (area) {
  42360. var targetInfo = this.findTargetInfo(area, ecModel);
  42361. if (targetInfo && targetInfo !== true) {
  42362. each$1(
  42363. targetInfo.coordSyses,
  42364. function (coordSys) {
  42365. var result = coordConvert[area.brushType](1, coordSys, area.range);
  42366. cb(area, result.values, coordSys, ecModel);
  42367. }
  42368. );
  42369. }
  42370. }, this);
  42371. };
  42372. proto$5.setInputRanges = function (areas, ecModel) {
  42373. each$18(areas, function (area) {
  42374. var targetInfo = this.findTargetInfo(area, ecModel);
  42375. if (__DEV__) {
  42376. assert$1(
  42377. !targetInfo || targetInfo === true || area.coordRange,
  42378. 'coordRange must be specified when coord index specified.'
  42379. );
  42380. assert$1(
  42381. !targetInfo || targetInfo !== true || area.range,
  42382. 'range must be specified in global brush.'
  42383. );
  42384. }
  42385. area.range = area.range || [];
  42386. // convert coordRange to global range and set panelId.
  42387. if (targetInfo && targetInfo !== true) {
  42388. area.panelId = targetInfo.panelId;
  42389. // (1) area.range shoule always be calculate from coordRange but does
  42390. // not keep its original value, for the sake of the dataZoom scenario,
  42391. // where area.coordRange remains unchanged but area.range may be changed.
  42392. // (2) Only support converting one coordRange to pixel range in brush
  42393. // component. So do not consider `coordRanges`.
  42394. // (3) About __rangeOffset, see comment above.
  42395. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  42396. var rangeOffset = area.__rangeOffset;
  42397. area.range = rangeOffset
  42398. ? diffProcessor[area.brushType](
  42399. result.values,
  42400. rangeOffset.offset,
  42401. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  42402. )
  42403. : result.values;
  42404. }
  42405. }, this);
  42406. };
  42407. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  42408. return map(this._targetInfoList, function (targetInfo) {
  42409. var rect = targetInfo.getPanelRect();
  42410. return {
  42411. panelId: targetInfo.panelId,
  42412. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  42413. clipPath: makeRectPanelClipPath(rect),
  42414. isTargetByCursor: makeRectIsTargetByCursor(
  42415. rect, api, targetInfo.coordSysModel
  42416. ),
  42417. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  42418. };
  42419. });
  42420. };
  42421. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  42422. // Check whether area is bound in coord, and series do not belong to that coord.
  42423. // If do not do this check, some brush (like lineX) will controll all axes.
  42424. var targetInfo = this.findTargetInfo(area, ecModel);
  42425. return targetInfo === true || (
  42426. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  42427. );
  42428. };
  42429. /**
  42430. * If return Object, a coord found.
  42431. * If reutrn true, global found.
  42432. * Otherwise nothing found.
  42433. *
  42434. * @param {Object} area
  42435. * @param {Array} targetInfoList
  42436. * @return {Object|boolean}
  42437. */
  42438. proto$5.findTargetInfo = function (area, ecModel) {
  42439. var targetInfoList = this._targetInfoList;
  42440. var foundCpts = parseFinder$1(ecModel, area);
  42441. for (var i = 0; i < targetInfoList.length; i++) {
  42442. var targetInfo = targetInfoList[i];
  42443. var areaPanelId = area.panelId;
  42444. if (areaPanelId) {
  42445. if (targetInfo.panelId === areaPanelId) {
  42446. return targetInfo;
  42447. }
  42448. }
  42449. else {
  42450. for (var i = 0; i < targetInfoMatchers.length; i++) {
  42451. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  42452. return targetInfo;
  42453. }
  42454. }
  42455. }
  42456. }
  42457. return true;
  42458. };
  42459. function formatMinMax(minMax) {
  42460. minMax[0] > minMax[1] && minMax.reverse();
  42461. return minMax;
  42462. }
  42463. function parseFinder$1(ecModel, option) {
  42464. return parseFinder(
  42465. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  42466. );
  42467. }
  42468. var targetInfoBuilders = {
  42469. grid: function (foundCpts, targetInfoList) {
  42470. var xAxisModels = foundCpts.xAxisModels;
  42471. var yAxisModels = foundCpts.yAxisModels;
  42472. var gridModels = foundCpts.gridModels;
  42473. // Remove duplicated.
  42474. var gridModelMap = createHashMap();
  42475. var xAxesHas = {};
  42476. var yAxesHas = {};
  42477. if (!xAxisModels && !yAxisModels && !gridModels) {
  42478. return;
  42479. }
  42480. each$18(xAxisModels, function (axisModel) {
  42481. var gridModel = axisModel.axis.grid.model;
  42482. gridModelMap.set(gridModel.id, gridModel);
  42483. xAxesHas[gridModel.id] = true;
  42484. });
  42485. each$18(yAxisModels, function (axisModel) {
  42486. var gridModel = axisModel.axis.grid.model;
  42487. gridModelMap.set(gridModel.id, gridModel);
  42488. yAxesHas[gridModel.id] = true;
  42489. });
  42490. each$18(gridModels, function (gridModel) {
  42491. gridModelMap.set(gridModel.id, gridModel);
  42492. xAxesHas[gridModel.id] = true;
  42493. yAxesHas[gridModel.id] = true;
  42494. });
  42495. gridModelMap.each(function (gridModel) {
  42496. var grid = gridModel.coordinateSystem;
  42497. var cartesians = [];
  42498. each$18(grid.getCartesians(), function (cartesian, index) {
  42499. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  42500. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  42501. ) {
  42502. cartesians.push(cartesian);
  42503. }
  42504. });
  42505. targetInfoList.push({
  42506. panelId: 'grid--' + gridModel.id,
  42507. gridModel: gridModel,
  42508. coordSysModel: gridModel,
  42509. // Use the first one as the representitive coordSys.
  42510. coordSys: cartesians[0],
  42511. coordSyses: cartesians,
  42512. getPanelRect: panelRectBuilder.grid,
  42513. xAxisDeclared: xAxesHas[gridModel.id],
  42514. yAxisDeclared: yAxesHas[gridModel.id]
  42515. });
  42516. });
  42517. },
  42518. geo: function (foundCpts, targetInfoList) {
  42519. each$18(foundCpts.geoModels, function (geoModel) {
  42520. var coordSys = geoModel.coordinateSystem;
  42521. targetInfoList.push({
  42522. panelId: 'geo--' + geoModel.id,
  42523. geoModel: geoModel,
  42524. coordSysModel: geoModel,
  42525. coordSys: coordSys,
  42526. coordSyses: [coordSys],
  42527. getPanelRect: panelRectBuilder.geo
  42528. });
  42529. });
  42530. }
  42531. };
  42532. var targetInfoMatchers = [
  42533. // grid
  42534. function (foundCpts, targetInfo) {
  42535. var xAxisModel = foundCpts.xAxisModel;
  42536. var yAxisModel = foundCpts.yAxisModel;
  42537. var gridModel = foundCpts.gridModel;
  42538. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  42539. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  42540. return gridModel && gridModel === targetInfo.gridModel;
  42541. },
  42542. // geo
  42543. function (foundCpts, targetInfo) {
  42544. var geoModel = foundCpts.geoModel;
  42545. return geoModel && geoModel === targetInfo.geoModel;
  42546. }
  42547. ];
  42548. var panelRectBuilder = {
  42549. grid: function () {
  42550. // grid is not Transformable.
  42551. return this.coordSys.grid.getRect().clone();
  42552. },
  42553. geo: function () {
  42554. var coordSys = this.coordSys;
  42555. var rect = coordSys.getBoundingRect().clone();
  42556. // geo roam and zoom transform
  42557. rect.applyTransform(getTransform(coordSys));
  42558. return rect;
  42559. }
  42560. };
  42561. var coordConvert = {
  42562. lineX: curry$7(axisConvert, 0),
  42563. lineY: curry$7(axisConvert, 1),
  42564. rect: function (to, coordSys, rangeOrCoordRange) {
  42565. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  42566. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  42567. var values = [
  42568. formatMinMax([xminymin[0], xmaxymax[0]]),
  42569. formatMinMax([xminymin[1], xmaxymax[1]])
  42570. ];
  42571. return {values: values, xyMinMax: values};
  42572. },
  42573. polygon: function (to, coordSys, rangeOrCoordRange) {
  42574. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  42575. var values = map(rangeOrCoordRange, function (item) {
  42576. var p = coordSys[COORD_CONVERTS[to]](item);
  42577. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  42578. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  42579. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  42580. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  42581. return p;
  42582. });
  42583. return {values: values, xyMinMax: xyMinMax};
  42584. }
  42585. };
  42586. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  42587. if (__DEV__) {
  42588. assert$1(
  42589. coordSys.type === 'cartesian2d',
  42590. 'lineX/lineY brush is available only in cartesian2d.'
  42591. );
  42592. }
  42593. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  42594. var values = formatMinMax(map([0, 1], function (i) {
  42595. return to
  42596. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  42597. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  42598. }));
  42599. var xyMinMax = [];
  42600. xyMinMax[axisNameIndex] = values;
  42601. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  42602. return {values: values, xyMinMax: xyMinMax};
  42603. }
  42604. var diffProcessor = {
  42605. lineX: curry$7(axisDiffProcessor, 0),
  42606. lineY: curry$7(axisDiffProcessor, 1),
  42607. rect: function (values, refer, scales) {
  42608. return [
  42609. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  42610. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  42611. ];
  42612. },
  42613. polygon: function (values, refer, scales) {
  42614. return map(values, function (item, idx) {
  42615. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  42616. });
  42617. }
  42618. };
  42619. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  42620. return [
  42621. values[0] - scales[axisNameIndex] * refer[0],
  42622. values[1] - scales[axisNameIndex] * refer[1]
  42623. ];
  42624. }
  42625. // We have to process scale caused by dataZoom manually,
  42626. // although it might be not accurate.
  42627. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  42628. var sizeCurr = getSize(xyMinMaxCurr);
  42629. var sizeOrigin = getSize(xyMinMaxOrigin);
  42630. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  42631. isNaN(scales[0]) && (scales[0] = 1);
  42632. isNaN(scales[1]) && (scales[1] = 1);
  42633. return scales;
  42634. }
  42635. function getSize(xyMinMax) {
  42636. return xyMinMax
  42637. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  42638. : [NaN, NaN];
  42639. }
  42640. var each$19 = each$1;
  42641. var ATTR$2 = '\0_ec_hist_store';
  42642. /**
  42643. * @param {module:echarts/model/Global} ecModel
  42644. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  42645. */
  42646. function push(ecModel, newSnapshot) {
  42647. var store = giveStore$1(ecModel);
  42648. // If previous dataZoom can not be found,
  42649. // complete an range with current range.
  42650. each$19(newSnapshot, function (batchItem, dataZoomId) {
  42651. var i = store.length - 1;
  42652. for (; i >= 0; i--) {
  42653. var snapshot = store[i];
  42654. if (snapshot[dataZoomId]) {
  42655. break;
  42656. }
  42657. }
  42658. if (i < 0) {
  42659. // No origin range set, create one by current range.
  42660. var dataZoomModel = ecModel.queryComponents(
  42661. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  42662. )[0];
  42663. if (dataZoomModel) {
  42664. var percentRange = dataZoomModel.getPercentRange();
  42665. store[0][dataZoomId] = {
  42666. dataZoomId: dataZoomId,
  42667. start: percentRange[0],
  42668. end: percentRange[1]
  42669. };
  42670. }
  42671. }
  42672. });
  42673. store.push(newSnapshot);
  42674. }
  42675. /**
  42676. * @param {module:echarts/model/Global} ecModel
  42677. * @return {Object} snapshot
  42678. */
  42679. function pop(ecModel) {
  42680. var store = giveStore$1(ecModel);
  42681. var head = store[store.length - 1];
  42682. store.length > 1 && store.pop();
  42683. // Find top for all dataZoom.
  42684. var snapshot = {};
  42685. each$19(head, function (batchItem, dataZoomId) {
  42686. for (var i = store.length - 1; i >= 0; i--) {
  42687. var batchItem = store[i][dataZoomId];
  42688. if (batchItem) {
  42689. snapshot[dataZoomId] = batchItem;
  42690. break;
  42691. }
  42692. }
  42693. });
  42694. return snapshot;
  42695. }
  42696. /**
  42697. * @param {module:echarts/model/Global} ecModel
  42698. */
  42699. function clear$1(ecModel) {
  42700. ecModel[ATTR$2] = null;
  42701. }
  42702. /**
  42703. * @param {module:echarts/model/Global} ecModel
  42704. * @return {number} records. always >= 1.
  42705. */
  42706. function count(ecModel) {
  42707. return giveStore$1(ecModel).length;
  42708. }
  42709. /**
  42710. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  42711. * History length of each dataZoom may be different.
  42712. * this._history[0] is used to store origin range.
  42713. * @type {Array.<Object>}
  42714. */
  42715. function giveStore$1(ecModel) {
  42716. var store = ecModel[ATTR$2];
  42717. if (!store) {
  42718. store = ecModel[ATTR$2] = [{}];
  42719. }
  42720. return store;
  42721. }
  42722. DataZoomModel.extend({
  42723. type: 'dataZoom.select'
  42724. });
  42725. DataZoomView.extend({
  42726. type: 'dataZoom.select'
  42727. });
  42728. /**
  42729. * DataZoom component entry
  42730. */
  42731. // Use dataZoomSelect
  42732. var dataZoomLang = lang.toolbox.dataZoom;
  42733. var each$16 = each$1;
  42734. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  42735. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  42736. function DataZoom(model, ecModel, api) {
  42737. /**
  42738. * @private
  42739. * @type {module:echarts/component/helper/BrushController}
  42740. */
  42741. (this._brushController = new BrushController(api.getZr()))
  42742. .on('brush', bind(this._onBrush, this))
  42743. .mount();
  42744. /**
  42745. * @private
  42746. * @type {boolean}
  42747. */
  42748. this._isZoomActive;
  42749. }
  42750. DataZoom.defaultOption = {
  42751. show: true,
  42752. // Icon group
  42753. icon: {
  42754. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  42755. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  42756. },
  42757. // `zoom`, `back`
  42758. title: clone(dataZoomLang.title)
  42759. };
  42760. var proto$4 = DataZoom.prototype;
  42761. proto$4.render = function (featureModel, ecModel, api, payload) {
  42762. this.model = featureModel;
  42763. this.ecModel = ecModel;
  42764. this.api = api;
  42765. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  42766. updateBackBtnStatus(featureModel, ecModel);
  42767. };
  42768. proto$4.onclick = function (ecModel, api, type) {
  42769. handlers[type].call(this);
  42770. };
  42771. proto$4.remove = function (ecModel, api) {
  42772. this._brushController.unmount();
  42773. };
  42774. proto$4.dispose = function (ecModel, api) {
  42775. this._brushController.dispose();
  42776. };
  42777. /**
  42778. * @private
  42779. */
  42780. var handlers = {
  42781. zoom: function () {
  42782. var nextActive = !this._isZoomActive;
  42783. this.api.dispatchAction({
  42784. type: 'takeGlobalCursor',
  42785. key: 'dataZoomSelect',
  42786. dataZoomSelectActive: nextActive
  42787. });
  42788. },
  42789. back: function () {
  42790. this._dispatchZoomAction(pop(this.ecModel));
  42791. }
  42792. };
  42793. /**
  42794. * @private
  42795. */
  42796. proto$4._onBrush = function (areas, opt) {
  42797. if (!opt.isEnd || !areas.length) {
  42798. return;
  42799. }
  42800. var snapshot = {};
  42801. var ecModel = this.ecModel;
  42802. this._brushController.updateCovers([]); // remove cover
  42803. var brushTargetManager = new BrushTargetManager(
  42804. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  42805. );
  42806. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  42807. if (coordSys.type !== 'cartesian2d') {
  42808. return;
  42809. }
  42810. var brushType = area.brushType;
  42811. if (brushType === 'rect') {
  42812. setBatch('x', coordSys, coordRange[0]);
  42813. setBatch('y', coordSys, coordRange[1]);
  42814. }
  42815. else {
  42816. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  42817. }
  42818. });
  42819. push(ecModel, snapshot);
  42820. this._dispatchZoomAction(snapshot);
  42821. function setBatch(dimName, coordSys, minMax) {
  42822. var axis = coordSys.getAxis(dimName);
  42823. var axisModel = axis.model;
  42824. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  42825. // Restrict range.
  42826. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  42827. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  42828. minMax = sliderMove(
  42829. 0, minMax.slice(), axis.scale.getExtent(), 0,
  42830. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  42831. );
  42832. }
  42833. dataZoomModel && (snapshot[dataZoomModel.id] = {
  42834. dataZoomId: dataZoomModel.id,
  42835. startValue: minMax[0],
  42836. endValue: minMax[1]
  42837. });
  42838. }
  42839. function findDataZoom(dimName, axisModel, ecModel) {
  42840. var found;
  42841. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  42842. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  42843. has && (found = dzModel);
  42844. });
  42845. return found;
  42846. }
  42847. };
  42848. /**
  42849. * @private
  42850. */
  42851. proto$4._dispatchZoomAction = function (snapshot) {
  42852. var batch = [];
  42853. // Convert from hash map to array.
  42854. each$16(snapshot, function (batchItem, dataZoomId) {
  42855. batch.push(clone(batchItem));
  42856. });
  42857. batch.length && this.api.dispatchAction({
  42858. type: 'dataZoom',
  42859. from: this.uid,
  42860. batch: batch
  42861. });
  42862. };
  42863. function retrieveAxisSetting(option) {
  42864. var setting = {};
  42865. // Compatible with previous setting: null => all axis, false => no axis.
  42866. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  42867. setting[name] = option[name];
  42868. setting[name] == null && (setting[name] = 'all');
  42869. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  42870. });
  42871. return setting;
  42872. }
  42873. function updateBackBtnStatus(featureModel, ecModel) {
  42874. featureModel.setIconStatus(
  42875. 'back',
  42876. count(ecModel) > 1 ? 'emphasis' : 'normal'
  42877. );
  42878. }
  42879. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  42880. var zoomActive = view._isZoomActive;
  42881. if (payload && payload.type === 'takeGlobalCursor') {
  42882. zoomActive = payload.key === 'dataZoomSelect'
  42883. ? payload.dataZoomSelectActive : false;
  42884. }
  42885. view._isZoomActive = zoomActive;
  42886. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  42887. var brushTargetManager = new BrushTargetManager(
  42888. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  42889. );
  42890. view._brushController
  42891. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  42892. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  42893. ? 'lineX'
  42894. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  42895. ? 'lineY'
  42896. : 'rect';
  42897. }))
  42898. .enableBrush(
  42899. zoomActive
  42900. ? {
  42901. brushType: 'auto',
  42902. brushStyle: {
  42903. // FIXME user customized?
  42904. lineWidth: 0,
  42905. fill: 'rgba(0,0,0,0.2)'
  42906. }
  42907. }
  42908. : false
  42909. );
  42910. }
  42911. register$2('dataZoom', DataZoom);
  42912. // Create special dataZoom option for select
  42913. registerPreprocessor(function (option) {
  42914. if (!option) {
  42915. return;
  42916. }
  42917. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  42918. if (!isArray(dataZoomOpts)) {
  42919. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  42920. }
  42921. var toolboxOpt = option.toolbox;
  42922. if (toolboxOpt) {
  42923. // Assume there is only one toolbox
  42924. if (isArray(toolboxOpt)) {
  42925. toolboxOpt = toolboxOpt[0];
  42926. }
  42927. if (toolboxOpt && toolboxOpt.feature) {
  42928. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  42929. addForAxis('xAxis', dataZoomOpt);
  42930. addForAxis('yAxis', dataZoomOpt);
  42931. }
  42932. }
  42933. function addForAxis(axisName, dataZoomOpt) {
  42934. if (!dataZoomOpt) {
  42935. return;
  42936. }
  42937. // Try not to modify model, because it is not merged yet.
  42938. var axisIndicesName = axisName + 'Index';
  42939. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  42940. if (givenAxisIndices != null
  42941. && givenAxisIndices != 'all'
  42942. && !isArray(givenAxisIndices)
  42943. ) {
  42944. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  42945. }
  42946. forEachComponent(axisName, function (axisOpt, axisIndex) {
  42947. if (givenAxisIndices != null
  42948. && givenAxisIndices != 'all'
  42949. && indexOf(givenAxisIndices, axisIndex) === -1
  42950. ) {
  42951. return;
  42952. }
  42953. var newOpt = {
  42954. type: 'select',
  42955. $fromToolbox: true,
  42956. // Id for merge mapping.
  42957. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  42958. };
  42959. // FIXME
  42960. // Only support one axis now.
  42961. newOpt[axisIndicesName] = axisIndex;
  42962. dataZoomOpts.push(newOpt);
  42963. });
  42964. }
  42965. function forEachComponent(mainType, cb) {
  42966. var opts = option[mainType];
  42967. if (!isArray(opts)) {
  42968. opts = opts ? [opts] : [];
  42969. }
  42970. each$16(opts, cb);
  42971. }
  42972. });
  42973. var restoreLang = lang.toolbox.restore;
  42974. function Restore(model) {
  42975. this.model = model;
  42976. }
  42977. Restore.defaultOption = {
  42978. show: true,
  42979. 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',
  42980. title: restoreLang.title
  42981. };
  42982. var proto$6 = Restore.prototype;
  42983. proto$6.onclick = function (ecModel, api, type) {
  42984. clear$1(ecModel);
  42985. api.dispatchAction({
  42986. type: 'restore',
  42987. from: this.uid
  42988. });
  42989. };
  42990. register$2('restore', Restore);
  42991. registerAction(
  42992. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  42993. function (payload, ecModel) {
  42994. ecModel.resetOption('recreate');
  42995. }
  42996. );
  42997. var urn = 'urn:schemas-microsoft-com:vml';
  42998. var win = typeof window === 'undefined' ? null : window;
  42999. var vmlInited = false;
  43000. var doc = win && win.document;
  43001. function createNode(tagName) {
  43002. return doCreateNode(tagName);
  43003. }
  43004. // Avoid assign to an exported variable, for transforming to cjs.
  43005. var doCreateNode;
  43006. if (doc && !env$1.canvasSupported) {
  43007. try {
  43008. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  43009. doCreateNode = function (tagName) {
  43010. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  43011. };
  43012. }
  43013. catch (e) {
  43014. doCreateNode = function (tagName) {
  43015. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  43016. };
  43017. }
  43018. }
  43019. // From raphael
  43020. function initVML() {
  43021. if (vmlInited || !doc) {
  43022. return;
  43023. }
  43024. vmlInited = true;
  43025. var styleSheets = doc.styleSheets;
  43026. if (styleSheets.length < 31) {
  43027. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  43028. }
  43029. else {
  43030. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  43031. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  43032. }
  43033. }
  43034. // http://www.w3.org/TR/NOTE-VML
  43035. // TODO Use proxy like svg instead of overwrite brush methods
  43036. var CMD$3 = PathProxy.CMD;
  43037. var round$2 = Math.round;
  43038. var sqrt = Math.sqrt;
  43039. var abs$1 = Math.abs;
  43040. var cos = Math.cos;
  43041. var sin = Math.sin;
  43042. var mathMax$5 = Math.max;
  43043. if (!env$1.canvasSupported) {
  43044. var comma = ',';
  43045. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  43046. var Z = 21600;
  43047. var Z2 = Z / 2;
  43048. var ZLEVEL_BASE = 100000;
  43049. var Z_BASE = 1000;
  43050. var initRootElStyle = function (el) {
  43051. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  43052. el.coordsize = Z + ',' + Z;
  43053. el.coordorigin = '0,0';
  43054. };
  43055. var encodeHtmlAttribute = function (s) {
  43056. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  43057. };
  43058. var rgb2Str = function (r, g, b) {
  43059. return 'rgb(' + [r, g, b].join(',') + ')';
  43060. };
  43061. var append = function (parent, child) {
  43062. if (child && parent && child.parentNode !== parent) {
  43063. parent.appendChild(child);
  43064. }
  43065. };
  43066. var remove = function (parent, child) {
  43067. if (child && parent && child.parentNode === parent) {
  43068. parent.removeChild(child);
  43069. }
  43070. };
  43071. var getZIndex = function (zlevel, z, z2) {
  43072. // z 的取值范围为 [0, 1000]
  43073. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  43074. };
  43075. var parsePercent$3 = function (value, maxValue) {
  43076. if (typeof value === 'string') {
  43077. if (value.lastIndexOf('%') >= 0) {
  43078. return parseFloat(value) / 100 * maxValue;
  43079. }
  43080. return parseFloat(value);
  43081. }
  43082. return value;
  43083. };
  43084. /***************************************************
  43085. * PATH
  43086. **************************************************/
  43087. var setColorAndOpacity = function (el, color, opacity) {
  43088. var colorArr = parse(color);
  43089. opacity = +opacity;
  43090. if (isNaN(opacity)) {
  43091. opacity = 1;
  43092. }
  43093. if (colorArr) {
  43094. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  43095. el.opacity = opacity * colorArr[3];
  43096. }
  43097. };
  43098. var getColorAndAlpha = function (color) {
  43099. var colorArr = parse(color);
  43100. return [
  43101. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  43102. colorArr[3]
  43103. ];
  43104. };
  43105. var updateFillNode = function (el, style, zrEl) {
  43106. // TODO pattern
  43107. var fill = style.fill;
  43108. if (fill != null) {
  43109. // Modified from excanvas
  43110. if (fill instanceof Gradient) {
  43111. var gradientType;
  43112. var angle = 0;
  43113. var focus = [0, 0];
  43114. // additional offset
  43115. var shift = 0;
  43116. // scale factor for offset
  43117. var expansion = 1;
  43118. var rect = zrEl.getBoundingRect();
  43119. var rectWidth = rect.width;
  43120. var rectHeight = rect.height;
  43121. if (fill.type === 'linear') {
  43122. gradientType = 'gradient';
  43123. var transform = zrEl.transform;
  43124. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43125. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  43126. if (transform) {
  43127. applyTransform(p0, p0, transform);
  43128. applyTransform(p1, p1, transform);
  43129. }
  43130. var dx = p1[0] - p0[0];
  43131. var dy = p1[1] - p0[1];
  43132. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  43133. // The angle should be a non-negative number.
  43134. if (angle < 0) {
  43135. angle += 360;
  43136. }
  43137. // Very small angles produce an unexpected result because they are
  43138. // converted to a scientific notation string.
  43139. if (angle < 1e-6) {
  43140. angle = 0;
  43141. }
  43142. }
  43143. else {
  43144. gradientType = 'gradientradial';
  43145. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43146. var transform = zrEl.transform;
  43147. var scale$$1 = zrEl.scale;
  43148. var width = rectWidth;
  43149. var height = rectHeight;
  43150. focus = [
  43151. // Percent in bounding rect
  43152. (p0[0] - rect.x) / width,
  43153. (p0[1] - rect.y) / height
  43154. ];
  43155. if (transform) {
  43156. applyTransform(p0, p0, transform);
  43157. }
  43158. width /= scale$$1[0] * Z;
  43159. height /= scale$$1[1] * Z;
  43160. var dimension = mathMax$5(width, height);
  43161. shift = 2 * 0 / dimension;
  43162. expansion = 2 * fill.r / dimension - shift;
  43163. }
  43164. // We need to sort the color stops in ascending order by offset,
  43165. // otherwise IE won't interpret it correctly.
  43166. var stops = fill.colorStops.slice();
  43167. stops.sort(function(cs1, cs2) {
  43168. return cs1.offset - cs2.offset;
  43169. });
  43170. var length$$1 = stops.length;
  43171. // Color and alpha list of first and last stop
  43172. var colorAndAlphaList = [];
  43173. var colors = [];
  43174. for (var i = 0; i < length$$1; i++) {
  43175. var stop = stops[i];
  43176. var colorAndAlpha = getColorAndAlpha(stop.color);
  43177. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  43178. if (i === 0 || i === length$$1 - 1) {
  43179. colorAndAlphaList.push(colorAndAlpha);
  43180. }
  43181. }
  43182. if (length$$1 >= 2) {
  43183. var color1 = colorAndAlphaList[0][0];
  43184. var color2 = colorAndAlphaList[1][0];
  43185. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  43186. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  43187. el.type = gradientType;
  43188. el.method = 'none';
  43189. el.focus = '100%';
  43190. el.angle = angle;
  43191. el.color = color1;
  43192. el.color2 = color2;
  43193. el.colors = colors.join(',');
  43194. // When colors attribute is used, the meanings of opacity and o:opacity2
  43195. // are reversed.
  43196. el.opacity = opacity2;
  43197. // FIXME g_o_:opacity ?
  43198. el.opacity2 = opacity1;
  43199. }
  43200. if (gradientType === 'radial') {
  43201. el.focusposition = focus.join(',');
  43202. }
  43203. }
  43204. else {
  43205. // FIXME Change from Gradient fill to color fill
  43206. setColorAndOpacity(el, fill, style.opacity);
  43207. }
  43208. }
  43209. };
  43210. var updateStrokeNode = function (el, style) {
  43211. // if (style.lineJoin != null) {
  43212. // el.joinstyle = style.lineJoin;
  43213. // }
  43214. // if (style.miterLimit != null) {
  43215. // el.miterlimit = style.miterLimit * Z;
  43216. // }
  43217. // if (style.lineCap != null) {
  43218. // el.endcap = style.lineCap;
  43219. // }
  43220. if (style.lineDash != null) {
  43221. el.dashstyle = style.lineDash.join(' ');
  43222. }
  43223. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  43224. setColorAndOpacity(el, style.stroke, style.opacity);
  43225. }
  43226. };
  43227. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  43228. var isFill = type == 'fill';
  43229. var el = vmlEl.getElementsByTagName(type)[0];
  43230. // Stroke must have lineWidth
  43231. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  43232. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  43233. // FIXME Remove before updating, or set `colors` will throw error
  43234. if (style[type] instanceof Gradient) {
  43235. remove(vmlEl, el);
  43236. }
  43237. if (!el) {
  43238. el = createNode(type);
  43239. }
  43240. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  43241. append(vmlEl, el);
  43242. }
  43243. else {
  43244. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  43245. remove(vmlEl, el);
  43246. }
  43247. };
  43248. var points$1 = [[], [], []];
  43249. var pathDataToString = function (path, m) {
  43250. var M = CMD$3.M;
  43251. var C = CMD$3.C;
  43252. var L = CMD$3.L;
  43253. var A = CMD$3.A;
  43254. var Q = CMD$3.Q;
  43255. var str = [];
  43256. var nPoint;
  43257. var cmdStr;
  43258. var cmd;
  43259. var i;
  43260. var xi;
  43261. var yi;
  43262. var data = path.data;
  43263. var dataLength = path.len();
  43264. for (i = 0; i < dataLength;) {
  43265. cmd = data[i++];
  43266. cmdStr = '';
  43267. nPoint = 0;
  43268. switch (cmd) {
  43269. case M:
  43270. cmdStr = ' m ';
  43271. nPoint = 1;
  43272. xi = data[i++];
  43273. yi = data[i++];
  43274. points$1[0][0] = xi;
  43275. points$1[0][1] = yi;
  43276. break;
  43277. case L:
  43278. cmdStr = ' l ';
  43279. nPoint = 1;
  43280. xi = data[i++];
  43281. yi = data[i++];
  43282. points$1[0][0] = xi;
  43283. points$1[0][1] = yi;
  43284. break;
  43285. case Q:
  43286. case C:
  43287. cmdStr = ' c ';
  43288. nPoint = 3;
  43289. var x1 = data[i++];
  43290. var y1 = data[i++];
  43291. var x2 = data[i++];
  43292. var y2 = data[i++];
  43293. var x3;
  43294. var y3;
  43295. if (cmd === Q) {
  43296. // Convert quadratic to cubic using degree elevation
  43297. x3 = x2;
  43298. y3 = y2;
  43299. x2 = (x2 + 2 * x1) / 3;
  43300. y2 = (y2 + 2 * y1) / 3;
  43301. x1 = (xi + 2 * x1) / 3;
  43302. y1 = (yi + 2 * y1) / 3;
  43303. }
  43304. else {
  43305. x3 = data[i++];
  43306. y3 = data[i++];
  43307. }
  43308. points$1[0][0] = x1;
  43309. points$1[0][1] = y1;
  43310. points$1[1][0] = x2;
  43311. points$1[1][1] = y2;
  43312. points$1[2][0] = x3;
  43313. points$1[2][1] = y3;
  43314. xi = x3;
  43315. yi = y3;
  43316. break;
  43317. case A:
  43318. var x = 0;
  43319. var y = 0;
  43320. var sx = 1;
  43321. var sy = 1;
  43322. var angle = 0;
  43323. if (m) {
  43324. // Extract SRT from matrix
  43325. x = m[4];
  43326. y = m[5];
  43327. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  43328. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  43329. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  43330. }
  43331. var cx = data[i++];
  43332. var cy = data[i++];
  43333. var rx = data[i++];
  43334. var ry = data[i++];
  43335. var startAngle = data[i++] + angle;
  43336. var endAngle = data[i++] + startAngle + angle;
  43337. // FIXME
  43338. // var psi = data[i++];
  43339. i++;
  43340. var clockwise = data[i++];
  43341. var x0 = cx + cos(startAngle) * rx;
  43342. var y0 = cy + sin(startAngle) * ry;
  43343. var x1 = cx + cos(endAngle) * rx;
  43344. var y1 = cy + sin(endAngle) * ry;
  43345. var type = clockwise ? ' wa ' : ' at ';
  43346. if (Math.abs(x0 - x1) < 1e-4) {
  43347. // IE won't render arches drawn counter clockwise if x0 == x1.
  43348. if (Math.abs(endAngle - startAngle) > 1e-2) {
  43349. // Offset x0 by 1/80 of a pixel. Use something
  43350. // that can be represented in binary
  43351. if (clockwise) {
  43352. x0 += 270 / Z;
  43353. }
  43354. }
  43355. else {
  43356. // Avoid case draw full circle
  43357. if (Math.abs(y0 - cy) < 1e-4) {
  43358. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  43359. y1 -= 270 / Z;
  43360. }
  43361. else {
  43362. y1 += 270 / Z;
  43363. }
  43364. }
  43365. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  43366. x1 += 270 / Z;
  43367. }
  43368. else {
  43369. x1 -= 270 / Z;
  43370. }
  43371. }
  43372. }
  43373. str.push(
  43374. type,
  43375. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  43376. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  43377. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  43378. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  43379. round$2((x0 * sx + x) * Z - Z2), comma,
  43380. round$2((y0 * sy + y) * Z - Z2), comma,
  43381. round$2((x1 * sx + x) * Z - Z2), comma,
  43382. round$2((y1 * sy + y) * Z - Z2)
  43383. );
  43384. xi = x1;
  43385. yi = y1;
  43386. break;
  43387. case CMD$3.R:
  43388. var p0 = points$1[0];
  43389. var p1 = points$1[1];
  43390. // x0, y0
  43391. p0[0] = data[i++];
  43392. p0[1] = data[i++];
  43393. // x1, y1
  43394. p1[0] = p0[0] + data[i++];
  43395. p1[1] = p0[1] + data[i++];
  43396. if (m) {
  43397. applyTransform(p0, p0, m);
  43398. applyTransform(p1, p1, m);
  43399. }
  43400. p0[0] = round$2(p0[0] * Z - Z2);
  43401. p1[0] = round$2(p1[0] * Z - Z2);
  43402. p0[1] = round$2(p0[1] * Z - Z2);
  43403. p1[1] = round$2(p1[1] * Z - Z2);
  43404. str.push(
  43405. // x0, y0
  43406. ' m ', p0[0], comma, p0[1],
  43407. // x1, y0
  43408. ' l ', p1[0], comma, p0[1],
  43409. // x1, y1
  43410. ' l ', p1[0], comma, p1[1],
  43411. // x0, y1
  43412. ' l ', p0[0], comma, p1[1]
  43413. );
  43414. break;
  43415. case CMD$3.Z:
  43416. // FIXME Update xi, yi
  43417. str.push(' x ');
  43418. }
  43419. if (nPoint > 0) {
  43420. str.push(cmdStr);
  43421. for (var k = 0; k < nPoint; k++) {
  43422. var p = points$1[k];
  43423. m && applyTransform(p, p, m);
  43424. // 不 round 会非常慢
  43425. str.push(
  43426. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  43427. k < nPoint - 1 ? comma : ''
  43428. );
  43429. }
  43430. }
  43431. }
  43432. return str.join('');
  43433. };
  43434. // Rewrite the original path method
  43435. Path.prototype.brushVML = function (vmlRoot) {
  43436. var style = this.style;
  43437. var vmlEl = this._vmlEl;
  43438. if (!vmlEl) {
  43439. vmlEl = createNode('shape');
  43440. initRootElStyle(vmlEl);
  43441. this._vmlEl = vmlEl;
  43442. }
  43443. updateFillAndStroke(vmlEl, 'fill', style, this);
  43444. updateFillAndStroke(vmlEl, 'stroke', style, this);
  43445. var m = this.transform;
  43446. var needTransform = m != null;
  43447. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  43448. if (strokeEl) {
  43449. var lineWidth = style.lineWidth;
  43450. // Get the line scale.
  43451. // Determinant of this.m_ means how much the area is enlarged by the
  43452. // transformation. So its square root can be used as a scale factor
  43453. // for width.
  43454. if (needTransform && !style.strokeNoScale) {
  43455. var det = m[0] * m[3] - m[1] * m[2];
  43456. lineWidth *= sqrt(abs$1(det));
  43457. }
  43458. strokeEl.weight = lineWidth + 'px';
  43459. }
  43460. var path = this.path || (this.path = new PathProxy());
  43461. if (this.__dirtyPath) {
  43462. path.beginPath();
  43463. this.buildPath(path, this.shape);
  43464. path.toStatic();
  43465. this.__dirtyPath = false;
  43466. }
  43467. vmlEl.path = pathDataToString(path, this.transform);
  43468. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43469. // Append to root
  43470. append(vmlRoot, vmlEl);
  43471. // Text
  43472. if (style.text != null) {
  43473. this.drawRectText(vmlRoot, this.getBoundingRect());
  43474. }
  43475. else {
  43476. this.removeRectText(vmlRoot);
  43477. }
  43478. };
  43479. Path.prototype.onRemove = function (vmlRoot) {
  43480. remove(vmlRoot, this._vmlEl);
  43481. this.removeRectText(vmlRoot);
  43482. };
  43483. Path.prototype.onAdd = function (vmlRoot) {
  43484. append(vmlRoot, this._vmlEl);
  43485. this.appendRectText(vmlRoot);
  43486. };
  43487. /***************************************************
  43488. * IMAGE
  43489. **************************************************/
  43490. var isImage = function (img) {
  43491. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  43492. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  43493. // return img instanceof Image;
  43494. };
  43495. // Rewrite the original path method
  43496. ZImage.prototype.brushVML = function (vmlRoot) {
  43497. var style = this.style;
  43498. var image = style.image;
  43499. // Image original width, height
  43500. var ow;
  43501. var oh;
  43502. if (isImage(image)) {
  43503. var src = image.src;
  43504. if (src === this._imageSrc) {
  43505. ow = this._imageWidth;
  43506. oh = this._imageHeight;
  43507. }
  43508. else {
  43509. var imageRuntimeStyle = image.runtimeStyle;
  43510. var oldRuntimeWidth = imageRuntimeStyle.width;
  43511. var oldRuntimeHeight = imageRuntimeStyle.height;
  43512. imageRuntimeStyle.width = 'auto';
  43513. imageRuntimeStyle.height = 'auto';
  43514. // get the original size
  43515. ow = image.width;
  43516. oh = image.height;
  43517. // and remove overides
  43518. imageRuntimeStyle.width = oldRuntimeWidth;
  43519. imageRuntimeStyle.height = oldRuntimeHeight;
  43520. // Caching image original width, height and src
  43521. this._imageSrc = src;
  43522. this._imageWidth = ow;
  43523. this._imageHeight = oh;
  43524. }
  43525. image = src;
  43526. }
  43527. else {
  43528. if (image === this._imageSrc) {
  43529. ow = this._imageWidth;
  43530. oh = this._imageHeight;
  43531. }
  43532. }
  43533. if (!image) {
  43534. return;
  43535. }
  43536. var x = style.x || 0;
  43537. var y = style.y || 0;
  43538. var dw = style.width;
  43539. var dh = style.height;
  43540. var sw = style.sWidth;
  43541. var sh = style.sHeight;
  43542. var sx = style.sx || 0;
  43543. var sy = style.sy || 0;
  43544. var hasCrop = sw && sh;
  43545. var vmlEl = this._vmlEl;
  43546. if (!vmlEl) {
  43547. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  43548. // vmlEl = vmlCore.createNode('group');
  43549. vmlEl = doc.createElement('div');
  43550. initRootElStyle(vmlEl);
  43551. this._vmlEl = vmlEl;
  43552. }
  43553. var vmlElStyle = vmlEl.style;
  43554. var hasRotation = false;
  43555. var m;
  43556. var scaleX = 1;
  43557. var scaleY = 1;
  43558. if (this.transform) {
  43559. m = this.transform;
  43560. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  43561. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  43562. hasRotation = m[1] || m[2];
  43563. }
  43564. if (hasRotation) {
  43565. // If filters are necessary (rotation exists), create them
  43566. // filters are bog-slow, so only create them if abbsolutely necessary
  43567. // The following check doesn't account for skews (which don't exist
  43568. // in the canvas spec (yet) anyway.
  43569. // From excanvas
  43570. var p0 = [x, y];
  43571. var p1 = [x + dw, y];
  43572. var p2 = [x, y + dh];
  43573. var p3 = [x + dw, y + dh];
  43574. applyTransform(p0, p0, m);
  43575. applyTransform(p1, p1, m);
  43576. applyTransform(p2, p2, m);
  43577. applyTransform(p3, p3, m);
  43578. var maxX = mathMax$5(p0[0], p1[0], p2[0], p3[0]);
  43579. var maxY = mathMax$5(p0[1], p1[1], p2[1], p3[1]);
  43580. var transformFilter = [];
  43581. transformFilter.push('M11=', m[0] / scaleX, comma,
  43582. 'M12=', m[2] / scaleY, comma,
  43583. 'M21=', m[1] / scaleX, comma,
  43584. 'M22=', m[3] / scaleY, comma,
  43585. 'Dx=', round$2(x * scaleX + m[4]), comma,
  43586. 'Dy=', round$2(y * scaleY + m[5]));
  43587. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  43588. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  43589. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  43590. + transformFilter.join('') + ', SizingMethod=clip)';
  43591. }
  43592. else {
  43593. if (m) {
  43594. x = x * scaleX + m[4];
  43595. y = y * scaleY + m[5];
  43596. }
  43597. vmlElStyle.filter = '';
  43598. vmlElStyle.left = round$2(x) + 'px';
  43599. vmlElStyle.top = round$2(y) + 'px';
  43600. }
  43601. var imageEl = this._imageEl;
  43602. var cropEl = this._cropEl;
  43603. if (!imageEl) {
  43604. imageEl = doc.createElement('div');
  43605. this._imageEl = imageEl;
  43606. }
  43607. var imageELStyle = imageEl.style;
  43608. if (hasCrop) {
  43609. // Needs know image original width and height
  43610. if (! (ow && oh)) {
  43611. var tmpImage = new Image();
  43612. var self = this;
  43613. tmpImage.onload = function () {
  43614. tmpImage.onload = null;
  43615. ow = tmpImage.width;
  43616. oh = tmpImage.height;
  43617. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  43618. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  43619. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  43620. // Caching image original width, height and src
  43621. self._imageWidth = ow;
  43622. self._imageHeight = oh;
  43623. self._imageSrc = image;
  43624. };
  43625. tmpImage.src = image;
  43626. }
  43627. else {
  43628. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  43629. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  43630. }
  43631. if (! cropEl) {
  43632. cropEl = doc.createElement('div');
  43633. cropEl.style.overflow = 'hidden';
  43634. this._cropEl = cropEl;
  43635. }
  43636. var cropElStyle = cropEl.style;
  43637. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  43638. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  43639. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  43640. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  43641. if (! cropEl.parentNode) {
  43642. vmlEl.appendChild(cropEl);
  43643. }
  43644. if (imageEl.parentNode != cropEl) {
  43645. cropEl.appendChild(imageEl);
  43646. }
  43647. }
  43648. else {
  43649. imageELStyle.width = round$2(scaleX * dw) + 'px';
  43650. imageELStyle.height = round$2(scaleY * dh) + 'px';
  43651. vmlEl.appendChild(imageEl);
  43652. if (cropEl && cropEl.parentNode) {
  43653. vmlEl.removeChild(cropEl);
  43654. this._cropEl = null;
  43655. }
  43656. }
  43657. var filterStr = '';
  43658. var alpha = style.opacity;
  43659. if (alpha < 1) {
  43660. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  43661. }
  43662. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  43663. imageELStyle.filter = filterStr;
  43664. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43665. // Append to root
  43666. append(vmlRoot, vmlEl);
  43667. // Text
  43668. if (style.text != null) {
  43669. this.drawRectText(vmlRoot, this.getBoundingRect());
  43670. }
  43671. };
  43672. ZImage.prototype.onRemove = function (vmlRoot) {
  43673. remove(vmlRoot, this._vmlEl);
  43674. this._vmlEl = null;
  43675. this._cropEl = null;
  43676. this._imageEl = null;
  43677. this.removeRectText(vmlRoot);
  43678. };
  43679. ZImage.prototype.onAdd = function (vmlRoot) {
  43680. append(vmlRoot, this._vmlEl);
  43681. this.appendRectText(vmlRoot);
  43682. };
  43683. /***************************************************
  43684. * TEXT
  43685. **************************************************/
  43686. var DEFAULT_STYLE_NORMAL = 'normal';
  43687. var fontStyleCache = {};
  43688. var fontStyleCacheCount = 0;
  43689. var MAX_FONT_CACHE_SIZE = 100;
  43690. var fontEl = document.createElement('div');
  43691. var getFontStyle = function (fontString) {
  43692. var fontStyle = fontStyleCache[fontString];
  43693. if (!fontStyle) {
  43694. // Clear cache
  43695. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  43696. fontStyleCacheCount = 0;
  43697. fontStyleCache = {};
  43698. }
  43699. var style = fontEl.style;
  43700. var fontFamily;
  43701. try {
  43702. style.font = fontString;
  43703. fontFamily = style.fontFamily.split(',')[0];
  43704. }
  43705. catch (e) {
  43706. }
  43707. fontStyle = {
  43708. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  43709. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  43710. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  43711. size: parseFloat(style.fontSize || 12) | 0,
  43712. family: fontFamily || 'Microsoft YaHei'
  43713. };
  43714. fontStyleCache[fontString] = fontStyle;
  43715. fontStyleCacheCount++;
  43716. }
  43717. return fontStyle;
  43718. };
  43719. var textMeasureEl;
  43720. // Overwrite measure text method
  43721. $override$1('measureText', function (text, textFont) {
  43722. var doc$$1 = doc;
  43723. if (!textMeasureEl) {
  43724. textMeasureEl = doc$$1.createElement('div');
  43725. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  43726. + 'padding:0;margin:0;border:none;white-space:pre;';
  43727. doc.body.appendChild(textMeasureEl);
  43728. }
  43729. try {
  43730. textMeasureEl.style.font = textFont;
  43731. } catch (ex) {
  43732. // Ignore failures to set to invalid font.
  43733. }
  43734. textMeasureEl.innerHTML = '';
  43735. // Don't use innerHTML or innerText because they allow markup/whitespace.
  43736. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  43737. return {
  43738. width: textMeasureEl.offsetWidth
  43739. };
  43740. });
  43741. var tmpRect$2 = new BoundingRect();
  43742. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  43743. var style = this.style;
  43744. // Optimize, avoid normalize every time.
  43745. this.__dirty && normalizeTextStyle(style, true);
  43746. var text = style.text;
  43747. // Convert to string
  43748. text != null && (text += '');
  43749. if (!text) {
  43750. return;
  43751. }
  43752. // Convert rich text to plain text. Rich text is not supported in
  43753. // IE8-, but tags in rich text template will be removed.
  43754. if (style.rich) {
  43755. var contentBlock = parseRichText(text, style);
  43756. text = [];
  43757. for (var i = 0; i < contentBlock.lines.length; i++) {
  43758. var tokens = contentBlock.lines[i].tokens;
  43759. var textLine = [];
  43760. for (var j = 0; j < tokens.length; j++) {
  43761. textLine.push(tokens[j].text);
  43762. }
  43763. text.push(textLine.join(''));
  43764. }
  43765. text = text.join('\n');
  43766. }
  43767. var x;
  43768. var y;
  43769. var align = style.textAlign;
  43770. var verticalAlign = style.textVerticalAlign;
  43771. var fontStyle = getFontStyle(style.font);
  43772. // FIXME encodeHtmlAttribute ?
  43773. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  43774. + fontStyle.size + 'px "' + fontStyle.family + '"';
  43775. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  43776. // Transform rect to view space
  43777. var m = this.transform;
  43778. // Ignore transform for text in other element
  43779. if (m && !fromTextEl) {
  43780. tmpRect$2.copy(rect);
  43781. tmpRect$2.applyTransform(m);
  43782. rect = tmpRect$2;
  43783. }
  43784. if (!fromTextEl) {
  43785. var textPosition = style.textPosition;
  43786. var distance$$1 = style.textDistance;
  43787. // Text position represented by coord
  43788. if (textPosition instanceof Array) {
  43789. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  43790. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  43791. align = align || 'left';
  43792. }
  43793. else {
  43794. var res = adjustTextPositionOnRect(
  43795. textPosition, rect, distance$$1
  43796. );
  43797. x = res.x;
  43798. y = res.y;
  43799. // Default align and baseline when has textPosition
  43800. align = align || res.textAlign;
  43801. verticalAlign = verticalAlign || res.textVerticalAlign;
  43802. }
  43803. }
  43804. else {
  43805. x = rect.x;
  43806. y = rect.y;
  43807. }
  43808. x = adjustTextX(x, textRect.width, align);
  43809. y = adjustTextY(y, textRect.height, verticalAlign);
  43810. // Force baseline 'middle'
  43811. y += textRect.height / 2;
  43812. // var fontSize = fontStyle.size;
  43813. // 1.75 is an arbitrary number, as there is no info about the text baseline
  43814. // switch (baseline) {
  43815. // case 'hanging':
  43816. // case 'top':
  43817. // y += fontSize / 1.75;
  43818. // break;
  43819. // case 'middle':
  43820. // break;
  43821. // default:
  43822. // // case null:
  43823. // // case 'alphabetic':
  43824. // // case 'ideographic':
  43825. // // case 'bottom':
  43826. // y -= fontSize / 2.25;
  43827. // break;
  43828. // }
  43829. // switch (align) {
  43830. // case 'left':
  43831. // break;
  43832. // case 'center':
  43833. // x -= textRect.width / 2;
  43834. // break;
  43835. // case 'right':
  43836. // x -= textRect.width;
  43837. // break;
  43838. // case 'end':
  43839. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  43840. // break;
  43841. // case 'start':
  43842. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  43843. // break;
  43844. // default:
  43845. // align = 'left';
  43846. // }
  43847. var createNode$$1 = createNode;
  43848. var textVmlEl = this._textVmlEl;
  43849. var pathEl;
  43850. var textPathEl;
  43851. var skewEl;
  43852. if (!textVmlEl) {
  43853. textVmlEl = createNode$$1('line');
  43854. pathEl = createNode$$1('path');
  43855. textPathEl = createNode$$1('textpath');
  43856. skewEl = createNode$$1('skew');
  43857. // FIXME Why here is not cammel case
  43858. // Align 'center' seems wrong
  43859. textPathEl.style['v-text-align'] = 'left';
  43860. initRootElStyle(textVmlEl);
  43861. pathEl.textpathok = true;
  43862. textPathEl.on = true;
  43863. textVmlEl.from = '0 0';
  43864. textVmlEl.to = '1000 0.05';
  43865. append(textVmlEl, skewEl);
  43866. append(textVmlEl, pathEl);
  43867. append(textVmlEl, textPathEl);
  43868. this._textVmlEl = textVmlEl;
  43869. }
  43870. else {
  43871. // 这里是在前面 appendChild 保证顺序的前提下
  43872. skewEl = textVmlEl.firstChild;
  43873. pathEl = skewEl.nextSibling;
  43874. textPathEl = pathEl.nextSibling;
  43875. }
  43876. var coords = [x, y];
  43877. var textVmlElStyle = textVmlEl.style;
  43878. // Ignore transform for text in other element
  43879. if (m && fromTextEl) {
  43880. applyTransform(coords, coords, m);
  43881. skewEl.on = true;
  43882. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  43883. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  43884. // Text position
  43885. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  43886. // Left top point as origin
  43887. skewEl.origin = '0 0';
  43888. textVmlElStyle.left = '0px';
  43889. textVmlElStyle.top = '0px';
  43890. }
  43891. else {
  43892. skewEl.on = false;
  43893. textVmlElStyle.left = round$2(x) + 'px';
  43894. textVmlElStyle.top = round$2(y) + 'px';
  43895. }
  43896. textPathEl.string = encodeHtmlAttribute(text);
  43897. // TODO
  43898. try {
  43899. textPathEl.style.font = font;
  43900. }
  43901. // Error font format
  43902. catch (e) {}
  43903. updateFillAndStroke(textVmlEl, 'fill', {
  43904. fill: style.textFill,
  43905. opacity: style.opacity
  43906. }, this);
  43907. updateFillAndStroke(textVmlEl, 'stroke', {
  43908. stroke: style.textStroke,
  43909. opacity: style.opacity,
  43910. lineDash: style.lineDash
  43911. }, this);
  43912. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43913. // Attached to root
  43914. append(vmlRoot, textVmlEl);
  43915. };
  43916. var removeRectText = function (vmlRoot) {
  43917. remove(vmlRoot, this._textVmlEl);
  43918. this._textVmlEl = null;
  43919. };
  43920. var appendRectText = function (vmlRoot) {
  43921. append(vmlRoot, this._textVmlEl);
  43922. };
  43923. var list = [RectText, Displayable, ZImage, Path, Text];
  43924. // In case Displayable has been mixed in RectText
  43925. for (var i$1 = 0; i$1 < list.length; i$1++) {
  43926. var proto$7 = list[i$1].prototype;
  43927. proto$7.drawRectText = drawRectText;
  43928. proto$7.removeRectText = removeRectText;
  43929. proto$7.appendRectText = appendRectText;
  43930. }
  43931. Text.prototype.brushVML = function (vmlRoot) {
  43932. var style = this.style;
  43933. if (style.text != null) {
  43934. this.drawRectText(vmlRoot, {
  43935. x: style.x || 0, y: style.y || 0,
  43936. width: 0, height: 0
  43937. }, this.getBoundingRect(), true);
  43938. }
  43939. else {
  43940. this.removeRectText(vmlRoot);
  43941. }
  43942. };
  43943. Text.prototype.onRemove = function (vmlRoot) {
  43944. this.removeRectText(vmlRoot);
  43945. };
  43946. Text.prototype.onAdd = function (vmlRoot) {
  43947. this.appendRectText(vmlRoot);
  43948. };
  43949. }
  43950. /**
  43951. * VML Painter.
  43952. *
  43953. * @module zrender/vml/Painter
  43954. */
  43955. function parseInt10$1(val) {
  43956. return parseInt(val, 10);
  43957. }
  43958. /**
  43959. * @alias module:zrender/vml/Painter
  43960. */
  43961. function VMLPainter(root, storage) {
  43962. initVML();
  43963. this.root = root;
  43964. this.storage = storage;
  43965. var vmlViewport = document.createElement('div');
  43966. var vmlRoot = document.createElement('div');
  43967. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  43968. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  43969. root.appendChild(vmlViewport);
  43970. this._vmlRoot = vmlRoot;
  43971. this._vmlViewport = vmlViewport;
  43972. this.resize();
  43973. // Modify storage
  43974. var oldDelFromStorage = storage.delFromStorage;
  43975. var oldAddToStorage = storage.addToStorage;
  43976. storage.delFromStorage = function (el) {
  43977. oldDelFromStorage.call(storage, el);
  43978. if (el) {
  43979. el.onRemove && el.onRemove(vmlRoot);
  43980. }
  43981. };
  43982. storage.addToStorage = function (el) {
  43983. // Displayable already has a vml node
  43984. el.onAdd && el.onAdd(vmlRoot);
  43985. oldAddToStorage.call(storage, el);
  43986. };
  43987. this._firstPaint = true;
  43988. }
  43989. VMLPainter.prototype = {
  43990. constructor: VMLPainter,
  43991. getType: function () {
  43992. return 'vml';
  43993. },
  43994. /**
  43995. * @return {HTMLDivElement}
  43996. */
  43997. getViewportRoot: function () {
  43998. return this._vmlViewport;
  43999. },
  44000. getViewportRootOffset: function () {
  44001. var viewportRoot = this.getViewportRoot();
  44002. if (viewportRoot) {
  44003. return {
  44004. offsetLeft: viewportRoot.offsetLeft || 0,
  44005. offsetTop: viewportRoot.offsetTop || 0
  44006. };
  44007. }
  44008. },
  44009. /**
  44010. * 刷新
  44011. */
  44012. refresh: function () {
  44013. var list = this.storage.getDisplayList(true, true);
  44014. this._paintList(list);
  44015. },
  44016. _paintList: function (list) {
  44017. var vmlRoot = this._vmlRoot;
  44018. for (var i = 0; i < list.length; i++) {
  44019. var el = list[i];
  44020. if (el.invisible || el.ignore) {
  44021. if (!el.__alreadyNotVisible) {
  44022. el.onRemove(vmlRoot);
  44023. }
  44024. // Set as already invisible
  44025. el.__alreadyNotVisible = true;
  44026. }
  44027. else {
  44028. if (el.__alreadyNotVisible) {
  44029. el.onAdd(vmlRoot);
  44030. }
  44031. el.__alreadyNotVisible = false;
  44032. if (el.__dirty) {
  44033. el.beforeBrush && el.beforeBrush();
  44034. (el.brushVML || el.brush).call(el, vmlRoot);
  44035. el.afterBrush && el.afterBrush();
  44036. }
  44037. }
  44038. el.__dirty = false;
  44039. }
  44040. if (this._firstPaint) {
  44041. // Detached from document at first time
  44042. // to avoid page refreshing too many times
  44043. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  44044. this._vmlViewport.appendChild(vmlRoot);
  44045. this._firstPaint = false;
  44046. }
  44047. },
  44048. resize: function (width, height) {
  44049. var width = width == null ? this._getWidth() : width;
  44050. var height = height == null ? this._getHeight() : height;
  44051. if (this._width != width || this._height != height) {
  44052. this._width = width;
  44053. this._height = height;
  44054. var vmlViewportStyle = this._vmlViewport.style;
  44055. vmlViewportStyle.width = width + 'px';
  44056. vmlViewportStyle.height = height + 'px';
  44057. }
  44058. },
  44059. dispose: function () {
  44060. this.root.innerHTML = '';
  44061. this._vmlRoot =
  44062. this._vmlViewport =
  44063. this.storage = null;
  44064. },
  44065. getWidth: function () {
  44066. return this._width;
  44067. },
  44068. getHeight: function () {
  44069. return this._height;
  44070. },
  44071. clear: function () {
  44072. if (this._vmlViewport) {
  44073. this.root.removeChild(this._vmlViewport);
  44074. }
  44075. },
  44076. _getWidth: function () {
  44077. var root = this.root;
  44078. var stl = root.currentStyle;
  44079. return ((root.clientWidth || parseInt10$1(stl.width))
  44080. - parseInt10$1(stl.paddingLeft)
  44081. - parseInt10$1(stl.paddingRight)) | 0;
  44082. },
  44083. _getHeight: function () {
  44084. var root = this.root;
  44085. var stl = root.currentStyle;
  44086. return ((root.clientHeight || parseInt10$1(stl.height))
  44087. - parseInt10$1(stl.paddingTop)
  44088. - parseInt10$1(stl.paddingBottom)) | 0;
  44089. }
  44090. };
  44091. // Not supported methods
  44092. function createMethodNotSupport(method) {
  44093. return function () {
  44094. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  44095. };
  44096. }
  44097. // Unsupported methods
  44098. each$1([
  44099. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  44100. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  44101. ], function (name) {
  44102. VMLPainter.prototype[name] = createMethodNotSupport(name);
  44103. });
  44104. registerPainter('vml', VMLPainter);
  44105. var svgURI = 'http://www.w3.org/2000/svg';
  44106. function createElement(name) {
  44107. return document.createElementNS(svgURI, name);
  44108. }
  44109. // TODO
  44110. // 1. shadow
  44111. // 2. Image: sx, sy, sw, sh
  44112. var CMD$4 = PathProxy.CMD;
  44113. var arrayJoin = Array.prototype.join;
  44114. var NONE = 'none';
  44115. var mathRound = Math.round;
  44116. var mathSin$3 = Math.sin;
  44117. var mathCos$3 = Math.cos;
  44118. var PI$3 = Math.PI;
  44119. var PI2$5 = Math.PI * 2;
  44120. var degree = 180 / PI$3;
  44121. var EPSILON$4 = 1e-4;
  44122. function round4(val) {
  44123. return mathRound(val * 1e4) / 1e4;
  44124. }
  44125. function isAroundZero$1(val) {
  44126. return val < EPSILON$4 && val > -EPSILON$4;
  44127. }
  44128. function pathHasFill(style, isText) {
  44129. var fill = isText ? style.textFill : style.fill;
  44130. return fill != null && fill !== NONE;
  44131. }
  44132. function pathHasStroke(style, isText) {
  44133. var stroke = isText ? style.textStroke : style.stroke;
  44134. return stroke != null && stroke !== NONE;
  44135. }
  44136. function setTransform(svgEl, m) {
  44137. if (m) {
  44138. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  44139. }
  44140. }
  44141. function attr(el, key, val) {
  44142. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  44143. // Don't set attribute for gradient, since it need new dom nodes
  44144. el.setAttribute(key, val);
  44145. }
  44146. }
  44147. function attrXLink(el, key, val) {
  44148. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  44149. }
  44150. function bindStyle(svgEl, style, isText) {
  44151. if (pathHasFill(style, isText)) {
  44152. var fill = isText ? style.textFill : style.fill;
  44153. fill = fill === 'transparent' ? NONE : fill;
  44154. /**
  44155. * FIXME:
  44156. * This is a temporary fix for Chrome's clipping bug
  44157. * that happens when a clip-path is referring another one.
  44158. * This fix should be used before Chrome's bug is fixed.
  44159. * For an element that has clip-path, and fill is none,
  44160. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  44161. * Otherwise, it will show black fill color.
  44162. * 0.002 is used because this won't work for alpha values smaller
  44163. * than 0.002.
  44164. *
  44165. * See
  44166. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  44167. * for more information.
  44168. */
  44169. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  44170. fill = 'rgba(0, 0, 0, 0.002)';
  44171. }
  44172. attr(svgEl, 'fill', fill);
  44173. attr(svgEl, 'fill-opacity', style.opacity);
  44174. }
  44175. else {
  44176. attr(svgEl, 'fill', NONE);
  44177. }
  44178. if (pathHasStroke(style, isText)) {
  44179. var stroke = isText ? style.textStroke : style.stroke;
  44180. stroke = stroke === 'transparent' ? NONE : stroke;
  44181. attr(svgEl, 'stroke', stroke);
  44182. var strokeWidth = isText
  44183. ? style.textStrokeWidth
  44184. : style.lineWidth;
  44185. var strokeScale = !isText && style.strokeNoScale
  44186. ? style.host.getLineScale()
  44187. : 1;
  44188. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  44189. // stroke then fill for text; fill then stroke for others
  44190. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  44191. attr(svgEl, 'stroke-opacity', style.opacity);
  44192. var lineDash = style.lineDash;
  44193. if (lineDash) {
  44194. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  44195. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  44196. }
  44197. else {
  44198. attr(svgEl, 'stroke-dasharray', '');
  44199. }
  44200. // PENDING
  44201. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  44202. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  44203. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  44204. }
  44205. else {
  44206. attr(svgEl, 'stroke', NONE);
  44207. }
  44208. }
  44209. /***************************************************
  44210. * PATH
  44211. **************************************************/
  44212. function pathDataToString$1(path) {
  44213. var str = [];
  44214. var data = path.data;
  44215. var dataLength = path.len();
  44216. for (var i = 0; i < dataLength;) {
  44217. var cmd = data[i++];
  44218. var cmdStr = '';
  44219. var nData = 0;
  44220. switch (cmd) {
  44221. case CMD$4.M:
  44222. cmdStr = 'M';
  44223. nData = 2;
  44224. break;
  44225. case CMD$4.L:
  44226. cmdStr = 'L';
  44227. nData = 2;
  44228. break;
  44229. case CMD$4.Q:
  44230. cmdStr = 'Q';
  44231. nData = 4;
  44232. break;
  44233. case CMD$4.C:
  44234. cmdStr = 'C';
  44235. nData = 6;
  44236. break;
  44237. case CMD$4.A:
  44238. var cx = data[i++];
  44239. var cy = data[i++];
  44240. var rx = data[i++];
  44241. var ry = data[i++];
  44242. var theta = data[i++];
  44243. var dTheta = data[i++];
  44244. var psi = data[i++];
  44245. var clockwise = data[i++];
  44246. var dThetaPositive = Math.abs(dTheta);
  44247. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  44248. && !isAroundZero$1(dThetaPositive);
  44249. var large = false;
  44250. if (dThetaPositive >= PI2$5) {
  44251. large = true;
  44252. }
  44253. else if (isAroundZero$1(dThetaPositive)) {
  44254. large = false;
  44255. }
  44256. else {
  44257. large = (dTheta > -PI$3 && dTheta < 0 || dTheta > PI$3)
  44258. === !!clockwise;
  44259. }
  44260. var x0 = round4(cx + rx * mathCos$3(theta));
  44261. var y0 = round4(cy + ry * mathSin$3(theta));
  44262. // It will not draw if start point and end point are exactly the same
  44263. // We need to shift the end point with a small value
  44264. // FIXME A better way to draw circle ?
  44265. if (isCircle) {
  44266. if (clockwise) {
  44267. dTheta = PI2$5 - 1e-4;
  44268. }
  44269. else {
  44270. dTheta = -PI2$5 + 1e-4;
  44271. }
  44272. large = true;
  44273. if (i === 9) {
  44274. // Move to (x0, y0) only when CMD.A comes at the
  44275. // first position of a shape.
  44276. // For instance, when drawing a ring, CMD.A comes
  44277. // after CMD.M, so it's unnecessary to move to
  44278. // (x0, y0).
  44279. str.push('M', x0, y0);
  44280. }
  44281. }
  44282. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  44283. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  44284. // FIXME Ellipse
  44285. str.push('A', round4(rx), round4(ry),
  44286. mathRound(psi * degree), +large, +clockwise, x, y);
  44287. break;
  44288. case CMD$4.Z:
  44289. cmdStr = 'Z';
  44290. break;
  44291. case CMD$4.R:
  44292. var x = round4(data[i++]);
  44293. var y = round4(data[i++]);
  44294. var w = round4(data[i++]);
  44295. var h = round4(data[i++]);
  44296. str.push(
  44297. 'M', x, y,
  44298. 'L', x + w, y,
  44299. 'L', x + w, y + h,
  44300. 'L', x, y + h,
  44301. 'L', x, y
  44302. );
  44303. break;
  44304. }
  44305. cmdStr && str.push(cmdStr);
  44306. for (var j = 0; j < nData; j++) {
  44307. // PENDING With scale
  44308. str.push(round4(data[i++]));
  44309. }
  44310. }
  44311. return str.join(' ');
  44312. }
  44313. var svgPath = {};
  44314. svgPath.brush = function (el) {
  44315. var style = el.style;
  44316. var svgEl = el.__svgEl;
  44317. if (!svgEl) {
  44318. svgEl = createElement('path');
  44319. el.__svgEl = svgEl;
  44320. }
  44321. if (!el.path) {
  44322. el.createPathProxy();
  44323. }
  44324. var path = el.path;
  44325. if (el.__dirtyPath) {
  44326. path.beginPath();
  44327. el.buildPath(path, el.shape);
  44328. el.__dirtyPath = false;
  44329. var pathStr = pathDataToString$1(path);
  44330. if (pathStr.indexOf('NaN') < 0) {
  44331. // Ignore illegal path, which may happen such in out-of-range
  44332. // data in Calendar series.
  44333. attr(svgEl, 'd', pathStr);
  44334. }
  44335. }
  44336. bindStyle(svgEl, style);
  44337. setTransform(svgEl, el.transform);
  44338. if (style.text != null) {
  44339. svgTextDrawRectText(el, el.getBoundingRect());
  44340. }
  44341. };
  44342. /***************************************************
  44343. * IMAGE
  44344. **************************************************/
  44345. var svgImage = {};
  44346. svgImage.brush = function (el) {
  44347. var style = el.style;
  44348. var image = style.image;
  44349. if (image instanceof HTMLImageElement) {
  44350. var src = image.src;
  44351. image = src;
  44352. }
  44353. if (! image) {
  44354. return;
  44355. }
  44356. var x = style.x || 0;
  44357. var y = style.y || 0;
  44358. var dw = style.width;
  44359. var dh = style.height;
  44360. var svgEl = el.__svgEl;
  44361. if (! svgEl) {
  44362. svgEl = createElement('image');
  44363. el.__svgEl = svgEl;
  44364. }
  44365. if (image !== el.__imageSrc) {
  44366. attrXLink(svgEl, 'href', image);
  44367. // Caching image src
  44368. el.__imageSrc = image;
  44369. }
  44370. attr(svgEl, 'width', dw);
  44371. attr(svgEl, 'height', dh);
  44372. attr(svgEl, 'x', x);
  44373. attr(svgEl, 'y', y);
  44374. setTransform(svgEl, el.transform);
  44375. if (style.text != null) {
  44376. svgTextDrawRectText(el, el.getBoundingRect());
  44377. }
  44378. };
  44379. /***************************************************
  44380. * TEXT
  44381. **************************************************/
  44382. var svgText = {};
  44383. var tmpRect$3 = new BoundingRect();
  44384. var svgTextDrawRectText = function (el, rect, textRect) {
  44385. var style = el.style;
  44386. el.__dirty && normalizeTextStyle(style, true);
  44387. var text = style.text;
  44388. // Convert to string
  44389. if (text == null) {
  44390. // Draw no text only when text is set to null, but not ''
  44391. return;
  44392. }
  44393. else {
  44394. text += '';
  44395. }
  44396. var textSvgEl = el.__textSvgEl;
  44397. if (! textSvgEl) {
  44398. textSvgEl = createElement('text');
  44399. el.__textSvgEl = textSvgEl;
  44400. }
  44401. bindStyle(textSvgEl, style, true);
  44402. if (el instanceof Text || el.style.transformText) {
  44403. // Transform text with element
  44404. setTransform(textSvgEl, el.transform);
  44405. }
  44406. else {
  44407. if (el.transform) {
  44408. tmpRect$3.copy(rect);
  44409. tmpRect$3.applyTransform(el.transform);
  44410. rect = tmpRect$3;
  44411. }
  44412. else {
  44413. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  44414. rect.x = pos[0];
  44415. rect.y = pos[1];
  44416. }
  44417. }
  44418. var x;
  44419. var y;
  44420. var textPosition = style.textPosition;
  44421. var distance = style.textDistance;
  44422. var align = style.textAlign || 'left';
  44423. if (typeof style.fontSize === 'number') {
  44424. style.fontSize += 'px';
  44425. }
  44426. var font = style.font
  44427. || [
  44428. style.fontStyle || '',
  44429. style.fontWeight || '',
  44430. style.fontSize || '',
  44431. style.fontFamily || ''
  44432. ].join(' ')
  44433. || DEFAULT_FONT;
  44434. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  44435. textRect = getBoundingRect(text, font, align,
  44436. verticalAlign);
  44437. var lineHeight = textRect.lineHeight;
  44438. // Text position represented by coord
  44439. if (textPosition instanceof Array) {
  44440. x = rect.x + textPosition[0];
  44441. y = rect.y + textPosition[1];
  44442. }
  44443. else {
  44444. var newPos = adjustTextPositionOnRect(
  44445. textPosition, rect, distance
  44446. );
  44447. x = newPos.x;
  44448. y = newPos.y;
  44449. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  44450. align = newPos.textAlign;
  44451. }
  44452. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  44453. if (font) {
  44454. textSvgEl.style.font = font;
  44455. }
  44456. var textPadding = style.textPadding;
  44457. // Make baseline top
  44458. attr(textSvgEl, 'x', x);
  44459. attr(textSvgEl, 'y', y);
  44460. var textLines = text.split('\n');
  44461. var nTextLines = textLines.length;
  44462. var textAnchor = align;
  44463. // PENDING
  44464. if (textAnchor === 'left') {
  44465. textAnchor = 'start';
  44466. textPadding && (x += textPadding[3]);
  44467. }
  44468. else if (textAnchor === 'right') {
  44469. textAnchor = 'end';
  44470. textPadding && (x -= textPadding[1]);
  44471. }
  44472. else if (textAnchor === 'center') {
  44473. textAnchor = 'middle';
  44474. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  44475. }
  44476. var dy = 0;
  44477. if (verticalAlign === 'baseline') {
  44478. dy = -textRect.height + lineHeight;
  44479. textPadding && (dy -= textPadding[2]);
  44480. }
  44481. else if (verticalAlign === 'middle') {
  44482. dy = (-textRect.height + lineHeight) / 2;
  44483. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  44484. }
  44485. else {
  44486. textPadding && (dy += textPadding[0]);
  44487. }
  44488. // Font may affect position of each tspan elements
  44489. if (el.__text !== text || el.__textFont !== font) {
  44490. var tspanList = el.__tspanList || [];
  44491. el.__tspanList = tspanList;
  44492. for (var i = 0; i < nTextLines; i++) {
  44493. // Using cached tspan elements
  44494. var tspan = tspanList[i];
  44495. if (! tspan) {
  44496. tspan = tspanList[i] = createElement('tspan');
  44497. textSvgEl.appendChild(tspan);
  44498. attr(tspan, 'alignment-baseline', verticalAlign);
  44499. attr(tspan, 'text-anchor', textAnchor);
  44500. }
  44501. else {
  44502. tspan.innerHTML = '';
  44503. }
  44504. attr(tspan, 'x', x);
  44505. attr(tspan, 'y', y + i * lineHeight + dy);
  44506. tspan.appendChild(document.createTextNode(textLines[i]));
  44507. }
  44508. // Remove unsed tspan elements
  44509. for (; i < tspanList.length; i++) {
  44510. textSvgEl.removeChild(tspanList[i]);
  44511. }
  44512. tspanList.length = nTextLines;
  44513. el.__text = text;
  44514. el.__textFont = font;
  44515. }
  44516. else if (el.__tspanList.length) {
  44517. // Update span x and y
  44518. var len = el.__tspanList.length;
  44519. for (var i = 0; i < len; ++i) {
  44520. var tspan = el.__tspanList[i];
  44521. if (tspan) {
  44522. attr(tspan, 'x', x);
  44523. attr(tspan, 'y', y + i * lineHeight + dy);
  44524. }
  44525. }
  44526. }
  44527. };
  44528. function getVerticalAlignForSvg(verticalAlign) {
  44529. if (verticalAlign === 'middle') {
  44530. return 'middle';
  44531. }
  44532. else if (verticalAlign === 'bottom') {
  44533. return 'baseline';
  44534. }
  44535. else {
  44536. return 'hanging';
  44537. }
  44538. }
  44539. svgText.drawRectText = svgTextDrawRectText;
  44540. svgText.brush = function (el) {
  44541. var style = el.style;
  44542. if (style.text != null) {
  44543. // 强制设置 textPosition
  44544. style.textPosition = [0, 0];
  44545. svgTextDrawRectText(el, {
  44546. x: style.x || 0, y: style.y || 0,
  44547. width: 0, height: 0
  44548. }, el.getBoundingRect());
  44549. }
  44550. };
  44551. // Myers' Diff Algorithm
  44552. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  44553. function Diff() {}
  44554. Diff.prototype = {
  44555. diff: function (oldArr, newArr, equals) {
  44556. if (!equals) {
  44557. equals = function (a, b) {
  44558. return a === b;
  44559. };
  44560. }
  44561. this.equals = equals;
  44562. var self = this;
  44563. oldArr = oldArr.slice();
  44564. newArr = newArr.slice();
  44565. // Allow subclasses to massage the input prior to running
  44566. var newLen = newArr.length;
  44567. var oldLen = oldArr.length;
  44568. var editLength = 1;
  44569. var maxEditLength = newLen + oldLen;
  44570. var bestPath = [{ newPos: -1, components: [] }];
  44571. // Seed editLength = 0, i.e. the content starts with the same values
  44572. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  44573. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  44574. var indices = [];
  44575. for (var i = 0; i < newArr.length; i++) {
  44576. indices.push(i);
  44577. }
  44578. // Identity per the equality and tokenizer
  44579. return [{
  44580. indices: indices, count: newArr.length
  44581. }];
  44582. }
  44583. // Main worker method. checks all permutations of a given edit length for acceptance.
  44584. function execEditLength() {
  44585. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  44586. var basePath;
  44587. var addPath = bestPath[diagonalPath - 1];
  44588. var removePath = bestPath[diagonalPath + 1];
  44589. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  44590. if (addPath) {
  44591. // No one else is going to attempt to use this value, clear it
  44592. bestPath[diagonalPath - 1] = undefined;
  44593. }
  44594. var canAdd = addPath && addPath.newPos + 1 < newLen;
  44595. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  44596. if (!canAdd && !canRemove) {
  44597. // If this path is a terminal then prune
  44598. bestPath[diagonalPath] = undefined;
  44599. continue;
  44600. }
  44601. // Select the diagonal that we want to branch from. We select the prior
  44602. // path whose position in the new string is the farthest from the origin
  44603. // and does not pass the bounds of the diff graph
  44604. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  44605. basePath = clonePath(removePath);
  44606. self.pushComponent(basePath.components, undefined, true);
  44607. }
  44608. else {
  44609. basePath = addPath; // No need to clone, we've pulled it from the list
  44610. basePath.newPos++;
  44611. self.pushComponent(basePath.components, true, undefined);
  44612. }
  44613. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  44614. // If we have hit the end of both strings, then we are done
  44615. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  44616. return buildValues(self, basePath.components, newArr, oldArr);
  44617. }
  44618. else {
  44619. // Otherwise track this path as a potential candidate and continue.
  44620. bestPath[diagonalPath] = basePath;
  44621. }
  44622. }
  44623. editLength++;
  44624. }
  44625. while (editLength <= maxEditLength) {
  44626. var ret = execEditLength();
  44627. if (ret) {
  44628. return ret;
  44629. }
  44630. }
  44631. },
  44632. pushComponent: function (components, added, removed) {
  44633. var last = components[components.length - 1];
  44634. if (last && last.added === added && last.removed === removed) {
  44635. // We need to clone here as the component clone operation is just
  44636. // as shallow array clone
  44637. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  44638. }
  44639. else {
  44640. components.push({count: 1, added: added, removed: removed });
  44641. }
  44642. },
  44643. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  44644. var newLen = newArr.length;
  44645. var oldLen = oldArr.length;
  44646. var newPos = basePath.newPos;
  44647. var oldPos = newPos - diagonalPath;
  44648. var commonCount = 0;
  44649. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  44650. newPos++;
  44651. oldPos++;
  44652. commonCount++;
  44653. }
  44654. if (commonCount) {
  44655. basePath.components.push({count: commonCount});
  44656. }
  44657. basePath.newPos = newPos;
  44658. return oldPos;
  44659. },
  44660. tokenize: function (value) {
  44661. return value.slice();
  44662. },
  44663. join: function (value) {
  44664. return value.slice();
  44665. }
  44666. };
  44667. function buildValues(diff, components, newArr, oldArr) {
  44668. var componentPos = 0;
  44669. var componentLen = components.length;
  44670. var newPos = 0;
  44671. var oldPos = 0;
  44672. for (; componentPos < componentLen; componentPos++) {
  44673. var component = components[componentPos];
  44674. if (!component.removed) {
  44675. var indices = [];
  44676. for (var i = newPos; i < newPos + component.count; i++) {
  44677. indices.push(i);
  44678. }
  44679. component.indices = indices;
  44680. newPos += component.count;
  44681. // Common case
  44682. if (!component.added) {
  44683. oldPos += component.count;
  44684. }
  44685. }
  44686. else {
  44687. var indices = [];
  44688. for (var i = oldPos; i < oldPos + component.count; i++) {
  44689. indices.push(i);
  44690. }
  44691. component.indices = indices;
  44692. oldPos += component.count;
  44693. }
  44694. }
  44695. return components;
  44696. }
  44697. function clonePath(path) {
  44698. return { newPos: path.newPos, components: path.components.slice(0) };
  44699. }
  44700. var arrayDiff = new Diff();
  44701. var arrayDiff$1 = function (oldArr, newArr, callback) {
  44702. return arrayDiff.diff(oldArr, newArr, callback);
  44703. };
  44704. /**
  44705. * @file Manages elements that can be defined in <defs> in SVG,
  44706. * e.g., gradients, clip path, etc.
  44707. * @author Zhang Wenli
  44708. */
  44709. var MARK_UNUSED = '0';
  44710. var MARK_USED = '1';
  44711. /**
  44712. * Manages elements that can be defined in <defs> in SVG,
  44713. * e.g., gradients, clip path, etc.
  44714. *
  44715. * @class
  44716. * @param {number} zrId zrender instance id
  44717. * @param {SVGElement} svgRoot root of SVG document
  44718. * @param {string|string[]} tagNames possible tag names
  44719. * @param {string} markLabel label name to make if the element
  44720. * is used
  44721. */
  44722. function Definable(
  44723. zrId,
  44724. svgRoot,
  44725. tagNames,
  44726. markLabel,
  44727. domName
  44728. ) {
  44729. this._zrId = zrId;
  44730. this._svgRoot = svgRoot;
  44731. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  44732. this._markLabel = markLabel;
  44733. this._domName = domName || '_dom';
  44734. this.nextId = 0;
  44735. }
  44736. Definable.prototype.createElement = createElement;
  44737. /**
  44738. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  44739. *
  44740. * @param {boolean} isForceCreating if need to create when not exists
  44741. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  44742. * exist and isForceCreating is false
  44743. */
  44744. Definable.prototype.getDefs = function (isForceCreating) {
  44745. var svgRoot = this._svgRoot;
  44746. var defs = this._svgRoot.getElementsByTagName('defs');
  44747. if (defs.length === 0) {
  44748. // Not exist
  44749. if (isForceCreating) {
  44750. defs = svgRoot.insertBefore(
  44751. this.createElement('defs'), // Create new tag
  44752. svgRoot.firstChild // Insert in the front of svg
  44753. );
  44754. if (!defs.contains) {
  44755. // IE doesn't support contains method
  44756. defs.contains = function (el) {
  44757. var children = defs.children;
  44758. if (!children) {
  44759. return false;
  44760. }
  44761. for (var i = children.length - 1; i >= 0; --i) {
  44762. if (children[i] === el) {
  44763. return true;
  44764. }
  44765. }
  44766. return false;
  44767. };
  44768. }
  44769. return defs;
  44770. }
  44771. else {
  44772. return null;
  44773. }
  44774. }
  44775. else {
  44776. return defs[0];
  44777. }
  44778. };
  44779. /**
  44780. * Update DOM element if necessary.
  44781. *
  44782. * @param {Object|string} element style element. e.g., for gradient,
  44783. * it may be '#ccc' or {type: 'linear', ...}
  44784. * @param {Function|undefined} onUpdate update callback
  44785. */
  44786. Definable.prototype.update = function (element, onUpdate) {
  44787. if (!element) {
  44788. return;
  44789. }
  44790. var defs = this.getDefs(false);
  44791. if (element[this._domName] && defs.contains(element[this._domName])) {
  44792. // Update DOM
  44793. if (typeof onUpdate === 'function') {
  44794. onUpdate(element);
  44795. }
  44796. }
  44797. else {
  44798. // No previous dom, create new
  44799. var dom = this.add(element);
  44800. if (dom) {
  44801. element[this._domName] = dom;
  44802. }
  44803. }
  44804. };
  44805. /**
  44806. * Add gradient dom to defs
  44807. *
  44808. * @param {SVGElement} dom DOM to be added to <defs>
  44809. */
  44810. Definable.prototype.addDom = function (dom) {
  44811. var defs = this.getDefs(true);
  44812. defs.appendChild(dom);
  44813. };
  44814. /**
  44815. * Remove DOM of a given element.
  44816. *
  44817. * @param {SVGElement} element element to remove dom
  44818. */
  44819. Definable.prototype.removeDom = function (element) {
  44820. var defs = this.getDefs(false);
  44821. if (defs && element[this._domName]) {
  44822. defs.removeChild(element[this._domName]);
  44823. element[this._domName] = null;
  44824. }
  44825. };
  44826. /**
  44827. * Get DOMs of this element.
  44828. *
  44829. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  44830. */
  44831. Definable.prototype.getDoms = function () {
  44832. var defs = this.getDefs(false);
  44833. if (!defs) {
  44834. // No dom when defs is not defined
  44835. return [];
  44836. }
  44837. var doms = [];
  44838. each$1(this._tagNames, function (tagName) {
  44839. var tags = defs.getElementsByTagName(tagName);
  44840. // Note that tags is HTMLCollection, which is array-like
  44841. // rather than real array.
  44842. // So `doms.concat(tags)` add tags as one object.
  44843. doms = doms.concat([].slice.call(tags));
  44844. });
  44845. return doms;
  44846. };
  44847. /**
  44848. * Mark DOMs to be unused before painting, and clear unused ones at the end
  44849. * of the painting.
  44850. */
  44851. Definable.prototype.markAllUnused = function () {
  44852. var doms = this.getDoms();
  44853. var that = this;
  44854. each$1(doms, function (dom) {
  44855. dom[that._markLabel] = MARK_UNUSED;
  44856. });
  44857. };
  44858. /**
  44859. * Mark a single DOM to be used.
  44860. *
  44861. * @param {SVGElement} dom DOM to mark
  44862. */
  44863. Definable.prototype.markUsed = function (dom) {
  44864. if (dom) {
  44865. dom[this._markLabel] = MARK_USED;
  44866. }
  44867. };
  44868. /**
  44869. * Remove unused DOMs defined in <defs>
  44870. */
  44871. Definable.prototype.removeUnused = function () {
  44872. var defs = this.getDefs(false);
  44873. if (!defs) {
  44874. // Nothing to remove
  44875. return;
  44876. }
  44877. var doms = this.getDoms();
  44878. var that = this;
  44879. each$1(doms, function (dom) {
  44880. if (dom[that._markLabel] !== MARK_USED) {
  44881. // Remove gradient
  44882. defs.removeChild(dom);
  44883. }
  44884. });
  44885. };
  44886. /**
  44887. * Get SVG proxy.
  44888. *
  44889. * @param {Displayable} displayable displayable element
  44890. * @return {Path|Image|Text} svg proxy of given element
  44891. */
  44892. Definable.prototype.getSvgProxy = function (displayable) {
  44893. if (displayable instanceof Path) {
  44894. return svgPath;
  44895. }
  44896. else if (displayable instanceof ZImage) {
  44897. return svgImage;
  44898. }
  44899. else if (displayable instanceof Text) {
  44900. return svgText;
  44901. }
  44902. else {
  44903. return svgPath;
  44904. }
  44905. };
  44906. /**
  44907. * Get text SVG element.
  44908. *
  44909. * @param {Displayable} displayable displayable element
  44910. * @return {SVGElement} SVG element of text
  44911. */
  44912. Definable.prototype.getTextSvgElement = function (displayable) {
  44913. return displayable.__textSvgEl;
  44914. };
  44915. /**
  44916. * Get SVG element.
  44917. *
  44918. * @param {Displayable} displayable displayable element
  44919. * @return {SVGElement} SVG element
  44920. */
  44921. Definable.prototype.getSvgElement = function (displayable) {
  44922. return displayable.__svgEl;
  44923. };
  44924. /**
  44925. * @file Manages SVG gradient elements.
  44926. * @author Zhang Wenli
  44927. */
  44928. /**
  44929. * Manages SVG gradient elements.
  44930. *
  44931. * @class
  44932. * @extends Definable
  44933. * @param {number} zrId zrender instance id
  44934. * @param {SVGElement} svgRoot root of SVG document
  44935. */
  44936. function GradientManager(zrId, svgRoot) {
  44937. Definable.call(
  44938. this,
  44939. zrId,
  44940. svgRoot,
  44941. ['linearGradient', 'radialGradient'],
  44942. '__gradient_in_use__'
  44943. );
  44944. }
  44945. inherits(GradientManager, Definable);
  44946. /**
  44947. * Create new gradient DOM for fill or stroke if not exist,
  44948. * but will not update gradient if exists.
  44949. *
  44950. * @param {SvgElement} svgElement SVG element to paint
  44951. * @param {Displayable} displayable zrender displayable element
  44952. */
  44953. GradientManager.prototype.addWithoutUpdate = function (
  44954. svgElement,
  44955. displayable
  44956. ) {
  44957. if (displayable && displayable.style) {
  44958. var that = this;
  44959. each$1(['fill', 'stroke'], function (fillOrStroke) {
  44960. if (displayable.style[fillOrStroke]
  44961. && (displayable.style[fillOrStroke].type === 'linear'
  44962. || displayable.style[fillOrStroke].type === 'radial')
  44963. ) {
  44964. var gradient = displayable.style[fillOrStroke];
  44965. var defs = that.getDefs(true);
  44966. // Create dom in <defs> if not exists
  44967. var dom;
  44968. if (gradient._dom) {
  44969. // Gradient exists
  44970. dom = gradient._dom;
  44971. if (!defs.contains(gradient._dom)) {
  44972. // _dom is no longer in defs, recreate
  44973. that.addDom(dom);
  44974. }
  44975. }
  44976. else {
  44977. // New dom
  44978. dom = that.add(gradient);
  44979. }
  44980. that.markUsed(displayable);
  44981. var id = dom.getAttribute('id');
  44982. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  44983. }
  44984. });
  44985. }
  44986. };
  44987. /**
  44988. * Add a new gradient tag in <defs>
  44989. *
  44990. * @param {Gradient} gradient zr gradient instance
  44991. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  44992. * created DOM
  44993. */
  44994. GradientManager.prototype.add = function (gradient) {
  44995. var dom;
  44996. if (gradient.type === 'linear') {
  44997. dom = this.createElement('linearGradient');
  44998. }
  44999. else if (gradient.type === 'radial') {
  45000. dom = this.createElement('radialGradient');
  45001. }
  45002. else {
  45003. zrLog('Illegal gradient type.');
  45004. return null;
  45005. }
  45006. // Set dom id with gradient id, since each gradient instance
  45007. // will have no more than one dom element.
  45008. // id may exists before for those dirty elements, in which case
  45009. // id should remain the same, and other attributes should be
  45010. // updated.
  45011. gradient.id = gradient.id || this.nextId++;
  45012. dom.setAttribute('id', 'zr' + this._zrId
  45013. + '-gradient-' + gradient.id);
  45014. this.updateDom(gradient, dom);
  45015. this.addDom(dom);
  45016. return dom;
  45017. };
  45018. /**
  45019. * Update gradient.
  45020. *
  45021. * @param {Gradient} gradient zr gradient instance
  45022. */
  45023. GradientManager.prototype.update = function (gradient) {
  45024. var that = this;
  45025. Definable.prototype.update.call(this, gradient, function () {
  45026. var type = gradient.type;
  45027. var tagName = gradient._dom.tagName;
  45028. if (type === 'linear' && tagName === 'linearGradient'
  45029. || type === 'radial' && tagName === 'radialGradient'
  45030. ) {
  45031. // Gradient type is not changed, update gradient
  45032. that.updateDom(gradient, gradient._dom);
  45033. }
  45034. else {
  45035. // Remove and re-create if type is changed
  45036. that.removeDom(gradient);
  45037. that.add(gradient);
  45038. }
  45039. });
  45040. };
  45041. /**
  45042. * Update gradient dom
  45043. *
  45044. * @param {Gradient} gradient zr gradient instance
  45045. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  45046. * DOM to update
  45047. */
  45048. GradientManager.prototype.updateDom = function (gradient, dom) {
  45049. if (gradient.type === 'linear') {
  45050. dom.setAttribute('x1', gradient.x);
  45051. dom.setAttribute('y1', gradient.y);
  45052. dom.setAttribute('x2', gradient.x2);
  45053. dom.setAttribute('y2', gradient.y2);
  45054. }
  45055. else if (gradient.type === 'radial') {
  45056. dom.setAttribute('cx', gradient.x);
  45057. dom.setAttribute('cy', gradient.y);
  45058. dom.setAttribute('r', gradient.r);
  45059. }
  45060. else {
  45061. zrLog('Illegal gradient type.');
  45062. return;
  45063. }
  45064. if (gradient.global) {
  45065. // x1, x2, y1, y2 in range of 0 to canvas width or height
  45066. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  45067. }
  45068. else {
  45069. // x1, x2, y1, y2 in range of 0 to 1
  45070. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  45071. }
  45072. // Remove color stops if exists
  45073. dom.innerHTML = '';
  45074. // Add color stops
  45075. var colors = gradient.colorStops;
  45076. for (var i = 0, len = colors.length; i < len; ++i) {
  45077. var stop = this.createElement('stop');
  45078. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  45079. stop.setAttribute('stop-color', colors[i].color);
  45080. dom.appendChild(stop);
  45081. }
  45082. // Store dom element in gradient, to avoid creating multiple
  45083. // dom instances for the same gradient element
  45084. gradient._dom = dom;
  45085. };
  45086. /**
  45087. * Mark a single gradient to be used
  45088. *
  45089. * @param {Displayable} displayable displayable element
  45090. */
  45091. GradientManager.prototype.markUsed = function (displayable) {
  45092. if (displayable.style) {
  45093. var gradient = displayable.style.fill;
  45094. if (gradient && gradient._dom) {
  45095. Definable.prototype.markUsed.call(this, gradient._dom);
  45096. }
  45097. gradient = displayable.style.stroke;
  45098. if (gradient && gradient._dom) {
  45099. Definable.prototype.markUsed.call(this, gradient._dom);
  45100. }
  45101. }
  45102. };
  45103. /**
  45104. * @file Manages SVG clipPath elements.
  45105. * @author Zhang Wenli
  45106. */
  45107. /**
  45108. * Manages SVG clipPath elements.
  45109. *
  45110. * @class
  45111. * @extends Definable
  45112. * @param {number} zrId zrender instance id
  45113. * @param {SVGElement} svgRoot root of SVG document
  45114. */
  45115. function ClippathManager(zrId, svgRoot) {
  45116. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  45117. }
  45118. inherits(ClippathManager, Definable);
  45119. /**
  45120. * Update clipPath.
  45121. *
  45122. * @param {Displayable} displayable displayable element
  45123. */
  45124. ClippathManager.prototype.update = function (displayable) {
  45125. var svgEl = this.getSvgElement(displayable);
  45126. if (svgEl) {
  45127. this.updateDom(svgEl, displayable.__clipPaths, false);
  45128. }
  45129. var textEl = this.getTextSvgElement(displayable);
  45130. if (textEl) {
  45131. // Make another clipPath for text, since it's transform
  45132. // matrix is not the same with svgElement
  45133. this.updateDom(textEl, displayable.__clipPaths, true);
  45134. }
  45135. this.markUsed(displayable);
  45136. };
  45137. /**
  45138. * Create an SVGElement of displayable and create a <clipPath> of its
  45139. * clipPath
  45140. *
  45141. * @param {Displayable} parentEl parent element
  45142. * @param {ClipPath[]} clipPaths clipPaths of parent element
  45143. * @param {boolean} isText if parent element is Text
  45144. */
  45145. ClippathManager.prototype.updateDom = function (
  45146. parentEl,
  45147. clipPaths,
  45148. isText
  45149. ) {
  45150. if (clipPaths && clipPaths.length > 0) {
  45151. // Has clipPath, create <clipPath> with the first clipPath
  45152. var defs = this.getDefs(true);
  45153. var clipPath = clipPaths[0];
  45154. var clipPathEl;
  45155. var id;
  45156. var dom = isText ? '_textDom' : '_dom';
  45157. if (clipPath[dom]) {
  45158. // Use a dom that is already in <defs>
  45159. id = clipPath[dom].getAttribute('id');
  45160. clipPathEl = clipPath[dom];
  45161. // Use a dom that is already in <defs>
  45162. if (!defs.contains(clipPathEl)) {
  45163. // This happens when set old clipPath that has
  45164. // been previously removed
  45165. defs.appendChild(clipPathEl);
  45166. }
  45167. }
  45168. else {
  45169. // New <clipPath>
  45170. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  45171. ++this.nextId;
  45172. clipPathEl = this.createElement('clipPath');
  45173. clipPathEl.setAttribute('id', id);
  45174. defs.appendChild(clipPathEl);
  45175. clipPath[dom] = clipPathEl;
  45176. }
  45177. // Build path and add to <clipPath>
  45178. var svgProxy = this.getSvgProxy(clipPath);
  45179. if (clipPath.transform
  45180. && clipPath.parent.invTransform
  45181. && !isText
  45182. ) {
  45183. /**
  45184. * If a clipPath has a parent with transform, the transform
  45185. * of parent should not be considered when setting transform
  45186. * of clipPath. So we need to transform back from parent's
  45187. * transform, which is done by multiplying parent's inverse
  45188. * transform.
  45189. */
  45190. // Store old transform
  45191. var transform = Array.prototype.slice.call(
  45192. clipPath.transform
  45193. );
  45194. // Transform back from parent, and brush path
  45195. mul$1(
  45196. clipPath.transform,
  45197. clipPath.parent.invTransform,
  45198. clipPath.transform
  45199. );
  45200. svgProxy.brush(clipPath);
  45201. // Set back transform of clipPath
  45202. clipPath.transform = transform;
  45203. }
  45204. else {
  45205. svgProxy.brush(clipPath);
  45206. }
  45207. var pathEl = this.getSvgElement(clipPath);
  45208. clipPathEl.innerHTML = '';
  45209. /**
  45210. * Use `cloneNode()` here to appendChild to multiple parents,
  45211. * which may happend when Text and other shapes are using the same
  45212. * clipPath. Since Text will create an extra clipPath DOM due to
  45213. * different transform rules.
  45214. */
  45215. clipPathEl.appendChild(pathEl.cloneNode());
  45216. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  45217. if (clipPaths.length > 1) {
  45218. // Make the other clipPaths recursively
  45219. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  45220. }
  45221. }
  45222. else {
  45223. // No clipPath
  45224. if (parentEl) {
  45225. parentEl.setAttribute('clip-path', 'none');
  45226. }
  45227. }
  45228. };
  45229. /**
  45230. * Mark a single clipPath to be used
  45231. *
  45232. * @param {Displayable} displayable displayable element
  45233. */
  45234. ClippathManager.prototype.markUsed = function (displayable) {
  45235. var that = this;
  45236. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  45237. each$1(displayable.__clipPaths, function (clipPath) {
  45238. if (clipPath._dom) {
  45239. Definable.prototype.markUsed.call(that, clipPath._dom);
  45240. }
  45241. if (clipPath._textDom) {
  45242. Definable.prototype.markUsed.call(that, clipPath._textDom);
  45243. }
  45244. });
  45245. }
  45246. };
  45247. /**
  45248. * @file Manages SVG shadow elements.
  45249. * @author Zhang Wenli
  45250. */
  45251. /**
  45252. * Manages SVG shadow elements.
  45253. *
  45254. * @class
  45255. * @extends Definable
  45256. * @param {number} zrId zrender instance id
  45257. * @param {SVGElement} svgRoot root of SVG document
  45258. */
  45259. function ShadowManager(zrId, svgRoot) {
  45260. Definable.call(
  45261. this,
  45262. zrId,
  45263. svgRoot,
  45264. ['filter'],
  45265. '__filter_in_use__',
  45266. '_shadowDom'
  45267. );
  45268. }
  45269. inherits(ShadowManager, Definable);
  45270. /**
  45271. * Create new shadow DOM for fill or stroke if not exist,
  45272. * but will not update shadow if exists.
  45273. *
  45274. * @param {SvgElement} svgElement SVG element to paint
  45275. * @param {Displayable} displayable zrender displayable element
  45276. */
  45277. ShadowManager.prototype.addWithoutUpdate = function (
  45278. svgElement,
  45279. displayable
  45280. ) {
  45281. if (displayable && hasShadow(displayable.style)) {
  45282. var style = displayable.style;
  45283. // Create dom in <defs> if not exists
  45284. var dom;
  45285. if (style._shadowDom) {
  45286. // Gradient exists
  45287. dom = style._shadowDom;
  45288. var defs = this.getDefs(true);
  45289. if (!defs.contains(style._shadowDom)) {
  45290. // _shadowDom is no longer in defs, recreate
  45291. this.addDom(dom);
  45292. }
  45293. }
  45294. else {
  45295. // New dom
  45296. dom = this.add(displayable);
  45297. }
  45298. this.markUsed(displayable);
  45299. var id = dom.getAttribute('id');
  45300. svgElement.style.filter = 'url(#' + id + ')';
  45301. }
  45302. };
  45303. /**
  45304. * Add a new shadow tag in <defs>
  45305. *
  45306. * @param {Displayable} displayable zrender displayable element
  45307. * @return {SVGFilterElement} created DOM
  45308. */
  45309. ShadowManager.prototype.add = function (displayable) {
  45310. var dom = this.createElement('filter');
  45311. var style = displayable.style;
  45312. // Set dom id with shadow id, since each shadow instance
  45313. // will have no more than one dom element.
  45314. // id may exists before for those dirty elements, in which case
  45315. // id should remain the same, and other attributes should be
  45316. // updated.
  45317. style._shadowDomId = style._shadowDomId || this.nextId++;
  45318. dom.setAttribute('id', 'zr' + this._zrId
  45319. + '-shadow-' + style._shadowDomId);
  45320. this.updateDom(displayable, dom);
  45321. this.addDom(dom);
  45322. return dom;
  45323. };
  45324. /**
  45325. * Update shadow.
  45326. *
  45327. * @param {Displayable} displayable zrender displayable element
  45328. */
  45329. ShadowManager.prototype.update = function (svgElement, displayable) {
  45330. var style = displayable.style;
  45331. if (hasShadow(style)) {
  45332. var that = this;
  45333. Definable.prototype.update.call(this, displayable, function (style) {
  45334. that.updateDom(displayable, style._shadowDom);
  45335. });
  45336. }
  45337. else {
  45338. // Remove shadow
  45339. this.remove(svgElement, style);
  45340. }
  45341. };
  45342. /**
  45343. * Remove DOM and clear parent filter
  45344. */
  45345. ShadowManager.prototype.remove = function (svgElement, style) {
  45346. if (style._shadowDomId != null) {
  45347. this.removeDom(style);
  45348. svgElement.style.filter = '';
  45349. }
  45350. };
  45351. /**
  45352. * Update shadow dom
  45353. *
  45354. * @param {Displayable} displayable zrender displayable element
  45355. * @param {SVGFilterElement} dom DOM to update
  45356. */
  45357. ShadowManager.prototype.updateDom = function (displayable, dom) {
  45358. var domChild = dom.getElementsByTagName('feDropShadow');
  45359. if (domChild.length === 0) {
  45360. domChild = this.createElement('feDropShadow');
  45361. }
  45362. else {
  45363. domChild = domChild[0];
  45364. }
  45365. var style = displayable.style;
  45366. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  45367. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  45368. // TODO: textBoxShadowBlur is not supported yet
  45369. var offsetX, offsetY, blur, color;
  45370. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  45371. offsetX = style.shadowOffsetX || 0;
  45372. offsetY = style.shadowOffsetY || 0;
  45373. blur = style.shadowBlur;
  45374. color = style.shadowColor;
  45375. }
  45376. else if (style.textShadowBlur) {
  45377. offsetX = style.textShadowOffsetX || 0;
  45378. offsetY = style.textShadowOffsetY || 0;
  45379. blur = style.textShadowBlur;
  45380. color = style.textShadowColor;
  45381. }
  45382. else {
  45383. // Remove shadow
  45384. this.removeDom(dom, style);
  45385. return;
  45386. }
  45387. domChild.setAttribute('dx', offsetX / scaleX);
  45388. domChild.setAttribute('dy', offsetY / scaleY);
  45389. domChild.setAttribute('flood-color', color);
  45390. // Divide by two here so that it looks the same as in canvas
  45391. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  45392. var stdDx = blur / 2 / scaleX;
  45393. var stdDy = blur / 2 / scaleY;
  45394. var stdDeviation = stdDx + ' ' + stdDy;
  45395. domChild.setAttribute('stdDeviation', stdDeviation);
  45396. // Fix filter clipping problem
  45397. dom.setAttribute('x', '-100%');
  45398. dom.setAttribute('y', '-100%');
  45399. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  45400. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  45401. dom.appendChild(domChild);
  45402. // Store dom element in shadow, to avoid creating multiple
  45403. // dom instances for the same shadow element
  45404. style._shadowDom = dom;
  45405. };
  45406. /**
  45407. * Mark a single shadow to be used
  45408. *
  45409. * @param {Displayable} displayable displayable element
  45410. */
  45411. ShadowManager.prototype.markUsed = function (displayable) {
  45412. var style = displayable.style;
  45413. if (style && style._shadowDom) {
  45414. Definable.prototype.markUsed.call(this, style._shadowDom);
  45415. }
  45416. };
  45417. function hasShadow(style) {
  45418. // TODO: textBoxShadowBlur is not supported yet
  45419. return style
  45420. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  45421. || style.textShadowBlur || style.textShadowOffsetX
  45422. || style.textShadowOffsetY);
  45423. }
  45424. /**
  45425. * SVG Painter
  45426. * @module zrender/svg/Painter
  45427. */
  45428. function parseInt10$2(val) {
  45429. return parseInt(val, 10);
  45430. }
  45431. function getSvgProxy(el) {
  45432. if (el instanceof Path) {
  45433. return svgPath;
  45434. }
  45435. else if (el instanceof ZImage) {
  45436. return svgImage;
  45437. }
  45438. else if (el instanceof Text) {
  45439. return svgText;
  45440. }
  45441. else {
  45442. return svgPath;
  45443. }
  45444. }
  45445. function checkParentAvailable(parent, child) {
  45446. return child && parent && child.parentNode !== parent;
  45447. }
  45448. function insertAfter(parent, child, prevSibling) {
  45449. if (checkParentAvailable(parent, child) && prevSibling) {
  45450. var nextSibling = prevSibling.nextSibling;
  45451. nextSibling ? parent.insertBefore(child, nextSibling)
  45452. : parent.appendChild(child);
  45453. }
  45454. }
  45455. function prepend(parent, child) {
  45456. if (checkParentAvailable(parent, child)) {
  45457. var firstChild = parent.firstChild;
  45458. firstChild ? parent.insertBefore(child, firstChild)
  45459. : parent.appendChild(child);
  45460. }
  45461. }
  45462. function remove$1(parent, child) {
  45463. if (child && parent && child.parentNode === parent) {
  45464. parent.removeChild(child);
  45465. }
  45466. }
  45467. function getTextSvgElement(displayable) {
  45468. return displayable.__textSvgEl;
  45469. }
  45470. function getSvgElement(displayable) {
  45471. return displayable.__svgEl;
  45472. }
  45473. /**
  45474. * @alias module:zrender/svg/Painter
  45475. * @constructor
  45476. * @param {HTMLElement} root 绘图容器
  45477. * @param {module:zrender/Storage} storage
  45478. * @param {Object} opts
  45479. */
  45480. var SVGPainter = function (root, storage, opts, zrId) {
  45481. this.root = root;
  45482. this.storage = storage;
  45483. this._opts = opts = extend({}, opts || {});
  45484. var svgRoot = createElement('svg');
  45485. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  45486. svgRoot.setAttribute('version', '1.1');
  45487. svgRoot.setAttribute('baseProfile', 'full');
  45488. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  45489. this.gradientManager = new GradientManager(zrId, svgRoot);
  45490. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  45491. this.shadowManager = new ShadowManager(zrId, svgRoot);
  45492. var viewport = document.createElement('div');
  45493. viewport.style.cssText = 'overflow:hidden;position:relative';
  45494. this._svgRoot = svgRoot;
  45495. this._viewport = viewport;
  45496. root.appendChild(viewport);
  45497. viewport.appendChild(svgRoot);
  45498. this.resize(opts.width, opts.height);
  45499. this._visibleList = [];
  45500. };
  45501. SVGPainter.prototype = {
  45502. constructor: SVGPainter,
  45503. getType: function () {
  45504. return 'svg';
  45505. },
  45506. getViewportRoot: function () {
  45507. return this._viewport;
  45508. },
  45509. getViewportRootOffset: function () {
  45510. var viewportRoot = this.getViewportRoot();
  45511. if (viewportRoot) {
  45512. return {
  45513. offsetLeft: viewportRoot.offsetLeft || 0,
  45514. offsetTop: viewportRoot.offsetTop || 0
  45515. };
  45516. }
  45517. },
  45518. refresh: function () {
  45519. var list = this.storage.getDisplayList(true);
  45520. this._paintList(list);
  45521. },
  45522. _paintList: function (list) {
  45523. this.gradientManager.markAllUnused();
  45524. this.clipPathManager.markAllUnused();
  45525. this.shadowManager.markAllUnused();
  45526. var svgRoot = this._svgRoot;
  45527. var visibleList = this._visibleList;
  45528. var listLen = list.length;
  45529. var newVisibleList = [];
  45530. var i;
  45531. for (i = 0; i < listLen; i++) {
  45532. var displayable = list[i];
  45533. var svgProxy = getSvgProxy(displayable);
  45534. var svgElement = getSvgElement(displayable)
  45535. || getTextSvgElement(displayable);
  45536. if (!displayable.invisible) {
  45537. if (displayable.__dirty) {
  45538. svgProxy && svgProxy.brush(displayable);
  45539. // Update clipPath
  45540. this.clipPathManager.update(displayable);
  45541. // Update gradient and shadow
  45542. if (displayable.style) {
  45543. this.gradientManager
  45544. .update(displayable.style.fill);
  45545. this.gradientManager
  45546. .update(displayable.style.stroke);
  45547. this.shadowManager
  45548. .update(svgElement, displayable);
  45549. }
  45550. displayable.__dirty = false;
  45551. }
  45552. newVisibleList.push(displayable);
  45553. }
  45554. }
  45555. var diff = arrayDiff$1(visibleList, newVisibleList);
  45556. var prevSvgElement;
  45557. // First do remove, in case element moved to the head and do remove
  45558. // after add
  45559. for (i = 0; i < diff.length; i++) {
  45560. var item = diff[i];
  45561. if (item.removed) {
  45562. for (var k = 0; k < item.count; k++) {
  45563. var displayable = visibleList[item.indices[k]];
  45564. var svgElement = getSvgElement(displayable);
  45565. var textSvgElement = getTextSvgElement(displayable);
  45566. remove$1(svgRoot, svgElement);
  45567. remove$1(svgRoot, textSvgElement);
  45568. }
  45569. }
  45570. }
  45571. for (i = 0; i < diff.length; i++) {
  45572. var item = diff[i];
  45573. if (item.added) {
  45574. for (var k = 0; k < item.count; k++) {
  45575. var displayable = newVisibleList[item.indices[k]];
  45576. var svgElement = getSvgElement(displayable);
  45577. var textSvgElement = getTextSvgElement(displayable);
  45578. prevSvgElement
  45579. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  45580. : prepend(svgRoot, svgElement);
  45581. if (svgElement) {
  45582. insertAfter(svgRoot, textSvgElement, svgElement);
  45583. }
  45584. else if (prevSvgElement) {
  45585. insertAfter(
  45586. svgRoot, textSvgElement, prevSvgElement
  45587. );
  45588. }
  45589. else {
  45590. prepend(svgRoot, textSvgElement);
  45591. }
  45592. // Insert text
  45593. insertAfter(svgRoot, textSvgElement, svgElement);
  45594. prevSvgElement = textSvgElement || svgElement
  45595. || prevSvgElement;
  45596. this.gradientManager
  45597. .addWithoutUpdate(svgElement, displayable);
  45598. this.shadowManager
  45599. .addWithoutUpdate(prevSvgElement, displayable);
  45600. this.clipPathManager.markUsed(displayable);
  45601. }
  45602. }
  45603. else if (!item.removed) {
  45604. for (var k = 0; k < item.count; k++) {
  45605. var displayable = newVisibleList[item.indices[k]];
  45606. prevSvgElement
  45607. = svgElement
  45608. = getTextSvgElement(displayable)
  45609. || getSvgElement(displayable)
  45610. || prevSvgElement;
  45611. this.gradientManager.markUsed(displayable);
  45612. this.gradientManager
  45613. .addWithoutUpdate(svgElement, displayable);
  45614. this.shadowManager.markUsed(displayable);
  45615. this.shadowManager
  45616. .addWithoutUpdate(svgElement, displayable);
  45617. this.clipPathManager.markUsed(displayable);
  45618. }
  45619. }
  45620. }
  45621. this.gradientManager.removeUnused();
  45622. this.clipPathManager.removeUnused();
  45623. this.shadowManager.removeUnused();
  45624. this._visibleList = newVisibleList;
  45625. },
  45626. _getDefs: function (isForceCreating) {
  45627. var svgRoot = this._svgRoot;
  45628. var defs = this._svgRoot.getElementsByTagName('defs');
  45629. if (defs.length === 0) {
  45630. // Not exist
  45631. if (isForceCreating) {
  45632. var defs = svgRoot.insertBefore(
  45633. createElement('defs'), // Create new tag
  45634. svgRoot.firstChild // Insert in the front of svg
  45635. );
  45636. if (!defs.contains) {
  45637. // IE doesn't support contains method
  45638. defs.contains = function (el) {
  45639. var children = defs.children;
  45640. if (!children) {
  45641. return false;
  45642. }
  45643. for (var i = children.length - 1; i >= 0; --i) {
  45644. if (children[i] === el) {
  45645. return true;
  45646. }
  45647. }
  45648. return false;
  45649. };
  45650. }
  45651. return defs;
  45652. }
  45653. else {
  45654. return null;
  45655. }
  45656. }
  45657. else {
  45658. return defs[0];
  45659. }
  45660. },
  45661. resize: function (width, height) {
  45662. var viewport = this._viewport;
  45663. // FIXME Why ?
  45664. viewport.style.display = 'none';
  45665. // Save input w/h
  45666. var opts = this._opts;
  45667. width != null && (opts.width = width);
  45668. height != null && (opts.height = height);
  45669. width = this._getSize(0);
  45670. height = this._getSize(1);
  45671. viewport.style.display = '';
  45672. if (this._width !== width || this._height !== height) {
  45673. this._width = width;
  45674. this._height = height;
  45675. var viewportStyle = viewport.style;
  45676. viewportStyle.width = width + 'px';
  45677. viewportStyle.height = height + 'px';
  45678. var svgRoot = this._svgRoot;
  45679. // Set width by 'svgRoot.width = width' is invalid
  45680. svgRoot.setAttribute('width', width);
  45681. svgRoot.setAttribute('height', height);
  45682. }
  45683. },
  45684. /**
  45685. * 获取绘图区域宽度
  45686. */
  45687. getWidth: function () {
  45688. return this._width;
  45689. },
  45690. /**
  45691. * 获取绘图区域高度
  45692. */
  45693. getHeight: function () {
  45694. return this._height;
  45695. },
  45696. _getSize: function (whIdx) {
  45697. var opts = this._opts;
  45698. var wh = ['width', 'height'][whIdx];
  45699. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  45700. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  45701. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  45702. if (opts[wh] != null && opts[wh] !== 'auto') {
  45703. return parseFloat(opts[wh]);
  45704. }
  45705. var root = this.root;
  45706. // IE8 does not support getComputedStyle, but it use VML.
  45707. var stl = document.defaultView.getComputedStyle(root);
  45708. return (
  45709. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  45710. - (parseInt10$2(stl[plt]) || 0)
  45711. - (parseInt10$2(stl[prb]) || 0)
  45712. ) | 0;
  45713. },
  45714. dispose: function () {
  45715. this.root.innerHTML = '';
  45716. this._svgRoot
  45717. = this._viewport
  45718. = this.storage
  45719. = null;
  45720. },
  45721. clear: function () {
  45722. if (this._viewport) {
  45723. this.root.removeChild(this._viewport);
  45724. }
  45725. },
  45726. pathToSvg: function () {
  45727. this.refresh();
  45728. var html = this._svgRoot.outerHTML;
  45729. return 'data:img/svg+xml;utf-8,' + unescape(html);
  45730. }
  45731. };
  45732. // Not supported methods
  45733. function createMethodNotSupport$1(method) {
  45734. return function () {
  45735. zrLog('In SVG mode painter not support method "' + method + '"');
  45736. };
  45737. }
  45738. // Unsuppoted methods
  45739. each$1([
  45740. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  45741. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  45742. 'toDataURL', 'pathToImage'
  45743. ], function (name) {
  45744. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  45745. });
  45746. registerPainter('svg', SVGPainter);
  45747. exports.version = version;
  45748. exports.dependencies = dependencies;
  45749. exports.PRIORITY = PRIORITY;
  45750. exports.init = init;
  45751. exports.connect = connect;
  45752. exports.disConnect = disConnect;
  45753. exports.disconnect = disconnect;
  45754. exports.dispose = dispose;
  45755. exports.getInstanceByDom = getInstanceByDom;
  45756. exports.getInstanceById = getInstanceById;
  45757. exports.registerTheme = registerTheme;
  45758. exports.registerPreprocessor = registerPreprocessor;
  45759. exports.registerProcessor = registerProcessor;
  45760. exports.registerPostUpdate = registerPostUpdate;
  45761. exports.registerAction = registerAction;
  45762. exports.registerCoordinateSystem = registerCoordinateSystem;
  45763. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  45764. exports.registerLayout = registerLayout;
  45765. exports.registerVisual = registerVisual;
  45766. exports.registerLoading = registerLoading;
  45767. exports.extendComponentModel = extendComponentModel;
  45768. exports.extendComponentView = extendComponentView;
  45769. exports.extendSeriesModel = extendSeriesModel;
  45770. exports.extendChartView = extendChartView;
  45771. exports.setCanvasCreator = setCanvasCreator;
  45772. exports.registerMap = registerMap;
  45773. exports.getMap = getMap;
  45774. exports.dataTool = dataTool;
  45775. exports.zrender = zrender;
  45776. exports.graphic = graphic;
  45777. exports.number = number;
  45778. exports.format = format;
  45779. exports.throttle = throttle;
  45780. exports.helper = helper;
  45781. exports.matrix = matrix;
  45782. exports.vector = vector;
  45783. exports.color = color;
  45784. exports.parseGeoJSON = parseGeoJSON;
  45785. exports.parseGeoJson = parseGeoJson;
  45786. exports.util = ecUtil;
  45787. exports.List = List;
  45788. exports.Model = Model;
  45789. exports.Axis = Axis;
  45790. exports.env = env$1;
  45791. })));