echarts-en.common.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080
  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: 'Box Select',
  19726. polygon: 'Lasso Select',
  19727. lineX: 'Horizontally Select',
  19728. lineY: 'Vertically Select',
  19729. keep: 'Keep Selections',
  19730. clear: 'Clear Selections'
  19731. }
  19732. },
  19733. dataView: {
  19734. title: 'Data View',
  19735. lang: ['Data View', 'Close', 'Refresh']
  19736. },
  19737. dataZoom: {
  19738. title: {
  19739. zoom: 'Zoom',
  19740. back: 'Zoom Reset'
  19741. }
  19742. },
  19743. magicType: {
  19744. title: {
  19745. line: 'Switch to Line Chart',
  19746. bar: 'Switch to Bar Chart',
  19747. stack: 'Stack',
  19748. tiled: 'Tile'
  19749. }
  19750. },
  19751. restore: {
  19752. title: 'Restore'
  19753. },
  19754. saveAsImage: {
  19755. title: 'Save as Image',
  19756. lang: ['Right Click to Save Image']
  19757. }
  19758. }
  19759. };
  19760. var aria = function (dom, ecModel) {
  19761. var ariaModel = ecModel.getModel('aria');
  19762. if (!ariaModel.get('show')) {
  19763. return;
  19764. }
  19765. else if (ariaModel.get('description')) {
  19766. dom.setAttribute('aria-label', ariaModel.get('description'));
  19767. return;
  19768. }
  19769. var seriesCnt = 0;
  19770. ecModel.eachSeries(function (seriesModel, idx) {
  19771. ++seriesCnt;
  19772. }, this);
  19773. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  19774. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  19775. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  19776. var ariaLabel;
  19777. if (seriesCnt < 1) {
  19778. // No series, no aria label
  19779. return;
  19780. }
  19781. else {
  19782. var title = getTitle();
  19783. if (title) {
  19784. ariaLabel = replace(getConfig('general.withTitle'), {
  19785. title: title
  19786. });
  19787. }
  19788. else {
  19789. ariaLabel = getConfig('general.withoutTitle');
  19790. }
  19791. var seriesLabels = [];
  19792. var prefix = seriesCnt > 1
  19793. ? 'series.multiple.prefix'
  19794. : 'series.single.prefix';
  19795. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  19796. ecModel.eachSeries(function (seriesModel, idx) {
  19797. if (idx < displaySeriesCnt) {
  19798. var seriesLabel;
  19799. var seriesName = seriesModel.get('name');
  19800. var seriesTpl = 'series.'
  19801. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  19802. seriesLabel = getConfig(seriesName
  19803. ? seriesTpl + 'withName'
  19804. : seriesTpl + 'withoutName');
  19805. seriesLabel = replace(seriesLabel, {
  19806. seriesId: seriesModel.seriesIndex,
  19807. seriesName: seriesModel.get('name'),
  19808. seriesType: getSeriesTypeName(seriesModel.subType)
  19809. });
  19810. var data = seriesModel.getData();
  19811. window.data = data;
  19812. if (data.count() > maxDataCnt) {
  19813. // Show part of data
  19814. seriesLabel += replace(getConfig('data.partialData'), {
  19815. displayCnt: maxDataCnt
  19816. });
  19817. }
  19818. else {
  19819. seriesLabel += getConfig('data.allData');
  19820. }
  19821. var dataLabels = [];
  19822. for (var i = 0; i < data.count(); i++) {
  19823. if (i < maxDataCnt) {
  19824. var name = data.getName(i);
  19825. var value = retrieveRawValue(data, i);
  19826. dataLabels.push(
  19827. replace(
  19828. name
  19829. ? getConfig('data.withName')
  19830. : getConfig('data.withoutName'),
  19831. {
  19832. name: name,
  19833. value: value
  19834. }
  19835. )
  19836. );
  19837. }
  19838. }
  19839. seriesLabel += dataLabels
  19840. .join(getConfig('data.separator.middle'))
  19841. + getConfig('data.separator.end');
  19842. seriesLabels.push(seriesLabel);
  19843. }
  19844. });
  19845. ariaLabel += seriesLabels
  19846. .join(getConfig('series.multiple.separator.middle'))
  19847. + getConfig('series.multiple.separator.end');
  19848. dom.setAttribute('aria-label', ariaLabel);
  19849. }
  19850. function replace(str, keyValues) {
  19851. if (typeof str !== 'string') {
  19852. return str;
  19853. }
  19854. var result = str;
  19855. each$1(keyValues, function (value, key) {
  19856. result = result.replace(
  19857. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  19858. value
  19859. );
  19860. });
  19861. return result;
  19862. }
  19863. function getConfig(path) {
  19864. var userConfig = ariaModel.get(path);
  19865. if (userConfig == null) {
  19866. var pathArr = path.split('.');
  19867. var result = lang.aria;
  19868. for (var i = 0; i < pathArr.length; ++i) {
  19869. result = result[pathArr[i]];
  19870. }
  19871. return result;
  19872. }
  19873. else {
  19874. return userConfig;
  19875. }
  19876. }
  19877. function getTitle() {
  19878. var title = ecModel.getModel('title').option;
  19879. if (title && title.length) {
  19880. title = title[0];
  19881. }
  19882. return title && title.text;
  19883. }
  19884. function getSeriesTypeName(type) {
  19885. return lang.series.typeNames[type] || '自定义图';
  19886. }
  19887. };
  19888. var PI$1 = Math.PI;
  19889. /**
  19890. * @param {module:echarts/ExtensionAPI} api
  19891. * @param {Object} [opts]
  19892. * @param {string} [opts.text]
  19893. * @param {string} [opts.color]
  19894. * @param {string} [opts.textColor]
  19895. * @return {module:zrender/Element}
  19896. */
  19897. var loadingDefault = function (api, opts) {
  19898. opts = opts || {};
  19899. defaults(opts, {
  19900. text: 'loading',
  19901. color: '#c23531',
  19902. textColor: '#000',
  19903. maskColor: 'rgba(255, 255, 255, 0.8)',
  19904. zlevel: 0
  19905. });
  19906. var mask = new Rect({
  19907. style: {
  19908. fill: opts.maskColor
  19909. },
  19910. zlevel: opts.zlevel,
  19911. z: 10000
  19912. });
  19913. var arc = new Arc({
  19914. shape: {
  19915. startAngle: -PI$1 / 2,
  19916. endAngle: -PI$1 / 2 + 0.1,
  19917. r: 10
  19918. },
  19919. style: {
  19920. stroke: opts.color,
  19921. lineCap: 'round',
  19922. lineWidth: 5
  19923. },
  19924. zlevel: opts.zlevel,
  19925. z: 10001
  19926. });
  19927. var labelRect = new Rect({
  19928. style: {
  19929. fill: 'none',
  19930. text: opts.text,
  19931. textPosition: 'right',
  19932. textDistance: 10,
  19933. textFill: opts.textColor
  19934. },
  19935. zlevel: opts.zlevel,
  19936. z: 10001
  19937. });
  19938. arc.animateShape(true)
  19939. .when(1000, {
  19940. endAngle: PI$1 * 3 / 2
  19941. })
  19942. .start('circularInOut');
  19943. arc.animateShape(true)
  19944. .when(1000, {
  19945. startAngle: PI$1 * 3 / 2
  19946. })
  19947. .delay(300)
  19948. .start('circularInOut');
  19949. var group = new Group();
  19950. group.add(arc);
  19951. group.add(labelRect);
  19952. group.add(mask);
  19953. // Inject resize
  19954. group.resize = function () {
  19955. var cx = api.getWidth() / 2;
  19956. var cy = api.getHeight() / 2;
  19957. arc.setShape({
  19958. cx: cx,
  19959. cy: cy
  19960. });
  19961. var r = arc.shape.r;
  19962. labelRect.setShape({
  19963. x: cx - r,
  19964. y: cy - r,
  19965. width: r * 2,
  19966. height: r * 2
  19967. });
  19968. mask.setShape({
  19969. x: 0,
  19970. y: 0,
  19971. width: api.getWidth(),
  19972. height: api.getHeight()
  19973. });
  19974. };
  19975. group.resize();
  19976. return group;
  19977. };
  19978. /**
  19979. * @module echarts/stream/Scheduler
  19980. */
  19981. /**
  19982. * @constructor
  19983. */
  19984. function Scheduler(ecInstance, api) {
  19985. // this._pipelineMap = createHashMap();
  19986. this.ecInstance = ecInstance;
  19987. this.api = api;
  19988. this.unfinished;
  19989. /**
  19990. * @private
  19991. * @type {
  19992. * [handlerUID: string]: {
  19993. * seriesTaskMap?: {
  19994. * [seriesUID: string]: Task
  19995. * },
  19996. * overallTask?: Task
  19997. * }
  19998. * }
  19999. */
  20000. this._stageTaskMap = createHashMap();
  20001. }
  20002. var proto = Scheduler.prototype;
  20003. // If seriesModel provided, incremental threshold is check by series data.
  20004. proto.getPerformArgs = function (task, isBlock) {
  20005. // For overall task
  20006. if (!task.__pipeline) {
  20007. return;
  20008. }
  20009. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20010. var pCtx = pipeline.context;
  20011. var incremental = !isBlock
  20012. && pipeline.progressiveEnabled
  20013. && (!pCtx || pCtx.incrementalRender)
  20014. && task.__idxInPipeline > pipeline.bockIndex;
  20015. return {step: incremental ? pipeline.step : null};
  20016. };
  20017. proto.getPipeline = function (pipelineId) {
  20018. return this._pipelineMap.get(pipelineId);
  20019. };
  20020. /**
  20021. * Current, progressive rendering starts from visual and layout.
  20022. * Always detect render mode in the same stage, avoiding that incorrect
  20023. * detection caused by data filtering.
  20024. * Caution:
  20025. * `updateStreamModes` use `seriesModel.getData()`.
  20026. */
  20027. proto.updateStreamModes = function (seriesModel, view) {
  20028. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20029. var data = seriesModel.getData();
  20030. var dataLen = data.count();
  20031. var incrementalRender = pipeline.progressiveEnabled
  20032. && view.incrementalPrepareRender
  20033. && dataLen >= pipeline.threshold;
  20034. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20035. seriesModel.pipelineContext = pipeline.context = {
  20036. incrementalRender: incrementalRender,
  20037. large: large
  20038. };
  20039. };
  20040. proto.restorePipelines = function (ecModel) {
  20041. var scheduler = this;
  20042. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20043. ecModel.eachSeries(function (seriesModel) {
  20044. var progressive = seriesModel.getProgressive();
  20045. var pipelineId = seriesModel.uid;
  20046. pipelineMap.set(pipelineId, {
  20047. id: pipelineId,
  20048. head: null,
  20049. tail: null,
  20050. threshold: seriesModel.getProgressiveThreshold(),
  20051. progressiveEnabled: progressive
  20052. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20053. bockIndex: -1,
  20054. step: progressive || 700, // ??? Temporarily number
  20055. count: 0
  20056. });
  20057. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20058. });
  20059. };
  20060. proto.prepareStageTasks = function (stageHandlers, useClearVisual) {
  20061. var stageTaskMap = this._stageTaskMap;
  20062. var ecModel = this.ecInstance.getModel();
  20063. var api = this.api;
  20064. each$1(stageHandlers, function (handler) {
  20065. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20066. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20067. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20068. }, this);
  20069. };
  20070. proto.prepareView = function (view, model, ecModel, api) {
  20071. var renderTask = view.renderTask;
  20072. var context = renderTask.context;
  20073. context.model = model;
  20074. context.ecModel = ecModel;
  20075. context.api = api;
  20076. renderTask.__block = !view.incrementalPrepareRender;
  20077. pipe(this, model, renderTask);
  20078. };
  20079. proto.performDataProcessorTasks = function (stageHandlers, ecModel, payload) {
  20080. // If we do not use `block` here, it should be considered when to update modes.
  20081. performStageTasks(this, stageHandlers, ecModel, payload, {block: true});
  20082. };
  20083. // opt
  20084. // opt.visualType: 'visual' or 'layout'
  20085. // opt.setDirty
  20086. proto.performVisualTasks = function (stageHandlers, ecModel, payload, opt) {
  20087. performStageTasks(this, stageHandlers, ecModel, payload, opt);
  20088. };
  20089. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20090. opt = opt || {};
  20091. var unfinished;
  20092. each$1(stageHandlers, function (stageHandler, idx) {
  20093. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20094. return;
  20095. }
  20096. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20097. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20098. var overallTask = stageHandlerRecord.overallTask;
  20099. if (overallTask) {
  20100. var overallNeedDirty;
  20101. var agentStubMap = overallTask.agentStubMap;
  20102. agentStubMap.each(function (stub) {
  20103. if (needSetDirty(opt, stub)) {
  20104. stub.dirty();
  20105. overallNeedDirty = true;
  20106. }
  20107. });
  20108. overallNeedDirty && overallTask.dirty();
  20109. updatePayload(overallTask, payload);
  20110. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20111. // Execute stubs firstly, which may set the overall task dirty,
  20112. // then execute the overall task. And stub will call seriesModel.setData,
  20113. // which ensures that in the overallTask seriesModel.getData() will not
  20114. // return incorrect data.
  20115. agentStubMap.each(function (stub) {
  20116. stub.perform(performArgs);
  20117. });
  20118. unfinished |= overallTask.perform(performArgs);
  20119. }
  20120. else if (seriesTaskMap) {
  20121. seriesTaskMap.each(function (task, pipelineId) {
  20122. if (needSetDirty(opt, task)) {
  20123. task.dirty();
  20124. }
  20125. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20126. performArgs.skip = !stageHandler.performRawSeries
  20127. && ecModel.isSeriesFiltered(task.context.model);
  20128. updatePayload(task, payload);
  20129. unfinished |= task.perform(performArgs);
  20130. });
  20131. }
  20132. });
  20133. function needSetDirty(opt, task) {
  20134. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20135. }
  20136. scheduler.unfinished |= unfinished;
  20137. }
  20138. proto.performSeriesTasks = function (ecModel) {
  20139. var unfinished;
  20140. ecModel.eachSeries(function (seriesModel) {
  20141. // Progress to the end for dataInit and dataRestore.
  20142. unfinished |= seriesModel.dataTask.perform();
  20143. });
  20144. this.unfinished |= unfinished;
  20145. };
  20146. proto.plan = function () {
  20147. // Travel pipelines, check block.
  20148. this._pipelineMap.each(function (pipeline) {
  20149. var task = pipeline.tail;
  20150. do {
  20151. if (task.__block) {
  20152. pipeline.bockIndex = task.__idxInPipeline;
  20153. break;
  20154. }
  20155. task = task.getUpstream();
  20156. }
  20157. while (task);
  20158. });
  20159. };
  20160. var updatePayload = proto.updatePayload = function (task, payload) {
  20161. payload !== 'remain' && (task.context.payload = payload);
  20162. };
  20163. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20164. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20165. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20166. var seriesType = stageHandler.seriesType;
  20167. var getTargetSeries = stageHandler.getTargetSeries;
  20168. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20169. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20170. // it works but it may cause other irrelevant charts blocked.
  20171. if (stageHandler.createOnAllSeries) {
  20172. ecModel.eachRawSeries(create);
  20173. }
  20174. else if (seriesType) {
  20175. ecModel.eachRawSeriesByType(seriesType, create);
  20176. }
  20177. else if (getTargetSeries) {
  20178. getTargetSeries(ecModel, api).each(create);
  20179. }
  20180. function create(seriesModel) {
  20181. var pipelineId = seriesModel.uid;
  20182. // Init tasks for each seriesModel only once.
  20183. // Reuse original task instance.
  20184. var task = seriesTaskMap.get(pipelineId)
  20185. || seriesTaskMap.set(pipelineId, createTask({
  20186. plan: seriesTaskPlan,
  20187. reset: seriesTaskReset,
  20188. count: seriesTaskCount
  20189. }));
  20190. task.context = {
  20191. model: seriesModel,
  20192. ecModel: ecModel,
  20193. api: api,
  20194. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20195. plan: stageHandler.plan,
  20196. reset: stageHandler.reset,
  20197. scheduler: scheduler
  20198. };
  20199. pipe(scheduler, seriesModel, task);
  20200. }
  20201. // Clear unused series tasks.
  20202. var pipelineMap = scheduler._pipelineMap;
  20203. seriesTaskMap.each(function (task, pipelineId) {
  20204. if (!pipelineMap.get(pipelineId)) {
  20205. task.dispose();
  20206. seriesTaskMap.removeKey(pipelineId);
  20207. }
  20208. });
  20209. }
  20210. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20211. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20212. // For overall task, the function only be called on reset stage.
  20213. || createTask({reset: overallTaskReset});
  20214. overallTask.context = {
  20215. ecModel: ecModel,
  20216. api: api,
  20217. overallReset: stageHandler.overallReset,
  20218. scheduler: scheduler
  20219. };
  20220. // Reuse orignal stubs.
  20221. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20222. var seriesType = stageHandler.seriesType;
  20223. var getTargetSeries = stageHandler.getTargetSeries;
  20224. var overallProgress = true;
  20225. var isOverallFilter = stageHandler.isOverallFilter;
  20226. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20227. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20228. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20229. // we set the pipeline block.
  20230. if (seriesType) {
  20231. ecModel.eachRawSeriesByType(seriesType, createStub);
  20232. }
  20233. else if (getTargetSeries) {
  20234. getTargetSeries(ecModel, api).each(createStub);
  20235. }
  20236. // Otherwise, (usually it is legancy case), the overall task will only be
  20237. // executed when upstream dirty. Otherwise the progressive rendering of all
  20238. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20239. // dirty info from upsteam.
  20240. else {
  20241. overallProgress = false;
  20242. each$1(ecModel.getSeries(), createStub);
  20243. }
  20244. function createStub(seriesModel) {
  20245. var pipelineId = seriesModel.uid;
  20246. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20247. {reset: stubReset, onDirty: stubOnDirty}
  20248. ));
  20249. stub.context = {
  20250. model: seriesModel,
  20251. overallProgress: overallProgress,
  20252. isOverallFilter: isOverallFilter
  20253. };
  20254. stub.agent = overallTask;
  20255. stub.__block = overallProgress;
  20256. pipe(scheduler, seriesModel, stub);
  20257. }
  20258. // Clear unused stubs.
  20259. var pipelineMap = scheduler._pipelineMap;
  20260. agentStubMap.each(function (stub, pipelineId) {
  20261. if (!pipelineMap.get(pipelineId)) {
  20262. stub.dispose();
  20263. agentStubMap.removeKey(pipelineId);
  20264. }
  20265. });
  20266. }
  20267. function overallTaskReset(context) {
  20268. context.overallReset(
  20269. context.ecModel, context.api, context.payload
  20270. );
  20271. }
  20272. function stubReset(context, upstreamContext) {
  20273. return context.overallProgress && stubProgress;
  20274. }
  20275. function stubProgress() {
  20276. this.agent.dirty();
  20277. this.getDownstream().dirty();
  20278. }
  20279. function stubOnDirty() {
  20280. this.agent && this.agent.dirty();
  20281. }
  20282. function seriesTaskPlan(context) {
  20283. return context.plan && context.plan(
  20284. context.model, context.ecModel, context.api, context.payload
  20285. );
  20286. }
  20287. function seriesTaskReset(context) {
  20288. if (context.useClearVisual) {
  20289. context.data.clearAllVisual();
  20290. }
  20291. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20292. context.model, context.ecModel, context.api, context.payload
  20293. ));
  20294. if (resetDefines.length) {
  20295. return seriesTaskProgress;
  20296. }
  20297. }
  20298. function seriesTaskProgress(params, context) {
  20299. var data = context.data;
  20300. var resetDefines = context.resetDefines;
  20301. for (var k = 0; k < resetDefines.length; k++) {
  20302. var resetDefine = resetDefines[k];
  20303. if (resetDefine && resetDefine.dataEach) {
  20304. for (var i = params.start; i < params.end; i++) {
  20305. resetDefine.dataEach(data, i);
  20306. }
  20307. }
  20308. else if (resetDefine && resetDefine.progress) {
  20309. resetDefine.progress(params, data);
  20310. }
  20311. }
  20312. }
  20313. function seriesTaskCount(context) {
  20314. return context.data.count();
  20315. }
  20316. function pipe(scheduler, seriesModel, task) {
  20317. var pipelineId = seriesModel.uid;
  20318. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20319. !pipeline.head && (pipeline.head = task);
  20320. pipeline.tail && pipeline.tail.pipe(task);
  20321. pipeline.tail = task;
  20322. task.__idxInPipeline = pipeline.count++;
  20323. task.__pipeline = pipeline;
  20324. }
  20325. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20326. if (isFunction$1(stageHandler)) {
  20327. stageHandler = {
  20328. overallReset: stageHandler,
  20329. seriesType: detectSeriseType(stageHandler)
  20330. };
  20331. }
  20332. stageHandler.uid = getUID('stageHandler');
  20333. visualType && (stageHandler.visualType = visualType);
  20334. return stageHandler;
  20335. };
  20336. /**
  20337. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20338. * To ensure that they can work normally, they should work in block mode, that is,
  20339. * they should not be started util the previous tasks finished. So they cause the
  20340. * progressive rendering disabled. We try to detect the series type, to narrow down
  20341. * the block range to only the series type they concern, but not all series.
  20342. */
  20343. function detectSeriseType(legacyFunc) {
  20344. seriesType = null;
  20345. try {
  20346. // Assume there is no async when calling `eachSeriesByType`.
  20347. legacyFunc(ecModelMock, apiMock);
  20348. }
  20349. catch (e) {
  20350. }
  20351. return seriesType;
  20352. }
  20353. var ecModelMock = {};
  20354. var apiMock = {};
  20355. var seriesType;
  20356. mockMethods(ecModelMock, GlobalModel);
  20357. mockMethods(apiMock, ExtensionAPI);
  20358. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20359. seriesType = type;
  20360. };
  20361. ecModelMock.eachComponent = function (cond) {
  20362. if (cond.mainType === 'series' && cond.subType) {
  20363. seriesType = cond.subType;
  20364. }
  20365. };
  20366. function mockMethods(target, Clz) {
  20367. for (var name in Clz.prototype) {
  20368. // Do not use hasOwnProperty
  20369. target[name] = noop;
  20370. }
  20371. }
  20372. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20373. var lightTheme = {
  20374. color: colorAll,
  20375. colorLayer: [
  20376. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20377. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20378. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20379. colorAll
  20380. ]
  20381. };
  20382. var contrastColor = '#eee';
  20383. var axisCommon = function () {
  20384. return {
  20385. axisLine: {
  20386. lineStyle: {
  20387. color: contrastColor
  20388. }
  20389. },
  20390. axisTick: {
  20391. lineStyle: {
  20392. color: contrastColor
  20393. }
  20394. },
  20395. axisLabel: {
  20396. textStyle: {
  20397. color: contrastColor
  20398. }
  20399. },
  20400. splitLine: {
  20401. lineStyle: {
  20402. type: 'dashed',
  20403. color: '#aaa'
  20404. }
  20405. },
  20406. splitArea: {
  20407. areaStyle: {
  20408. color: contrastColor
  20409. }
  20410. }
  20411. };
  20412. };
  20413. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20414. var theme = {
  20415. color: colorPalette,
  20416. backgroundColor: '#333',
  20417. tooltip: {
  20418. axisPointer: {
  20419. lineStyle: {
  20420. color: contrastColor
  20421. },
  20422. crossStyle: {
  20423. color: contrastColor
  20424. }
  20425. }
  20426. },
  20427. legend: {
  20428. textStyle: {
  20429. color: contrastColor
  20430. }
  20431. },
  20432. textStyle: {
  20433. color: contrastColor
  20434. },
  20435. title: {
  20436. textStyle: {
  20437. color: contrastColor
  20438. }
  20439. },
  20440. toolbox: {
  20441. iconStyle: {
  20442. normal: {
  20443. borderColor: contrastColor
  20444. }
  20445. }
  20446. },
  20447. dataZoom: {
  20448. textStyle: {
  20449. color: contrastColor
  20450. }
  20451. },
  20452. visualMap: {
  20453. textStyle: {
  20454. color: contrastColor
  20455. }
  20456. },
  20457. timeline: {
  20458. lineStyle: {
  20459. color: contrastColor
  20460. },
  20461. itemStyle: {
  20462. normal: {
  20463. color: colorPalette[1]
  20464. }
  20465. },
  20466. label: {
  20467. normal: {
  20468. textStyle: {
  20469. color: contrastColor
  20470. }
  20471. }
  20472. },
  20473. controlStyle: {
  20474. normal: {
  20475. color: contrastColor,
  20476. borderColor: contrastColor
  20477. }
  20478. }
  20479. },
  20480. timeAxis: axisCommon(),
  20481. logAxis: axisCommon(),
  20482. valueAxis: axisCommon(),
  20483. categoryAxis: axisCommon(),
  20484. line: {
  20485. symbol: 'circle'
  20486. },
  20487. graph: {
  20488. color: colorPalette
  20489. },
  20490. gauge: {
  20491. title: {
  20492. textStyle: {
  20493. color: contrastColor
  20494. }
  20495. }
  20496. },
  20497. candlestick: {
  20498. itemStyle: {
  20499. normal: {
  20500. color: '#FD1050',
  20501. color0: '#0CF49B',
  20502. borderColor: '#FD1050',
  20503. borderColor0: '#0CF49B'
  20504. }
  20505. }
  20506. }
  20507. };
  20508. theme.categoryAxis.splitLine.show = false;
  20509. /*!
  20510. * ECharts, a free, powerful charting and visualization library.
  20511. *
  20512. * Copyright (c) 2017, Baidu Inc.
  20513. * All rights reserved.
  20514. *
  20515. * LICENSE
  20516. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20517. */
  20518. var assert = assert$1;
  20519. var each = each$1;
  20520. var isFunction = isFunction$1;
  20521. var isObject = isObject$1;
  20522. var parseClassType = ComponentModel.parseClassType;
  20523. var version = '4.0.2';
  20524. var dependencies = {
  20525. zrender: '4.0.1'
  20526. };
  20527. var TEST_FRAME_REMAIN_TIME = 1;
  20528. var PRIORITY_PROCESSOR_FILTER = 1000;
  20529. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20530. var PRIORITY_VISUAL_LAYOUT = 1000;
  20531. var PRIORITY_VISUAL_GLOBAL = 2000;
  20532. var PRIORITY_VISUAL_CHART = 3000;
  20533. var PRIORITY_VISUAL_COMPONENT = 4000;
  20534. // FIXME
  20535. // necessary?
  20536. var PRIORITY_VISUAL_BRUSH = 5000;
  20537. var PRIORITY = {
  20538. PROCESSOR: {
  20539. FILTER: PRIORITY_PROCESSOR_FILTER,
  20540. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20541. },
  20542. VISUAL: {
  20543. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20544. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20545. CHART: PRIORITY_VISUAL_CHART,
  20546. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20547. BRUSH: PRIORITY_VISUAL_BRUSH
  20548. }
  20549. };
  20550. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20551. // where they must not be invoked nestedly, except the only case: invoke
  20552. // dispatchAction with updateMethod "none" in main process.
  20553. // This flag is used to carry out this rule.
  20554. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20555. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20556. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  20557. var OPTION_UPDATED = '__optionUpdated';
  20558. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20559. function createRegisterEventWithLowercaseName(method) {
  20560. return function (eventName, handler, context) {
  20561. // Event name is all lowercase
  20562. eventName = eventName && eventName.toLowerCase();
  20563. Eventful.prototype[method].call(this, eventName, handler, context);
  20564. };
  20565. }
  20566. /**
  20567. * @module echarts~MessageCenter
  20568. */
  20569. function MessageCenter() {
  20570. Eventful.call(this);
  20571. }
  20572. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20573. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20574. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20575. mixin(MessageCenter, Eventful);
  20576. /**
  20577. * @module echarts~ECharts
  20578. */
  20579. function ECharts(dom, theme$$1, opts) {
  20580. opts = opts || {};
  20581. // Get theme by name
  20582. if (typeof theme$$1 === 'string') {
  20583. theme$$1 = themeStorage[theme$$1];
  20584. }
  20585. /**
  20586. * @type {string}
  20587. */
  20588. this.id;
  20589. /**
  20590. * Group id
  20591. * @type {string}
  20592. */
  20593. this.group;
  20594. /**
  20595. * @type {HTMLElement}
  20596. * @private
  20597. */
  20598. this._dom = dom;
  20599. var defaultRenderer = 'canvas';
  20600. if (__DEV__) {
  20601. defaultRenderer = (
  20602. typeof window === 'undefined' ? global : window
  20603. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20604. }
  20605. /**
  20606. * @type {module:zrender/ZRender}
  20607. * @private
  20608. */
  20609. var zr = this._zr = init$1(dom, {
  20610. renderer: opts.renderer || defaultRenderer,
  20611. devicePixelRatio: opts.devicePixelRatio,
  20612. width: opts.width,
  20613. height: opts.height
  20614. });
  20615. /**
  20616. * Expect 60 pfs.
  20617. * @type {Function}
  20618. * @private
  20619. */
  20620. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20621. var theme$$1 = clone(theme$$1);
  20622. theme$$1 && backwardCompat(theme$$1, true);
  20623. /**
  20624. * @type {Object}
  20625. * @private
  20626. */
  20627. this._theme = theme$$1;
  20628. /**
  20629. * @type {Array.<module:echarts/view/Chart>}
  20630. * @private
  20631. */
  20632. this._chartsViews = [];
  20633. /**
  20634. * @type {Object.<string, module:echarts/view/Chart>}
  20635. * @private
  20636. */
  20637. this._chartsMap = {};
  20638. /**
  20639. * @type {Array.<module:echarts/view/Component>}
  20640. * @private
  20641. */
  20642. this._componentsViews = [];
  20643. /**
  20644. * @type {Object.<string, module:echarts/view/Component>}
  20645. * @private
  20646. */
  20647. this._componentsMap = {};
  20648. /**
  20649. * @type {module:echarts/CoordinateSystem}
  20650. * @private
  20651. */
  20652. this._coordSysMgr = new CoordinateSystemManager();
  20653. /**
  20654. * @type {module:echarts/ExtensionAPI}
  20655. * @private
  20656. */
  20657. var api = this._api = createExtensionAPI(this);
  20658. /**
  20659. * @type {module:echarts/stream/Scheduler}
  20660. */
  20661. this._scheduler = new Scheduler(this, api);
  20662. Eventful.call(this);
  20663. /**
  20664. * @type {module:echarts~MessageCenter}
  20665. * @private
  20666. */
  20667. this._messageCenter = new MessageCenter();
  20668. // this._scheduler = new Scheduler();
  20669. // Init mouse events
  20670. this._initEvents();
  20671. // In case some people write `window.onresize = chart.resize`
  20672. this.resize = bind(this.resize, this);
  20673. // Can't dispatch action during rendering procedure
  20674. this._pendingActions = [];
  20675. // Sort on demand
  20676. function prioritySortFunc(a, b) {
  20677. return a.__prio - b.__prio;
  20678. }
  20679. sort(visualFuncs, prioritySortFunc);
  20680. sort(dataProcessorFuncs, prioritySortFunc);
  20681. zr.animation.on('frame', this._onframe, this);
  20682. // ECharts instance can be used as value.
  20683. setAsPrimitive(this);
  20684. }
  20685. var echartsProto = ECharts.prototype;
  20686. echartsProto._onframe = function () {
  20687. if (this._disposed) {
  20688. return;
  20689. }
  20690. var scheduler = this._scheduler;
  20691. // Lazy update
  20692. if (this[OPTION_UPDATED]) {
  20693. var silent = this[OPTION_UPDATED].silent;
  20694. this[IN_MAIN_PROCESS] = true;
  20695. prepare(this);
  20696. updateMethods.update.call(this);
  20697. this[IN_MAIN_PROCESS] = false;
  20698. this[OPTION_UPDATED] = false;
  20699. flushPendingActions.call(this, silent);
  20700. triggerUpdatedEvent.call(this, silent);
  20701. }
  20702. // Avoid do both lazy update and progress in one frame.
  20703. else if (scheduler.unfinished) {
  20704. // Stream progress.
  20705. var remainTime = TEST_FRAME_REMAIN_TIME;
  20706. var ecModel = this._model;
  20707. var api = this._api;
  20708. scheduler.unfinished = false;
  20709. do {
  20710. var startTime = +new Date();
  20711. scheduler.performSeriesTasks(ecModel);
  20712. // Currently dataProcessorFuncs do not check threshold.
  20713. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel);
  20714. updateStreamModes(this, ecModel);
  20715. // Do not update coordinate system here. Because that coord system update in
  20716. // each frame is not a good user experience. So we follow the rule that
  20717. // the extent of the coordinate system is determin in the first frame (the
  20718. // frame is executed immedietely after task reset.
  20719. // this._coordSysMgr.update(ecModel, api);
  20720. // console.log('--- ec frame visual ---', remainTime);
  20721. scheduler.performVisualTasks(visualFuncs, ecModel);
  20722. renderSeries(this, this._model, api, 'remain');
  20723. remainTime -= (+new Date() - startTime);
  20724. }
  20725. while (remainTime > 0 && scheduler.unfinished);
  20726. if (!scheduler.unfinished) {
  20727. this._zr && this._zr.flush();
  20728. this.trigger('finished');
  20729. }
  20730. // Else, zr flushing be ensue within the same frame,
  20731. // because zr flushing is after onframe event.
  20732. }
  20733. };
  20734. /**
  20735. * @return {HTMLElement}
  20736. */
  20737. echartsProto.getDom = function () {
  20738. return this._dom;
  20739. };
  20740. /**
  20741. * @return {module:zrender~ZRender}
  20742. */
  20743. echartsProto.getZr = function () {
  20744. return this._zr;
  20745. };
  20746. /**
  20747. * Usage:
  20748. * chart.setOption(option, notMerge, lazyUpdate);
  20749. * chart.setOption(option, {
  20750. * notMerge: ...,
  20751. * lazyUpdate: ...,
  20752. * silent: ...
  20753. * });
  20754. *
  20755. * @param {Object} option
  20756. * @param {Object|boolean} [opts] opts or notMerge.
  20757. * @param {boolean} [opts.notMerge=false]
  20758. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  20759. */
  20760. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  20761. if (__DEV__) {
  20762. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  20763. }
  20764. var silent;
  20765. if (isObject(notMerge)) {
  20766. lazyUpdate = notMerge.lazyUpdate;
  20767. silent = notMerge.silent;
  20768. notMerge = notMerge.notMerge;
  20769. }
  20770. this[IN_MAIN_PROCESS] = true;
  20771. if (!this._model || notMerge) {
  20772. var optionManager = new OptionManager(this._api);
  20773. var theme$$1 = this._theme;
  20774. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  20775. ecModel.scheduler = this._scheduler;
  20776. ecModel.init(null, null, theme$$1, optionManager);
  20777. }
  20778. this._model.setOption(option, optionPreprocessorFuncs);
  20779. if (lazyUpdate) {
  20780. this[OPTION_UPDATED] = {silent: silent};
  20781. this[IN_MAIN_PROCESS] = false;
  20782. }
  20783. else {
  20784. prepare(this);
  20785. updateMethods.update.call(this);
  20786. // Ensure zr refresh sychronously, and then pixel in canvas can be
  20787. // fetched after `setOption`.
  20788. this._zr.flush();
  20789. this[OPTION_UPDATED] = false;
  20790. this[IN_MAIN_PROCESS] = false;
  20791. flushPendingActions.call(this, silent);
  20792. triggerUpdatedEvent.call(this, silent);
  20793. }
  20794. };
  20795. /**
  20796. * @DEPRECATED
  20797. */
  20798. echartsProto.setTheme = function () {
  20799. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  20800. };
  20801. /**
  20802. * @return {module:echarts/model/Global}
  20803. */
  20804. echartsProto.getModel = function () {
  20805. return this._model;
  20806. };
  20807. /**
  20808. * @return {Object}
  20809. */
  20810. echartsProto.getOption = function () {
  20811. return this._model && this._model.getOption();
  20812. };
  20813. /**
  20814. * @return {number}
  20815. */
  20816. echartsProto.getWidth = function () {
  20817. return this._zr.getWidth();
  20818. };
  20819. /**
  20820. * @return {number}
  20821. */
  20822. echartsProto.getHeight = function () {
  20823. return this._zr.getHeight();
  20824. };
  20825. /**
  20826. * @return {number}
  20827. */
  20828. echartsProto.getDevicePixelRatio = function () {
  20829. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  20830. };
  20831. /**
  20832. * Get canvas which has all thing rendered
  20833. * @param {Object} opts
  20834. * @param {string} [opts.backgroundColor]
  20835. * @return {string}
  20836. */
  20837. echartsProto.getRenderedCanvas = function (opts) {
  20838. if (!env$1.canvasSupported) {
  20839. return;
  20840. }
  20841. opts = opts || {};
  20842. opts.pixelRatio = opts.pixelRatio || 1;
  20843. opts.backgroundColor = opts.backgroundColor
  20844. || this._model.get('backgroundColor');
  20845. var zr = this._zr;
  20846. var list = zr.storage.getDisplayList();
  20847. // Stop animations
  20848. each$1(list, function (el) {
  20849. el.stopAnimation(true);
  20850. });
  20851. return zr.painter.getRenderedCanvas(opts);
  20852. };
  20853. /**
  20854. * Get svg data url
  20855. * @return {string}
  20856. */
  20857. echartsProto.getSvgDataUrl = function () {
  20858. if (!env$1.svgSupported) {
  20859. return;
  20860. }
  20861. var zr = this._zr;
  20862. var list = zr.storage.getDisplayList();
  20863. // Stop animations
  20864. each$1(list, function (el) {
  20865. el.stopAnimation(true);
  20866. });
  20867. return zr.painter.pathToSvg();
  20868. };
  20869. /**
  20870. * @return {string}
  20871. * @param {Object} opts
  20872. * @param {string} [opts.type='png']
  20873. * @param {string} [opts.pixelRatio=1]
  20874. * @param {string} [opts.backgroundColor]
  20875. * @param {string} [opts.excludeComponents]
  20876. */
  20877. echartsProto.getDataURL = function (opts) {
  20878. opts = opts || {};
  20879. var excludeComponents = opts.excludeComponents;
  20880. var ecModel = this._model;
  20881. var excludesComponentViews = [];
  20882. var self = this;
  20883. each(excludeComponents, function (componentType) {
  20884. ecModel.eachComponent({
  20885. mainType: componentType
  20886. }, function (component) {
  20887. var view = self._componentsMap[component.__viewId];
  20888. if (!view.group.ignore) {
  20889. excludesComponentViews.push(view);
  20890. view.group.ignore = true;
  20891. }
  20892. });
  20893. });
  20894. var url = this._zr.painter.getType() === 'svg'
  20895. ? this.getSvgDataUrl()
  20896. : this.getRenderedCanvas(opts).toDataURL(
  20897. 'image/' + (opts && opts.type || 'png')
  20898. );
  20899. each(excludesComponentViews, function (view) {
  20900. view.group.ignore = false;
  20901. });
  20902. return url;
  20903. };
  20904. /**
  20905. * @return {string}
  20906. * @param {Object} opts
  20907. * @param {string} [opts.type='png']
  20908. * @param {string} [opts.pixelRatio=1]
  20909. * @param {string} [opts.backgroundColor]
  20910. */
  20911. echartsProto.getConnectedDataURL = function (opts) {
  20912. if (!env$1.canvasSupported) {
  20913. return;
  20914. }
  20915. var groupId = this.group;
  20916. var mathMin = Math.min;
  20917. var mathMax = Math.max;
  20918. var MAX_NUMBER = Infinity;
  20919. if (connectedGroups[groupId]) {
  20920. var left = MAX_NUMBER;
  20921. var top = MAX_NUMBER;
  20922. var right = -MAX_NUMBER;
  20923. var bottom = -MAX_NUMBER;
  20924. var canvasList = [];
  20925. var dpr = (opts && opts.pixelRatio) || 1;
  20926. each$1(instances, function (chart, id) {
  20927. if (chart.group === groupId) {
  20928. var canvas = chart.getRenderedCanvas(
  20929. clone(opts)
  20930. );
  20931. var boundingRect = chart.getDom().getBoundingClientRect();
  20932. left = mathMin(boundingRect.left, left);
  20933. top = mathMin(boundingRect.top, top);
  20934. right = mathMax(boundingRect.right, right);
  20935. bottom = mathMax(boundingRect.bottom, bottom);
  20936. canvasList.push({
  20937. dom: canvas,
  20938. left: boundingRect.left,
  20939. top: boundingRect.top
  20940. });
  20941. }
  20942. });
  20943. left *= dpr;
  20944. top *= dpr;
  20945. right *= dpr;
  20946. bottom *= dpr;
  20947. var width = right - left;
  20948. var height = bottom - top;
  20949. var targetCanvas = createCanvas();
  20950. targetCanvas.width = width;
  20951. targetCanvas.height = height;
  20952. var zr = init$1(targetCanvas);
  20953. each(canvasList, function (item) {
  20954. var img = new ZImage({
  20955. style: {
  20956. x: item.left * dpr - left,
  20957. y: item.top * dpr - top,
  20958. image: item.dom
  20959. }
  20960. });
  20961. zr.add(img);
  20962. });
  20963. zr.refreshImmediately();
  20964. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  20965. }
  20966. else {
  20967. return this.getDataURL(opts);
  20968. }
  20969. };
  20970. /**
  20971. * Convert from logical coordinate system to pixel coordinate system.
  20972. * See CoordinateSystem#convertToPixel.
  20973. * @param {string|Object} finder
  20974. * If string, e.g., 'geo', means {geoIndex: 0}.
  20975. * If Object, could contain some of these properties below:
  20976. * {
  20977. * seriesIndex / seriesId / seriesName,
  20978. * geoIndex / geoId, geoName,
  20979. * bmapIndex / bmapId / bmapName,
  20980. * xAxisIndex / xAxisId / xAxisName,
  20981. * yAxisIndex / yAxisId / yAxisName,
  20982. * gridIndex / gridId / gridName,
  20983. * ... (can be extended)
  20984. * }
  20985. * @param {Array|number} value
  20986. * @return {Array|number} result
  20987. */
  20988. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  20989. /**
  20990. * Convert from pixel coordinate system to logical coordinate system.
  20991. * See CoordinateSystem#convertFromPixel.
  20992. * @param {string|Object} finder
  20993. * If string, e.g., 'geo', means {geoIndex: 0}.
  20994. * If Object, could contain some of these properties below:
  20995. * {
  20996. * seriesIndex / seriesId / seriesName,
  20997. * geoIndex / geoId / geoName,
  20998. * bmapIndex / bmapId / bmapName,
  20999. * xAxisIndex / xAxisId / xAxisName,
  21000. * yAxisIndex / yAxisId / yAxisName
  21001. * gridIndex / gridId / gridName,
  21002. * ... (can be extended)
  21003. * }
  21004. * @param {Array|number} value
  21005. * @return {Array|number} result
  21006. */
  21007. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21008. function doConvertPixel(methodName, finder, value) {
  21009. var ecModel = this._model;
  21010. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21011. var result;
  21012. finder = parseFinder(ecModel, finder);
  21013. for (var i = 0; i < coordSysList.length; i++) {
  21014. var coordSys = coordSysList[i];
  21015. if (coordSys[methodName]
  21016. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21017. ) {
  21018. return result;
  21019. }
  21020. }
  21021. if (__DEV__) {
  21022. console.warn(
  21023. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21024. );
  21025. }
  21026. }
  21027. /**
  21028. * Is the specified coordinate systems or components contain the given pixel point.
  21029. * @param {string|Object} finder
  21030. * If string, e.g., 'geo', means {geoIndex: 0}.
  21031. * If Object, could contain some of these properties below:
  21032. * {
  21033. * seriesIndex / seriesId / seriesName,
  21034. * geoIndex / geoId / geoName,
  21035. * bmapIndex / bmapId / bmapName,
  21036. * xAxisIndex / xAxisId / xAxisName,
  21037. * yAxisIndex / yAxisId / yAxisName,
  21038. * gridIndex / gridId / gridName,
  21039. * ... (can be extended)
  21040. * }
  21041. * @param {Array|number} value
  21042. * @return {boolean} result
  21043. */
  21044. echartsProto.containPixel = function (finder, value) {
  21045. var ecModel = this._model;
  21046. var result;
  21047. finder = parseFinder(ecModel, finder);
  21048. each$1(finder, function (models, key) {
  21049. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21050. var coordSys = model.coordinateSystem;
  21051. if (coordSys && coordSys.containPoint) {
  21052. result |= !!coordSys.containPoint(value);
  21053. }
  21054. else if (key === 'seriesModels') {
  21055. var view = this._chartsMap[model.__viewId];
  21056. if (view && view.containPoint) {
  21057. result |= view.containPoint(value, model);
  21058. }
  21059. else {
  21060. if (__DEV__) {
  21061. console.warn(key + ': ' + (view
  21062. ? 'The found component do not support containPoint.'
  21063. : 'No view mapping to the found component.'
  21064. ));
  21065. }
  21066. }
  21067. }
  21068. else {
  21069. if (__DEV__) {
  21070. console.warn(key + ': containPoint is not supported');
  21071. }
  21072. }
  21073. }, this);
  21074. }, this);
  21075. return !!result;
  21076. };
  21077. /**
  21078. * Get visual from series or data.
  21079. * @param {string|Object} finder
  21080. * If string, e.g., 'series', means {seriesIndex: 0}.
  21081. * If Object, could contain some of these properties below:
  21082. * {
  21083. * seriesIndex / seriesId / seriesName,
  21084. * dataIndex / dataIndexInside
  21085. * }
  21086. * If dataIndex is not specified, series visual will be fetched,
  21087. * but not data item visual.
  21088. * If all of seriesIndex, seriesId, seriesName are not specified,
  21089. * visual will be fetched from first series.
  21090. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21091. */
  21092. echartsProto.getVisual = function (finder, visualType) {
  21093. var ecModel = this._model;
  21094. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21095. var seriesModel = finder.seriesModel;
  21096. if (__DEV__) {
  21097. if (!seriesModel) {
  21098. console.warn('There is no specified seires model');
  21099. }
  21100. }
  21101. var data = seriesModel.getData();
  21102. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21103. ? finder.dataIndexInside
  21104. : finder.hasOwnProperty('dataIndex')
  21105. ? data.indexOfRawIndex(finder.dataIndex)
  21106. : null;
  21107. return dataIndexInside != null
  21108. ? data.getItemVisual(dataIndexInside, visualType)
  21109. : data.getVisual(visualType);
  21110. };
  21111. /**
  21112. * Get view of corresponding component model
  21113. * @param {module:echarts/model/Component} componentModel
  21114. * @return {module:echarts/view/Component}
  21115. */
  21116. echartsProto.getViewOfComponentModel = function (componentModel) {
  21117. return this._componentsMap[componentModel.__viewId];
  21118. };
  21119. /**
  21120. * Get view of corresponding series model
  21121. * @param {module:echarts/model/Series} seriesModel
  21122. * @return {module:echarts/view/Chart}
  21123. */
  21124. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21125. return this._chartsMap[seriesModel.__viewId];
  21126. };
  21127. var updateMethods = {
  21128. prepareAndUpdate: function (payload) {
  21129. prepare(this);
  21130. updateMethods.update.call(this, payload);
  21131. },
  21132. /**
  21133. * @param {Object} payload
  21134. * @private
  21135. */
  21136. update: function (payload) {
  21137. // console.profile && console.profile('update');
  21138. var ecModel = this._model;
  21139. var api = this._api;
  21140. var zr = this._zr;
  21141. var coordSysMgr = this._coordSysMgr;
  21142. var scheduler = this._scheduler;
  21143. // update before setOption
  21144. if (!ecModel) {
  21145. return;
  21146. }
  21147. ecModel.restoreData(payload);
  21148. scheduler.performSeriesTasks(ecModel);
  21149. // TODO
  21150. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21151. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21152. // Create new coordinate system each update
  21153. // In LineView may save the old coordinate system and use it to get the orignal point
  21154. coordSysMgr.create(ecModel, api);
  21155. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);
  21156. // Current stream render is not supported in data process. So we can update
  21157. // stream modes after data processing, where the filtered data is used to
  21158. // deteming whether use progressive rendering.
  21159. updateStreamModes(this, ecModel);
  21160. stackSeriesData(ecModel);
  21161. coordSysMgr.update(ecModel, api);
  21162. clearColorPalette(ecModel);
  21163. scheduler.performVisualTasks(visualFuncs, ecModel, payload);
  21164. render(this, ecModel, api, payload);
  21165. // Set background
  21166. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21167. var painter = zr.painter;
  21168. // TODO all use clearColor ?
  21169. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  21170. zr.configLayer(0, {
  21171. clearColor: backgroundColor
  21172. });
  21173. }
  21174. else {
  21175. // In IE8
  21176. if (!env$1.canvasSupported) {
  21177. var colorArr = parse(backgroundColor);
  21178. backgroundColor = stringify(colorArr, 'rgb');
  21179. if (colorArr[3] === 0) {
  21180. backgroundColor = 'transparent';
  21181. }
  21182. }
  21183. if (backgroundColor.colorStops || backgroundColor.image) {
  21184. // Gradient background
  21185. // FIXME Fixed layer?
  21186. zr.configLayer(0, {
  21187. clearColor: backgroundColor
  21188. });
  21189. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  21190. this._dom.style.background = 'transparent';
  21191. }
  21192. else {
  21193. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  21194. zr.configLayer(0, {
  21195. clearColor: null
  21196. });
  21197. }
  21198. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  21199. this._dom.style.background = backgroundColor;
  21200. }
  21201. }
  21202. performPostUpdateFuncs(ecModel, api);
  21203. // console.profile && console.profileEnd('update');
  21204. },
  21205. /**
  21206. * @param {Object} payload
  21207. * @private
  21208. */
  21209. updateTransform: function (payload) {
  21210. var ecModel = this._model;
  21211. var ecIns = this;
  21212. var api = this._api;
  21213. // update before setOption
  21214. if (!ecModel) {
  21215. return;
  21216. }
  21217. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21218. var componentDirtyList = [];
  21219. ecModel.eachComponent(function (componentType, componentModel) {
  21220. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21221. if (componentView && componentView.__alive) {
  21222. if (componentView.updateTransform) {
  21223. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21224. result && result.update && componentDirtyList.push(componentView);
  21225. }
  21226. else {
  21227. componentDirtyList.push(componentView);
  21228. }
  21229. }
  21230. });
  21231. var seriesDirtyMap = createHashMap();
  21232. ecModel.eachSeries(function (seriesModel) {
  21233. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21234. if (chartView.updateTransform) {
  21235. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21236. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21237. }
  21238. else {
  21239. seriesDirtyMap.set(seriesModel.uid, 1);
  21240. }
  21241. });
  21242. clearColorPalette(ecModel);
  21243. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21244. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21245. this._scheduler.performVisualTasks(
  21246. visualFuncs, ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21247. );
  21248. // Currently, not call render of components. Geo render cost a lot.
  21249. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21250. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21251. performPostUpdateFuncs(ecModel, this._api);
  21252. },
  21253. /**
  21254. * @param {Object} payload
  21255. * @private
  21256. */
  21257. updateView: function (payload) {
  21258. var ecModel = this._model;
  21259. // update before setOption
  21260. if (!ecModel) {
  21261. return;
  21262. }
  21263. Chart.markUpdateMethod(payload, 'updateView');
  21264. clearColorPalette(ecModel);
  21265. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21266. this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21267. render(this, this._model, this._api, payload);
  21268. performPostUpdateFuncs(ecModel, this._api);
  21269. },
  21270. /**
  21271. * @param {Object} payload
  21272. * @private
  21273. */
  21274. updateVisual: function (payload) {
  21275. updateMethods.update.call(this, payload);
  21276. // var ecModel = this._model;
  21277. // // update before setOption
  21278. // if (!ecModel) {
  21279. // return;
  21280. // }
  21281. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21282. // clearColorPalette(ecModel);
  21283. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21284. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {visualType: 'visual', setDirty: true});
  21285. // render(this, this._model, this._api, payload);
  21286. // performPostUpdateFuncs(ecModel, this._api);
  21287. },
  21288. /**
  21289. * @param {Object} payload
  21290. * @private
  21291. */
  21292. updateLayout: function (payload) {
  21293. updateMethods.update.call(this, payload);
  21294. // var ecModel = this._model;
  21295. // // update before setOption
  21296. // if (!ecModel) {
  21297. // return;
  21298. // }
  21299. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21300. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21301. // // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21302. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21303. // render(this, this._model, this._api, payload);
  21304. // performPostUpdateFuncs(ecModel, this._api);
  21305. }
  21306. };
  21307. function prepare(ecIns) {
  21308. var ecModel = ecIns._model;
  21309. var scheduler = ecIns._scheduler;
  21310. scheduler.restorePipelines(ecModel);
  21311. scheduler.prepareStageTasks(dataProcessorFuncs);
  21312. scheduler.prepareStageTasks(visualFuncs);
  21313. prepareView(ecIns, 'component', ecModel, scheduler);
  21314. prepareView(ecIns, 'chart', ecModel, scheduler);
  21315. scheduler.plan();
  21316. }
  21317. /**
  21318. * @private
  21319. */
  21320. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21321. var ecModel = ecIns._model;
  21322. // broadcast
  21323. if (!mainType) {
  21324. // FIXME
  21325. // Chart will not be update directly here, except set dirty.
  21326. // But there is no such scenario now.
  21327. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21328. return;
  21329. }
  21330. var query = {};
  21331. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21332. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21333. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21334. var condition = {mainType: mainType, query: query};
  21335. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21336. // If dispatchAction before setOption, do nothing.
  21337. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21338. callView(ecIns[
  21339. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21340. ][model.__viewId]);
  21341. }, ecIns);
  21342. function callView(view) {
  21343. view && view.__alive && view[method] && view[method](
  21344. view.__model, ecModel, ecIns._api, payload
  21345. );
  21346. }
  21347. }
  21348. /**
  21349. * Resize the chart
  21350. * @param {Object} opts
  21351. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21352. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21353. * @param {boolean} [opts.silent=false]
  21354. */
  21355. echartsProto.resize = function (opts) {
  21356. if (__DEV__) {
  21357. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21358. }
  21359. this._zr.resize(opts);
  21360. var ecModel = this._model;
  21361. // Resize loading effect
  21362. this._loadingFX && this._loadingFX.resize();
  21363. if (!ecModel) {
  21364. return;
  21365. }
  21366. var optionChanged = ecModel.resetOption('media');
  21367. refresh(this, optionChanged, opts && opts.silent);
  21368. };
  21369. function refresh(ecIns, needPrepare, silent) {
  21370. ecIns[IN_MAIN_PROCESS] = true;
  21371. needPrepare && prepare(ecIns);
  21372. updateMethods.update.call(ecIns);
  21373. ecIns[IN_MAIN_PROCESS] = false;
  21374. flushPendingActions.call(ecIns, silent);
  21375. triggerUpdatedEvent.call(ecIns, silent);
  21376. }
  21377. function updateStreamModes(ecIns, ecModel) {
  21378. var chartsMap = ecIns._chartsMap;
  21379. var scheduler = ecIns._scheduler;
  21380. ecModel.eachSeries(function (seriesModel) {
  21381. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21382. });
  21383. }
  21384. /**
  21385. * Show loading effect
  21386. * @param {string} [name='default']
  21387. * @param {Object} [cfg]
  21388. */
  21389. echartsProto.showLoading = function (name, cfg) {
  21390. if (isObject(name)) {
  21391. cfg = name;
  21392. name = '';
  21393. }
  21394. name = name || 'default';
  21395. this.hideLoading();
  21396. if (!loadingEffects[name]) {
  21397. if (__DEV__) {
  21398. console.warn('Loading effects ' + name + ' not exists.');
  21399. }
  21400. return;
  21401. }
  21402. var el = loadingEffects[name](this._api, cfg);
  21403. var zr = this._zr;
  21404. this._loadingFX = el;
  21405. zr.add(el);
  21406. };
  21407. /**
  21408. * Hide loading effect
  21409. */
  21410. echartsProto.hideLoading = function () {
  21411. this._loadingFX && this._zr.remove(this._loadingFX);
  21412. this._loadingFX = null;
  21413. };
  21414. /**
  21415. * @param {Object} eventObj
  21416. * @return {Object}
  21417. */
  21418. echartsProto.makeActionFromEvent = function (eventObj) {
  21419. var payload = extend({}, eventObj);
  21420. payload.type = eventActionMap[eventObj.type];
  21421. return payload;
  21422. };
  21423. /**
  21424. * @pubilc
  21425. * @param {Object} payload
  21426. * @param {string} [payload.type] Action type
  21427. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21428. * @param {boolean} [opt.silent=false] Whether trigger events.
  21429. * @param {boolean} [opt.flush=undefined]
  21430. * true: Flush immediately, and then pixel in canvas can be fetched
  21431. * immediately. Caution: it might affect performance.
  21432. * false: Not not flush.
  21433. * undefined: Auto decide whether perform flush.
  21434. */
  21435. echartsProto.dispatchAction = function (payload, opt) {
  21436. if (!isObject(opt)) {
  21437. opt = {silent: !!opt};
  21438. }
  21439. if (!actions[payload.type]) {
  21440. return;
  21441. }
  21442. // Avoid dispatch action before setOption. Especially in `connect`.
  21443. if (!this._model) {
  21444. return;
  21445. }
  21446. // May dispatchAction in rendering procedure
  21447. if (this[IN_MAIN_PROCESS]) {
  21448. this._pendingActions.push(payload);
  21449. return;
  21450. }
  21451. doDispatchAction.call(this, payload, opt.silent);
  21452. if (opt.flush) {
  21453. this._zr.flush(true);
  21454. }
  21455. else if (opt.flush !== false && env$1.browser.weChat) {
  21456. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21457. // hang when sliding page (on touch event), which cause that zr does not
  21458. // refresh util user interaction finished, which is not expected.
  21459. // But `dispatchAction` may be called too frequently when pan on touch
  21460. // screen, which impacts performance if do not throttle them.
  21461. this._throttledZrFlush();
  21462. }
  21463. flushPendingActions.call(this, opt.silent);
  21464. triggerUpdatedEvent.call(this, opt.silent);
  21465. };
  21466. function doDispatchAction(payload, silent) {
  21467. var payloadType = payload.type;
  21468. var escapeConnect = payload.escapeConnect;
  21469. var actionWrap = actions[payloadType];
  21470. var actionInfo = actionWrap.actionInfo;
  21471. var cptType = (actionInfo.update || 'update').split(':');
  21472. var updateMethod = cptType.pop();
  21473. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21474. this[IN_MAIN_PROCESS] = true;
  21475. var payloads = [payload];
  21476. var batched = false;
  21477. // Batch action
  21478. if (payload.batch) {
  21479. batched = true;
  21480. payloads = map(payload.batch, function (item) {
  21481. item = defaults(extend({}, item), payload);
  21482. item.batch = null;
  21483. return item;
  21484. });
  21485. }
  21486. var eventObjBatch = [];
  21487. var eventObj;
  21488. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21489. each(payloads, function (batchItem) {
  21490. // Action can specify the event by return it.
  21491. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21492. // Emit event outside
  21493. eventObj = eventObj || extend({}, batchItem);
  21494. // Convert type to eventType
  21495. eventObj.type = actionInfo.event || eventObj.type;
  21496. eventObjBatch.push(eventObj);
  21497. // light update does not perform data process, layout and visual.
  21498. if (isHighDown) {
  21499. // method, payload, mainType, subType
  21500. updateDirectly(this, updateMethod, batchItem, 'series');
  21501. }
  21502. else if (cptType) {
  21503. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21504. }
  21505. }, this);
  21506. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21507. // Still dirty
  21508. if (this[OPTION_UPDATED]) {
  21509. // FIXME Pass payload ?
  21510. prepare(this);
  21511. updateMethods.update.call(this, payload);
  21512. this[OPTION_UPDATED] = false;
  21513. }
  21514. else {
  21515. updateMethods[updateMethod].call(this, payload);
  21516. }
  21517. }
  21518. // Follow the rule of action batch
  21519. if (batched) {
  21520. eventObj = {
  21521. type: actionInfo.event || payloadType,
  21522. escapeConnect: escapeConnect,
  21523. batch: eventObjBatch
  21524. };
  21525. }
  21526. else {
  21527. eventObj = eventObjBatch[0];
  21528. }
  21529. this[IN_MAIN_PROCESS] = false;
  21530. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21531. }
  21532. function flushPendingActions(silent) {
  21533. var pendingActions = this._pendingActions;
  21534. while (pendingActions.length) {
  21535. var payload = pendingActions.shift();
  21536. doDispatchAction.call(this, payload, silent);
  21537. }
  21538. }
  21539. function triggerUpdatedEvent(silent) {
  21540. !silent && this.trigger('updated');
  21541. }
  21542. /**
  21543. * @param {Object} params
  21544. * @param {number} params.seriesIndex
  21545. * @param {Array|TypedArray} params.data
  21546. */
  21547. echartsProto.appendData = function (params) {
  21548. var seriesIndex = params.seriesIndex;
  21549. var ecModel = this.getModel();
  21550. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21551. if (__DEV__) {
  21552. assert(params.data && seriesModel);
  21553. }
  21554. seriesModel.appendData(params);
  21555. this._scheduler.unfinished = true;
  21556. };
  21557. /**
  21558. * Register event
  21559. * @method
  21560. */
  21561. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21562. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21563. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21564. /**
  21565. * Prepare view instances of charts and components
  21566. * @param {module:echarts/model/Global} ecModel
  21567. * @private
  21568. */
  21569. function prepareView(ecIns, type, ecModel, scheduler) {
  21570. var isComponent = type === 'component';
  21571. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21572. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21573. var zr = ecIns._zr;
  21574. var api = ecIns._api;
  21575. for (var i = 0; i < viewList.length; i++) {
  21576. viewList[i].__alive = false;
  21577. }
  21578. isComponent
  21579. ? ecModel.eachComponent(function (componentType, model) {
  21580. componentType !== 'series' && doPrepare(model);
  21581. })
  21582. : ecModel.eachSeries(doPrepare);
  21583. function doPrepare(model) {
  21584. // Consider: id same and type changed.
  21585. var viewId = '_ec_' + model.id + '_' + model.type;
  21586. var view = viewMap[viewId];
  21587. if (!view) {
  21588. var classType = parseClassType(model.type);
  21589. var Clazz = isComponent
  21590. ? Component$1.getClass(classType.main, classType.sub)
  21591. : Chart.getClass(classType.sub);
  21592. if (__DEV__) {
  21593. assert(Clazz, classType.sub + ' does not exist.');
  21594. }
  21595. view = new Clazz();
  21596. view.init(ecModel, api);
  21597. viewMap[viewId] = view;
  21598. viewList.push(view);
  21599. zr.add(view.group);
  21600. }
  21601. model.__viewId = view.__id = viewId;
  21602. view.__alive = true;
  21603. view.__model = model;
  21604. view.group.__ecComponentInfo = {
  21605. mainType: model.mainType,
  21606. index: model.componentIndex
  21607. };
  21608. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21609. }
  21610. for (var i = 0; i < viewList.length;) {
  21611. var view = viewList[i];
  21612. if (!view.__alive) {
  21613. !isComponent && view.renderTask.dispose();
  21614. zr.remove(view.group);
  21615. view.dispose(ecModel, api);
  21616. viewList.splice(i, 1);
  21617. delete viewMap[view.__id];
  21618. view.__id = view.group.__ecComponentInfo = null;
  21619. }
  21620. else {
  21621. i++;
  21622. }
  21623. }
  21624. }
  21625. /**
  21626. * @private
  21627. */
  21628. function stackSeriesData(ecModel) {
  21629. var stackedDataMap = {};
  21630. ecModel.eachSeries(function (series) {
  21631. var stack = series.get('stack');
  21632. var data = series.getData();
  21633. if (stack && data.type === 'list') {
  21634. var previousStack = stackedDataMap[stack];
  21635. // Avoid conflict with Object.prototype
  21636. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  21637. data.stackedOn = previousStack;
  21638. }
  21639. stackedDataMap[stack] = data;
  21640. }
  21641. });
  21642. }
  21643. // /**
  21644. // * Encode visual infomation from data after data processing
  21645. // *
  21646. // * @param {module:echarts/model/Global} ecModel
  21647. // * @param {object} layout
  21648. // * @param {boolean} [layoutFilter] `true`: only layout,
  21649. // * `false`: only not layout,
  21650. // * `null`/`undefined`: all.
  21651. // * @param {string} taskBaseTag
  21652. // * @private
  21653. // */
  21654. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21655. // each(visualFuncs, function (visual, index) {
  21656. // var isLayout = visual.isLayout;
  21657. // if (layoutFilter == null
  21658. // || (layoutFilter === false && !isLayout)
  21659. // || (layoutFilter === true && isLayout)
  21660. // ) {
  21661. // visual.func(ecModel, api, payload);
  21662. // }
  21663. // });
  21664. // }
  21665. function clearColorPalette(ecModel) {
  21666. ecModel.clearColorPalette();
  21667. ecModel.eachSeries(function (seriesModel) {
  21668. seriesModel.clearColorPalette();
  21669. });
  21670. }
  21671. function render(ecIns, ecModel, api, payload) {
  21672. renderComponents(ecIns, ecModel, api, payload);
  21673. each(ecIns._chartsViews, function (chart) {
  21674. chart.__alive = false;
  21675. });
  21676. renderSeries(ecIns, ecModel, api, payload);
  21677. // Remove groups of unrendered charts
  21678. each(ecIns._chartsViews, function (chart) {
  21679. if (!chart.__alive) {
  21680. chart.remove(ecModel, api);
  21681. }
  21682. });
  21683. }
  21684. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  21685. each(dirtyList || ecIns._componentsViews, function (componentView) {
  21686. var componentModel = componentView.__model;
  21687. componentView.render(componentModel, ecModel, api, payload);
  21688. updateZ(componentModel, componentView);
  21689. });
  21690. }
  21691. /**
  21692. * Render each chart and component
  21693. * @private
  21694. */
  21695. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  21696. // Render all charts
  21697. var scheduler = ecIns._scheduler;
  21698. var unfinished;
  21699. ecModel.eachSeries(function (seriesModel) {
  21700. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21701. chartView.__alive = true;
  21702. var renderTask = chartView.renderTask;
  21703. scheduler.updatePayload(renderTask, payload);
  21704. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  21705. renderTask.dirty();
  21706. }
  21707. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  21708. chartView.group.silent = !!seriesModel.get('silent');
  21709. updateZ(seriesModel, chartView);
  21710. updateBlend(seriesModel, chartView);
  21711. });
  21712. scheduler.unfinished |= unfinished;
  21713. // If use hover layer
  21714. updateHoverLayerStatus(ecIns._zr, ecModel);
  21715. // Add aria
  21716. aria(ecIns._zr.dom, ecModel);
  21717. }
  21718. function performPostUpdateFuncs(ecModel, api) {
  21719. each(postUpdateFuncs, function (func) {
  21720. func(ecModel, api);
  21721. });
  21722. }
  21723. var MOUSE_EVENT_NAMES = [
  21724. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  21725. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  21726. ];
  21727. /**
  21728. * @private
  21729. */
  21730. echartsProto._initEvents = function () {
  21731. each(MOUSE_EVENT_NAMES, function (eveName) {
  21732. this._zr.on(eveName, function (e) {
  21733. var ecModel = this.getModel();
  21734. var el = e.target;
  21735. var params;
  21736. // no e.target when 'globalout'.
  21737. if (eveName === 'globalout') {
  21738. params = {};
  21739. }
  21740. else if (el && el.dataIndex != null) {
  21741. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  21742. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  21743. }
  21744. // If element has custom eventData of components
  21745. else if (el && el.eventData) {
  21746. params = extend({}, el.eventData);
  21747. }
  21748. if (params) {
  21749. params.event = e;
  21750. params.type = eveName;
  21751. this.trigger(eveName, params);
  21752. }
  21753. }, this);
  21754. }, this);
  21755. each(eventActionMap, function (actionType, eventType) {
  21756. this._messageCenter.on(eventType, function (event) {
  21757. this.trigger(eventType, event);
  21758. }, this);
  21759. }, this);
  21760. };
  21761. /**
  21762. * @return {boolean}
  21763. */
  21764. echartsProto.isDisposed = function () {
  21765. return this._disposed;
  21766. };
  21767. /**
  21768. * Clear
  21769. */
  21770. echartsProto.clear = function () {
  21771. this.setOption({ series: [] }, true);
  21772. };
  21773. /**
  21774. * Dispose instance
  21775. */
  21776. echartsProto.dispose = function () {
  21777. if (this._disposed) {
  21778. if (__DEV__) {
  21779. console.warn('Instance ' + this.id + ' has been disposed');
  21780. }
  21781. return;
  21782. }
  21783. this._disposed = true;
  21784. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  21785. var api = this._api;
  21786. var ecModel = this._model;
  21787. each(this._componentsViews, function (component) {
  21788. component.dispose(ecModel, api);
  21789. });
  21790. each(this._chartsViews, function (chart) {
  21791. chart.dispose(ecModel, api);
  21792. });
  21793. // Dispose after all views disposed
  21794. this._zr.dispose();
  21795. delete instances[this.id];
  21796. };
  21797. mixin(ECharts, Eventful);
  21798. function updateHoverLayerStatus(zr, ecModel) {
  21799. var storage = zr.storage;
  21800. var elCount = 0;
  21801. storage.traverse(function (el) {
  21802. if (!el.isGroup) {
  21803. elCount++;
  21804. }
  21805. });
  21806. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  21807. storage.traverse(function (el) {
  21808. if (!el.isGroup) {
  21809. // Don't switch back.
  21810. el.useHoverLayer = true;
  21811. }
  21812. });
  21813. }
  21814. }
  21815. /**
  21816. * Update chart progressive and blend.
  21817. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21818. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21819. */
  21820. function updateBlend(seriesModel, chartView) {
  21821. var blendMode = seriesModel.get('blendMode') || null;
  21822. if (__DEV__) {
  21823. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  21824. console.warn('Only canvas support blendMode');
  21825. }
  21826. }
  21827. chartView.group.traverse(function (el) {
  21828. // FIXME marker and other components
  21829. if (!el.isGroup) {
  21830. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  21831. if (el.style.blend !== blendMode) {
  21832. el.setStyle('blend', blendMode);
  21833. }
  21834. }
  21835. if (el.eachPendingDisplayable) {
  21836. el.eachPendingDisplayable(function (displayable) {
  21837. displayable.setStyle('blend', blendMode);
  21838. });
  21839. }
  21840. });
  21841. }
  21842. /**
  21843. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21844. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21845. */
  21846. function updateZ(model, view) {
  21847. var z = model.get('z');
  21848. var zlevel = model.get('zlevel');
  21849. // Set z and zlevel
  21850. view.group.traverse(function (el) {
  21851. if (el.type !== 'group') {
  21852. z != null && (el.z = z);
  21853. zlevel != null && (el.zlevel = zlevel);
  21854. }
  21855. });
  21856. }
  21857. function createExtensionAPI(ecInstance) {
  21858. var coordSysMgr = ecInstance._coordSysMgr;
  21859. return extend(new ExtensionAPI(ecInstance), {
  21860. // Inject methods
  21861. getCoordinateSystems: bind(
  21862. coordSysMgr.getCoordinateSystems, coordSysMgr
  21863. ),
  21864. getComponentByElement: function (el) {
  21865. while (el) {
  21866. var modelInfo = el.__ecComponentInfo;
  21867. if (modelInfo != null) {
  21868. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  21869. }
  21870. el = el.parent;
  21871. }
  21872. }
  21873. });
  21874. }
  21875. /**
  21876. * @type {Object} key: actionType.
  21877. * @inner
  21878. */
  21879. var actions = {};
  21880. /**
  21881. * Map eventType to actionType
  21882. * @type {Object}
  21883. */
  21884. var eventActionMap = {};
  21885. /**
  21886. * Data processor functions of each stage
  21887. * @type {Array.<Object.<string, Function>>}
  21888. * @inner
  21889. */
  21890. var dataProcessorFuncs = [];
  21891. /**
  21892. * @type {Array.<Function>}
  21893. * @inner
  21894. */
  21895. var optionPreprocessorFuncs = [];
  21896. /**
  21897. * @type {Array.<Function>}
  21898. * @inner
  21899. */
  21900. var postUpdateFuncs = [];
  21901. /**
  21902. * Visual encoding functions of each stage
  21903. * @type {Array.<Object.<string, Function>>}
  21904. */
  21905. var visualFuncs = [];
  21906. /**
  21907. * Theme storage
  21908. * @type {Object.<key, Object>}
  21909. */
  21910. var themeStorage = {};
  21911. /**
  21912. * Loading effects
  21913. */
  21914. var loadingEffects = {};
  21915. var instances = {};
  21916. var connectedGroups = {};
  21917. var idBase = new Date() - 0;
  21918. var groupIdBase = new Date() - 0;
  21919. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  21920. var mapDataStores = {};
  21921. function enableConnect(chart) {
  21922. var STATUS_PENDING = 0;
  21923. var STATUS_UPDATING = 1;
  21924. var STATUS_UPDATED = 2;
  21925. var STATUS_KEY = '__connectUpdateStatus';
  21926. function updateConnectedChartsStatus(charts, status) {
  21927. for (var i = 0; i < charts.length; i++) {
  21928. var otherChart = charts[i];
  21929. otherChart[STATUS_KEY] = status;
  21930. }
  21931. }
  21932. each(eventActionMap, function (actionType, eventType) {
  21933. chart._messageCenter.on(eventType, function (event) {
  21934. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  21935. if (event && event.escapeConnect) {
  21936. return;
  21937. }
  21938. var action = chart.makeActionFromEvent(event);
  21939. var otherCharts = [];
  21940. each(instances, function (otherChart) {
  21941. if (otherChart !== chart && otherChart.group === chart.group) {
  21942. otherCharts.push(otherChart);
  21943. }
  21944. });
  21945. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  21946. each(otherCharts, function (otherChart) {
  21947. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  21948. otherChart.dispatchAction(action);
  21949. }
  21950. });
  21951. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  21952. }
  21953. });
  21954. });
  21955. }
  21956. /**
  21957. * @param {HTMLElement} dom
  21958. * @param {Object} [theme]
  21959. * @param {Object} opts
  21960. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  21961. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  21962. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  21963. * Can be 'auto' (the same as null/undefined)
  21964. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  21965. * Can be 'auto' (the same as null/undefined)
  21966. */
  21967. function init(dom, theme$$1, opts) {
  21968. if (__DEV__) {
  21969. // Check version
  21970. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  21971. throw new Error(
  21972. 'zrender/src ' + version$1
  21973. + ' is too old for ECharts ' + version
  21974. + '. Current version need ZRender '
  21975. + dependencies.zrender + '+'
  21976. );
  21977. }
  21978. if (!dom) {
  21979. throw new Error('Initialize failed: invalid dom.');
  21980. }
  21981. }
  21982. var existInstance = getInstanceByDom(dom);
  21983. if (existInstance) {
  21984. if (__DEV__) {
  21985. console.warn('There is a chart instance already initialized on the dom.');
  21986. }
  21987. return existInstance;
  21988. }
  21989. if (__DEV__) {
  21990. if (isDom(dom)
  21991. && dom.nodeName.toUpperCase() !== 'CANVAS'
  21992. && (
  21993. (!dom.clientWidth && (!opts || opts.width == null))
  21994. || (!dom.clientHeight && (!opts || opts.height == null))
  21995. )
  21996. ) {
  21997. console.warn('Can\'t get dom width or height');
  21998. }
  21999. }
  22000. var chart = new ECharts(dom, theme$$1, opts);
  22001. chart.id = 'ec_' + idBase++;
  22002. instances[chart.id] = chart;
  22003. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22004. enableConnect(chart);
  22005. return chart;
  22006. }
  22007. /**
  22008. * @return {string|Array.<module:echarts~ECharts>} groupId
  22009. */
  22010. function connect(groupId) {
  22011. // Is array of charts
  22012. if (isArray(groupId)) {
  22013. var charts = groupId;
  22014. groupId = null;
  22015. // If any chart has group
  22016. each(charts, function (chart) {
  22017. if (chart.group != null) {
  22018. groupId = chart.group;
  22019. }
  22020. });
  22021. groupId = groupId || ('g_' + groupIdBase++);
  22022. each(charts, function (chart) {
  22023. chart.group = groupId;
  22024. });
  22025. }
  22026. connectedGroups[groupId] = true;
  22027. return groupId;
  22028. }
  22029. /**
  22030. * @DEPRECATED
  22031. * @return {string} groupId
  22032. */
  22033. function disConnect(groupId) {
  22034. connectedGroups[groupId] = false;
  22035. }
  22036. /**
  22037. * @return {string} groupId
  22038. */
  22039. var disconnect = disConnect;
  22040. /**
  22041. * Dispose a chart instance
  22042. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22043. */
  22044. function dispose(chart) {
  22045. if (typeof chart === 'string') {
  22046. chart = instances[chart];
  22047. }
  22048. else if (!(chart instanceof ECharts)){
  22049. // Try to treat as dom
  22050. chart = getInstanceByDom(chart);
  22051. }
  22052. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22053. chart.dispose();
  22054. }
  22055. }
  22056. /**
  22057. * @param {HTMLElement} dom
  22058. * @return {echarts~ECharts}
  22059. */
  22060. function getInstanceByDom(dom) {
  22061. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22062. }
  22063. /**
  22064. * @param {string} key
  22065. * @return {echarts~ECharts}
  22066. */
  22067. function getInstanceById(key) {
  22068. return instances[key];
  22069. }
  22070. /**
  22071. * Register theme
  22072. */
  22073. function registerTheme(name, theme$$1) {
  22074. themeStorage[name] = theme$$1;
  22075. }
  22076. /**
  22077. * Register option preprocessor
  22078. * @param {Function} preprocessorFunc
  22079. */
  22080. function registerPreprocessor(preprocessorFunc) {
  22081. optionPreprocessorFuncs.push(preprocessorFunc);
  22082. }
  22083. /**
  22084. * @param {number} [priority=1000]
  22085. * @param {Object|Function} processor
  22086. */
  22087. function registerProcessor(priority, processor) {
  22088. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22089. }
  22090. /**
  22091. * Register postUpdater
  22092. * @param {Function} postUpdateFunc
  22093. */
  22094. function registerPostUpdate(postUpdateFunc) {
  22095. postUpdateFuncs.push(postUpdateFunc);
  22096. }
  22097. /**
  22098. * Usage:
  22099. * registerAction('someAction', 'someEvent', function () { ... });
  22100. * registerAction('someAction', function () { ... });
  22101. * registerAction(
  22102. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22103. * function () { ... }
  22104. * );
  22105. *
  22106. * @param {(string|Object)} actionInfo
  22107. * @param {string} actionInfo.type
  22108. * @param {string} [actionInfo.event]
  22109. * @param {string} [actionInfo.update]
  22110. * @param {string} [eventName]
  22111. * @param {Function} action
  22112. */
  22113. function registerAction(actionInfo, eventName, action) {
  22114. if (typeof eventName === 'function') {
  22115. action = eventName;
  22116. eventName = '';
  22117. }
  22118. var actionType = isObject(actionInfo)
  22119. ? actionInfo.type
  22120. : ([actionInfo, actionInfo = {
  22121. event: eventName
  22122. }][0]);
  22123. // Event name is all lowercase
  22124. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22125. eventName = actionInfo.event;
  22126. // Validate action type and event name.
  22127. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22128. if (!actions[actionType]) {
  22129. actions[actionType] = {action: action, actionInfo: actionInfo};
  22130. }
  22131. eventActionMap[eventName] = actionType;
  22132. }
  22133. /**
  22134. * @param {string} type
  22135. * @param {*} CoordinateSystem
  22136. */
  22137. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22138. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22139. }
  22140. /**
  22141. * Get dimensions of specified coordinate system.
  22142. * @param {string} type
  22143. * @return {Array.<string|Object>}
  22144. */
  22145. function getCoordinateSystemDimensions(type) {
  22146. var coordSysCreator = CoordinateSystemManager.get(type);
  22147. if (coordSysCreator) {
  22148. return coordSysCreator.getDimensionsInfo
  22149. ? coordSysCreator.getDimensionsInfo()
  22150. : coordSysCreator.dimensions.slice();
  22151. }
  22152. }
  22153. /**
  22154. * Layout is a special stage of visual encoding
  22155. * Most visual encoding like color are common for different chart
  22156. * But each chart has it's own layout algorithm
  22157. *
  22158. * @param {number} [priority=1000]
  22159. * @param {Function} layoutTask
  22160. */
  22161. function registerLayout(priority, layoutTask) {
  22162. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22163. }
  22164. /**
  22165. * @param {number} [priority=3000]
  22166. * @param {module:echarts/stream/Task} visualTask
  22167. */
  22168. function registerVisual(priority, visualTask) {
  22169. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22170. }
  22171. /**
  22172. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22173. */
  22174. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22175. if (isFunction(priority) || isObject(priority)) {
  22176. fn = priority;
  22177. priority = defaultPriority;
  22178. }
  22179. if (__DEV__) {
  22180. if (isNaN(priority) || priority == null) {
  22181. throw new Error('Illegal priority');
  22182. }
  22183. // Check duplicate
  22184. each(targetList, function (wrap) {
  22185. assert(wrap.__raw !== fn);
  22186. });
  22187. }
  22188. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22189. stageHandler.__prio = priority;
  22190. stageHandler.__raw = fn;
  22191. targetList.push(stageHandler);
  22192. return stageHandler;
  22193. }
  22194. /**
  22195. * @param {string} name
  22196. */
  22197. function registerLoading(name, loadingFx) {
  22198. loadingEffects[name] = loadingFx;
  22199. }
  22200. /**
  22201. * @param {Object} opts
  22202. * @param {string} [superClass]
  22203. */
  22204. function extendComponentModel(opts/*, superClass*/) {
  22205. // var Clazz = ComponentModel;
  22206. // if (superClass) {
  22207. // var classType = parseClassType(superClass);
  22208. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22209. // }
  22210. return ComponentModel.extend(opts);
  22211. }
  22212. /**
  22213. * @param {Object} opts
  22214. * @param {string} [superClass]
  22215. */
  22216. function extendComponentView(opts/*, superClass*/) {
  22217. // var Clazz = ComponentView;
  22218. // if (superClass) {
  22219. // var classType = parseClassType(superClass);
  22220. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22221. // }
  22222. return Component$1.extend(opts);
  22223. }
  22224. /**
  22225. * @param {Object} opts
  22226. * @param {string} [superClass]
  22227. */
  22228. function extendSeriesModel(opts/*, superClass*/) {
  22229. // var Clazz = SeriesModel;
  22230. // if (superClass) {
  22231. // superClass = 'series.' + superClass.replace('series.', '');
  22232. // var classType = parseClassType(superClass);
  22233. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22234. // }
  22235. return SeriesModel.extend(opts);
  22236. }
  22237. /**
  22238. * @param {Object} opts
  22239. * @param {string} [superClass]
  22240. */
  22241. function extendChartView(opts/*, superClass*/) {
  22242. // var Clazz = ChartView;
  22243. // if (superClass) {
  22244. // superClass = superClass.replace('series.', '');
  22245. // var classType = parseClassType(superClass);
  22246. // Clazz = ChartView.getClass(classType.main, true);
  22247. // }
  22248. return Chart.extend(opts);
  22249. }
  22250. /**
  22251. * ZRender need a canvas context to do measureText.
  22252. * But in node environment canvas may be created by node-canvas.
  22253. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22254. *
  22255. * Be careful of using it in the browser.
  22256. *
  22257. * @param {Function} creator
  22258. * @example
  22259. * var Canvas = require('canvas');
  22260. * var echarts = require('echarts');
  22261. * echarts.setCanvasCreator(function () {
  22262. * // Small size is enough.
  22263. * return new Canvas(32, 32);
  22264. * });
  22265. */
  22266. function setCanvasCreator(creator) {
  22267. $override('createCanvas', creator);
  22268. }
  22269. /**
  22270. * @param {string} mapName
  22271. * @param {Object|string} geoJson
  22272. * @param {Object} [specialAreas]
  22273. *
  22274. * @example
  22275. * $.get('USA.json', function (geoJson) {
  22276. * echarts.registerMap('USA', geoJson);
  22277. * // Or
  22278. * echarts.registerMap('USA', {
  22279. * geoJson: geoJson,
  22280. * specialAreas: {}
  22281. * })
  22282. * });
  22283. */
  22284. function registerMap(mapName, geoJson, specialAreas) {
  22285. if (geoJson.geoJson && !geoJson.features) {
  22286. specialAreas = geoJson.specialAreas;
  22287. geoJson = geoJson.geoJson;
  22288. }
  22289. if (typeof geoJson === 'string') {
  22290. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22291. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22292. }
  22293. mapDataStores[mapName] = {
  22294. geoJson: geoJson,
  22295. specialAreas: specialAreas
  22296. };
  22297. }
  22298. /**
  22299. * @param {string} mapName
  22300. * @return {Object}
  22301. */
  22302. function getMap(mapName) {
  22303. return mapDataStores[mapName];
  22304. }
  22305. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22306. registerPreprocessor(backwardCompat);
  22307. registerLoading('default', loadingDefault);
  22308. // Default actions
  22309. registerAction({
  22310. type: 'highlight',
  22311. event: 'highlight',
  22312. update: 'highlight'
  22313. }, noop);
  22314. registerAction({
  22315. type: 'downplay',
  22316. event: 'downplay',
  22317. update: 'downplay'
  22318. }, noop);
  22319. // Default theme
  22320. registerTheme('light', lightTheme);
  22321. registerTheme('dark', theme);
  22322. // For backward compatibility, where the namespace `dataTool` will
  22323. // be mounted on `echarts` is the extension `dataTool` is imported.
  22324. var dataTool = {};
  22325. function defaultKeyGetter(item) {
  22326. return item;
  22327. }
  22328. /**
  22329. * @param {Array} oldArr
  22330. * @param {Array} newArr
  22331. * @param {Function} oldKeyGetter
  22332. * @param {Function} newKeyGetter
  22333. * @param {Object} [context] Can be visited by this.context in callback.
  22334. */
  22335. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22336. this._old = oldArr;
  22337. this._new = newArr;
  22338. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22339. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22340. this.context = context;
  22341. }
  22342. DataDiffer.prototype = {
  22343. constructor: DataDiffer,
  22344. /**
  22345. * Callback function when add a data
  22346. */
  22347. add: function (func) {
  22348. this._add = func;
  22349. return this;
  22350. },
  22351. /**
  22352. * Callback function when update a data
  22353. */
  22354. update: function (func) {
  22355. this._update = func;
  22356. return this;
  22357. },
  22358. /**
  22359. * Callback function when remove a data
  22360. */
  22361. remove: function (func) {
  22362. this._remove = func;
  22363. return this;
  22364. },
  22365. execute: function () {
  22366. var oldArr = this._old;
  22367. var newArr = this._new;
  22368. var oldDataIndexMap = {};
  22369. var newDataIndexMap = {};
  22370. var oldDataKeyArr = [];
  22371. var newDataKeyArr = [];
  22372. var i;
  22373. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22374. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22375. // Travel by inverted order to make sure order consistency
  22376. // when duplicate keys exists (consider newDataIndex.pop() below).
  22377. // For performance consideration, these code below do not look neat.
  22378. for (i = 0; i < oldArr.length; i++) {
  22379. var key = oldDataKeyArr[i];
  22380. var idx = newDataIndexMap[key];
  22381. // idx can never be empty array here. see 'set null' logic below.
  22382. if (idx != null) {
  22383. // Consider there is duplicate key (for example, use dataItem.name as key).
  22384. // We should make sure every item in newArr and oldArr can be visited.
  22385. var len = idx.length;
  22386. if (len) {
  22387. len === 1 && (newDataIndexMap[key] = null);
  22388. idx = idx.unshift();
  22389. }
  22390. else {
  22391. newDataIndexMap[key] = null;
  22392. }
  22393. this._update && this._update(idx, i);
  22394. }
  22395. else {
  22396. this._remove && this._remove(i);
  22397. }
  22398. }
  22399. for (var i = 0; i < newDataKeyArr.length; i++) {
  22400. var key = newDataKeyArr[i];
  22401. if (newDataIndexMap.hasOwnProperty(key)) {
  22402. var idx = newDataIndexMap[key];
  22403. if (idx == null) {
  22404. continue;
  22405. }
  22406. // idx can never be empty array here. see 'set null' logic above.
  22407. if (!idx.length) {
  22408. this._add && this._add(idx);
  22409. }
  22410. else {
  22411. for (var j = 0, len = idx.length; j < len; j++) {
  22412. this._add && this._add(idx[j]);
  22413. }
  22414. }
  22415. }
  22416. }
  22417. }
  22418. };
  22419. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22420. for (var i = 0; i < arr.length; i++) {
  22421. // Add prefix to avoid conflict with Object.prototype.
  22422. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22423. var existence = map[key];
  22424. if (existence == null) {
  22425. keyArr.push(key);
  22426. map[key] = i;
  22427. }
  22428. else {
  22429. if (!existence.length) {
  22430. map[key] = existence = [existence];
  22431. }
  22432. existence.push(i);
  22433. }
  22434. }
  22435. }
  22436. var OTHER_DIMENSIONS = createHashMap([
  22437. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22438. ]);
  22439. function summarizeDimensions(data) {
  22440. var summary = {};
  22441. var encode = summary.encode = {};
  22442. var coordDimMap = summary.coordDimMap = createHashMap();
  22443. var defaultedLabel = [];
  22444. each$1(data.dimensions, function (dimName) {
  22445. var dimItem = data.getDimensionInfo(dimName);
  22446. var coordDim = dimItem.coordDim;
  22447. if (coordDim) {
  22448. if (__DEV__) {
  22449. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22450. }
  22451. var coordDimArr = encode[coordDim];
  22452. if (!encode.hasOwnProperty(coordDim)) {
  22453. coordDimArr = encode[coordDim] = [];
  22454. }
  22455. coordDimArr[dimItem.coordDimIndex] = dimName;
  22456. if (dimItem.isSysCoord && mayLabelDimType(dimItem.type)) {
  22457. // Use the last coord dim (and label friendly) as default label,
  22458. // because both show x, y on label is not look good, and usually
  22459. // y axis is more focusd conventionally.
  22460. defaultedLabel[0] = dimName;
  22461. }
  22462. coordDimMap.set(coordDim, 1);
  22463. }
  22464. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22465. var otherDimArr = encode[otherDim];
  22466. if (!encode.hasOwnProperty(otherDim)) {
  22467. otherDimArr = encode[otherDim] = [];
  22468. }
  22469. var dimIndex = dimItem.otherDims[otherDim];
  22470. if (dimIndex != null && dimIndex !== false) {
  22471. otherDimArr[dimIndex] = dimItem.name;
  22472. }
  22473. });
  22474. });
  22475. var dataDimsOnCoord = [];
  22476. coordDimMap.each(function (v, coordDim) {
  22477. dataDimsOnCoord = dataDimsOnCoord.concat(encode[coordDim]);
  22478. });
  22479. summary.dataDimsOnCoord = dataDimsOnCoord;
  22480. var encodeLabel = encode.label;
  22481. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22482. // in this way. Use label.formatter instead. May be remove this approach someday.
  22483. if (encodeLabel && encodeLabel.length) {
  22484. defaultedLabel = encodeLabel.slice();
  22485. }
  22486. var defaultedTooltip = defaultedLabel.slice();
  22487. var encodeTooltip = encode.tooltip;
  22488. if (encodeTooltip && encodeTooltip.length) {
  22489. defaultedTooltip = encodeTooltip.slice();
  22490. }
  22491. encode.defaultedLabel = defaultedLabel;
  22492. encode.defaultedTooltip = defaultedTooltip;
  22493. return summary;
  22494. }
  22495. function getDimensionTypeByAxis(axisType) {
  22496. return axisType === 'category'
  22497. ? 'ordinal'
  22498. : axisType === 'time'
  22499. ? 'time'
  22500. : 'float';
  22501. }
  22502. function mayLabelDimType(dimType) {
  22503. // In most cases, ordinal and time do not suitable for label.
  22504. // Ordinal info can be displayed on axis. Time is too long.
  22505. return !(dimType === 'ordinal' || dimType === 'time');
  22506. }
  22507. // function findTheLastDimMayLabel(data) {
  22508. // // Get last value dim
  22509. // var dimensions = data.dimensions.slice();
  22510. // var valueType;
  22511. // var valueDim;
  22512. // while (dimensions.length && (
  22513. // valueDim = dimensions.pop(),
  22514. // valueType = data.getDimensionInfo(valueDim).type,
  22515. // valueType === 'ordinal' || valueType === 'time'
  22516. // )) {} // jshint ignore:line
  22517. // return valueDim;
  22518. // }
  22519. /**
  22520. * List for data storage
  22521. * @module echarts/data/List
  22522. */
  22523. var isObject$4 = isObject$1;
  22524. var UNDEFINED = 'undefined';
  22525. var globalObj = typeof window === UNDEFINED ? global : window;
  22526. // Use prefix to avoid index to be the same as otherIdList[idx],
  22527. // which will cause weird udpate animation.
  22528. var ID_PREFIX = 'e\0\0';
  22529. var dataCtors = {
  22530. 'float': typeof globalObj.Float64Array === UNDEFINED
  22531. ? Array : globalObj.Float64Array,
  22532. 'int': typeof globalObj.Int32Array === UNDEFINED
  22533. ? Array : globalObj.Int32Array,
  22534. // Ordinal data type can be string or int
  22535. 'ordinal': Array,
  22536. 'number': Array,
  22537. 'time': Array
  22538. };
  22539. function getIndicesCtor(list) {
  22540. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22541. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22542. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22543. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22544. }
  22545. function cloneChunk(originalChunk) {
  22546. var Ctor = originalChunk.constructor;
  22547. // Only shallow clone is enough when Array.
  22548. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22549. }
  22550. var TRANSFERABLE_PROPERTIES = [
  22551. 'stackedOn', 'hasItemOption', '_nameList', '_idList',
  22552. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22553. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22554. ];
  22555. function transferProperties(a, b) {
  22556. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22557. if (b.hasOwnProperty(propName)) {
  22558. a[propName] = b[propName];
  22559. }
  22560. });
  22561. a.__wrappedMethods = b.__wrappedMethods;
  22562. }
  22563. /**
  22564. * @constructor
  22565. * @alias module:echarts/data/List
  22566. *
  22567. * @param {Array.<string|Object>} dimensions
  22568. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22569. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22570. * Spetial fields: {
  22571. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22572. * }
  22573. * @param {module:echarts/model/Model} hostModel
  22574. */
  22575. var List = function (dimensions, hostModel) {
  22576. dimensions = dimensions || ['x', 'y'];
  22577. var dimensionInfos = {};
  22578. var dimensionNames = [];
  22579. for (var i = 0; i < dimensions.length; i++) {
  22580. var dimensionName;
  22581. var dimensionInfo = {};
  22582. if (typeof dimensions[i] === 'string') {
  22583. dimensionName = dimensions[i];
  22584. dimensionInfo = {
  22585. name: dimensionName,
  22586. coordDim: dimensionName,
  22587. coordDimIndex: 0,
  22588. stackable: false,
  22589. // Type can be 'float', 'int', 'number'
  22590. // Default is float64
  22591. type: 'float'
  22592. };
  22593. }
  22594. else {
  22595. dimensionInfo = dimensions[i];
  22596. dimensionName = dimensionInfo.name;
  22597. dimensionInfo.type = dimensionInfo.type || 'float';
  22598. if (!dimensionInfo.coordDim) {
  22599. dimensionInfo.coordDim = dimensionName;
  22600. dimensionInfo.coordDimIndex = 0;
  22601. }
  22602. }
  22603. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22604. dimensionNames.push(dimensionName);
  22605. dimensionInfos[dimensionName] = dimensionInfo;
  22606. dimensionInfo.index = i;
  22607. }
  22608. /**
  22609. * @readOnly
  22610. * @type {Array.<string>}
  22611. */
  22612. this.dimensions = dimensionNames;
  22613. /**
  22614. * Infomation of each data dimension, like data type.
  22615. * @type {Object}
  22616. */
  22617. this._dimensionInfos = dimensionInfos;
  22618. /**
  22619. * @type {module:echarts/model/Model}
  22620. */
  22621. this.hostModel = hostModel;
  22622. /**
  22623. * @type {module:echarts/model/Model}
  22624. */
  22625. this.dataType;
  22626. /**
  22627. * Indices stores the indices of data subset after filtered.
  22628. * This data subset will be used in chart.
  22629. * @type {Array.<number>}
  22630. * @readOnly
  22631. */
  22632. this._indices = null;
  22633. this._count = 0;
  22634. this._rawCount = 0;
  22635. /**
  22636. * Data storage
  22637. * @type {Object.<key, Array.<TypedArray|Array>>}
  22638. * @private
  22639. */
  22640. this._storage = {};
  22641. /**
  22642. * @type {Array.<string>}
  22643. */
  22644. this._nameList = [];
  22645. /**
  22646. * @type {Array.<string>}
  22647. */
  22648. this._idList = [];
  22649. /**
  22650. * Models of data option is stored sparse for optimizing memory cost
  22651. * @type {Array.<module:echarts/model/Model>}
  22652. * @private
  22653. */
  22654. this._optionModels = [];
  22655. /**
  22656. * @param {module:echarts/data/List}
  22657. */
  22658. this.stackedOn = null;
  22659. /**
  22660. * Global visual properties after visual coding
  22661. * @type {Object}
  22662. * @private
  22663. */
  22664. this._visual = {};
  22665. /**
  22666. * Globel layout properties.
  22667. * @type {Object}
  22668. * @private
  22669. */
  22670. this._layout = {};
  22671. /**
  22672. * Item visual properties after visual coding
  22673. * @type {Array.<Object>}
  22674. * @private
  22675. */
  22676. this._itemVisuals = [];
  22677. /**
  22678. * Key: visual type, Value: boolean
  22679. * @type {Object}
  22680. * @readOnly
  22681. */
  22682. this.hasItemVisual = {};
  22683. /**
  22684. * Item layout properties after layout
  22685. * @type {Array.<Object>}
  22686. * @private
  22687. */
  22688. this._itemLayouts = [];
  22689. /**
  22690. * Graphic elemnents
  22691. * @type {Array.<module:zrender/Element>}
  22692. * @private
  22693. */
  22694. this._graphicEls = [];
  22695. /**
  22696. * Max size of each chunk.
  22697. * @type {number}
  22698. * @private
  22699. */
  22700. this._chunkSize = 1e5;
  22701. /**
  22702. * @type {number}
  22703. * @private
  22704. */
  22705. this._chunkCount = 0;
  22706. /**
  22707. * @type {Array.<Array|Object>}
  22708. * @private
  22709. */
  22710. this._rawData;
  22711. /**
  22712. * Raw extent will not be cloned, but only transfered.
  22713. * It will not be calculated util needed.
  22714. * key: dim,
  22715. * value: {end: number, extent: Array.<number>}
  22716. * @type {Object}
  22717. * @private
  22718. */
  22719. this._rawExtent = {};
  22720. /**
  22721. * @type {Object}
  22722. * @private
  22723. */
  22724. this._extent = {};
  22725. /**
  22726. * key: dim
  22727. * value: extent
  22728. * @type {Object}
  22729. * @private
  22730. */
  22731. this._approximateExtent = {};
  22732. /**
  22733. * Cache summary info for fast visit. See "dimensionHelper".
  22734. * @type {Object}
  22735. * @private
  22736. */
  22737. this._dimensionsSummary = summarizeDimensions(this);
  22738. };
  22739. var listProto = List.prototype;
  22740. listProto.type = 'list';
  22741. /**
  22742. * If each data item has it's own option
  22743. * @type {boolean}
  22744. */
  22745. listProto.hasItemOption = true;
  22746. /**
  22747. * Get dimension name
  22748. * @param {string|number} dim
  22749. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22750. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22751. * @return {string} Concrete dim name.
  22752. */
  22753. listProto.getDimension = function (dim) {
  22754. if (!isNaN(dim)) {
  22755. dim = this.dimensions[dim] || dim;
  22756. }
  22757. return dim;
  22758. };
  22759. /**
  22760. * Get type and stackable info of particular dimension
  22761. * @param {string|number} dim
  22762. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22763. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22764. */
  22765. listProto.getDimensionInfo = function (dim) {
  22766. // Do not clone, because there may be categories in dimInfo.
  22767. return this._dimensionInfos[this.getDimension(dim)];
  22768. };
  22769. /**
  22770. * @return {Array.<string>} concrete dimension name list on coord.
  22771. */
  22772. listProto.getDimensionsOnCoord = function () {
  22773. return this._dimensionsSummary.dataDimsOnCoord.slice();
  22774. };
  22775. /**
  22776. * @param {string} coordDim
  22777. * @param {number|Array} [idx=0] A coordDim may map to more than one data dim.
  22778. * If idx is `true`, return a array of all mapped dims.
  22779. * @return {string|Array.<string>} concrete data dim.
  22780. * If idx is number, and not found, return null/undefined.
  22781. * If idx is `true`, and not found, return empty array.
  22782. */
  22783. listProto.mapDimension = function (coordDim, idx) {
  22784. var dims = this._dimensionsSummary.encode[coordDim];
  22785. return idx === true
  22786. ? (dims && dims.slice() || [])
  22787. : dims
  22788. ? dims[idx || 0]
  22789. : null;
  22790. };
  22791. /**
  22792. * Initialize from data
  22793. * @param {Array.<Object|number|Array>} data source or data or data provider.
  22794. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  22795. * defualt label/tooltip.
  22796. * A name can be specified in encode.itemName,
  22797. * or dataItem.name (only for series option data),
  22798. * or provided in nameList from outside.
  22799. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  22800. */
  22801. listProto.initData = function (data, nameList, dimValueGetter) {
  22802. var notProvider = Source.isInstance(data) || isArrayLike(data);
  22803. if (notProvider) {
  22804. data = new DefaultDataProvider(data, this.dimensions.length);
  22805. }
  22806. if (__DEV__) {
  22807. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  22808. throw new Error('Inavlid data provider.');
  22809. }
  22810. }
  22811. this._rawData = data;
  22812. // Clear
  22813. this._storage = {};
  22814. this._indices = null;
  22815. this._nameList = nameList || [];
  22816. this._idList = [];
  22817. this._nameRepeatCount = {};
  22818. if (!dimValueGetter) {
  22819. this.hasItemOption = false;
  22820. }
  22821. /**
  22822. * @readOnly
  22823. */
  22824. this.defaultDimValueGetter = defaultDimValueGetters[
  22825. this._rawData.getSource().sourceFormat
  22826. ];
  22827. // Default dim value getter
  22828. this._dimValueGetter = dimValueGetter = dimValueGetter
  22829. || this.defaultDimValueGetter;
  22830. // Reset raw extent.
  22831. this._rawExtent = {};
  22832. this._initDataFromProvider(0, data.count());
  22833. // If data has no item option.
  22834. if (data.pure) {
  22835. this.hasItemOption = false;
  22836. }
  22837. };
  22838. listProto.getProvider = function () {
  22839. return this._rawData;
  22840. };
  22841. listProto.appendData = function (data) {
  22842. if (__DEV__) {
  22843. assert$1(!this._indices, 'appendData can only be called on raw data.');
  22844. }
  22845. var rawData = this._rawData;
  22846. var start = this.count();
  22847. rawData.appendData(data);
  22848. var end = rawData.count();
  22849. if (!rawData.persistent) {
  22850. end += start;
  22851. }
  22852. this._initDataFromProvider(start, end);
  22853. };
  22854. listProto._initDataFromProvider = function (start, end) {
  22855. // Optimize.
  22856. if (start >= end) {
  22857. return;
  22858. }
  22859. var chunkSize = this._chunkSize;
  22860. var rawData = this._rawData;
  22861. var storage = this._storage;
  22862. var dimensions = this.dimensions;
  22863. var dimensionInfoMap = this._dimensionInfos;
  22864. var nameList = this._nameList;
  22865. var idList = this._idList;
  22866. var rawExtent = this._rawExtent;
  22867. var nameRepeatCount = this._nameRepeatCount = {};
  22868. var nameDimIdx;
  22869. var chunkCount = this._chunkCount;
  22870. var lastChunkIndex = chunkCount - 1;
  22871. for (var i = 0; i < dimensions.length; i++) {
  22872. var dim = dimensions[i];
  22873. if (!rawExtent[dim]) {
  22874. rawExtent[dim] = [Infinity, -Infinity];
  22875. }
  22876. var dimInfo = dimensionInfoMap[dim];
  22877. if (dimInfo.otherDims.itemName === 0) {
  22878. nameDimIdx = this._nameDimIdx = i;
  22879. }
  22880. if (dimInfo.otherDims.itemId === 0) {
  22881. this._idDimIdx = i;
  22882. }
  22883. var DataCtor = dataCtors[dimInfo.type];
  22884. if (!storage[dim]) {
  22885. storage[dim] = [];
  22886. }
  22887. var resizeChunkArray = storage[dim][lastChunkIndex];
  22888. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  22889. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  22890. // The cost of the copy is probably inconsiderable
  22891. // within the initial chunkSize.
  22892. for (var j = 0; j < resizeChunkArray.length; j++) {
  22893. newStore[j] = resizeChunkArray[j];
  22894. }
  22895. storage[dim][lastChunkIndex] = newStore;
  22896. }
  22897. // Create new chunks.
  22898. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  22899. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  22900. }
  22901. this._chunkCount = storage[dim].length;
  22902. }
  22903. for (var idx = start; idx < end; idx++) {
  22904. // NOTICE: Try not to write things into dataItem
  22905. var dataItem = rawData.getItem(idx);
  22906. // Each data item is value
  22907. // [1, 2]
  22908. // 2
  22909. // Bar chart, line chart which uses category axis
  22910. // only gives the 'y' value. 'x' value is the indices of category
  22911. // Use a tempValue to normalize the value to be a (x, y) value
  22912. var chunkIndex = Math.floor(idx / chunkSize);
  22913. var chunkOffset = idx % chunkSize;
  22914. // Store the data by dimensions
  22915. for (var k = 0; k < dimensions.length; k++) {
  22916. var dim = dimensions[k];
  22917. var dimStorage = storage[dim][chunkIndex];
  22918. // PENDING NULL is empty or zero
  22919. var val = this._dimValueGetter(dataItem, dim, idx, k);
  22920. dimStorage[chunkOffset] = val;
  22921. if (val < rawExtent[dim][0]) {
  22922. rawExtent[dim][0] = val;
  22923. }
  22924. if (val > rawExtent[dim][1]) {
  22925. rawExtent[dim][1] = val;
  22926. }
  22927. }
  22928. // ??? FIXME not check by pure but sourceFormat?
  22929. // TODO refactor these logic.
  22930. if (!rawData.pure) {
  22931. var name = nameList[idx];
  22932. if (dataItem && !name) {
  22933. if (nameDimIdx != null) {
  22934. name = this._getNameFromStore(idx);
  22935. }
  22936. else if (dataItem.name != null) {
  22937. // There is no other place to persistent dataItem.name,
  22938. // so save it to nameList.
  22939. nameList[idx] = name = dataItem.name;
  22940. }
  22941. }
  22942. // Try using the id in option
  22943. // id or name is used on dynamical data, mapping old and new items.
  22944. var id = dataItem == null ? null : dataItem.id;
  22945. if (id == null && name != null) {
  22946. // Use name as id and add counter to avoid same name
  22947. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  22948. id = name;
  22949. if (nameRepeatCount[name] > 0) {
  22950. id += '__ec__' + nameRepeatCount[name];
  22951. }
  22952. nameRepeatCount[name]++;
  22953. }
  22954. id != null && (idList[idx] = id);
  22955. }
  22956. }
  22957. if (!rawData.persistent && rawData.clean) {
  22958. // Clean unused data if data source is typed array.
  22959. rawData.clean();
  22960. }
  22961. this._rawCount = this._count = end;
  22962. // Reset data extent
  22963. this._extent = {};
  22964. };
  22965. // TODO refactor
  22966. listProto._getNameFromStore = function (rawIndex) {
  22967. var nameDimIdx = this._nameDimIdx;
  22968. if (nameDimIdx != null) {
  22969. var chunkSize = this._chunkSize;
  22970. var chunkIndex = Math.floor(rawIndex / chunkSize);
  22971. var chunkOffset = rawIndex % chunkSize;
  22972. var dim = this.dimensions[nameDimIdx];
  22973. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  22974. if (ordinalMeta) {
  22975. return ordinalMeta.categories[rawIndex];
  22976. }
  22977. else {
  22978. var chunk = this._storage[dim][chunkIndex];
  22979. return chunk && chunk[chunkOffset];
  22980. }
  22981. }
  22982. };
  22983. // TODO refactor
  22984. listProto._getIdFromStore = function (rawIndex) {
  22985. var idDimIdx = this._idDimIdx;
  22986. if (idDimIdx != null) {
  22987. var chunkSize = this._chunkSize;
  22988. var chunkIndex = Math.floor(rawIndex / chunkSize);
  22989. var chunkOffset = rawIndex % chunkSize;
  22990. var dim = this.dimensions[idDimIdx];
  22991. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  22992. if (ordinalMeta) {
  22993. return ordinalMeta.categories[rawIndex];
  22994. }
  22995. else {
  22996. var chunk = this._storage[dim][chunkIndex];
  22997. return chunk && chunk[chunkOffset];
  22998. }
  22999. }
  23000. };
  23001. /**
  23002. * @return {number}
  23003. */
  23004. listProto.count = function () {
  23005. return this._count;
  23006. };
  23007. listProto.getIndices = function () {
  23008. if (this._indices) {
  23009. var Ctor = this._indices.constructor;
  23010. return new Ctor(this._indices.buffer, 0, this._count);
  23011. }
  23012. var Ctor = getIndicesCtor(this);
  23013. var arr = new Ctor(this.count());
  23014. for (var i = 0; i < arr.length; i++) {
  23015. arr[i] = i;
  23016. }
  23017. return arr;
  23018. };
  23019. /**
  23020. * Get value. Return NaN if idx is out of range.
  23021. * @param {string} dim Dim must be concrete name.
  23022. * @param {number} idx
  23023. * @param {boolean} stack
  23024. * @return {number}
  23025. */
  23026. listProto.get = function (dim, idx, stack) {
  23027. if (!(idx >= 0 && idx < this._count)) {
  23028. return NaN;
  23029. }
  23030. var storage = this._storage;
  23031. if (!storage[dim]) {
  23032. // TODO Warn ?
  23033. return NaN;
  23034. }
  23035. idx = this.getRawIndex(idx);
  23036. var chunkIndex = Math.floor(idx / this._chunkSize);
  23037. var chunkOffset = idx % this._chunkSize;
  23038. var chunkStore = storage[dim][chunkIndex];
  23039. var value = chunkStore[chunkOffset];
  23040. // FIXME ordinal data type is not stackable
  23041. if (stack) {
  23042. var dimensionInfo = this._dimensionInfos[dim];
  23043. if (dimensionInfo && dimensionInfo.stackable) {
  23044. var stackedOn = this.stackedOn;
  23045. while (stackedOn) {
  23046. // Get no stacked data of stacked on
  23047. var stackedValue = stackedOn.get(dim, idx);
  23048. // Considering positive stack, negative stack and empty data
  23049. if ((value >= 0 && stackedValue > 0) // Positive stack
  23050. || (value <= 0 && stackedValue < 0) // Negative stack
  23051. ) {
  23052. value += stackedValue;
  23053. }
  23054. stackedOn = stackedOn.stackedOn;
  23055. }
  23056. }
  23057. }
  23058. return value;
  23059. };
  23060. // FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23061. // Hack a much simpler _getFast
  23062. listProto._getFast = function (dim, rawIdx) {
  23063. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23064. var chunkOffset = rawIdx % this._chunkSize;
  23065. var chunkStore = this._storage[dim][chunkIndex];
  23066. return chunkStore[chunkOffset];
  23067. };
  23068. /**
  23069. * Get value for multi dimensions.
  23070. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23071. * @param {number} idx
  23072. * @param {boolean} stack
  23073. * @return {number}
  23074. */
  23075. listProto.getValues = function (dimensions, idx, stack) {
  23076. var values = [];
  23077. if (!isArray(dimensions)) {
  23078. stack = idx;
  23079. idx = dimensions;
  23080. dimensions = this.dimensions;
  23081. }
  23082. for (var i = 0, len = dimensions.length; i < len; i++) {
  23083. values.push(this.get(dimensions[i], idx, stack));
  23084. }
  23085. return values;
  23086. };
  23087. /**
  23088. * If value is NaN. Inlcuding '-'
  23089. * Only check the coord dimensions.
  23090. * @param {string} dim
  23091. * @param {number} idx
  23092. * @return {number}
  23093. */
  23094. listProto.hasValue = function (idx) {
  23095. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23096. var dimensionInfos = this._dimensionInfos;
  23097. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23098. if (
  23099. // Ordinal type can be string or number
  23100. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23101. // FIXME check ordinal when using index?
  23102. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23103. ) {
  23104. return false;
  23105. }
  23106. }
  23107. return true;
  23108. };
  23109. /**
  23110. * Get extent of data in one dimension
  23111. * @param {string} dim
  23112. * @param {boolean} stack
  23113. */
  23114. listProto.getDataExtent = function (dim, stack) {
  23115. // Make sure use concrete dim as cache name.
  23116. dim = this.getDimension(dim);
  23117. var dimData = this._storage[dim];
  23118. var initialExtent = [Infinity, -Infinity];
  23119. stack = (stack || false) && this.isStacked(dim);
  23120. if (!dimData) {
  23121. return initialExtent;
  23122. }
  23123. // Make more strict checkings to ensure hitting cache.
  23124. var currEnd = this.count();
  23125. var cacheName = [dim, !!stack].join('_');
  23126. // Consider the most cases when using data zoom, `getDataExtent`
  23127. // happened before filtering. We cache raw extent, which is not
  23128. // necessary to be cleared and recalculated when restore data.
  23129. var useRaw = !this._indices && !stack;
  23130. var dimExtent;
  23131. if (useRaw) {
  23132. return this._rawExtent[dim].slice();
  23133. }
  23134. dimExtent = this._extent[cacheName];
  23135. if (dimExtent) {
  23136. return dimExtent.slice();
  23137. }
  23138. dimExtent = initialExtent;
  23139. var min = dimExtent[0];
  23140. var max = dimExtent[1];
  23141. for (var i = 0; i < currEnd; i++) {
  23142. var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23143. value < min && (min = value);
  23144. value > max && (max = value);
  23145. }
  23146. dimExtent = [min, max];
  23147. this._extent[cacheName] = dimExtent;
  23148. return dimExtent;
  23149. };
  23150. /**
  23151. * Optimize for the scenario that data is filtered by a given extent.
  23152. * Consider that if data amount is more than hundreds of thousand,
  23153. * extent calculation will cost more than 10ms and the cache will
  23154. * be erased because of the filtering.
  23155. */
  23156. listProto.getApproximateExtent = function (dim, stack) {
  23157. dim = this.getDimension(dim);
  23158. return this._approximateExtent[dim] || this.getDataExtent(dim, stack);
  23159. };
  23160. listProto.setApproximateExtent = function (extent, dim, stack) {
  23161. dim = this.getDimension(dim);
  23162. this._approximateExtent[dim] = extent.slice();
  23163. };
  23164. listProto.isStacked = function (concreteDim) {
  23165. var dimensionInfo = this._dimensionInfos[concreteDim];
  23166. return dimensionInfo && dimensionInfo.stackable && this.stackedOn;
  23167. };
  23168. /**
  23169. * Get sum of data in one dimension
  23170. * @param {string} dim
  23171. * @param {boolean} stack
  23172. */
  23173. listProto.getSum = function (dim, stack) {
  23174. var dimData = this._storage[dim];
  23175. var sum = 0;
  23176. if (dimData) {
  23177. for (var i = 0, len = this.count(); i < len; i++) {
  23178. var value = this.get(dim, i, stack);
  23179. if (!isNaN(value)) {
  23180. sum += value;
  23181. }
  23182. }
  23183. }
  23184. return sum;
  23185. };
  23186. /**
  23187. * Retreive the index with given value
  23188. * @param {number} idx
  23189. * @param {number} value
  23190. * @return {number}
  23191. */
  23192. // FIXME Precision of float value
  23193. listProto.indexOf = function (dim, value) {
  23194. var storage = this._storage;
  23195. var dimData = storage[dim];
  23196. var chunkSize = this._chunkSize;
  23197. if (dimData) {
  23198. for (var i = 0, len = this.count(); i < len; i++) {
  23199. var chunkIndex = Math.floor(i / chunkSize);
  23200. var chunkOffset = i % chunkSize;
  23201. if (dimData[chunkIndex][chunkOffset] === value) {
  23202. return i;
  23203. }
  23204. }
  23205. }
  23206. return -1;
  23207. };
  23208. /**
  23209. * Retreive the index with given name
  23210. * @param {number} idx
  23211. * @param {number} name
  23212. * @return {number}
  23213. */
  23214. listProto.indexOfName = function (name) {
  23215. for (var i = 0, len = this.count(); i < len; i++) {
  23216. if (this.getName(i) === name) {
  23217. return i;
  23218. }
  23219. }
  23220. return -1;
  23221. };
  23222. /**
  23223. * Retreive the index with given raw data index
  23224. * @param {number} idx
  23225. * @param {number} name
  23226. * @return {number}
  23227. */
  23228. listProto.indexOfRawIndex = function (rawIndex) {
  23229. if (!this._indices) {
  23230. return rawIndex;
  23231. }
  23232. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23233. return -1;
  23234. }
  23235. // Indices are ascending
  23236. var indices = this._indices;
  23237. // If rawIndex === dataIndex
  23238. var rawDataIndex = indices[rawIndex];
  23239. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23240. return rawIndex;
  23241. }
  23242. var left = 0;
  23243. var right = this._count - 1;
  23244. while (left <= right) {
  23245. var mid = (left + right) / 2 | 0;
  23246. if (indices[mid] < rawIndex) {
  23247. left = mid + 1;
  23248. }
  23249. else if (indices[mid] > rawIndex) {
  23250. right = mid - 1;
  23251. }
  23252. else {
  23253. return mid;
  23254. }
  23255. }
  23256. return -1;
  23257. };
  23258. /**
  23259. * Retreive the index of nearest value
  23260. * @param {string} dim
  23261. * @param {number} value
  23262. * @param {boolean} stack If given value is after stacked
  23263. * @param {number} [maxDistance=Infinity]
  23264. * @return {Array.<number>} Considere multiple points has the same value.
  23265. */
  23266. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  23267. var storage = this._storage;
  23268. var dimData = storage[dim];
  23269. var nearestIndices = [];
  23270. if (!dimData) {
  23271. return nearestIndices;
  23272. }
  23273. if (maxDistance == null) {
  23274. maxDistance = Infinity;
  23275. }
  23276. var minDist = Number.MAX_VALUE;
  23277. var minDiff = -1;
  23278. for (var i = 0, len = this.count(); i < len; i++) {
  23279. var diff = value - this.get(dim, i, stack);
  23280. var dist = Math.abs(diff);
  23281. if (diff <= maxDistance && dist <= minDist) {
  23282. // For the case of two data are same on xAxis, which has sequence data.
  23283. // Show the nearest index
  23284. // https://github.com/ecomfe/echarts/issues/2869
  23285. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23286. minDist = dist;
  23287. minDiff = diff;
  23288. nearestIndices.length = 0;
  23289. }
  23290. nearestIndices.push(i);
  23291. }
  23292. }
  23293. return nearestIndices;
  23294. };
  23295. /**
  23296. * Get raw data index
  23297. * @param {number} idx
  23298. * @return {number}
  23299. */
  23300. listProto.getRawIndex = getRawIndexWithoutIndices;
  23301. function getRawIndexWithoutIndices(idx) {
  23302. return idx;
  23303. }
  23304. function getRawIndexWithIndices(idx) {
  23305. if (idx < this._count && idx >= 0) {
  23306. return this._indices[idx];
  23307. }
  23308. return -1;
  23309. }
  23310. /**
  23311. * Get raw data item
  23312. * @param {number} idx
  23313. * @return {number}
  23314. */
  23315. listProto.getRawDataItem = function (idx) {
  23316. if (!this._rawData.persistent) {
  23317. var val = [];
  23318. for (var i = 0; i < this.dimensions.length; i++) {
  23319. var dim = this.dimensions[i];
  23320. val.push(this.get(dim, idx));
  23321. }
  23322. return val;
  23323. }
  23324. else {
  23325. return this._rawData.getItem(this.getRawIndex(idx));
  23326. }
  23327. };
  23328. /**
  23329. * @param {number} idx
  23330. * @param {boolean} [notDefaultIdx=false]
  23331. * @return {string}
  23332. */
  23333. listProto.getName = function (idx) {
  23334. var rawIndex = this.getRawIndex(idx);
  23335. return this._nameList[rawIndex]
  23336. || this._getNameFromStore(rawIndex)
  23337. || '';
  23338. };
  23339. /**
  23340. * @param {number} idx
  23341. * @param {boolean} [notDefaultIdx=false]
  23342. * @return {string}
  23343. */
  23344. listProto.getId = function (idx) {
  23345. return getId(this, this.getRawIndex(idx));
  23346. };
  23347. function getId(list, rawIndex) {
  23348. var id = list._idList[rawIndex];
  23349. if (id == null) {
  23350. id = list._getIdFromStore(rawIndex);
  23351. }
  23352. if (id == null) {
  23353. // FIXME Check the usage in graph, should not use prefix.
  23354. id = ID_PREFIX + rawIndex;
  23355. }
  23356. return id;
  23357. }
  23358. function normalizeDimensions(dimensions) {
  23359. if (!isArray(dimensions)) {
  23360. dimensions = [dimensions];
  23361. }
  23362. return dimensions;
  23363. }
  23364. function validateDimensions(list, dims) {
  23365. for (var i = 0; i < dims.length; i++) {
  23366. // stroage may be empty when no data, so use
  23367. // dimensionInfos to check.
  23368. if (!list._dimensionInfos[dims[i]]) {
  23369. console.error('Unkown dimension ' + dims[i]);
  23370. }
  23371. }
  23372. }
  23373. /**
  23374. * Data iteration
  23375. * @param {string|Array.<string>}
  23376. * @param {Function} cb
  23377. * @param {boolean} [stack=false]
  23378. * @param {*} [context=this]
  23379. *
  23380. * @example
  23381. * list.each('x', function (x, idx) {});
  23382. * list.each(['x', 'y'], function (x, y, idx) {});
  23383. * list.each(function (idx) {})
  23384. */
  23385. listProto.each = function (dims, cb, stack, context) {
  23386. 'use strict';
  23387. if (!this._count) {
  23388. return;
  23389. }
  23390. if (typeof dims === 'function') {
  23391. context = stack;
  23392. stack = cb;
  23393. cb = dims;
  23394. dims = [];
  23395. }
  23396. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23397. if (__DEV__) {
  23398. validateDimensions(this, dims);
  23399. }
  23400. var dimSize = dims.length;
  23401. context = context || this;
  23402. for (var i = 0; i < this.count(); i++) {
  23403. // Simple optimization
  23404. switch (dimSize) {
  23405. case 0:
  23406. cb.call(context, i);
  23407. break;
  23408. case 1:
  23409. cb.call(context, this.get(dims[0], i, stack), i);
  23410. break;
  23411. case 2:
  23412. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  23413. break;
  23414. default:
  23415. var k = 0;
  23416. var value = [];
  23417. for (; k < dimSize; k++) {
  23418. value[k] = this.get(dims[k], i, stack);
  23419. }
  23420. // Index
  23421. value[k] = i;
  23422. cb.apply(context, value);
  23423. }
  23424. }
  23425. };
  23426. /**
  23427. * Data filter
  23428. * @param {string|Array.<string>}
  23429. * @param {Function} cb
  23430. * @param {boolean} [stack=false]
  23431. * @param {*} [context=this]
  23432. */
  23433. listProto.filterSelf = function (dimensions, cb, stack, context) {
  23434. 'use strict';
  23435. if (!this._count) {
  23436. return;
  23437. }
  23438. if (typeof dimensions === 'function') {
  23439. context = stack;
  23440. stack = cb;
  23441. cb = dimensions;
  23442. dimensions = [];
  23443. }
  23444. stack = stack || false;
  23445. context = context || this;
  23446. dimensions = map(
  23447. normalizeDimensions(dimensions), this.getDimension, this
  23448. );
  23449. if (__DEV__) {
  23450. validateDimensions(this, dimensions);
  23451. }
  23452. var count = this.count();
  23453. var Ctor = getIndicesCtor(this);
  23454. var newIndices = new Ctor(count);
  23455. var value = [];
  23456. var dimSize = dimensions.length;
  23457. var offset = 0;
  23458. var dim0 = dimensions[0];
  23459. for (var i = 0; i < count; i++) {
  23460. var keep;
  23461. var rawIdx = this.getRawIndex(i);
  23462. // Simple optimization
  23463. if (dimSize === 0) {
  23464. keep = cb.call(context, i);
  23465. }
  23466. else if (dimSize === 1) {
  23467. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIdx);
  23468. keep = cb.call(context, val, i);
  23469. }
  23470. else {
  23471. for (var k = 0; k < dimSize; k++) {
  23472. value[k] = stack ? this.get(dimensions[k], i, true) : this._getFast(dim0, rawIdx);
  23473. }
  23474. value[k] = i;
  23475. keep = cb.apply(context, value);
  23476. }
  23477. if (keep) {
  23478. newIndices[offset++] = rawIdx;
  23479. }
  23480. }
  23481. // Set indices after filtered.
  23482. if (offset < count) {
  23483. this._indices = newIndices;
  23484. }
  23485. this._count = offset;
  23486. // Reset data extent
  23487. this._extent = {};
  23488. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23489. return this;
  23490. };
  23491. /**
  23492. * Select data in range. (For optimization of filter)
  23493. * (Manually inline code, support 5 million data filtering in data zoom.)
  23494. */
  23495. listProto.selectRange = function (range, stack) {
  23496. 'use strict';
  23497. if (!this._count) {
  23498. return;
  23499. }
  23500. stack = stack || false;
  23501. var dimensions = [];
  23502. for (var dim in range) {
  23503. if (range.hasOwnProperty(dim)) {
  23504. dimensions.push(dim);
  23505. }
  23506. }
  23507. if (__DEV__) {
  23508. validateDimensions(this, dimensions);
  23509. }
  23510. var dimSize = dimensions.length;
  23511. if (!dimSize) {
  23512. return;
  23513. }
  23514. var originalCount = this.count();
  23515. var Ctor = getIndicesCtor(this);
  23516. var newIndices = new Ctor(originalCount);
  23517. var offset = 0;
  23518. var dim0 = dimensions[0];
  23519. var min = range[dim0][0];
  23520. var max = range[dim0][1];
  23521. var quickFinished = false;
  23522. if (!this._indices && !stack) {
  23523. // Extreme optimization for common case. About 2x faster in chrome.
  23524. var idx = 0;
  23525. if (dimSize === 1) {
  23526. var dimStorage = this._storage[dimensions[0]];
  23527. for (var k = 0; k < this._chunkCount; k++) {
  23528. var chunkStorage = dimStorage[k];
  23529. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23530. for (var i = 0; i < len; i++) {
  23531. var val = chunkStorage[i];
  23532. if (val >= min && val <= max) {
  23533. newIndices[offset++] = idx;
  23534. }
  23535. idx++;
  23536. }
  23537. }
  23538. quickFinished = true;
  23539. }
  23540. else if (dimSize === 2) {
  23541. var dimStorage = this._storage[dim0];
  23542. var dimStorage2 = this._storage[dimensions[1]];
  23543. var min2 = range[dimensions[1]][0];
  23544. var max2 = range[dimensions[1]][1];
  23545. for (var k = 0; k < this._chunkCount; k++) {
  23546. var chunkStorage = dimStorage[k];
  23547. var chunkStorage2= dimStorage2[k];
  23548. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23549. for (var i = 0; i < len; i++) {
  23550. var val = chunkStorage[i];
  23551. var val2 = chunkStorage2[i];
  23552. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23553. newIndices[offset++] = idx;
  23554. }
  23555. idx++;
  23556. }
  23557. }
  23558. quickFinished = true;
  23559. }
  23560. }
  23561. if (!quickFinished) {
  23562. if (dimSize === 1) {
  23563. stack = stack || this.isStacked(dim0);
  23564. for (var i = 0; i < originalCount; i++) {
  23565. var rawIndex = this.getRawIndex(i);
  23566. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23567. if (val >= min && val <= max) {
  23568. newIndices[offset++] = rawIndex;
  23569. }
  23570. }
  23571. }
  23572. else {
  23573. for (var i = 0; i < originalCount; i++) {
  23574. var keep = true;
  23575. var rawIndex = this.getRawIndex(i);
  23576. for (var k = 0; k < dimSize; k++) {
  23577. var dimk = dimensions[k];
  23578. var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23579. if (val < range[dimk][0] || val > range[dimk][1]) {
  23580. keep = false;
  23581. }
  23582. }
  23583. if (keep) {
  23584. newIndices[offset++] = this.getRawIndex(i);
  23585. }
  23586. }
  23587. }
  23588. }
  23589. // Set indices after filtered.
  23590. if (offset < originalCount) {
  23591. this._indices = newIndices;
  23592. }
  23593. this._count = offset;
  23594. // Reset data extent
  23595. this._extent = {};
  23596. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23597. return this;
  23598. };
  23599. /**
  23600. * Data mapping to a plain array
  23601. * @param {string|Array.<string>} [dimensions]
  23602. * @param {Function} cb
  23603. * @param {boolean} [stack=false]
  23604. * @param {*} [context=this]
  23605. * @return {Array}
  23606. */
  23607. listProto.mapArray = function (dimensions, cb, stack, context) {
  23608. 'use strict';
  23609. if (typeof dimensions === 'function') {
  23610. context = stack;
  23611. stack = cb;
  23612. cb = dimensions;
  23613. dimensions = [];
  23614. }
  23615. var result = [];
  23616. this.each(dimensions, function () {
  23617. result.push(cb && cb.apply(this, arguments));
  23618. }, stack, context);
  23619. return result;
  23620. };
  23621. // Data in excludeDimensions is copied, otherwise transfered.
  23622. function cloneListForMapAndSample(original, excludeDimensions) {
  23623. var allDimensions = original.dimensions;
  23624. var list = new List(
  23625. map(allDimensions, original.getDimensionInfo, original),
  23626. original.hostModel
  23627. );
  23628. // FIXME If needs stackedOn, value may already been stacked
  23629. transferProperties(list, original);
  23630. var storage = list._storage = {};
  23631. var originalStorage = original._storage;
  23632. // Init storage
  23633. for (var i = 0; i < allDimensions.length; i++) {
  23634. var dim = allDimensions[i];
  23635. if (originalStorage[dim]) {
  23636. storage[dim] = indexOf(excludeDimensions, dim) >= 0
  23637. ? cloneDimStore(originalStorage[dim])
  23638. // Direct reference for other dimensions
  23639. : originalStorage[dim];
  23640. }
  23641. }
  23642. return list;
  23643. }
  23644. function cloneDimStore(originalDimStore) {
  23645. var newDimStore = new Array(originalDimStore.length);
  23646. for (var j = 0; j < originalDimStore.length; j++) {
  23647. newDimStore[j] = cloneChunk(originalDimStore[j]);
  23648. }
  23649. return newDimStore;
  23650. }
  23651. /**
  23652. * Data mapping to a new List with given dimensions
  23653. * @param {string|Array.<string>} dimensions
  23654. * @param {Function} cb
  23655. * @param {boolean} [stack=false]
  23656. * @param {*} [context=this]
  23657. * @return {Array}
  23658. */
  23659. listProto.map = function (dimensions, cb, stack, context) {
  23660. 'use strict';
  23661. dimensions = map(
  23662. normalizeDimensions(dimensions), this.getDimension, this
  23663. );
  23664. if (__DEV__) {
  23665. validateDimensions(this, dimensions);
  23666. }
  23667. var list = cloneListForMapAndSample(this, dimensions);
  23668. // Following properties are all immutable.
  23669. // So we can reference to the same value
  23670. list._indices = this._indices;
  23671. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23672. var storage = list._storage;
  23673. var tmpRetValue = [];
  23674. var chunkSize = this._chunkSize;
  23675. var dimSize = dimensions.length;
  23676. var dataCount = this.count();
  23677. var values = [];
  23678. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  23679. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  23680. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex, stack);
  23681. }
  23682. values[dimSize] = dataIndex;
  23683. var retValue = cb && cb.apply(context, values);
  23684. if (retValue != null) {
  23685. // a number or string (in oridinal dimension)?
  23686. if (typeof retValue !== 'object') {
  23687. tmpRetValue[0] = retValue;
  23688. retValue = tmpRetValue;
  23689. }
  23690. var rawIndex = this.getRawIndex(dataIndex);
  23691. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23692. var chunkOffset = rawIndex % chunkSize;
  23693. for (var i = 0; i < retValue.length; i++) {
  23694. var dim = dimensions[i];
  23695. var dimStore = storage[dim];
  23696. if (dimStore) {
  23697. dimStore[chunkIndex][chunkOffset] = retValue[i];
  23698. }
  23699. }
  23700. }
  23701. }
  23702. return list;
  23703. };
  23704. /**
  23705. * Large data down sampling on given dimension
  23706. * @param {string} dimension
  23707. * @param {number} rate
  23708. * @param {Function} sampleValue
  23709. * @param {Function} sampleIndex Sample index for name and id
  23710. */
  23711. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  23712. var list = cloneListForMapAndSample(this, [dimension]);
  23713. var targetStorage = list._storage;
  23714. var frameValues = [];
  23715. var frameSize = Math.floor(1 / rate);
  23716. var dimStore = targetStorage[dimension];
  23717. var len = this.count();
  23718. var chunkSize = this._chunkSize;
  23719. var newIndices = new (getIndicesCtor(this))(len);
  23720. var offset = 0;
  23721. for (var i = 0; i < len; i += frameSize) {
  23722. // Last frame
  23723. if (frameSize > len - i) {
  23724. frameSize = len - i;
  23725. frameValues.length = frameSize;
  23726. }
  23727. for (var k = 0; k < frameSize; k++) {
  23728. var dataIdx = this.getRawIndex(i + k);
  23729. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  23730. var originalChunkOffset = dataIdx % chunkSize;
  23731. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  23732. }
  23733. var value = sampleValue(frameValues);
  23734. var sampleFrameIdx = this.getRawIndex(
  23735. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  23736. );
  23737. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  23738. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  23739. // Only write value on the filtered data
  23740. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  23741. newIndices[offset++] = sampleFrameIdx;
  23742. }
  23743. list._count = offset;
  23744. list._indices = newIndices;
  23745. list.getRawIndex = getRawIndexWithIndices;
  23746. return list;
  23747. };
  23748. /**
  23749. * Get model of one data item.
  23750. *
  23751. * @param {number} idx
  23752. */
  23753. // FIXME Model proxy ?
  23754. listProto.getItemModel = function (idx) {
  23755. var hostModel = this.hostModel;
  23756. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  23757. };
  23758. /**
  23759. * Create a data differ
  23760. * @param {module:echarts/data/List} otherList
  23761. * @return {module:echarts/data/DataDiffer}
  23762. */
  23763. listProto.diff = function (otherList) {
  23764. var thisList = this;
  23765. return new DataDiffer(
  23766. otherList ? otherList.getIndices() : [],
  23767. this.getIndices(),
  23768. function (idx) {
  23769. return getId(otherList, idx);
  23770. },
  23771. function (idx) {
  23772. return getId(thisList, idx);
  23773. }
  23774. );
  23775. };
  23776. /**
  23777. * Get visual property.
  23778. * @param {string} key
  23779. */
  23780. listProto.getVisual = function (key) {
  23781. var visual = this._visual;
  23782. return visual && visual[key];
  23783. };
  23784. /**
  23785. * Set visual property
  23786. * @param {string|Object} key
  23787. * @param {*} [value]
  23788. *
  23789. * @example
  23790. * setVisual('color', color);
  23791. * setVisual({
  23792. * 'color': color
  23793. * });
  23794. */
  23795. listProto.setVisual = function (key, val) {
  23796. if (isObject$4(key)) {
  23797. for (var name in key) {
  23798. if (key.hasOwnProperty(name)) {
  23799. this.setVisual(name, key[name]);
  23800. }
  23801. }
  23802. return;
  23803. }
  23804. this._visual = this._visual || {};
  23805. this._visual[key] = val;
  23806. };
  23807. /**
  23808. * Set layout property.
  23809. * @param {string|Object} key
  23810. * @param {*} [val]
  23811. */
  23812. listProto.setLayout = function (key, val) {
  23813. if (isObject$4(key)) {
  23814. for (var name in key) {
  23815. if (key.hasOwnProperty(name)) {
  23816. this.setLayout(name, key[name]);
  23817. }
  23818. }
  23819. return;
  23820. }
  23821. this._layout[key] = val;
  23822. };
  23823. /**
  23824. * Get layout property.
  23825. * @param {string} key.
  23826. * @return {*}
  23827. */
  23828. listProto.getLayout = function (key) {
  23829. return this._layout[key];
  23830. };
  23831. /**
  23832. * Get layout of single data item
  23833. * @param {number} idx
  23834. */
  23835. listProto.getItemLayout = function (idx) {
  23836. return this._itemLayouts[idx];
  23837. };
  23838. /**
  23839. * Set layout of single data item
  23840. * @param {number} idx
  23841. * @param {Object} layout
  23842. * @param {boolean=} [merge=false]
  23843. */
  23844. listProto.setItemLayout = function (idx, layout, merge$$1) {
  23845. this._itemLayouts[idx] = merge$$1
  23846. ? extend(this._itemLayouts[idx] || {}, layout)
  23847. : layout;
  23848. };
  23849. /**
  23850. * Clear all layout of single data item
  23851. */
  23852. listProto.clearItemLayouts = function () {
  23853. this._itemLayouts.length = 0;
  23854. };
  23855. /**
  23856. * Get visual property of single data item
  23857. * @param {number} idx
  23858. * @param {string} key
  23859. * @param {boolean} [ignoreParent=false]
  23860. */
  23861. listProto.getItemVisual = function (idx, key, ignoreParent) {
  23862. var itemVisual = this._itemVisuals[idx];
  23863. var val = itemVisual && itemVisual[key];
  23864. if (val == null && !ignoreParent) {
  23865. // Use global visual property
  23866. return this.getVisual(key);
  23867. }
  23868. return val;
  23869. };
  23870. /**
  23871. * Set visual property of single data item
  23872. *
  23873. * @param {number} idx
  23874. * @param {string|Object} key
  23875. * @param {*} [value]
  23876. *
  23877. * @example
  23878. * setItemVisual(0, 'color', color);
  23879. * setItemVisual(0, {
  23880. * 'color': color
  23881. * });
  23882. */
  23883. listProto.setItemVisual = function (idx, key, value) {
  23884. var itemVisual = this._itemVisuals[idx] || {};
  23885. var hasItemVisual = this.hasItemVisual;
  23886. this._itemVisuals[idx] = itemVisual;
  23887. if (isObject$4(key)) {
  23888. for (var name in key) {
  23889. if (key.hasOwnProperty(name)) {
  23890. itemVisual[name] = key[name];
  23891. hasItemVisual[name] = true;
  23892. }
  23893. }
  23894. return;
  23895. }
  23896. itemVisual[key] = value;
  23897. hasItemVisual[key] = true;
  23898. };
  23899. /**
  23900. * Clear itemVisuals and list visual.
  23901. */
  23902. listProto.clearAllVisual = function () {
  23903. this._visual = {};
  23904. this._itemVisuals = [];
  23905. this.hasItemVisual = {};
  23906. };
  23907. var setItemDataAndSeriesIndex = function (child) {
  23908. child.seriesIndex = this.seriesIndex;
  23909. child.dataIndex = this.dataIndex;
  23910. child.dataType = this.dataType;
  23911. };
  23912. /**
  23913. * Set graphic element relative to data. It can be set as null
  23914. * @param {number} idx
  23915. * @param {module:zrender/Element} [el]
  23916. */
  23917. listProto.setItemGraphicEl = function (idx, el) {
  23918. var hostModel = this.hostModel;
  23919. if (el) {
  23920. // Add data index and series index for indexing the data by element
  23921. // Useful in tooltip
  23922. el.dataIndex = idx;
  23923. el.dataType = this.dataType;
  23924. el.seriesIndex = hostModel && hostModel.seriesIndex;
  23925. if (el.type === 'group') {
  23926. el.traverse(setItemDataAndSeriesIndex, el);
  23927. }
  23928. }
  23929. this._graphicEls[idx] = el;
  23930. };
  23931. /**
  23932. * @param {number} idx
  23933. * @return {module:zrender/Element}
  23934. */
  23935. listProto.getItemGraphicEl = function (idx) {
  23936. return this._graphicEls[idx];
  23937. };
  23938. /**
  23939. * @param {Function} cb
  23940. * @param {*} context
  23941. */
  23942. listProto.eachItemGraphicEl = function (cb, context) {
  23943. each$1(this._graphicEls, function (el, idx) {
  23944. if (el) {
  23945. cb && cb.call(context, el, idx);
  23946. }
  23947. });
  23948. };
  23949. /**
  23950. * Shallow clone a new list except visual and layout properties, and graph elements.
  23951. * New list only change the indices.
  23952. */
  23953. listProto.cloneShallow = function (list) {
  23954. if (!list) {
  23955. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  23956. list = new List(dimensionInfoList, this.hostModel);
  23957. }
  23958. // FIXME
  23959. list._storage = this._storage;
  23960. transferProperties(list, this);
  23961. // Clone will not change the data extent and indices
  23962. if (this._indices) {
  23963. var Ctor = this._indices.constructor;
  23964. list._indices = new Ctor(this._indices);
  23965. }
  23966. else {
  23967. list._indices = null;
  23968. }
  23969. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23970. list._extent = clone(this._extent);
  23971. list._approximateExtent = clone(this._approximateExtent);
  23972. return list;
  23973. };
  23974. /**
  23975. * Wrap some method to add more feature
  23976. * @param {string} methodName
  23977. * @param {Function} injectFunction
  23978. */
  23979. listProto.wrapMethod = function (methodName, injectFunction) {
  23980. var originalMethod = this[methodName];
  23981. if (typeof originalMethod !== 'function') {
  23982. return;
  23983. }
  23984. this.__wrappedMethods = this.__wrappedMethods || [];
  23985. this.__wrappedMethods.push(methodName);
  23986. this[methodName] = function () {
  23987. var res = originalMethod.apply(this, arguments);
  23988. return injectFunction.apply(this, [res].concat(slice(arguments)));
  23989. };
  23990. };
  23991. // Methods that create a new list based on this list should be listed here.
  23992. // Notice that those method should `RETURN` the new list.
  23993. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  23994. // Methods that change indices of this list should be listed here.
  23995. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  23996. /**
  23997. * @deprecated
  23998. * Use `echarts/data/helper/createDimensions` instead.
  23999. */
  24000. /**
  24001. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24002. *
  24003. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24004. * and guessing from the data structure.
  24005. * If no 'value' dimension specified, the first no-named dimension will be
  24006. * named as 'value'.
  24007. *
  24008. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24009. * provides not only dim template, but also default order.
  24010. * properties: 'name', 'type', 'displayName'.
  24011. * `name` of each item provides default coord name.
  24012. * [{dimsDef: [string...]}, ...] can be specified to give names.
  24013. * [{ordinalMeta}] can be specified.
  24014. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24015. * @param {Object} [opt]
  24016. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24017. * For example: ['asdf', {name, type}, ...].
  24018. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24019. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  24020. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  24021. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  24022. * If not specified, extra dim names will be:
  24023. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  24024. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24025. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24026. * @return {Array.<Object>} [{
  24027. * name: string mandatory,
  24028. * displayName: string, the origin name in dimsDef, see source helper.
  24029. * If displayName given, the tooltip will displayed vertically.
  24030. * coordDim: string mandatory,
  24031. * isSysCoord: boolean True if the coord is from sys dimension.
  24032. * coordDimIndex: number mandatory,
  24033. * type: string optional,
  24034. * otherDims: { never null/undefined
  24035. * tooltip: number optional,
  24036. * label: number optional,
  24037. * itemName: number optional,
  24038. * seriesName: number optional,
  24039. * },
  24040. * isExtraCoord: boolean true or undefined.
  24041. * other props ...
  24042. * }]
  24043. */
  24044. function completeDimensions(sysDims, source, opt) {
  24045. if (!Source.isInstance(source)) {
  24046. source = Source.seriesDataToSource(source);
  24047. }
  24048. opt = opt || {};
  24049. sysDims = (sysDims || []).slice();
  24050. var dimsDef = (opt.dimsDef || []).slice();
  24051. var encodeDef = createHashMap(opt.encodeDef);
  24052. var dataDimNameMap = createHashMap();
  24053. var coordDimNameMap = createHashMap();
  24054. // var valueCandidate;
  24055. var result = [];
  24056. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24057. // Apply user defined dims (`name` and `type`) and init result.
  24058. for (var i = 0; i < dimCount; i++) {
  24059. var dimDefItem = dimsDef[i] = extend(
  24060. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24061. );
  24062. var userDimName = dimDefItem.name;
  24063. var resultItem = result[i] = {otherDims: {}};
  24064. // Name will be applied later for avoiding duplication.
  24065. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24066. // Only if `series.dimensions` is defined in option
  24067. // displayName, will be set, and dimension will be diplayed vertically in
  24068. // tooltip by default.
  24069. resultItem.name = resultItem.displayName = userDimName;
  24070. dataDimNameMap.set(userDimName, i);
  24071. }
  24072. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24073. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24074. }
  24075. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24076. encodeDef.each(function (dataDims, coordDim) {
  24077. dataDims = normalizeToArray(dataDims).slice();
  24078. var validDataDims = encodeDef.set(coordDim, []);
  24079. each$1(dataDims, function (resultDimIdx, idx) {
  24080. // The input resultDimIdx can be dim name or index.
  24081. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24082. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24083. validDataDims[idx] = resultDimIdx;
  24084. applyDim(result[resultDimIdx], coordDim, idx);
  24085. }
  24086. });
  24087. });
  24088. // Apply templetes and default order from `sysDims`.
  24089. var availDimIdx = 0;
  24090. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24091. var coordDim;
  24092. var sysDimItem;
  24093. var sysDimItemDimsDef;
  24094. var sysDimItemOtherDims;
  24095. if (isString(sysDimItem)) {
  24096. coordDim = sysDimItem;
  24097. sysDimItem = {};
  24098. }
  24099. else {
  24100. coordDim = sysDimItem.name;
  24101. var ordinalMeta = sysDimItem.ordinalMeta;
  24102. sysDimItem.ordinalMeta = null;
  24103. sysDimItem = clone(sysDimItem);
  24104. sysDimItem.ordinalMeta = ordinalMeta;
  24105. // `coordDimIndex` should not be set directly.
  24106. sysDimItemDimsDef = sysDimItem.dimsDef;
  24107. sysDimItemOtherDims = sysDimItem.otherDims;
  24108. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24109. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24110. }
  24111. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24112. // dimensions provides default dim sequences.
  24113. if (!dataDims.length) {
  24114. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24115. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24116. availDimIdx++;
  24117. }
  24118. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24119. }
  24120. }
  24121. // Apply templates.
  24122. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24123. var resultItem = result[resultDimIdx];
  24124. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24125. if (resultItem.name == null && sysDimItemDimsDef) {
  24126. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24127. }
  24128. resultItem.isSysCoord = true;
  24129. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24130. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24131. });
  24132. });
  24133. function applyDim(resultItem, coordDim, coordDimIndex) {
  24134. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24135. resultItem.otherDims[coordDim] = coordDimIndex;
  24136. }
  24137. else {
  24138. resultItem.coordDim = coordDim;
  24139. resultItem.coordDimIndex = coordDimIndex;
  24140. coordDimNameMap.set(coordDim, true);
  24141. }
  24142. }
  24143. // Make sure the first extra dim is 'value'.
  24144. var extra = opt.extraPrefix || 'value';
  24145. // Set dim `name` and other `coordDim` and other props.
  24146. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24147. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24148. var coordDim = resultItem.coordDim;
  24149. coordDim == null && (
  24150. resultItem.coordDim = genName(
  24151. extra, coordDimNameMap, opt.extraFromZero
  24152. ),
  24153. resultItem.coordDimIndex = 0,
  24154. resultItem.isExtraCoord = true
  24155. );
  24156. resultItem.name == null && (resultItem.name = genName(
  24157. resultItem.coordDim,
  24158. dataDimNameMap
  24159. ));
  24160. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24161. resultItem.type = 'ordinal';
  24162. }
  24163. }
  24164. return result;
  24165. }
  24166. // ??? TODO
  24167. // Originally detect dimCount by data[0]. Should we
  24168. // optimize it to only by sysDims and dimensions and encode.
  24169. // So only necessary dims will be initialized.
  24170. // But
  24171. // (1) custom series should be considered. where other dims
  24172. // may be visited.
  24173. // (2) sometimes user need to calcualte bubble size or use visualMap
  24174. // on other dimensions besides coordSys needed.
  24175. function getDimCount(source, sysDims, dimsDef, dimCount) {
  24176. if (dimCount == null) {
  24177. dimCount = Math.max(
  24178. source.dimensionsDetectCount || 1,
  24179. sysDims.length,
  24180. dimsDef.length
  24181. );
  24182. each$1(sysDims, function (sysDimItem) {
  24183. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24184. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24185. });
  24186. }
  24187. return dimCount;
  24188. }
  24189. function genName(name, map$$1, fromZero) {
  24190. if (fromZero || map$$1.get(name) != null) {
  24191. var i = 0;
  24192. while (map$$1.get(name + i) != null) {
  24193. i++;
  24194. }
  24195. name += i;
  24196. }
  24197. map$$1.set(name, true);
  24198. return name;
  24199. }
  24200. /**
  24201. * Substitute `completeDimensions`.
  24202. * `completeDimensions` is to be deprecated.
  24203. */
  24204. /**
  24205. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24206. * @param {Object|Array} [opt]
  24207. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24208. * @param {number} [opt.dimensionsCount]
  24209. * @param {string} [opt.extraPrefix]
  24210. * @param {boolean} [opt.extraFromZero]
  24211. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24212. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24213. * @return {Array.<Object>} dimensionsInfo
  24214. */
  24215. var createDimensions = function (source, opt) {
  24216. opt = opt || {};
  24217. return completeDimensions(opt.coordDimensions || [], source, {
  24218. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24219. encodeDef: opt.encodeDefine || source.encodeDefine,
  24220. dimCount: opt.dimensionsCount,
  24221. extraPrefix: opt.extraPrefix,
  24222. extraFromZero: opt.extraFromZero
  24223. });
  24224. };
  24225. /**
  24226. * @param {module:echarts/data/Source|Array} source Or raw data.
  24227. * @param {module:echarts/model/Series} seriesModel
  24228. */
  24229. function createListFromArray(source, seriesModel) {
  24230. if (!Source.isInstance(source)) {
  24231. source = Source.seriesDataToSource(source);
  24232. }
  24233. var coordSysName = seriesModel.get('coordinateSystem');
  24234. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24235. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24236. var coordSysDimDefs;
  24237. if (coordSysDefine) {
  24238. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24239. var dimInfo = {name: dim};
  24240. var axisModel = coordSysDefine.axisMap.get(dim);
  24241. if (axisModel) {
  24242. var axisType = axisModel.get('type');
  24243. dimInfo.type = getDimensionTypeByAxis(axisType);
  24244. dimInfo.stackable = isStackable(axisType);
  24245. }
  24246. return dimInfo;
  24247. });
  24248. }
  24249. if (!coordSysDimDefs) {
  24250. // Get dimensions from registered coordinate system
  24251. coordSysDimDefs = (registeredCoordSys && (
  24252. registeredCoordSys.getDimensionsInfo
  24253. ? registeredCoordSys.getDimensionsInfo()
  24254. : registeredCoordSys.dimensions.slice()
  24255. )) || ['x', 'y'];
  24256. }
  24257. var dimInfoList = createDimensions(source, {
  24258. coordDimensions: coordSysDimDefs
  24259. });
  24260. var firstCategoryDimIndex;
  24261. var hasNameEncode;
  24262. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24263. var coordDim = dimInfo.coordDim;
  24264. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24265. if (categoryAxisModel) {
  24266. if (firstCategoryDimIndex == null) {
  24267. firstCategoryDimIndex = dimIndex;
  24268. }
  24269. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24270. }
  24271. if (dimInfo.otherDims.itemName != null) {
  24272. hasNameEncode = true;
  24273. }
  24274. });
  24275. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24276. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24277. }
  24278. var list = new List(dimInfoList, seriesModel);
  24279. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24280. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24281. // Use dataIndex as ordinal value in categoryAxis
  24282. return dimIndex === firstCategoryDimIndex
  24283. ? dataIndex
  24284. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24285. }
  24286. : null;
  24287. list.hasItemOption = false;
  24288. list.initData(source, null, dimValueGetter);
  24289. return list;
  24290. }
  24291. function isStackable(axisType) {
  24292. return axisType !== 'category' && axisType !== 'time';
  24293. }
  24294. function isNeedCompleteOrdinalData(source) {
  24295. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24296. var sampleItem = firstDataNotNull(source.data || []);
  24297. return sampleItem != null
  24298. && !isArray(getDataItemValue(sampleItem));
  24299. }
  24300. }
  24301. function firstDataNotNull(data) {
  24302. var i = 0;
  24303. while (i < data.length && data[i] == null) {
  24304. i++;
  24305. }
  24306. return data[i];
  24307. }
  24308. /**
  24309. * // Scale class management
  24310. * @module echarts/scale/Scale
  24311. */
  24312. /**
  24313. * @param {Object} [setting]
  24314. */
  24315. function Scale(setting) {
  24316. this._setting = setting || {};
  24317. /**
  24318. * Extent
  24319. * @type {Array.<number>}
  24320. * @protected
  24321. */
  24322. this._extent = [Infinity, -Infinity];
  24323. /**
  24324. * Step is calculated in adjustExtent
  24325. * @type {Array.<number>}
  24326. * @protected
  24327. */
  24328. this._interval = 0;
  24329. this.init && this.init.apply(this, arguments);
  24330. }
  24331. /**
  24332. * Parse input val to valid inner number.
  24333. * @param {*} val
  24334. * @return {number}
  24335. */
  24336. Scale.prototype.parse = function (val) {
  24337. // Notice: This would be a trap here, If the implementation
  24338. // of this method depends on extent, and this method is used
  24339. // before extent set (like in dataZoom), it would be wrong.
  24340. // Nevertheless, parse does not depend on extent generally.
  24341. return val;
  24342. };
  24343. Scale.prototype.getSetting = function (name) {
  24344. return this._setting[name];
  24345. };
  24346. Scale.prototype.contain = function (val) {
  24347. var extent = this._extent;
  24348. return val >= extent[0] && val <= extent[1];
  24349. };
  24350. /**
  24351. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24352. * @param {number} val
  24353. * @return {number}
  24354. */
  24355. Scale.prototype.normalize = function (val) {
  24356. var extent = this._extent;
  24357. if (extent[1] === extent[0]) {
  24358. return 0.5;
  24359. }
  24360. return (val - extent[0]) / (extent[1] - extent[0]);
  24361. };
  24362. /**
  24363. * Scale normalized value
  24364. * @param {number} val
  24365. * @return {number}
  24366. */
  24367. Scale.prototype.scale = function (val) {
  24368. var extent = this._extent;
  24369. return val * (extent[1] - extent[0]) + extent[0];
  24370. };
  24371. /**
  24372. * Set extent from data
  24373. * @param {Array.<number>} other
  24374. */
  24375. Scale.prototype.unionExtent = function (other) {
  24376. var extent = this._extent;
  24377. other[0] < extent[0] && (extent[0] = other[0]);
  24378. other[1] > extent[1] && (extent[1] = other[1]);
  24379. // not setExtent because in log axis it may transformed to power
  24380. // this.setExtent(extent[0], extent[1]);
  24381. };
  24382. /**
  24383. * Set extent from data
  24384. * @param {module:echarts/data/List} data
  24385. * @param {string} dim
  24386. */
  24387. Scale.prototype.unionExtentFromData = function (data, dim) {
  24388. this.unionExtent(data.getApproximateExtent(dim, true));
  24389. };
  24390. /**
  24391. * Get extent
  24392. * @return {Array.<number>}
  24393. */
  24394. Scale.prototype.getExtent = function () {
  24395. return this._extent.slice();
  24396. };
  24397. /**
  24398. * Set extent
  24399. * @param {number} start
  24400. * @param {number} end
  24401. */
  24402. Scale.prototype.setExtent = function (start, end) {
  24403. var thisExtent = this._extent;
  24404. if (!isNaN(start)) {
  24405. thisExtent[0] = start;
  24406. }
  24407. if (!isNaN(end)) {
  24408. thisExtent[1] = end;
  24409. }
  24410. };
  24411. /**
  24412. * @return {Array.<string>}
  24413. */
  24414. Scale.prototype.getTicksLabels = function () {
  24415. var labels = [];
  24416. var ticks = this.getTicks();
  24417. for (var i = 0; i < ticks.length; i++) {
  24418. labels.push(this.getLabel(ticks[i]));
  24419. }
  24420. return labels;
  24421. };
  24422. /**
  24423. * When axis extent depends on data and no data exists,
  24424. * axis ticks should not be drawn, which is named 'blank'.
  24425. */
  24426. Scale.prototype.isBlank = function () {
  24427. return this._isBlank;
  24428. },
  24429. /**
  24430. * When axis extent depends on data and no data exists,
  24431. * axis ticks should not be drawn, which is named 'blank'.
  24432. */
  24433. Scale.prototype.setBlank = function (isBlank) {
  24434. this._isBlank = isBlank;
  24435. };
  24436. enableClassExtend(Scale);
  24437. enableClassManagement(Scale, {
  24438. registerWhenExtend: true
  24439. });
  24440. /**
  24441. * @constructor
  24442. * @param {Object} [opt]
  24443. * @param {Object} [opt.categories=[]]
  24444. * @param {Object} [opt.needCollect=false]
  24445. * @param {Object} [opt.deduplication=false]
  24446. */
  24447. function OrdinalMeta(opt) {
  24448. /**
  24449. * @readOnly
  24450. * @type {Array.<string>}
  24451. */
  24452. this.categories = opt.categories || [];
  24453. /**
  24454. * @private
  24455. * @type {boolean}
  24456. */
  24457. this._needCollect = opt.needCollect;
  24458. /**
  24459. * @private
  24460. * @type {boolean}
  24461. */
  24462. this._deduplication = opt.deduplication;
  24463. /**
  24464. * @private
  24465. * @type {boolean}
  24466. */
  24467. this._map;
  24468. }
  24469. /**
  24470. * @param {module:echarts/model/Model} axisModel
  24471. * @return {module:echarts/data/OrdinalMeta}
  24472. */
  24473. OrdinalMeta.createByAxisModel = function (axisModel) {
  24474. var option = axisModel.option;
  24475. var data = option.data;
  24476. var categories = data && map(data, getName);
  24477. return new OrdinalMeta({
  24478. categories: categories,
  24479. needCollect: !categories,
  24480. // deduplication is default in axis.
  24481. deduplication: option.dedplication !== false
  24482. });
  24483. };
  24484. var proto$1 = OrdinalMeta.prototype;
  24485. /**
  24486. * @param {string} category
  24487. * @return {number} ordinal
  24488. */
  24489. proto$1.getOrdinal = function (category) {
  24490. return getOrCreateMap(this).get(category);
  24491. };
  24492. /**
  24493. * @param {*} category
  24494. * @return {number} The ordinal. If not found, return NaN.
  24495. */
  24496. proto$1.parseAndCollect = function (category) {
  24497. var index;
  24498. var needCollect = this._needCollect;
  24499. // The value of category dim can be the index of the given category set.
  24500. // This feature is only supported when !needCollect, because we should
  24501. // consider a common case: a value is 2017, which is a number but is
  24502. // expected to be tread as a category. This case usually happen in dataset,
  24503. // where it happent to be no need of the index feature.
  24504. if (typeof category !== 'string' && !needCollect) {
  24505. return category;
  24506. }
  24507. // Optimize for the scenario:
  24508. // category is ['2012-01-01', '2012-01-02', ...], where the input
  24509. // data has been ensured not duplicate and is large data.
  24510. // Notice, if a dataset dimension provide categroies, usually echarts
  24511. // should remove duplication except user tell echarts dont do that
  24512. // (set axis.deduplication = false), because echarts do not know whether
  24513. // the values in the category dimension has duplication (consider the
  24514. // parallel-aqi example)
  24515. if (needCollect && !this._deduplication) {
  24516. index = this.categories.length;
  24517. this.categories[index] = category;
  24518. return index;
  24519. }
  24520. var map$$1 = getOrCreateMap(this);
  24521. index = map$$1.get(category);
  24522. if (index == null) {
  24523. if (needCollect) {
  24524. index = this.categories.length;
  24525. this.categories[index] = category;
  24526. map$$1.set(category, index);
  24527. }
  24528. else {
  24529. index = NaN;
  24530. }
  24531. }
  24532. return index;
  24533. };
  24534. // Consider big data, do not create map until needed.
  24535. function getOrCreateMap(ordinalMeta) {
  24536. return ordinalMeta._map || (
  24537. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  24538. );
  24539. }
  24540. function getName(obj) {
  24541. if (isObject$1(obj) && obj.value != null) {
  24542. return obj.value;
  24543. }
  24544. else {
  24545. return obj + '';
  24546. }
  24547. }
  24548. /**
  24549. * Linear continuous scale
  24550. * @module echarts/coord/scale/Ordinal
  24551. *
  24552. * http://en.wikipedia.org/wiki/Level_of_measurement
  24553. */
  24554. // FIXME only one data
  24555. var scaleProto = Scale.prototype;
  24556. var OrdinalScale = Scale.extend({
  24557. type: 'ordinal',
  24558. /**
  24559. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  24560. */
  24561. init: function (ordinalMeta, extent) {
  24562. // Caution: Should not use instanceof, consider ec-extensions using
  24563. // import approach to get OrdinalMeta class.
  24564. if (!ordinalMeta || isArray(ordinalMeta)) {
  24565. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  24566. }
  24567. this._ordinalMeta = ordinalMeta;
  24568. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  24569. },
  24570. parse: function (val) {
  24571. return typeof val === 'string'
  24572. ? this._ordinalMeta.getOrdinal(val)
  24573. // val might be float.
  24574. : Math.round(val);
  24575. },
  24576. contain: function (rank) {
  24577. rank = this.parse(rank);
  24578. return scaleProto.contain.call(this, rank)
  24579. && this._ordinalMeta.categories[rank] != null;
  24580. },
  24581. /**
  24582. * Normalize given rank or name to linear [0, 1]
  24583. * @param {number|string} [val]
  24584. * @return {number}
  24585. */
  24586. normalize: function (val) {
  24587. return scaleProto.normalize.call(this, this.parse(val));
  24588. },
  24589. scale: function (val) {
  24590. return Math.round(scaleProto.scale.call(this, val));
  24591. },
  24592. /**
  24593. * @return {Array}
  24594. */
  24595. getTicks: function () {
  24596. var ticks = [];
  24597. var extent = this._extent;
  24598. var rank = extent[0];
  24599. while (rank <= extent[1]) {
  24600. ticks.push(rank);
  24601. rank++;
  24602. }
  24603. return ticks;
  24604. },
  24605. /**
  24606. * Get item on rank n
  24607. * @param {number} n
  24608. * @return {string}
  24609. */
  24610. getLabel: function (n) {
  24611. return this._ordinalMeta.categories[n];
  24612. },
  24613. /**
  24614. * @return {number}
  24615. */
  24616. count: function () {
  24617. return this._extent[1] - this._extent[0] + 1;
  24618. },
  24619. /**
  24620. * @override
  24621. */
  24622. unionExtentFromData: function (data, dim) {
  24623. this.unionExtent(data.getApproximateExtent(dim, false));
  24624. },
  24625. niceTicks: noop,
  24626. niceExtent: noop
  24627. });
  24628. /**
  24629. * @return {module:echarts/scale/Time}
  24630. */
  24631. OrdinalScale.create = function () {
  24632. return new OrdinalScale();
  24633. };
  24634. /**
  24635. * For testable.
  24636. */
  24637. var roundNumber$1 = round$1;
  24638. /**
  24639. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  24640. * Should be extent[0] < extent[1].
  24641. * @param {number} splitNumber splitNumber should be >= 1.
  24642. * @param {number} [minInterval]
  24643. * @param {number} [maxInterval]
  24644. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  24645. */
  24646. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  24647. var result = {};
  24648. var span = extent[1] - extent[0];
  24649. var interval = result.interval = nice(span / splitNumber, true);
  24650. if (minInterval != null && interval < minInterval) {
  24651. interval = result.interval = minInterval;
  24652. }
  24653. if (maxInterval != null && interval > maxInterval) {
  24654. interval = result.interval = maxInterval;
  24655. }
  24656. // Tow more digital for tick.
  24657. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  24658. // Niced extent inside original extent
  24659. var niceTickExtent = result.niceTickExtent = [
  24660. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  24661. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  24662. ];
  24663. fixExtent(niceTickExtent, extent);
  24664. return result;
  24665. }
  24666. /**
  24667. * @param {number} interval
  24668. * @return {number} interval precision
  24669. */
  24670. function getIntervalPrecision(interval) {
  24671. // Tow more digital for tick.
  24672. return getPrecisionSafe(interval) + 2;
  24673. }
  24674. function clamp(niceTickExtent, idx, extent) {
  24675. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  24676. }
  24677. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  24678. function fixExtent(niceTickExtent, extent) {
  24679. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  24680. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  24681. clamp(niceTickExtent, 0, extent);
  24682. clamp(niceTickExtent, 1, extent);
  24683. if (niceTickExtent[0] > niceTickExtent[1]) {
  24684. niceTickExtent[0] = niceTickExtent[1];
  24685. }
  24686. }
  24687. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  24688. var ticks = [];
  24689. // If interval is 0, return [];
  24690. if (!interval) {
  24691. return ticks;
  24692. }
  24693. // Consider this case: using dataZoom toolbox, zoom and zoom.
  24694. var safeLimit = 10000;
  24695. if (extent[0] < niceTickExtent[0]) {
  24696. ticks.push(extent[0]);
  24697. }
  24698. var tick = niceTickExtent[0];
  24699. while (tick <= niceTickExtent[1]) {
  24700. ticks.push(tick);
  24701. // Avoid rounding error
  24702. tick = roundNumber$1(tick + interval, intervalPrecision);
  24703. if (tick === ticks[ticks.length - 1]) {
  24704. // Consider out of safe float point, e.g.,
  24705. // -3711126.9907707 + 2e-10 === -3711126.9907707
  24706. break;
  24707. }
  24708. if (ticks.length > safeLimit) {
  24709. return [];
  24710. }
  24711. }
  24712. // Consider this case: the last item of ticks is smaller
  24713. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  24714. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  24715. ticks.push(extent[1]);
  24716. }
  24717. return ticks;
  24718. }
  24719. /**
  24720. * Interval scale
  24721. * @module echarts/scale/Interval
  24722. */
  24723. var roundNumber = round$1;
  24724. /**
  24725. * @alias module:echarts/coord/scale/Interval
  24726. * @constructor
  24727. */
  24728. var IntervalScale = Scale.extend({
  24729. type: 'interval',
  24730. _interval: 0,
  24731. _intervalPrecision: 2,
  24732. setExtent: function (start, end) {
  24733. var thisExtent = this._extent;
  24734. //start,end may be a Number like '25',so...
  24735. if (!isNaN(start)) {
  24736. thisExtent[0] = parseFloat(start);
  24737. }
  24738. if (!isNaN(end)) {
  24739. thisExtent[1] = parseFloat(end);
  24740. }
  24741. },
  24742. unionExtent: function (other) {
  24743. var extent = this._extent;
  24744. other[0] < extent[0] && (extent[0] = other[0]);
  24745. other[1] > extent[1] && (extent[1] = other[1]);
  24746. // unionExtent may called by it's sub classes
  24747. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  24748. },
  24749. /**
  24750. * Get interval
  24751. */
  24752. getInterval: function () {
  24753. return this._interval;
  24754. },
  24755. /**
  24756. * Set interval
  24757. */
  24758. setInterval: function (interval) {
  24759. this._interval = interval;
  24760. // Dropped auto calculated niceExtent and use user setted extent
  24761. // We assume user wan't to set both interval, min, max to get a better result
  24762. this._niceExtent = this._extent.slice();
  24763. this._intervalPrecision = getIntervalPrecision(interval);
  24764. },
  24765. /**
  24766. * @return {Array.<number>}
  24767. */
  24768. getTicks: function () {
  24769. return intervalScaleGetTicks(
  24770. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  24771. );
  24772. },
  24773. /**
  24774. * @return {Array.<string>}
  24775. */
  24776. getTicksLabels: function () {
  24777. var labels = [];
  24778. var ticks = this.getTicks();
  24779. for (var i = 0; i < ticks.length; i++) {
  24780. labels.push(this.getLabel(ticks[i]));
  24781. }
  24782. return labels;
  24783. },
  24784. /**
  24785. * @param {number} data
  24786. * @param {Object} [opt]
  24787. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  24788. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  24789. * @return {string}
  24790. */
  24791. getLabel: function (data, opt) {
  24792. if (data == null) {
  24793. return '';
  24794. }
  24795. var precision = opt && opt.precision;
  24796. if (precision == null) {
  24797. precision = getPrecisionSafe(data) || 0;
  24798. }
  24799. else if (precision === 'auto') {
  24800. // Should be more precise then tick.
  24801. precision = this._intervalPrecision;
  24802. }
  24803. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  24804. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  24805. data = roundNumber(data, precision, true);
  24806. return addCommas(data);
  24807. },
  24808. /**
  24809. * Update interval and extent of intervals for nice ticks
  24810. *
  24811. * @param {number} [splitNumber = 5] Desired number of ticks
  24812. * @param {number} [minInterval]
  24813. * @param {number} [maxInterval]
  24814. */
  24815. niceTicks: function (splitNumber, minInterval, maxInterval) {
  24816. splitNumber = splitNumber || 5;
  24817. var extent = this._extent;
  24818. var span = extent[1] - extent[0];
  24819. if (!isFinite(span)) {
  24820. return;
  24821. }
  24822. // User may set axis min 0 and data are all negative
  24823. // FIXME If it needs to reverse ?
  24824. if (span < 0) {
  24825. span = -span;
  24826. extent.reverse();
  24827. }
  24828. var result = intervalScaleNiceTicks(
  24829. extent, splitNumber, minInterval, maxInterval
  24830. );
  24831. this._intervalPrecision = result.intervalPrecision;
  24832. this._interval = result.interval;
  24833. this._niceExtent = result.niceTickExtent;
  24834. },
  24835. /**
  24836. * Nice extent.
  24837. * @param {Object} opt
  24838. * @param {number} [opt.splitNumber = 5] Given approx tick number
  24839. * @param {boolean} [opt.fixMin=false]
  24840. * @param {boolean} [opt.fixMax=false]
  24841. * @param {boolean} [opt.minInterval]
  24842. * @param {boolean} [opt.maxInterval]
  24843. */
  24844. niceExtent: function (opt) {
  24845. var extent = this._extent;
  24846. // If extent start and end are same, expand them
  24847. if (extent[0] === extent[1]) {
  24848. if (extent[0] !== 0) {
  24849. // Expand extent
  24850. var expandSize = extent[0];
  24851. // In the fowllowing case
  24852. // Axis has been fixed max 100
  24853. // Plus data are all 100 and axis extent are [100, 100].
  24854. // Extend to the both side will cause expanded max is larger than fixed max.
  24855. // So only expand to the smaller side.
  24856. if (!opt.fixMax) {
  24857. extent[1] += expandSize / 2;
  24858. extent[0] -= expandSize / 2;
  24859. }
  24860. else {
  24861. extent[0] -= expandSize / 2;
  24862. }
  24863. }
  24864. else {
  24865. extent[1] = 1;
  24866. }
  24867. }
  24868. var span = extent[1] - extent[0];
  24869. // If there are no data and extent are [Infinity, -Infinity]
  24870. if (!isFinite(span)) {
  24871. extent[0] = 0;
  24872. extent[1] = 1;
  24873. }
  24874. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  24875. // var extent = this._extent;
  24876. var interval = this._interval;
  24877. if (!opt.fixMin) {
  24878. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  24879. }
  24880. if (!opt.fixMax) {
  24881. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  24882. }
  24883. }
  24884. });
  24885. /**
  24886. * @return {module:echarts/scale/Time}
  24887. */
  24888. IntervalScale.create = function () {
  24889. return new IntervalScale();
  24890. };
  24891. var STACK_PREFIX = '__ec_stack_';
  24892. function getSeriesStackId(seriesModel) {
  24893. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  24894. }
  24895. function getAxisKey(axis) {
  24896. return axis.dim + axis.index;
  24897. }
  24898. /**
  24899. * @param {Object} opt
  24900. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  24901. * @param {number} opt.count Positive interger.
  24902. * @param {number} [opt.barWidth]
  24903. * @param {number} [opt.barMaxWidth]
  24904. * @param {number} [opt.barGap]
  24905. * @param {number} [opt.barCategoryGap]
  24906. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  24907. */
  24908. function calBarWidthAndOffset(barSeries, api) {
  24909. var seriesInfoList = map(barSeries, function (seriesModel) {
  24910. var data = seriesModel.getData();
  24911. var cartesian = seriesModel.coordinateSystem;
  24912. var baseAxis = cartesian.getBaseAxis();
  24913. var axisExtent = baseAxis.getExtent();
  24914. var bandWidth = baseAxis.type === 'category'
  24915. ? baseAxis.getBandWidth()
  24916. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  24917. var barWidth = parsePercent$1(
  24918. seriesModel.get('barWidth'), bandWidth
  24919. );
  24920. var barMaxWidth = parsePercent$1(
  24921. seriesModel.get('barMaxWidth'), bandWidth
  24922. );
  24923. var barGap = seriesModel.get('barGap');
  24924. var barCategoryGap = seriesModel.get('barCategoryGap');
  24925. return {
  24926. bandWidth: bandWidth,
  24927. barWidth: barWidth,
  24928. barMaxWidth: barMaxWidth,
  24929. barGap: barGap,
  24930. barCategoryGap: barCategoryGap,
  24931. axisKey: getAxisKey(baseAxis),
  24932. stackId: getSeriesStackId(seriesModel)
  24933. };
  24934. });
  24935. return doCalBarWidthAndOffset(seriesInfoList, api);
  24936. }
  24937. function doCalBarWidthAndOffset(seriesInfoList, api) {
  24938. // Columns info on each category axis. Key is cartesian name
  24939. var columnsMap = {};
  24940. each$1(seriesInfoList, function (seriesInfo, idx) {
  24941. var axisKey = seriesInfo.axisKey;
  24942. var bandWidth = seriesInfo.bandWidth;
  24943. var columnsOnAxis = columnsMap[axisKey] || {
  24944. bandWidth: bandWidth,
  24945. remainedWidth: bandWidth,
  24946. autoWidthCount: 0,
  24947. categoryGap: '20%',
  24948. gap: '30%',
  24949. stacks: {}
  24950. };
  24951. var stacks = columnsOnAxis.stacks;
  24952. columnsMap[axisKey] = columnsOnAxis;
  24953. var stackId = seriesInfo.stackId;
  24954. if (!stacks[stackId]) {
  24955. columnsOnAxis.autoWidthCount++;
  24956. }
  24957. stacks[stackId] = stacks[stackId] || {
  24958. width: 0,
  24959. maxWidth: 0
  24960. };
  24961. // Caution: In a single coordinate system, these barGrid attributes
  24962. // will be shared by series. Consider that they have default values,
  24963. // only the attributes set on the last series will work.
  24964. // Do not change this fact unless there will be a break change.
  24965. // TODO
  24966. var barWidth = seriesInfo.barWidth;
  24967. if (barWidth && !stacks[stackId].width) {
  24968. // See #6312, do not restrict width.
  24969. stacks[stackId].width = barWidth;
  24970. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  24971. columnsOnAxis.remainedWidth -= barWidth;
  24972. }
  24973. var barMaxWidth = seriesInfo.barMaxWidth;
  24974. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  24975. var barGap = seriesInfo.barGap;
  24976. (barGap != null) && (columnsOnAxis.gap = barGap);
  24977. var barCategoryGap = seriesInfo.barCategoryGap;
  24978. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  24979. });
  24980. var result = {};
  24981. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  24982. result[coordSysName] = {};
  24983. var stacks = columnsOnAxis.stacks;
  24984. var bandWidth = columnsOnAxis.bandWidth;
  24985. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  24986. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  24987. var remainedWidth = columnsOnAxis.remainedWidth;
  24988. var autoWidthCount = columnsOnAxis.autoWidthCount;
  24989. var autoWidth = (remainedWidth - categoryGap)
  24990. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  24991. autoWidth = Math.max(autoWidth, 0);
  24992. // Find if any auto calculated bar exceeded maxBarWidth
  24993. each$1(stacks, function (column, stack) {
  24994. var maxWidth = column.maxWidth;
  24995. if (maxWidth && maxWidth < autoWidth) {
  24996. maxWidth = Math.min(maxWidth, remainedWidth);
  24997. if (column.width) {
  24998. maxWidth = Math.min(maxWidth, column.width);
  24999. }
  25000. remainedWidth -= maxWidth;
  25001. column.width = maxWidth;
  25002. autoWidthCount--;
  25003. }
  25004. });
  25005. // Recalculate width again
  25006. autoWidth = (remainedWidth - categoryGap)
  25007. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25008. autoWidth = Math.max(autoWidth, 0);
  25009. var widthSum = 0;
  25010. var lastColumn;
  25011. each$1(stacks, function (column, idx) {
  25012. if (!column.width) {
  25013. column.width = autoWidth;
  25014. }
  25015. lastColumn = column;
  25016. widthSum += column.width * (1 + barGapPercent);
  25017. });
  25018. if (lastColumn) {
  25019. widthSum -= lastColumn.width * barGapPercent;
  25020. }
  25021. var offset = -widthSum / 2;
  25022. each$1(stacks, function (column, stackId) {
  25023. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25024. offset: offset,
  25025. width: column.width
  25026. };
  25027. offset += column.width * (1 + barGapPercent);
  25028. });
  25029. });
  25030. return result;
  25031. }
  25032. /**
  25033. * @param {string} seriesType
  25034. * @param {module:echarts/model/Global} ecModel
  25035. * @param {module:echarts/ExtensionAPI} api
  25036. */
  25037. function layout(seriesType, ecModel, api) {
  25038. var barWidthAndOffset = calBarWidthAndOffset(
  25039. filter(
  25040. ecModel.getSeriesByType(seriesType),
  25041. function (seriesModel) {
  25042. return !ecModel.isSeriesFiltered(seriesModel)
  25043. && seriesModel.coordinateSystem
  25044. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25045. }
  25046. )
  25047. );
  25048. var lastStackCoords = {};
  25049. var lastStackCoordsOrigin = {};
  25050. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25051. // Check series coordinate, do layout for cartesian2d only
  25052. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  25053. return;
  25054. }
  25055. var data = seriesModel.getData();
  25056. var cartesian = seriesModel.coordinateSystem;
  25057. var baseAxis = cartesian.getBaseAxis();
  25058. var stackId = getSeriesStackId(seriesModel);
  25059. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25060. var columnOffset = columnLayoutInfo.offset;
  25061. var columnWidth = columnLayoutInfo.width;
  25062. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25063. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25064. var valueAxisStart = baseAxis.onZero
  25065. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25066. : valueAxis.getGlobalExtent()[0];
  25067. var coordDims = [
  25068. data.mapDimension('x'),
  25069. data.mapDimension('y')
  25070. ];
  25071. var coords = data.mapArray(coordDims, function (x, y) {
  25072. return cartesian.dataToPoint([x, y]);
  25073. }, true);
  25074. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25075. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  25076. data.setLayout({
  25077. offset: columnOffset,
  25078. size: columnWidth
  25079. });
  25080. data.each(data.mapDimension(valueAxis.dim), function (value, idx) {
  25081. if (isNaN(value)) {
  25082. return;
  25083. }
  25084. if (!lastStackCoords[stackId][idx]) {
  25085. lastStackCoords[stackId][idx] = {
  25086. p: valueAxisStart, // Positive stack
  25087. n: valueAxisStart // Negative stack
  25088. };
  25089. lastStackCoordsOrigin[stackId][idx] = {
  25090. p: valueAxisStart, // Positive stack
  25091. n: valueAxisStart // Negative stack
  25092. };
  25093. }
  25094. var sign = value >= 0 ? 'p' : 'n';
  25095. var coord = coords[idx];
  25096. var lastCoord = lastStackCoords[stackId][idx][sign];
  25097. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  25098. var x;
  25099. var y;
  25100. var width;
  25101. var height;
  25102. if (valueAxis.isHorizontal()) {
  25103. x = lastCoord;
  25104. y = coord[1] + columnOffset;
  25105. width = coord[0] - lastCoordOrigin;
  25106. height = columnWidth;
  25107. lastStackCoordsOrigin[stackId][idx][sign] += width;
  25108. if (Math.abs(width) < barMinHeight) {
  25109. width = (width < 0 ? -1 : 1) * barMinHeight;
  25110. }
  25111. lastStackCoords[stackId][idx][sign] += width;
  25112. }
  25113. else {
  25114. x = coord[0] + columnOffset;
  25115. y = lastCoord;
  25116. width = columnWidth;
  25117. height = coord[1] - lastCoordOrigin;
  25118. lastStackCoordsOrigin[stackId][idx][sign] += height;
  25119. if (Math.abs(height) < barMinHeight) {
  25120. // Include zero to has a positive bar
  25121. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25122. }
  25123. lastStackCoords[stackId][idx][sign] += height;
  25124. }
  25125. data.setItemLayout(idx, {
  25126. x: x,
  25127. y: y,
  25128. width: width,
  25129. height: height
  25130. });
  25131. }, true);
  25132. }, this);
  25133. }
  25134. // [About UTC and local time zone]:
  25135. // In most cases, `number.parseDate` will treat input data string as local time
  25136. // (except time zone is specified in time string). And `format.formateTime` returns
  25137. // local time by default. option.useUTC is false by default. This design have
  25138. // concidered these common case:
  25139. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25140. // in local time by default.
  25141. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25142. // as its original time, without any time difference.
  25143. var intervalScaleProto = IntervalScale.prototype;
  25144. var mathCeil = Math.ceil;
  25145. var mathFloor = Math.floor;
  25146. var ONE_SECOND = 1000;
  25147. var ONE_MINUTE = ONE_SECOND * 60;
  25148. var ONE_HOUR = ONE_MINUTE * 60;
  25149. var ONE_DAY = ONE_HOUR * 24;
  25150. // FIXME 公用?
  25151. var bisect = function (a, x, lo, hi) {
  25152. while (lo < hi) {
  25153. var mid = lo + hi >>> 1;
  25154. if (a[mid][1] < x) {
  25155. lo = mid + 1;
  25156. }
  25157. else {
  25158. hi = mid;
  25159. }
  25160. }
  25161. return lo;
  25162. };
  25163. /**
  25164. * @alias module:echarts/coord/scale/Time
  25165. * @constructor
  25166. */
  25167. var TimeScale = IntervalScale.extend({
  25168. type: 'time',
  25169. /**
  25170. * @override
  25171. */
  25172. getLabel: function (val) {
  25173. var stepLvl = this._stepLvl;
  25174. var date = new Date(val);
  25175. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25176. },
  25177. /**
  25178. * @override
  25179. */
  25180. niceExtent: function (opt) {
  25181. var extent = this._extent;
  25182. // If extent start and end are same, expand them
  25183. if (extent[0] === extent[1]) {
  25184. // Expand extent
  25185. extent[0] -= ONE_DAY;
  25186. extent[1] += ONE_DAY;
  25187. }
  25188. // If there are no data and extent are [Infinity, -Infinity]
  25189. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25190. var d = new Date();
  25191. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25192. extent[0] = extent[1] - ONE_DAY;
  25193. }
  25194. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25195. // var extent = this._extent;
  25196. var interval = this._interval;
  25197. if (!opt.fixMin) {
  25198. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25199. }
  25200. if (!opt.fixMax) {
  25201. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25202. }
  25203. },
  25204. /**
  25205. * @override
  25206. */
  25207. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25208. approxTickNum = approxTickNum || 10;
  25209. var extent = this._extent;
  25210. var span = extent[1] - extent[0];
  25211. var approxInterval = span / approxTickNum;
  25212. if (minInterval != null && approxInterval < minInterval) {
  25213. approxInterval = minInterval;
  25214. }
  25215. if (maxInterval != null && approxInterval > maxInterval) {
  25216. approxInterval = maxInterval;
  25217. }
  25218. var scaleLevelsLen = scaleLevels.length;
  25219. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25220. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25221. var interval = level[1];
  25222. // Same with interval scale if span is much larger than 1 year
  25223. if (level[0] === 'year') {
  25224. var yearSpan = span / interval;
  25225. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25226. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25227. var yearStep = nice(yearSpan / approxTickNum, true);
  25228. interval *= yearStep;
  25229. }
  25230. var timezoneOffset = this.getSetting('useUTC')
  25231. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25232. var niceExtent = [
  25233. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25234. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25235. ];
  25236. fixExtent(niceExtent, extent);
  25237. this._stepLvl = level;
  25238. // Interval will be used in getTicks
  25239. this._interval = interval;
  25240. this._niceExtent = niceExtent;
  25241. },
  25242. parse: function (val) {
  25243. // val might be float.
  25244. return +parseDate(val);
  25245. }
  25246. });
  25247. each$1(['contain', 'normalize'], function (methodName) {
  25248. TimeScale.prototype[methodName] = function (val) {
  25249. return intervalScaleProto[methodName].call(this, this.parse(val));
  25250. };
  25251. });
  25252. // Steps from d3
  25253. var scaleLevels = [
  25254. // Format interval
  25255. ['hh:mm:ss', ONE_SECOND], // 1s
  25256. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25257. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25258. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25259. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25260. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25261. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25262. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25263. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25264. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25265. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25266. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25267. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25268. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25269. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25270. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25271. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25272. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25273. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25274. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25275. ['week', ONE_DAY * 7], // 7d
  25276. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25277. ['week', ONE_DAY * 14], // 2w
  25278. ['week', ONE_DAY * 21], // 3w
  25279. ['month', ONE_DAY * 31], // 1M
  25280. ['week', ONE_DAY * 42], // 6w
  25281. ['month', ONE_DAY * 62], // 2M
  25282. ['week', ONE_DAY * 42], // 10w
  25283. ['quarter', ONE_DAY * 380 / 4], // 3M
  25284. ['month', ONE_DAY * 31 * 4], // 4M
  25285. ['month', ONE_DAY * 31 * 5], // 5M
  25286. ['half-year', ONE_DAY * 380 / 2], // 6M
  25287. ['month', ONE_DAY * 31 * 8], // 8M
  25288. ['month', ONE_DAY * 31 * 10], // 10M
  25289. ['year', ONE_DAY * 380] // 1Y
  25290. ];
  25291. /**
  25292. * @param {module:echarts/model/Model}
  25293. * @return {module:echarts/scale/Time}
  25294. */
  25295. TimeScale.create = function (model) {
  25296. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25297. };
  25298. /**
  25299. * Log scale
  25300. * @module echarts/scale/Log
  25301. */
  25302. // Use some method of IntervalScale
  25303. var scaleProto$1 = Scale.prototype;
  25304. var intervalScaleProto$1 = IntervalScale.prototype;
  25305. var getPrecisionSafe$1 = getPrecisionSafe;
  25306. var roundingErrorFix = round$1;
  25307. var mathFloor$1 = Math.floor;
  25308. var mathCeil$1 = Math.ceil;
  25309. var mathPow$1 = Math.pow;
  25310. var mathLog = Math.log;
  25311. var LogScale = Scale.extend({
  25312. type: 'log',
  25313. base: 10,
  25314. $constructor: function () {
  25315. Scale.apply(this, arguments);
  25316. this._originalScale = new IntervalScale();
  25317. },
  25318. /**
  25319. * @return {Array.<number>}
  25320. */
  25321. getTicks: function () {
  25322. var originalScale = this._originalScale;
  25323. var extent = this._extent;
  25324. var originalExtent = originalScale.getExtent();
  25325. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25326. var powVal = round$1(mathPow$1(this.base, val));
  25327. // Fix #4158
  25328. powVal = (val === extent[0] && originalScale.__fixMin)
  25329. ? fixRoundingError(powVal, originalExtent[0])
  25330. : powVal;
  25331. powVal = (val === extent[1] && originalScale.__fixMax)
  25332. ? fixRoundingError(powVal, originalExtent[1])
  25333. : powVal;
  25334. return powVal;
  25335. }, this);
  25336. },
  25337. /**
  25338. * @param {number} val
  25339. * @return {string}
  25340. */
  25341. getLabel: intervalScaleProto$1.getLabel,
  25342. /**
  25343. * @param {number} val
  25344. * @return {number}
  25345. */
  25346. scale: function (val) {
  25347. val = scaleProto$1.scale.call(this, val);
  25348. return mathPow$1(this.base, val);
  25349. },
  25350. /**
  25351. * @param {number} start
  25352. * @param {number} end
  25353. */
  25354. setExtent: function (start, end) {
  25355. var base = this.base;
  25356. start = mathLog(start) / mathLog(base);
  25357. end = mathLog(end) / mathLog(base);
  25358. intervalScaleProto$1.setExtent.call(this, start, end);
  25359. },
  25360. /**
  25361. * @return {number} end
  25362. */
  25363. getExtent: function () {
  25364. var base = this.base;
  25365. var extent = scaleProto$1.getExtent.call(this);
  25366. extent[0] = mathPow$1(base, extent[0]);
  25367. extent[1] = mathPow$1(base, extent[1]);
  25368. // Fix #4158
  25369. var originalScale = this._originalScale;
  25370. var originalExtent = originalScale.getExtent();
  25371. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25372. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25373. return extent;
  25374. },
  25375. /**
  25376. * @param {Array.<number>} extent
  25377. */
  25378. unionExtent: function (extent) {
  25379. this._originalScale.unionExtent(extent);
  25380. var base = this.base;
  25381. extent[0] = mathLog(extent[0]) / mathLog(base);
  25382. extent[1] = mathLog(extent[1]) / mathLog(base);
  25383. scaleProto$1.unionExtent.call(this, extent);
  25384. },
  25385. /**
  25386. * @override
  25387. */
  25388. unionExtentFromData: function (data, dim) {
  25389. this.unionExtent(data.getApproximateExtent(dim, true, function (val) {
  25390. return val > 0;
  25391. }));
  25392. },
  25393. /**
  25394. * Update interval and extent of intervals for nice ticks
  25395. * @param {number} [approxTickNum = 10] Given approx tick number
  25396. */
  25397. niceTicks: function (approxTickNum) {
  25398. approxTickNum = approxTickNum || 10;
  25399. var extent = this._extent;
  25400. var span = extent[1] - extent[0];
  25401. if (span === Infinity || span <= 0) {
  25402. return;
  25403. }
  25404. var interval = quantity(span);
  25405. var err = approxTickNum / span * interval;
  25406. // Filter ticks to get closer to the desired count.
  25407. if (err <= 0.5) {
  25408. interval *= 10;
  25409. }
  25410. // Interval should be integer
  25411. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  25412. interval *= 10;
  25413. }
  25414. var niceExtent = [
  25415. round$1(mathCeil$1(extent[0] / interval) * interval),
  25416. round$1(mathFloor$1(extent[1] / interval) * interval)
  25417. ];
  25418. this._interval = interval;
  25419. this._niceExtent = niceExtent;
  25420. },
  25421. /**
  25422. * Nice extent.
  25423. * @override
  25424. */
  25425. niceExtent: function (opt) {
  25426. intervalScaleProto$1.niceExtent.call(this, opt);
  25427. var originalScale = this._originalScale;
  25428. originalScale.__fixMin = opt.fixMin;
  25429. originalScale.__fixMax = opt.fixMax;
  25430. }
  25431. });
  25432. each$1(['contain', 'normalize'], function (methodName) {
  25433. LogScale.prototype[methodName] = function (val) {
  25434. val = mathLog(val) / mathLog(this.base);
  25435. return scaleProto$1[methodName].call(this, val);
  25436. };
  25437. });
  25438. LogScale.create = function () {
  25439. return new LogScale();
  25440. };
  25441. function fixRoundingError(val, originalVal) {
  25442. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  25443. }
  25444. /**
  25445. * Get axis scale extent before niced.
  25446. * Item of returned array can only be number (including Infinity and NaN).
  25447. */
  25448. function getScaleExtent(scale, model) {
  25449. var scaleType = scale.type;
  25450. var min = model.getMin();
  25451. var max = model.getMax();
  25452. var fixMin = min != null;
  25453. var fixMax = max != null;
  25454. var originalExtent = scale.getExtent();
  25455. var axisDataLen;
  25456. var boundaryGap;
  25457. var span;
  25458. if (scaleType === 'ordinal') {
  25459. axisDataLen = model.getCategories().length;
  25460. }
  25461. else {
  25462. boundaryGap = model.get('boundaryGap');
  25463. if (!isArray(boundaryGap)) {
  25464. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  25465. }
  25466. if (typeof boundaryGap[0] === 'boolean') {
  25467. if (__DEV__) {
  25468. console.warn('Boolean type for boundaryGap is only '
  25469. + 'allowed for ordinal axis. Please use string in '
  25470. + 'percentage instead, e.g., "20%". Currently, '
  25471. + 'boundaryGap is set to be 0.');
  25472. }
  25473. boundaryGap = [0, 0];
  25474. }
  25475. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  25476. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  25477. span = (originalExtent[1] - originalExtent[0])
  25478. || Math.abs(originalExtent[0]);
  25479. }
  25480. // Notice: When min/max is not set (that is, when there are null/undefined,
  25481. // which is the most common case), these cases should be ensured:
  25482. // (1) For 'ordinal', show all axis.data.
  25483. // (2) For others:
  25484. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  25485. // disabled).
  25486. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  25487. // be the result that originalExtent enlarged by boundaryGap.
  25488. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  25489. // FIXME
  25490. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  25491. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  25492. // that the results processed by boundaryGap are positive/negative?
  25493. if (min == null) {
  25494. min = scaleType === 'ordinal'
  25495. ? (axisDataLen ? 0 : NaN)
  25496. : originalExtent[0] - boundaryGap[0] * span;
  25497. }
  25498. if (max == null) {
  25499. max = scaleType === 'ordinal'
  25500. ? (axisDataLen ? axisDataLen - 1 : NaN)
  25501. : originalExtent[1] + boundaryGap[1] * span;
  25502. }
  25503. if (min === 'dataMin') {
  25504. min = originalExtent[0];
  25505. }
  25506. else if (typeof min === 'function') {
  25507. min = min({
  25508. min: originalExtent[0],
  25509. max: originalExtent[1]
  25510. });
  25511. }
  25512. if (max === 'dataMax') {
  25513. max = originalExtent[1];
  25514. }
  25515. else if (typeof max === 'function') {
  25516. max = max({
  25517. min: originalExtent[0],
  25518. max: originalExtent[1]
  25519. });
  25520. }
  25521. (min == null || !isFinite(min)) && (min = NaN);
  25522. (max == null || !isFinite(max)) && (max = NaN);
  25523. scale.setBlank(eqNaN(min) || eqNaN(max));
  25524. // Evaluate if axis needs cross zero
  25525. if (model.getNeedCrossZero()) {
  25526. // Axis is over zero and min is not set
  25527. if (min > 0 && max > 0 && !fixMin) {
  25528. min = 0;
  25529. }
  25530. // Axis is under zero and max is not set
  25531. if (min < 0 && max < 0 && !fixMax) {
  25532. max = 0;
  25533. }
  25534. }
  25535. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  25536. // is base axis
  25537. var ecModel = model.ecModel;
  25538. if (ecModel) {
  25539. var isBaseAxisAndHasBarSeries = filter(ecModel.getSeriesByType('bar'), function (seriesModel) {
  25540. return seriesModel.getBaseAxis() === model.axis;
  25541. }).length > 0;
  25542. if ((scaleType === 'time' || scaleType === 'interval') && isBaseAxisAndHasBarSeries) {
  25543. // Adjust axis min and max to account for overflow
  25544. var adjustedScale = adjustScaleForOverflow(min, max, model);
  25545. min = adjustedScale.min;
  25546. max = adjustedScale.max;
  25547. }
  25548. }
  25549. return [min, max];
  25550. }
  25551. function adjustScaleForOverflow(min, max, model) {
  25552. var ecModel = model.ecModel;
  25553. // Get Axis Length
  25554. var axisExtent = model.axis.getExtent();
  25555. var axisLength = axisExtent[1] - axisExtent[0];
  25556. // Calculate placement of bars on axis
  25557. var barWidthAndOffset = calBarWidthAndOffset(filter(
  25558. ecModel.getSeriesByType('bar'),
  25559. function (seriesModel) {
  25560. return !ecModel.isSeriesFiltered(seriesModel)
  25561. && seriesModel.coordinateSystem
  25562. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25563. }
  25564. ));
  25565. // Get bars on current base axis and calculate min and max overflow
  25566. var baseAxisKey = model.axis.dim + model.axis.index;
  25567. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  25568. if (barsOnCurrentAxis === undefined) {
  25569. return {min: min, max: max};
  25570. }
  25571. var minOverflow = Infinity;
  25572. each$1(barsOnCurrentAxis, function (item) {
  25573. minOverflow = Math.min(item.offset, minOverflow);
  25574. });
  25575. var maxOverflow = -Infinity;
  25576. each$1(barsOnCurrentAxis, function (item) {
  25577. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  25578. });
  25579. var totalOverFlow = Math.abs(minOverflow) + maxOverflow;
  25580. // Calulate required buffer based on old range and overflow
  25581. var oldRange = max - min;
  25582. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  25583. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  25584. max += overflowBuffer * (maxOverflow / totalOverFlow);
  25585. min -= overflowBuffer * (minOverflow / totalOverFlow);
  25586. return {min: min, max: max};
  25587. }
  25588. function niceScaleExtent(scale, model) {
  25589. var extent = getScaleExtent(scale, model);
  25590. var fixMin = model.getMin() != null;
  25591. var fixMax = model.getMax() != null;
  25592. var splitNumber = model.get('splitNumber');
  25593. if (scale.type === 'log') {
  25594. scale.base = model.get('logBase');
  25595. }
  25596. var scaleType = scale.type;
  25597. scale.setExtent(extent[0], extent[1]);
  25598. scale.niceExtent({
  25599. splitNumber: splitNumber,
  25600. fixMin: fixMin,
  25601. fixMax: fixMax,
  25602. minInterval: (scaleType === 'interval' || scaleType === 'time')
  25603. ? model.get('minInterval') : null,
  25604. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  25605. ? model.get('maxInterval') : null
  25606. });
  25607. // If some one specified the min, max. And the default calculated interval
  25608. // is not good enough. He can specify the interval. It is often appeared
  25609. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  25610. // to be 60.
  25611. // FIXME
  25612. var interval = model.get('interval');
  25613. if (interval != null) {
  25614. scale.setInterval && scale.setInterval(interval);
  25615. }
  25616. }
  25617. /**
  25618. * @param {module:echarts/model/Model} model
  25619. * @param {string} [axisType] Default retrieve from model.type
  25620. * @return {module:echarts/scale/*}
  25621. */
  25622. function createScaleByModel(model, axisType) {
  25623. axisType = axisType || model.get('type');
  25624. if (axisType) {
  25625. switch (axisType) {
  25626. // Buildin scale
  25627. case 'category':
  25628. return new OrdinalScale(
  25629. model.getOrdinalMeta
  25630. ? model.getOrdinalMeta()
  25631. : model.getCategories(),
  25632. [Infinity, -Infinity]
  25633. );
  25634. case 'value':
  25635. return new IntervalScale();
  25636. // Extended scale, like time and log
  25637. default:
  25638. return (Scale.getClass(axisType) || IntervalScale).create(model);
  25639. }
  25640. }
  25641. }
  25642. /**
  25643. * Check if the axis corss 0
  25644. */
  25645. function ifAxisCrossZero(axis) {
  25646. var dataExtent = axis.scale.getExtent();
  25647. var min = dataExtent[0];
  25648. var max = dataExtent[1];
  25649. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  25650. }
  25651. /**
  25652. * @param {Array.<number>} tickCoords In axis self coordinate.
  25653. * @param {Array.<string>} labels
  25654. * @param {string} font
  25655. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  25656. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  25657. * @return {number}
  25658. */
  25659. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  25660. var textSpaceTakenRect;
  25661. var autoLabelInterval = 0;
  25662. var accumulatedLabelInterval = 0;
  25663. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  25664. var step = 1;
  25665. if (labels.length > 40) {
  25666. // Simple optimization for large amount of labels
  25667. step = Math.floor(labels.length / 40);
  25668. }
  25669. for (var i = 0; i < tickCoords.length; i += step) {
  25670. var tickCoord = tickCoords[i];
  25671. // Not precise, do not consider align and vertical align
  25672. // and each distance from axis line yet.
  25673. var rect = getBoundingRect(
  25674. labels[i], font, 'center', 'top'
  25675. );
  25676. rect.x += tickCoord * Math.cos(rotation);
  25677. rect.y += tickCoord * Math.sin(rotation);
  25678. // Magic number
  25679. rect.width *= 1.3;
  25680. rect.height *= 1.3;
  25681. if (!textSpaceTakenRect) {
  25682. textSpaceTakenRect = rect.clone();
  25683. }
  25684. // There is no space for current label;
  25685. else if (textSpaceTakenRect.intersect(rect)) {
  25686. accumulatedLabelInterval++;
  25687. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  25688. }
  25689. else {
  25690. textSpaceTakenRect.union(rect);
  25691. // Reset
  25692. accumulatedLabelInterval = 0;
  25693. }
  25694. }
  25695. if (autoLabelInterval === 0 && step > 1) {
  25696. return step;
  25697. }
  25698. return (autoLabelInterval + 1) * step - 1;
  25699. }
  25700. /**
  25701. * @param {Object} axis
  25702. * @param {Function} labelFormatter
  25703. * @return {Array.<string>}
  25704. */
  25705. function getFormattedLabels(axis, labelFormatter) {
  25706. var scale = axis.scale;
  25707. var labels = scale.getTicksLabels();
  25708. var ticks = scale.getTicks();
  25709. if (typeof labelFormatter === 'string') {
  25710. labelFormatter = (function (tpl) {
  25711. return function (val) {
  25712. return tpl.replace('{value}', val != null ? val : '');
  25713. };
  25714. })(labelFormatter);
  25715. // Consider empty array
  25716. return map(labels, labelFormatter);
  25717. }
  25718. else if (typeof labelFormatter === 'function') {
  25719. return map(ticks, function (tick, idx) {
  25720. return labelFormatter(
  25721. getAxisRawValue(axis, tick),
  25722. idx
  25723. );
  25724. }, this);
  25725. }
  25726. else {
  25727. return labels;
  25728. }
  25729. }
  25730. function getAxisRawValue(axis, value) {
  25731. // In category axis with data zoom, tick is not the original
  25732. // index of axis.data. So tick should not be exposed to user
  25733. // in category axis.
  25734. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  25735. }
  25736. var axisModelCommonMixin = {
  25737. /**
  25738. * Format labels
  25739. * @return {Array.<string>}
  25740. */
  25741. getFormattedLabels: function () {
  25742. return getFormattedLabels(
  25743. this.axis,
  25744. this.get('axisLabel.formatter')
  25745. );
  25746. },
  25747. /**
  25748. * @param {boolean} origin
  25749. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  25750. */
  25751. getMin: function (origin) {
  25752. var option = this.option;
  25753. var min = (!origin && option.rangeStart != null)
  25754. ? option.rangeStart : option.min;
  25755. if (this.axis
  25756. && min != null
  25757. && min !== 'dataMin'
  25758. && typeof min !== 'function'
  25759. && !eqNaN(min)
  25760. ) {
  25761. min = this.axis.scale.parse(min);
  25762. }
  25763. return min;
  25764. },
  25765. /**
  25766. * @param {boolean} origin
  25767. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  25768. */
  25769. getMax: function (origin) {
  25770. var option = this.option;
  25771. var max = (!origin && option.rangeEnd != null)
  25772. ? option.rangeEnd : option.max;
  25773. if (this.axis
  25774. && max != null
  25775. && max !== 'dataMax'
  25776. && typeof max !== 'function'
  25777. && !eqNaN(max)
  25778. ) {
  25779. max = this.axis.scale.parse(max);
  25780. }
  25781. return max;
  25782. },
  25783. /**
  25784. * @return {boolean}
  25785. */
  25786. getNeedCrossZero: function () {
  25787. var option = this.option;
  25788. return (option.rangeStart != null || option.rangeEnd != null)
  25789. ? false : !option.scale;
  25790. },
  25791. /**
  25792. * Should be implemented by each axis model if necessary.
  25793. * @return {module:echarts/model/Component} coordinate system model
  25794. */
  25795. getCoordSysModel: noop,
  25796. /**
  25797. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  25798. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  25799. */
  25800. setRange: function (rangeStart, rangeEnd) {
  25801. this.option.rangeStart = rangeStart;
  25802. this.option.rangeEnd = rangeEnd;
  25803. },
  25804. /**
  25805. * Reset range
  25806. */
  25807. resetRange: function () {
  25808. // rangeStart and rangeEnd is readonly.
  25809. this.option.rangeStart = this.option.rangeEnd = null;
  25810. }
  25811. };
  25812. // Symbol factory
  25813. /**
  25814. * Triangle shape
  25815. * @inner
  25816. */
  25817. var Triangle = extendShape({
  25818. type: 'triangle',
  25819. shape: {
  25820. cx: 0,
  25821. cy: 0,
  25822. width: 0,
  25823. height: 0
  25824. },
  25825. buildPath: function (path, shape) {
  25826. var cx = shape.cx;
  25827. var cy = shape.cy;
  25828. var width = shape.width / 2;
  25829. var height = shape.height / 2;
  25830. path.moveTo(cx, cy - height);
  25831. path.lineTo(cx + width, cy + height);
  25832. path.lineTo(cx - width, cy + height);
  25833. path.closePath();
  25834. }
  25835. });
  25836. /**
  25837. * Diamond shape
  25838. * @inner
  25839. */
  25840. var Diamond = extendShape({
  25841. type: 'diamond',
  25842. shape: {
  25843. cx: 0,
  25844. cy: 0,
  25845. width: 0,
  25846. height: 0
  25847. },
  25848. buildPath: function (path, shape) {
  25849. var cx = shape.cx;
  25850. var cy = shape.cy;
  25851. var width = shape.width / 2;
  25852. var height = shape.height / 2;
  25853. path.moveTo(cx, cy - height);
  25854. path.lineTo(cx + width, cy);
  25855. path.lineTo(cx, cy + height);
  25856. path.lineTo(cx - width, cy);
  25857. path.closePath();
  25858. }
  25859. });
  25860. /**
  25861. * Pin shape
  25862. * @inner
  25863. */
  25864. var Pin = extendShape({
  25865. type: 'pin',
  25866. shape: {
  25867. // x, y on the cusp
  25868. x: 0,
  25869. y: 0,
  25870. width: 0,
  25871. height: 0
  25872. },
  25873. buildPath: function (path, shape) {
  25874. var x = shape.x;
  25875. var y = shape.y;
  25876. var w = shape.width / 5 * 3;
  25877. // Height must be larger than width
  25878. var h = Math.max(w, shape.height);
  25879. var r = w / 2;
  25880. // Dist on y with tangent point and circle center
  25881. var dy = r * r / (h - r);
  25882. var cy = y - h + r + dy;
  25883. var angle = Math.asin(dy / r);
  25884. // Dist on x with tangent point and circle center
  25885. var dx = Math.cos(angle) * r;
  25886. var tanX = Math.sin(angle);
  25887. var tanY = Math.cos(angle);
  25888. var cpLen = r * 0.6;
  25889. var cpLen2 = r * 0.7;
  25890. path.moveTo(x - dx, cy + dy);
  25891. path.arc(
  25892. x, cy, r,
  25893. Math.PI - angle,
  25894. Math.PI * 2 + angle
  25895. );
  25896. path.bezierCurveTo(
  25897. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  25898. x, y - cpLen2,
  25899. x, y
  25900. );
  25901. path.bezierCurveTo(
  25902. x, y - cpLen2,
  25903. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  25904. x - dx, cy + dy
  25905. );
  25906. path.closePath();
  25907. }
  25908. });
  25909. /**
  25910. * Arrow shape
  25911. * @inner
  25912. */
  25913. var Arrow = extendShape({
  25914. type: 'arrow',
  25915. shape: {
  25916. x: 0,
  25917. y: 0,
  25918. width: 0,
  25919. height: 0
  25920. },
  25921. buildPath: function (ctx, shape) {
  25922. var height = shape.height;
  25923. var width = shape.width;
  25924. var x = shape.x;
  25925. var y = shape.y;
  25926. var dx = width / 3 * 2;
  25927. ctx.moveTo(x, y);
  25928. ctx.lineTo(x + dx, y + height);
  25929. ctx.lineTo(x, y + height / 4 * 3);
  25930. ctx.lineTo(x - dx, y + height);
  25931. ctx.lineTo(x, y);
  25932. ctx.closePath();
  25933. }
  25934. });
  25935. /**
  25936. * Map of path contructors
  25937. * @type {Object.<string, module:zrender/graphic/Path>}
  25938. */
  25939. var symbolCtors = {
  25940. line: Line,
  25941. rect: Rect,
  25942. roundRect: Rect,
  25943. square: Rect,
  25944. circle: Circle,
  25945. diamond: Diamond,
  25946. pin: Pin,
  25947. arrow: Arrow,
  25948. triangle: Triangle
  25949. };
  25950. var symbolShapeMakers = {
  25951. line: function (x, y, w, h, shape) {
  25952. // FIXME
  25953. shape.x1 = x;
  25954. shape.y1 = y + h / 2;
  25955. shape.x2 = x + w;
  25956. shape.y2 = y + h / 2;
  25957. },
  25958. rect: function (x, y, w, h, shape) {
  25959. shape.x = x;
  25960. shape.y = y;
  25961. shape.width = w;
  25962. shape.height = h;
  25963. },
  25964. roundRect: function (x, y, w, h, shape) {
  25965. shape.x = x;
  25966. shape.y = y;
  25967. shape.width = w;
  25968. shape.height = h;
  25969. shape.r = Math.min(w, h) / 4;
  25970. },
  25971. square: function (x, y, w, h, shape) {
  25972. var size = Math.min(w, h);
  25973. shape.x = x;
  25974. shape.y = y;
  25975. shape.width = size;
  25976. shape.height = size;
  25977. },
  25978. circle: function (x, y, w, h, shape) {
  25979. // Put circle in the center of square
  25980. shape.cx = x + w / 2;
  25981. shape.cy = y + h / 2;
  25982. shape.r = Math.min(w, h) / 2;
  25983. },
  25984. diamond: function (x, y, w, h, shape) {
  25985. shape.cx = x + w / 2;
  25986. shape.cy = y + h / 2;
  25987. shape.width = w;
  25988. shape.height = h;
  25989. },
  25990. pin: function (x, y, w, h, shape) {
  25991. shape.x = x + w / 2;
  25992. shape.y = y + h / 2;
  25993. shape.width = w;
  25994. shape.height = h;
  25995. },
  25996. arrow: function (x, y, w, h, shape) {
  25997. shape.x = x + w / 2;
  25998. shape.y = y + h / 2;
  25999. shape.width = w;
  26000. shape.height = h;
  26001. },
  26002. triangle: function (x, y, w, h, shape) {
  26003. shape.cx = x + w / 2;
  26004. shape.cy = y + h / 2;
  26005. shape.width = w;
  26006. shape.height = h;
  26007. }
  26008. };
  26009. var symbolBuildProxies = {};
  26010. each$1(symbolCtors, function (Ctor, name) {
  26011. symbolBuildProxies[name] = new Ctor();
  26012. });
  26013. var SymbolClz = extendShape({
  26014. type: 'symbol',
  26015. shape: {
  26016. symbolType: '',
  26017. x: 0,
  26018. y: 0,
  26019. width: 0,
  26020. height: 0
  26021. },
  26022. beforeBrush: function () {
  26023. var style = this.style;
  26024. var shape = this.shape;
  26025. // FIXME
  26026. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26027. style.textPosition = ['50%', '40%'];
  26028. style.textAlign = 'center';
  26029. style.textVerticalAlign = 'middle';
  26030. }
  26031. },
  26032. buildPath: function (ctx, shape, inBundle) {
  26033. var symbolType = shape.symbolType;
  26034. var proxySymbol = symbolBuildProxies[symbolType];
  26035. if (shape.symbolType !== 'none') {
  26036. if (!proxySymbol) {
  26037. // Default rect
  26038. symbolType = 'rect';
  26039. proxySymbol = symbolBuildProxies[symbolType];
  26040. }
  26041. symbolShapeMakers[symbolType](
  26042. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26043. );
  26044. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26045. }
  26046. }
  26047. });
  26048. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26049. function symbolPathSetColor(color, innerColor) {
  26050. if (this.type !== 'image') {
  26051. var symbolStyle = this.style;
  26052. var symbolShape = this.shape;
  26053. if (symbolShape && symbolShape.symbolType === 'line') {
  26054. symbolStyle.stroke = color;
  26055. }
  26056. else if (this.__isEmptyBrush) {
  26057. symbolStyle.stroke = color;
  26058. symbolStyle.fill = innerColor || '#fff';
  26059. }
  26060. else {
  26061. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26062. symbolStyle.fill && (symbolStyle.fill = color);
  26063. symbolStyle.stroke && (symbolStyle.stroke = color);
  26064. }
  26065. this.dirty(false);
  26066. }
  26067. }
  26068. /**
  26069. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26070. * @param {string} symbolType
  26071. * @param {number} x
  26072. * @param {number} y
  26073. * @param {number} w
  26074. * @param {number} h
  26075. * @param {string} color
  26076. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26077. * for path and image only.
  26078. */
  26079. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26080. // TODO Support image object, DynamicImage.
  26081. var isEmpty = symbolType.indexOf('empty') === 0;
  26082. if (isEmpty) {
  26083. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26084. }
  26085. var symbolPath;
  26086. if (symbolType.indexOf('image://') === 0) {
  26087. symbolPath = makeImage(
  26088. symbolType.slice(8),
  26089. new BoundingRect(x, y, w, h),
  26090. keepAspect ? 'center' : 'cover'
  26091. );
  26092. }
  26093. else if (symbolType.indexOf('path://') === 0) {
  26094. symbolPath = makePath(
  26095. symbolType.slice(7),
  26096. {},
  26097. new BoundingRect(x, y, w, h),
  26098. keepAspect ? 'center' : 'cover'
  26099. );
  26100. }
  26101. else {
  26102. symbolPath = new SymbolClz({
  26103. shape: {
  26104. symbolType: symbolType,
  26105. x: x,
  26106. y: y,
  26107. width: w,
  26108. height: h
  26109. }
  26110. });
  26111. }
  26112. symbolPath.__isEmptyBrush = isEmpty;
  26113. symbolPath.setColor = symbolPathSetColor;
  26114. symbolPath.setColor(color);
  26115. return symbolPath;
  26116. }
  26117. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26118. /**
  26119. * Create a muti dimension List structure from seriesModel.
  26120. * @param {module:echarts/model/Model} seriesModel
  26121. * @return {module:echarts/data/List} list
  26122. */
  26123. function createList(seriesModel) {
  26124. return createListFromArray(seriesModel.getSource(), seriesModel);
  26125. }
  26126. /**
  26127. * Create scale
  26128. * @param {Array.<number>} dataExtent
  26129. * @param {Object|module:echarts/Model} option
  26130. */
  26131. function createScale(dataExtent, option) {
  26132. var axisModel = option;
  26133. if (!Model.isInstance(option)) {
  26134. axisModel = new Model(option);
  26135. mixin(axisModel, axisModelCommonMixin);
  26136. }
  26137. var scale = createScaleByModel(axisModel);
  26138. scale.setExtent(dataExtent[0], dataExtent[1]);
  26139. niceScaleExtent(scale, axisModel);
  26140. return scale;
  26141. }
  26142. /**
  26143. * Mixin common methods to axis model,
  26144. *
  26145. * Inlcude methods
  26146. * `getFormattedLabels() => Array.<string>`
  26147. * `getCategories() => Array.<string>`
  26148. * `getMin(origin: boolean) => number`
  26149. * `getMax(origin: boolean) => number`
  26150. * `getNeedCrossZero() => boolean`
  26151. * `setRange(start: number, end: number)`
  26152. * `resetRange()`
  26153. */
  26154. function mixinAxisModelCommonMethods(Model$$1) {
  26155. mixin(Model$$1, axisModelCommonMixin);
  26156. }
  26157. var helper = (Object.freeze || Object)({
  26158. createList: createList,
  26159. getLayoutRect: getLayoutRect,
  26160. createScale: createScale,
  26161. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26162. completeDimensions: completeDimensions,
  26163. createDimensions: createDimensions,
  26164. createSymbol: createSymbol
  26165. });
  26166. var EPSILON$3 = 1e-8;
  26167. function isAroundEqual$1(a, b) {
  26168. return Math.abs(a - b) < EPSILON$3;
  26169. }
  26170. function contain$1(points, x, y) {
  26171. var w = 0;
  26172. var p = points[0];
  26173. if (!p) {
  26174. return false;
  26175. }
  26176. for (var i = 1; i < points.length; i++) {
  26177. var p2 = points[i];
  26178. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26179. p = p2;
  26180. }
  26181. // Close polygon
  26182. var p0 = points[0];
  26183. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26184. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26185. }
  26186. return w !== 0;
  26187. }
  26188. /**
  26189. * @module echarts/coord/geo/Region
  26190. */
  26191. /**
  26192. * @param {string} name
  26193. * @param {Array} geometries
  26194. * @param {Array.<number>} cp
  26195. */
  26196. function Region(name, geometries, cp) {
  26197. /**
  26198. * @type {string}
  26199. * @readOnly
  26200. */
  26201. this.name = name;
  26202. /**
  26203. * @type {Array.<Array>}
  26204. * @readOnly
  26205. */
  26206. this.geometries = geometries;
  26207. if (!cp) {
  26208. var rect = this.getBoundingRect();
  26209. cp = [
  26210. rect.x + rect.width / 2,
  26211. rect.y + rect.height / 2
  26212. ];
  26213. }
  26214. else {
  26215. cp = [cp[0], cp[1]];
  26216. }
  26217. /**
  26218. * @type {Array.<number>}
  26219. */
  26220. this.center = cp;
  26221. }
  26222. Region.prototype = {
  26223. constructor: Region,
  26224. properties: null,
  26225. /**
  26226. * @return {module:zrender/core/BoundingRect}
  26227. */
  26228. getBoundingRect: function () {
  26229. var rect = this._rect;
  26230. if (rect) {
  26231. return rect;
  26232. }
  26233. var MAX_NUMBER = Number.MAX_VALUE;
  26234. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26235. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26236. var min2 = [];
  26237. var max2 = [];
  26238. var geometries = this.geometries;
  26239. for (var i = 0; i < geometries.length; i++) {
  26240. // Only support polygon
  26241. if (geometries[i].type !== 'polygon') {
  26242. continue;
  26243. }
  26244. // Doesn't consider hole
  26245. var exterior = geometries[i].exterior;
  26246. fromPoints(exterior, min2, max2);
  26247. min(min$$1, min$$1, min2);
  26248. max(max$$1, max$$1, max2);
  26249. }
  26250. // No data
  26251. if (i === 0) {
  26252. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26253. }
  26254. return (this._rect = new BoundingRect(
  26255. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26256. ));
  26257. },
  26258. /**
  26259. * @param {<Array.<number>} coord
  26260. * @return {boolean}
  26261. */
  26262. contain: function (coord) {
  26263. var rect = this.getBoundingRect();
  26264. var geometries = this.geometries;
  26265. if (!rect.contain(coord[0], coord[1])) {
  26266. return false;
  26267. }
  26268. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26269. // Only support polygon.
  26270. if (geometries[i].type !== 'polygon') {
  26271. continue;
  26272. }
  26273. var exterior = geometries[i].exterior;
  26274. var interiors = geometries[i].interiors;
  26275. if (contain$1(exterior, coord[0], coord[1])) {
  26276. // Not in the region if point is in the hole.
  26277. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26278. if (contain$1(interiors[k])) {
  26279. continue loopGeo;
  26280. }
  26281. }
  26282. return true;
  26283. }
  26284. }
  26285. return false;
  26286. },
  26287. transformTo: function (x, y, width, height) {
  26288. var rect = this.getBoundingRect();
  26289. var aspect = rect.width / rect.height;
  26290. if (!width) {
  26291. width = aspect * height;
  26292. }
  26293. else if (!height) {
  26294. height = width / aspect ;
  26295. }
  26296. var target = new BoundingRect(x, y, width, height);
  26297. var transform = rect.calculateTransform(target);
  26298. var geometries = this.geometries;
  26299. for (var i = 0; i < geometries.length; i++) {
  26300. // Only support polygon.
  26301. if (geometries[i].type !== 'polygon') {
  26302. continue;
  26303. }
  26304. var exterior = geometries[i].exterior;
  26305. var interiors = geometries[i].interiors;
  26306. for (var p = 0; p < exterior.length; p++) {
  26307. applyTransform(exterior[p], exterior[p], transform);
  26308. }
  26309. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26310. for (var p = 0; p < interiors[h].length; p++) {
  26311. applyTransform(interiors[h][p], interiors[h][p], transform);
  26312. }
  26313. }
  26314. }
  26315. rect = this._rect;
  26316. rect.copy(target);
  26317. // Update center
  26318. this.center = [
  26319. rect.x + rect.width / 2,
  26320. rect.y + rect.height / 2
  26321. ];
  26322. }
  26323. };
  26324. /**
  26325. * Parse and decode geo json
  26326. * @module echarts/coord/geo/parseGeoJson
  26327. */
  26328. function decode(json) {
  26329. if (!json.UTF8Encoding) {
  26330. return json;
  26331. }
  26332. var encodeScale = json.UTF8Scale;
  26333. if (encodeScale == null) {
  26334. encodeScale = 1024;
  26335. }
  26336. var features = json.features;
  26337. for (var f = 0; f < features.length; f++) {
  26338. var feature = features[f];
  26339. var geometry = feature.geometry;
  26340. var coordinates = geometry.coordinates;
  26341. var encodeOffsets = geometry.encodeOffsets;
  26342. for (var c = 0; c < coordinates.length; c++) {
  26343. var coordinate = coordinates[c];
  26344. if (geometry.type === 'Polygon') {
  26345. coordinates[c] = decodePolygon(
  26346. coordinate,
  26347. encodeOffsets[c],
  26348. encodeScale
  26349. );
  26350. }
  26351. else if (geometry.type === 'MultiPolygon') {
  26352. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26353. var polygon = coordinate[c2];
  26354. coordinate[c2] = decodePolygon(
  26355. polygon,
  26356. encodeOffsets[c][c2],
  26357. encodeScale
  26358. );
  26359. }
  26360. }
  26361. }
  26362. }
  26363. // Has been decoded
  26364. json.UTF8Encoding = false;
  26365. return json;
  26366. }
  26367. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26368. var result = [];
  26369. var prevX = encodeOffsets[0];
  26370. var prevY = encodeOffsets[1];
  26371. for (var i = 0; i < coordinate.length; i += 2) {
  26372. var x = coordinate.charCodeAt(i) - 64;
  26373. var y = coordinate.charCodeAt(i + 1) - 64;
  26374. // ZigZag decoding
  26375. x = (x >> 1) ^ (-(x & 1));
  26376. y = (y >> 1) ^ (-(y & 1));
  26377. // Delta deocding
  26378. x += prevX;
  26379. y += prevY;
  26380. prevX = x;
  26381. prevY = y;
  26382. // Dequantize
  26383. result.push([x / encodeScale, y / encodeScale]);
  26384. }
  26385. return result;
  26386. }
  26387. /**
  26388. * @alias module:echarts/coord/geo/parseGeoJson
  26389. * @param {Object} geoJson
  26390. * @return {module:zrender/container/Group}
  26391. */
  26392. var parseGeoJSON = function (geoJson) {
  26393. decode(geoJson);
  26394. return map(filter(geoJson.features, function (featureObj) {
  26395. // Output of mapshaper may have geometry null
  26396. return featureObj.geometry
  26397. && featureObj.properties
  26398. && featureObj.geometry.coordinates.length > 0;
  26399. }), function (featureObj) {
  26400. var properties = featureObj.properties;
  26401. var geo = featureObj.geometry;
  26402. var coordinates = geo.coordinates;
  26403. var geometries = [];
  26404. if (geo.type === 'Polygon') {
  26405. geometries.push({
  26406. type: 'polygon',
  26407. // According to the GeoJSON specification.
  26408. // First must be exterior, and the rest are all interior(holes).
  26409. exterior: coordinates[0],
  26410. interiors: coordinates.slice(1)
  26411. });
  26412. }
  26413. if (geo.type === 'MultiPolygon') {
  26414. each$1(coordinates, function (item) {
  26415. if (item[0]) {
  26416. geometries.push({
  26417. type: 'polygon',
  26418. exterior: item[0],
  26419. interiors: item.slice(1)
  26420. });
  26421. }
  26422. });
  26423. }
  26424. var region = new Region(
  26425. properties.name,
  26426. geometries,
  26427. properties.cp
  26428. );
  26429. region.properties = properties;
  26430. return region;
  26431. });
  26432. };
  26433. var linearMap$1 = linearMap;
  26434. function fixExtentWithBands(extent, nTick) {
  26435. var size = extent[1] - extent[0];
  26436. var len = nTick;
  26437. var margin = size / len / 2;
  26438. extent[0] += margin;
  26439. extent[1] -= margin;
  26440. }
  26441. var normalizedExtent = [0, 1];
  26442. /**
  26443. * @name module:echarts/coord/CartesianAxis
  26444. * @constructor
  26445. */
  26446. var Axis = function (dim, scale, extent) {
  26447. /**
  26448. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  26449. * @type {string}
  26450. */
  26451. this.dim = dim;
  26452. /**
  26453. * Axis scale
  26454. * @type {module:echarts/coord/scale/*}
  26455. */
  26456. this.scale = scale;
  26457. /**
  26458. * @type {Array.<number>}
  26459. * @private
  26460. */
  26461. this._extent = extent || [0, 0];
  26462. /**
  26463. * @type {boolean}
  26464. */
  26465. this.inverse = false;
  26466. /**
  26467. * Usually true when axis has a ordinal scale
  26468. * @type {boolean}
  26469. */
  26470. this.onBand = false;
  26471. /**
  26472. * @private
  26473. * @type {number}
  26474. */
  26475. this._labelInterval;
  26476. };
  26477. Axis.prototype = {
  26478. constructor: Axis,
  26479. /**
  26480. * If axis extent contain given coord
  26481. * @param {number} coord
  26482. * @return {boolean}
  26483. */
  26484. contain: function (coord) {
  26485. var extent = this._extent;
  26486. var min = Math.min(extent[0], extent[1]);
  26487. var max = Math.max(extent[0], extent[1]);
  26488. return coord >= min && coord <= max;
  26489. },
  26490. /**
  26491. * If axis extent contain given data
  26492. * @param {number} data
  26493. * @return {boolean}
  26494. */
  26495. containData: function (data) {
  26496. return this.contain(this.dataToCoord(data));
  26497. },
  26498. /**
  26499. * Get coord extent.
  26500. * @return {Array.<number>}
  26501. */
  26502. getExtent: function () {
  26503. return this._extent.slice();
  26504. },
  26505. /**
  26506. * Get precision used for formatting
  26507. * @param {Array.<number>} [dataExtent]
  26508. * @return {number}
  26509. */
  26510. getPixelPrecision: function (dataExtent) {
  26511. return getPixelPrecision(
  26512. dataExtent || this.scale.getExtent(),
  26513. this._extent
  26514. );
  26515. },
  26516. /**
  26517. * Set coord extent
  26518. * @param {number} start
  26519. * @param {number} end
  26520. */
  26521. setExtent: function (start, end) {
  26522. var extent = this._extent;
  26523. extent[0] = start;
  26524. extent[1] = end;
  26525. },
  26526. /**
  26527. * Convert data to coord. Data is the rank if it has a ordinal scale
  26528. * @param {number} data
  26529. * @param {boolean} clamp
  26530. * @return {number}
  26531. */
  26532. dataToCoord: function (data, clamp) {
  26533. var extent = this._extent;
  26534. var scale = this.scale;
  26535. data = scale.normalize(data);
  26536. if (this.onBand && scale.type === 'ordinal') {
  26537. extent = extent.slice();
  26538. fixExtentWithBands(extent, scale.count());
  26539. }
  26540. return linearMap$1(data, normalizedExtent, extent, clamp);
  26541. },
  26542. /**
  26543. * Convert coord to data. Data is the rank if it has a ordinal scale
  26544. * @param {number} coord
  26545. * @param {boolean} clamp
  26546. * @return {number}
  26547. */
  26548. coordToData: function (coord, clamp) {
  26549. var extent = this._extent;
  26550. var scale = this.scale;
  26551. if (this.onBand && scale.type === 'ordinal') {
  26552. extent = extent.slice();
  26553. fixExtentWithBands(extent, scale.count());
  26554. }
  26555. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  26556. return this.scale.scale(t);
  26557. },
  26558. /**
  26559. * Convert pixel point to data in axis
  26560. * @param {Array.<number>} point
  26561. * @param {boolean} clamp
  26562. * @return {number} data
  26563. */
  26564. pointToData: function (point, clamp) {
  26565. // Should be implemented in derived class if necessary.
  26566. },
  26567. /**
  26568. * @return {Array.<number>}
  26569. */
  26570. getTicksCoords: function (alignWithLabel) {
  26571. if (this.onBand && !alignWithLabel) {
  26572. var bands = this.getBands();
  26573. var coords = [];
  26574. for (var i = 0; i < bands.length; i++) {
  26575. coords.push(bands[i][0]);
  26576. }
  26577. if (bands[i - 1]) {
  26578. coords.push(bands[i - 1][1]);
  26579. }
  26580. return coords;
  26581. }
  26582. else {
  26583. return map(this.scale.getTicks(), this.dataToCoord, this);
  26584. }
  26585. },
  26586. /**
  26587. * Coords of labels are on the ticks or on the middle of bands
  26588. * @return {Array.<number>}
  26589. */
  26590. getLabelsCoords: function () {
  26591. return map(this.scale.getTicks(), this.dataToCoord, this);
  26592. },
  26593. /**
  26594. * Get bands.
  26595. *
  26596. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  26597. * |---1---|---2---|---3---|---4---|.
  26598. *
  26599. * @return {Array}
  26600. */
  26601. // FIXME Situation when labels is on ticks
  26602. getBands: function () {
  26603. var extent = this.getExtent();
  26604. var bands = [];
  26605. var len = this.scale.count();
  26606. var start = extent[0];
  26607. var end = extent[1];
  26608. var span = end - start;
  26609. for (var i = 0; i < len; i++) {
  26610. bands.push([
  26611. span * i / len + start,
  26612. span * (i + 1) / len + start
  26613. ]);
  26614. }
  26615. return bands;
  26616. },
  26617. /**
  26618. * Get width of band
  26619. * @return {number}
  26620. */
  26621. getBandWidth: function () {
  26622. var axisExtent = this._extent;
  26623. var dataExtent = this.scale.getExtent();
  26624. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  26625. // Fix #2728, avoid NaN when only one data.
  26626. len === 0 && (len = 1);
  26627. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  26628. return Math.abs(size) / len;
  26629. },
  26630. /**
  26631. * @abstract
  26632. * @return {boolean} Is horizontal
  26633. */
  26634. isHorizontal: null,
  26635. /**
  26636. * @abstract
  26637. * @return {number} Get axis rotate, by degree.
  26638. */
  26639. getRotate: null,
  26640. /**
  26641. * Get interval of the axis label.
  26642. * To get precise result, at least one of `getRotate` and `isHorizontal`
  26643. * should be implemented.
  26644. * @return {number}
  26645. */
  26646. getLabelInterval: function () {
  26647. var labelInterval = this._labelInterval;
  26648. if (!labelInterval) {
  26649. var axisModel = this.model;
  26650. var labelModel = axisModel.getModel('axisLabel');
  26651. labelInterval = labelModel.get('interval');
  26652. if (this.type === 'category'
  26653. && (labelInterval == null || labelInterval === 'auto')
  26654. ) {
  26655. labelInterval = getAxisLabelInterval(
  26656. map(this.scale.getTicks(), this.dataToCoord, this),
  26657. axisModel.getFormattedLabels(),
  26658. labelModel.getFont(),
  26659. this.getRotate
  26660. ? this.getRotate()
  26661. : (this.isHorizontal && !this.isHorizontal())
  26662. ? 90
  26663. : 0,
  26664. labelModel.get('rotate')
  26665. );
  26666. }
  26667. this._labelInterval = labelInterval;
  26668. }
  26669. return labelInterval;
  26670. }
  26671. };
  26672. /**
  26673. * Do not mount those modules on 'src/echarts' for better tree shaking.
  26674. */
  26675. var parseGeoJson = parseGeoJSON;
  26676. var ecUtil = {};
  26677. each$1([
  26678. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  26679. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  26680. 'extend', 'defaults', 'clone', 'merge'
  26681. ],
  26682. function (name) {
  26683. ecUtil[name] = zrUtil[name];
  26684. }
  26685. );
  26686. var DatasetModel = extendComponentModel({
  26687. type: 'dataset',
  26688. /**
  26689. * @protected
  26690. */
  26691. defaultOption: {
  26692. // 'row', 'column'
  26693. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  26694. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  26695. sourceHeader: null,
  26696. dimensions: null,
  26697. source: null
  26698. },
  26699. optionUpdated: function () {
  26700. detectSourceFormat(this);
  26701. }
  26702. });
  26703. extendComponentView({type: 'dataset'});
  26704. SeriesModel.extend({
  26705. type: 'series.line',
  26706. dependencies: ['grid', 'polar'],
  26707. getInitialData: function (option, ecModel) {
  26708. if (__DEV__) {
  26709. var coordSys = option.coordinateSystem;
  26710. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  26711. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  26712. }
  26713. }
  26714. return createListFromArray(this.getSource(), this);
  26715. },
  26716. defaultOption: {
  26717. zlevel: 0, // 一级层叠
  26718. z: 2, // 二级层叠
  26719. coordinateSystem: 'cartesian2d',
  26720. legendHoverLink: true,
  26721. hoverAnimation: true,
  26722. // stack: null
  26723. // xAxisIndex: 0,
  26724. // yAxisIndex: 0,
  26725. // polarIndex: 0,
  26726. // If clip the overflow value
  26727. clipOverflow: true,
  26728. // cursor: null,
  26729. label: {
  26730. position: 'top'
  26731. },
  26732. // itemStyle: {
  26733. // },
  26734. lineStyle: {
  26735. width: 2,
  26736. type: 'solid'
  26737. },
  26738. // areaStyle: {origin: 'auto'},
  26739. // false, 'start', 'end', 'middle'
  26740. step: false,
  26741. // Disabled if step is true
  26742. smooth: false,
  26743. smoothMonotone: null,
  26744. // 拐点图形类型
  26745. symbol: 'emptyCircle',
  26746. // 拐点图形大小
  26747. symbolSize: 4,
  26748. // 拐点图形旋转控制
  26749. symbolRotate: null,
  26750. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  26751. showSymbol: true,
  26752. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  26753. showAllSymbol: false,
  26754. // 是否连接断点
  26755. connectNulls: false,
  26756. // 数据过滤,'average', 'max', 'min', 'sum'
  26757. sampling: 'none',
  26758. animationEasing: 'linear',
  26759. // Disable progressive
  26760. progressive: 0,
  26761. hoverLayerThreshold: Infinity
  26762. }
  26763. });
  26764. /**
  26765. * @param {module:echarts/data/List} data
  26766. * @param {number} dataIndex
  26767. * @return {string} label string. Not null/undefined
  26768. */
  26769. function getDefaultLabel(data, dataIndex) {
  26770. var labelDims = data.mapDimension('defaultedLabel', true);
  26771. var len = labelDims.length;
  26772. // Simple optimization (in lots of cases, label dims length is 1)
  26773. if (len === 1) {
  26774. return retrieveRawValue(data, dataIndex, labelDims[0]);
  26775. }
  26776. else if (len) {
  26777. var vals = [];
  26778. for (var i = 0; i < labelDims.length; i++) {
  26779. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  26780. vals.push(val);
  26781. }
  26782. return vals.join(' ');
  26783. }
  26784. }
  26785. /**
  26786. * @module echarts/chart/helper/Symbol
  26787. */
  26788. function getSymbolSize(data, idx) {
  26789. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  26790. return symbolSize instanceof Array
  26791. ? symbolSize.slice()
  26792. : [+symbolSize, +symbolSize];
  26793. }
  26794. function getScale(symbolSize) {
  26795. return [symbolSize[0] / 2, symbolSize[1] / 2];
  26796. }
  26797. /**
  26798. * @constructor
  26799. * @alias {module:echarts/chart/helper/Symbol}
  26800. * @param {module:echarts/data/List} data
  26801. * @param {number} idx
  26802. * @extends {module:zrender/graphic/Group}
  26803. */
  26804. function SymbolClz$1(data, idx, seriesScope) {
  26805. Group.call(this);
  26806. this.updateData(data, idx, seriesScope);
  26807. }
  26808. var symbolProto = SymbolClz$1.prototype;
  26809. function driftSymbol(dx, dy) {
  26810. this.parent.drift(dx, dy);
  26811. }
  26812. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  26813. // Remove paths created before
  26814. this.removeAll();
  26815. var color = data.getItemVisual(idx, 'color');
  26816. // var symbolPath = createSymbol(
  26817. // symbolType, -0.5, -0.5, 1, 1, color
  26818. // );
  26819. // If width/height are set too small (e.g., set to 1) on ios10
  26820. // and macOS Sierra, a circle stroke become a rect, no matter what
  26821. // the scale is set. So we set width/height as 2. See #4150.
  26822. var symbolPath = createSymbol(
  26823. symbolType, -1, -1, 2, 2, color
  26824. );
  26825. symbolPath.attr({
  26826. z2: 100,
  26827. culling: true,
  26828. scale: getScale(symbolSize)
  26829. });
  26830. // Rewrite drift method
  26831. symbolPath.drift = driftSymbol;
  26832. this._symbolType = symbolType;
  26833. this.add(symbolPath);
  26834. };
  26835. /**
  26836. * Stop animation
  26837. * @param {boolean} toLastFrame
  26838. */
  26839. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  26840. this.childAt(0).stopAnimation(toLastFrame);
  26841. };
  26842. /**
  26843. * FIXME:
  26844. * Caution: This method breaks the encapsulation of this module,
  26845. * but it indeed brings convenience. So do not use the method
  26846. * unless you detailedly know all the implements of `Symbol`,
  26847. * especially animation.
  26848. *
  26849. * Get symbol path element.
  26850. */
  26851. symbolProto.getSymbolPath = function () {
  26852. return this.childAt(0);
  26853. };
  26854. /**
  26855. * Get scale(aka, current symbol size).
  26856. * Including the change caused by animation
  26857. */
  26858. symbolProto.getScale = function () {
  26859. return this.childAt(0).scale;
  26860. };
  26861. /**
  26862. * Highlight symbol
  26863. */
  26864. symbolProto.highlight = function () {
  26865. this.childAt(0).trigger('emphasis');
  26866. };
  26867. /**
  26868. * Downplay symbol
  26869. */
  26870. symbolProto.downplay = function () {
  26871. this.childAt(0).trigger('normal');
  26872. };
  26873. /**
  26874. * @param {number} zlevel
  26875. * @param {number} z
  26876. */
  26877. symbolProto.setZ = function (zlevel, z) {
  26878. var symbolPath = this.childAt(0);
  26879. symbolPath.zlevel = zlevel;
  26880. symbolPath.z = z;
  26881. };
  26882. symbolProto.setDraggable = function (draggable) {
  26883. var symbolPath = this.childAt(0);
  26884. symbolPath.draggable = draggable;
  26885. symbolPath.cursor = draggable ? 'move' : 'pointer';
  26886. };
  26887. /**
  26888. * Update symbol properties
  26889. * @param {module:echarts/data/List} data
  26890. * @param {number} idx
  26891. * @param {Object} [seriesScope]
  26892. * @param {Object} [seriesScope.itemStyle]
  26893. * @param {Object} [seriesScope.hoverItemStyle]
  26894. * @param {Object} [seriesScope.symbolRotate]
  26895. * @param {Object} [seriesScope.symbolOffset]
  26896. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  26897. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  26898. * @param {boolean} [seriesScope.hoverAnimation]
  26899. * @param {Object} [seriesScope.cursorStyle]
  26900. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  26901. * @param {string} [seriesScope.symbolInnerColor]
  26902. * @param {Object} [seriesScope.fadeIn=false]
  26903. */
  26904. symbolProto.updateData = function (data, idx, seriesScope) {
  26905. this.silent = false;
  26906. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  26907. var seriesModel = data.hostModel;
  26908. var symbolSize = getSymbolSize(data, idx);
  26909. var isInit = symbolType !== this._symbolType;
  26910. if (isInit) {
  26911. this._createSymbol(symbolType, data, idx, symbolSize);
  26912. }
  26913. else {
  26914. var symbolPath = this.childAt(0);
  26915. symbolPath.silent = false;
  26916. updateProps(symbolPath, {
  26917. scale: getScale(symbolSize)
  26918. }, seriesModel, idx);
  26919. }
  26920. this._updateCommon(data, idx, symbolSize, seriesScope);
  26921. if (isInit) {
  26922. var symbolPath = this.childAt(0);
  26923. var fadeIn = seriesScope && seriesScope.fadeIn;
  26924. var target = {scale: symbolPath.scale.slice()};
  26925. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  26926. symbolPath.scale = [0, 0];
  26927. fadeIn && (symbolPath.style.opacity = 0);
  26928. initProps(symbolPath, target, seriesModel, idx);
  26929. }
  26930. this._seriesModel = seriesModel;
  26931. };
  26932. // Update common properties
  26933. var normalStyleAccessPath = ['itemStyle'];
  26934. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  26935. var normalLabelAccessPath = ['label'];
  26936. var emphasisLabelAccessPath = ['emphasis', 'label'];
  26937. /**
  26938. * @param {module:echarts/data/List} data
  26939. * @param {number} idx
  26940. * @param {Array.<number>} symbolSize
  26941. * @param {Object} [seriesScope]
  26942. */
  26943. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  26944. var symbolPath = this.childAt(0);
  26945. var seriesModel = data.hostModel;
  26946. var color = data.getItemVisual(idx, 'color');
  26947. // Reset style
  26948. if (symbolPath.type !== 'image') {
  26949. symbolPath.useStyle({
  26950. strokeNoScale: true
  26951. });
  26952. }
  26953. var itemStyle = seriesScope && seriesScope.itemStyle;
  26954. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  26955. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  26956. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  26957. var labelModel = seriesScope && seriesScope.labelModel;
  26958. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  26959. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  26960. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  26961. if (!seriesScope || data.hasItemOption) {
  26962. var itemModel = (seriesScope && seriesScope.itemModel)
  26963. ? seriesScope.itemModel : data.getItemModel(idx);
  26964. // Color must be excluded.
  26965. // Because symbol provide setColor individually to set fill and stroke
  26966. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  26967. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  26968. symbolRotate = itemModel.getShallow('symbolRotate');
  26969. symbolOffset = itemModel.getShallow('symbolOffset');
  26970. labelModel = itemModel.getModel(normalLabelAccessPath);
  26971. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  26972. hoverAnimation = itemModel.getShallow('hoverAnimation');
  26973. cursorStyle = itemModel.getShallow('cursor');
  26974. }
  26975. else {
  26976. hoverItemStyle = extend({}, hoverItemStyle);
  26977. }
  26978. var elStyle = symbolPath.style;
  26979. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  26980. if (symbolOffset) {
  26981. symbolPath.attr('position', [
  26982. parsePercent$1(symbolOffset[0], symbolSize[0]),
  26983. parsePercent$1(symbolOffset[1], symbolSize[1])
  26984. ]);
  26985. }
  26986. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  26987. // PENDING setColor before setStyle!!!
  26988. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  26989. symbolPath.setStyle(itemStyle);
  26990. var opacity = data.getItemVisual(idx, 'opacity');
  26991. if (opacity != null) {
  26992. elStyle.opacity = opacity;
  26993. }
  26994. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  26995. setLabelStyle(
  26996. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  26997. {
  26998. labelFetcher: seriesModel,
  26999. labelDataIndex: idx,
  27000. defaultText: getLabelDefaultText,
  27001. isRectText: true,
  27002. autoColor: color
  27003. }
  27004. );
  27005. // Do not execute util needed.
  27006. function getLabelDefaultText(idx, opt) {
  27007. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27008. }
  27009. symbolPath.off('mouseover')
  27010. .off('mouseout')
  27011. .off('emphasis')
  27012. .off('normal');
  27013. symbolPath.hoverStyle = hoverItemStyle;
  27014. // FIXME
  27015. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27016. setHoverStyle(symbolPath);
  27017. var scale = getScale(symbolSize);
  27018. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27019. var onEmphasis = function() {
  27020. var ratio = scale[1] / scale[0];
  27021. this.animateTo({
  27022. scale: [
  27023. Math.max(scale[0] * 1.1, scale[0] + 3),
  27024. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27025. ]
  27026. }, 400, 'elasticOut');
  27027. };
  27028. var onNormal = function() {
  27029. this.animateTo({
  27030. scale: scale
  27031. }, 400, 'elasticOut');
  27032. };
  27033. symbolPath.on('mouseover', onEmphasis)
  27034. .on('mouseout', onNormal)
  27035. .on('emphasis', onEmphasis)
  27036. .on('normal', onNormal);
  27037. }
  27038. };
  27039. /**
  27040. * @param {Function} cb
  27041. * @param {Object} [opt]
  27042. * @param {Object} [opt.keepLabel=true]
  27043. */
  27044. symbolProto.fadeOut = function (cb, opt) {
  27045. var symbolPath = this.childAt(0);
  27046. // Avoid mistaken hover when fading out
  27047. this.silent = symbolPath.silent = true;
  27048. // Not show text when animating
  27049. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27050. updateProps(
  27051. symbolPath,
  27052. {
  27053. style: {opacity: 0},
  27054. scale: [0, 0]
  27055. },
  27056. this._seriesModel,
  27057. this.dataIndex,
  27058. cb
  27059. );
  27060. };
  27061. inherits(SymbolClz$1, Group);
  27062. /**
  27063. * @module echarts/chart/helper/SymbolDraw
  27064. */
  27065. /**
  27066. * @constructor
  27067. * @alias module:echarts/chart/helper/SymbolDraw
  27068. * @param {module:zrender/graphic/Group} [symbolCtor]
  27069. */
  27070. function SymbolDraw(symbolCtor) {
  27071. this.group = new Group();
  27072. this._symbolCtor = symbolCtor || SymbolClz$1;
  27073. }
  27074. var symbolDrawProto = SymbolDraw.prototype;
  27075. function symbolNeedsDraw(data, point, idx, isIgnore) {
  27076. return point && !isNaN(point[0]) && !isNaN(point[1])
  27077. && !(isIgnore && isIgnore(idx))
  27078. && data.getItemVisual(idx, 'symbol') !== 'none';
  27079. }
  27080. /**
  27081. * Update symbols draw by new data
  27082. * @param {module:echarts/data/List} data
  27083. * @param {Array.<boolean>} [isIgnore]
  27084. */
  27085. symbolDrawProto.updateData = function (data, isIgnore) {
  27086. var group = this.group;
  27087. var seriesModel = data.hostModel;
  27088. var oldData = this._data;
  27089. var SymbolCtor = this._symbolCtor;
  27090. var seriesScope = makeSeriesScope(data);
  27091. // There is no oldLineData only when first rendering or switching from
  27092. // stream mode to normal mode, where previous elements should be removed.
  27093. if (!oldData) {
  27094. group.removeAll();
  27095. }
  27096. data.diff(oldData)
  27097. .add(function (newIdx) {
  27098. var point = data.getItemLayout(newIdx);
  27099. if (symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27100. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27101. symbolEl.attr('position', point);
  27102. data.setItemGraphicEl(newIdx, symbolEl);
  27103. group.add(symbolEl);
  27104. }
  27105. })
  27106. .update(function (newIdx, oldIdx) {
  27107. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27108. var point = data.getItemLayout(newIdx);
  27109. if (!symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27110. group.remove(symbolEl);
  27111. return;
  27112. }
  27113. if (!symbolEl) {
  27114. symbolEl = new SymbolCtor(data, newIdx);
  27115. symbolEl.attr('position', point);
  27116. }
  27117. else {
  27118. symbolEl.updateData(data, newIdx, seriesScope);
  27119. updateProps(symbolEl, {
  27120. position: point
  27121. }, seriesModel);
  27122. }
  27123. // Add back
  27124. group.add(symbolEl);
  27125. data.setItemGraphicEl(newIdx, symbolEl);
  27126. })
  27127. .remove(function (oldIdx) {
  27128. var el = oldData.getItemGraphicEl(oldIdx);
  27129. el && el.fadeOut(function () {
  27130. group.remove(el);
  27131. });
  27132. })
  27133. .execute();
  27134. this._data = data;
  27135. };
  27136. symbolDrawProto.isPersistent = function () {
  27137. return true;
  27138. };
  27139. symbolDrawProto.updateLayout = function () {
  27140. var data = this._data;
  27141. if (data) {
  27142. // Not use animation
  27143. data.eachItemGraphicEl(function (el, idx) {
  27144. var point = data.getItemLayout(idx);
  27145. el.attr('position', point);
  27146. });
  27147. }
  27148. };
  27149. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27150. this._seriesScope = makeSeriesScope(data);
  27151. this._data = null;
  27152. this.group.removeAll();
  27153. };
  27154. symbolDrawProto.incrementalUpdate = function (taskParams, data, isIgnore) {
  27155. function updateIncrementalAndHover(el) {
  27156. if (!el.isGroup) {
  27157. el.incremental = el.useHoverLayer = true;
  27158. }
  27159. }
  27160. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27161. var point = data.getItemLayout(idx);
  27162. if (symbolNeedsDraw(data, point, idx, isIgnore)) {
  27163. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27164. el.traverse(updateIncrementalAndHover);
  27165. el.attr('position', point);
  27166. this.group.add(el);
  27167. data.setItemGraphicEl(idx, el);
  27168. }
  27169. }
  27170. };
  27171. symbolDrawProto.remove = function (enableAnimation) {
  27172. var group = this.group;
  27173. var data = this._data;
  27174. if (data) {
  27175. if (enableAnimation) {
  27176. data.eachItemGraphicEl(function (el) {
  27177. el.fadeOut(function () {
  27178. group.remove(el);
  27179. });
  27180. });
  27181. }
  27182. else {
  27183. group.removeAll();
  27184. }
  27185. }
  27186. };
  27187. function makeSeriesScope(data) {
  27188. var seriesModel = data.hostModel;
  27189. return {
  27190. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27191. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27192. symbolRotate: seriesModel.get('symbolRotate'),
  27193. symbolOffset: seriesModel.get('symbolOffset'),
  27194. hoverAnimation: seriesModel.get('hoverAnimation'),
  27195. labelModel: seriesModel.getModel('label'),
  27196. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27197. cursorStyle: seriesModel.get('cursor')
  27198. };
  27199. }
  27200. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27201. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27202. // not do well in performance when roam with fixed dataZoom window.
  27203. function sign$1(val) {
  27204. return val >= 0 ? 1 : -1;
  27205. }
  27206. function getStackedOnPoint(coordSys, data, idx) {
  27207. var baseAxis = coordSys.getBaseAxis();
  27208. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27209. var valueStart = baseAxis.onZero
  27210. ? 0 : valueAxis.scale.getExtent()[0];
  27211. var valueDim = valueAxis.dim;
  27212. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  27213. var stackedOnSameSign;
  27214. var stackedOn = data.stackedOn;
  27215. var val = data.get(valueDim, idx);
  27216. // Find first stacked value with same sign
  27217. while (stackedOn &&
  27218. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  27219. ) {
  27220. stackedOnSameSign = stackedOn;
  27221. break;
  27222. }
  27223. var stackedData = [];
  27224. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27225. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27226. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27227. return coordSys.dataToPoint(stackedData);
  27228. }
  27229. // function convertToIntId(newIdList, oldIdList) {
  27230. // // Generate int id instead of string id.
  27231. // // Compare string maybe slow in score function of arrDiff
  27232. // // Assume id in idList are all unique
  27233. // var idIndicesMap = {};
  27234. // var idx = 0;
  27235. // for (var i = 0; i < newIdList.length; i++) {
  27236. // idIndicesMap[newIdList[i]] = idx;
  27237. // newIdList[i] = idx++;
  27238. // }
  27239. // for (var i = 0; i < oldIdList.length; i++) {
  27240. // var oldId = oldIdList[i];
  27241. // // Same with newIdList
  27242. // if (idIndicesMap[oldId]) {
  27243. // oldIdList[i] = idIndicesMap[oldId];
  27244. // }
  27245. // else {
  27246. // oldIdList[i] = idx++;
  27247. // }
  27248. // }
  27249. // }
  27250. function diffData(oldData, newData) {
  27251. var diffResult = [];
  27252. newData.diff(oldData)
  27253. .add(function (idx) {
  27254. diffResult.push({cmd: '+', idx: idx});
  27255. })
  27256. .update(function (newIdx, oldIdx) {
  27257. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27258. })
  27259. .remove(function (idx) {
  27260. diffResult.push({cmd: '-', idx: idx});
  27261. })
  27262. .execute();
  27263. return diffResult;
  27264. }
  27265. var lineAnimationDiff = function (
  27266. oldData, newData,
  27267. oldStackedOnPoints, newStackedOnPoints,
  27268. oldCoordSys, newCoordSys
  27269. ) {
  27270. var diff = diffData(oldData, newData);
  27271. // var newIdList = newData.mapArray(newData.getId);
  27272. // var oldIdList = oldData.mapArray(oldData.getId);
  27273. // convertToIntId(newIdList, oldIdList);
  27274. // // FIXME One data ?
  27275. // diff = arrayDiff(oldIdList, newIdList);
  27276. var currPoints = [];
  27277. var nextPoints = [];
  27278. // Points for stacking base line
  27279. var currStackedPoints = [];
  27280. var nextStackedPoints = [];
  27281. var status = [];
  27282. var sortedIndices = [];
  27283. var rawIndices = [];
  27284. var dims = newCoordSys.dimensions;
  27285. for (var i = 0; i < diff.length; i++) {
  27286. var diffItem = diff[i];
  27287. var pointAdded = true;
  27288. // FIXME, animation is not so perfect when dataZoom window moves fast
  27289. // Which is in case remvoing or add more than one data in the tail or head
  27290. switch (diffItem.cmd) {
  27291. case '=':
  27292. var currentPt = oldData.getItemLayout(diffItem.idx);
  27293. var nextPt = newData.getItemLayout(diffItem.idx1);
  27294. // If previous data is NaN, use next point directly
  27295. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27296. currentPt = nextPt.slice();
  27297. }
  27298. currPoints.push(currentPt);
  27299. nextPoints.push(nextPt);
  27300. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27301. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27302. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27303. break;
  27304. case '+':
  27305. var idx = diffItem.idx;
  27306. currPoints.push(
  27307. oldCoordSys.dataToPoint([
  27308. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  27309. ])
  27310. );
  27311. nextPoints.push(newData.getItemLayout(idx).slice());
  27312. currStackedPoints.push(
  27313. getStackedOnPoint(oldCoordSys, newData, idx)
  27314. );
  27315. nextStackedPoints.push(newStackedOnPoints[idx]);
  27316. rawIndices.push(newData.getRawIndex(idx));
  27317. break;
  27318. case '-':
  27319. var idx = diffItem.idx;
  27320. var rawIndex = oldData.getRawIndex(idx);
  27321. // Data is replaced. In the case of dynamic data queue
  27322. // FIXME FIXME FIXME
  27323. if (rawIndex !== idx) {
  27324. currPoints.push(oldData.getItemLayout(idx));
  27325. nextPoints.push(newCoordSys.dataToPoint([
  27326. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  27327. ]));
  27328. currStackedPoints.push(oldStackedOnPoints[idx]);
  27329. nextStackedPoints.push(
  27330. getStackedOnPoint(
  27331. newCoordSys, oldData, idx
  27332. )
  27333. );
  27334. rawIndices.push(rawIndex);
  27335. }
  27336. else {
  27337. pointAdded = false;
  27338. }
  27339. }
  27340. // Original indices
  27341. if (pointAdded) {
  27342. status.push(diffItem);
  27343. sortedIndices.push(sortedIndices.length);
  27344. }
  27345. }
  27346. // Diff result may be crossed if all items are changed
  27347. // Sort by data index
  27348. sortedIndices.sort(function (a, b) {
  27349. return rawIndices[a] - rawIndices[b];
  27350. });
  27351. var sortedCurrPoints = [];
  27352. var sortedNextPoints = [];
  27353. var sortedCurrStackedPoints = [];
  27354. var sortedNextStackedPoints = [];
  27355. var sortedStatus = [];
  27356. for (var i = 0; i < sortedIndices.length; i++) {
  27357. var idx = sortedIndices[i];
  27358. sortedCurrPoints[i] = currPoints[idx];
  27359. sortedNextPoints[i] = nextPoints[idx];
  27360. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  27361. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  27362. sortedStatus[i] = status[idx];
  27363. }
  27364. return {
  27365. current: sortedCurrPoints,
  27366. next: sortedNextPoints,
  27367. stackedOnCurrent: sortedCurrStackedPoints,
  27368. stackedOnNext: sortedNextStackedPoints,
  27369. status: sortedStatus
  27370. };
  27371. };
  27372. // Poly path support NaN point
  27373. var vec2Min = min;
  27374. var vec2Max = max;
  27375. var scaleAndAdd$1 = scaleAndAdd;
  27376. var v2Copy = copy;
  27377. // Temporary variable
  27378. var v = [];
  27379. var cp0 = [];
  27380. var cp1 = [];
  27381. function isPointNull(p) {
  27382. return isNaN(p[0]) || isNaN(p[1]);
  27383. }
  27384. function drawSegment(
  27385. ctx, points, start, segLen, allLen,
  27386. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  27387. ) {
  27388. var prevIdx = 0;
  27389. var idx = start;
  27390. for (var k = 0; k < segLen; k++) {
  27391. var p = points[idx];
  27392. if (idx >= allLen || idx < 0) {
  27393. break;
  27394. }
  27395. if (isPointNull(p)) {
  27396. if (connectNulls) {
  27397. idx += dir;
  27398. continue;
  27399. }
  27400. break;
  27401. }
  27402. if (idx === start) {
  27403. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  27404. v2Copy(cp0, p);
  27405. }
  27406. else {
  27407. if (smooth > 0) {
  27408. var nextIdx = idx + dir;
  27409. var nextP = points[nextIdx];
  27410. if (connectNulls) {
  27411. // Find next point not null
  27412. while (nextP && isPointNull(points[nextIdx])) {
  27413. nextIdx += dir;
  27414. nextP = points[nextIdx];
  27415. }
  27416. }
  27417. var ratioNextSeg = 0.5;
  27418. var prevP = points[prevIdx];
  27419. var nextP = points[nextIdx];
  27420. // Last point
  27421. if (!nextP || isPointNull(nextP)) {
  27422. v2Copy(cp1, p);
  27423. }
  27424. else {
  27425. // If next data is null in not connect case
  27426. if (isPointNull(nextP) && !connectNulls) {
  27427. nextP = p;
  27428. }
  27429. sub(v, nextP, prevP);
  27430. var lenPrevSeg;
  27431. var lenNextSeg;
  27432. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  27433. var dim = smoothMonotone === 'x' ? 0 : 1;
  27434. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  27435. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  27436. }
  27437. else {
  27438. lenPrevSeg = dist(p, prevP);
  27439. lenNextSeg = dist(p, nextP);
  27440. }
  27441. // Use ratio of seg length
  27442. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  27443. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  27444. }
  27445. // Smooth constraint
  27446. vec2Min(cp0, cp0, smoothMax);
  27447. vec2Max(cp0, cp0, smoothMin);
  27448. vec2Min(cp1, cp1, smoothMax);
  27449. vec2Max(cp1, cp1, smoothMin);
  27450. ctx.bezierCurveTo(
  27451. cp0[0], cp0[1],
  27452. cp1[0], cp1[1],
  27453. p[0], p[1]
  27454. );
  27455. // cp0 of next segment
  27456. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  27457. }
  27458. else {
  27459. ctx.lineTo(p[0], p[1]);
  27460. }
  27461. }
  27462. prevIdx = idx;
  27463. idx += dir;
  27464. }
  27465. return k;
  27466. }
  27467. function getBoundingBox(points, smoothConstraint) {
  27468. var ptMin = [Infinity, Infinity];
  27469. var ptMax = [-Infinity, -Infinity];
  27470. if (smoothConstraint) {
  27471. for (var i = 0; i < points.length; i++) {
  27472. var pt = points[i];
  27473. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  27474. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  27475. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  27476. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  27477. }
  27478. }
  27479. return {
  27480. min: smoothConstraint ? ptMin : ptMax,
  27481. max: smoothConstraint ? ptMax : ptMin
  27482. };
  27483. }
  27484. var Polyline$1 = Path.extend({
  27485. type: 'ec-polyline',
  27486. shape: {
  27487. points: [],
  27488. smooth: 0,
  27489. smoothConstraint: true,
  27490. smoothMonotone: null,
  27491. connectNulls: false
  27492. },
  27493. style: {
  27494. fill: null,
  27495. stroke: '#000'
  27496. },
  27497. brush: fixClipWithShadow(Path.prototype.brush),
  27498. buildPath: function (ctx, shape) {
  27499. var points = shape.points;
  27500. var i = 0;
  27501. var len$$1 = points.length;
  27502. var result = getBoundingBox(points, shape.smoothConstraint);
  27503. if (shape.connectNulls) {
  27504. // Must remove first and last null values avoid draw error in polygon
  27505. for (; len$$1 > 0; len$$1--) {
  27506. if (!isPointNull(points[len$$1 - 1])) {
  27507. break;
  27508. }
  27509. }
  27510. for (; i < len$$1; i++) {
  27511. if (!isPointNull(points[i])) {
  27512. break;
  27513. }
  27514. }
  27515. }
  27516. while (i < len$$1) {
  27517. i += drawSegment(
  27518. ctx, points, i, len$$1, len$$1,
  27519. 1, result.min, result.max, shape.smooth,
  27520. shape.smoothMonotone, shape.connectNulls
  27521. ) + 1;
  27522. }
  27523. }
  27524. });
  27525. var Polygon$1 = Path.extend({
  27526. type: 'ec-polygon',
  27527. shape: {
  27528. points: [],
  27529. // Offset between stacked base points and points
  27530. stackedOnPoints: [],
  27531. smooth: 0,
  27532. stackedOnSmooth: 0,
  27533. smoothConstraint: true,
  27534. smoothMonotone: null,
  27535. connectNulls: false
  27536. },
  27537. brush: fixClipWithShadow(Path.prototype.brush),
  27538. buildPath: function (ctx, shape) {
  27539. var points = shape.points;
  27540. var stackedOnPoints = shape.stackedOnPoints;
  27541. var i = 0;
  27542. var len$$1 = points.length;
  27543. var smoothMonotone = shape.smoothMonotone;
  27544. var bbox = getBoundingBox(points, shape.smoothConstraint);
  27545. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  27546. if (shape.connectNulls) {
  27547. // Must remove first and last null values avoid draw error in polygon
  27548. for (; len$$1 > 0; len$$1--) {
  27549. if (!isPointNull(points[len$$1 - 1])) {
  27550. break;
  27551. }
  27552. }
  27553. for (; i < len$$1; i++) {
  27554. if (!isPointNull(points[i])) {
  27555. break;
  27556. }
  27557. }
  27558. }
  27559. while (i < len$$1) {
  27560. var k = drawSegment(
  27561. ctx, points, i, len$$1, len$$1,
  27562. 1, bbox.min, bbox.max, shape.smooth,
  27563. smoothMonotone, shape.connectNulls
  27564. );
  27565. drawSegment(
  27566. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  27567. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  27568. smoothMonotone, shape.connectNulls
  27569. );
  27570. i += k + 1;
  27571. ctx.closePath();
  27572. }
  27573. }
  27574. });
  27575. // FIXME step not support polar
  27576. function isPointsSame(points1, points2) {
  27577. if (points1.length !== points2.length) {
  27578. return;
  27579. }
  27580. for (var i = 0; i < points1.length; i++) {
  27581. var p1 = points1[i];
  27582. var p2 = points2[i];
  27583. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  27584. return;
  27585. }
  27586. }
  27587. return true;
  27588. }
  27589. function getSmooth(smooth) {
  27590. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  27591. }
  27592. function getAxisExtentWithGap(axis) {
  27593. var extent = axis.getGlobalExtent();
  27594. if (axis.onBand) {
  27595. // Remove extra 1px to avoid line miter in clipped edge
  27596. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  27597. var dir = extent[1] > extent[0] ? 1 : -1;
  27598. extent[0] += dir * halfBandWidth;
  27599. extent[1] -= dir * halfBandWidth;
  27600. }
  27601. return extent;
  27602. }
  27603. function sign(val) {
  27604. return val >= 0 ? 1 : -1;
  27605. }
  27606. /**
  27607. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  27608. * @param {module:echarts/data/List} data
  27609. * @param {Array.<Array.<number>>} points
  27610. * @param {string} origin origin of areaStyle. Valid values: 'auto', 'start',
  27611. * 'end'.
  27612. * auto: from axisLine to data
  27613. * start: from min to data
  27614. * end: from data to max
  27615. * @private
  27616. */
  27617. function getStackedOnPoints(seriesModel, coordSys, data, origin) {
  27618. var baseAxis = coordSys.getBaseAxis();
  27619. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27620. var valueStart = 0;
  27621. var extent = valueAxis.scale.getExtent();
  27622. if (origin === 'start') {
  27623. valueStart = extent[0];
  27624. }
  27625. else if (origin === 'end') {
  27626. valueStart = extent[1];
  27627. }
  27628. else {
  27629. // auto
  27630. var extent = valueAxis.scale.getExtent();
  27631. if (extent[0] > 0) {
  27632. // Both positive
  27633. valueStart = extent[0];
  27634. }
  27635. else if (extent[1] < 0) {
  27636. // Both negative
  27637. valueStart = extent[1];
  27638. }
  27639. // If is one positive, and one negative, onZero shall be true
  27640. }
  27641. var valueCoordDim = valueAxis.dim;
  27642. var baseDataOffset = valueCoordDim === 'x' || valueCoordDim === 'radius' ? 1 : 0;
  27643. var valueDim = data.mapDimension(valueCoordDim);
  27644. return data.mapArray(valueDim ? [valueDim] : [], function (val, idx) {
  27645. var stackedOnSameSign;
  27646. var stackedOn = data.stackedOn;
  27647. // Find first stacked value with same sign
  27648. while (stackedOn &&
  27649. sign(stackedOn.get(valueDim, idx)) === sign(val)
  27650. ) {
  27651. stackedOnSameSign = stackedOn;
  27652. break;
  27653. }
  27654. var stackedData = [];
  27655. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27656. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27657. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27658. return coordSys.dataToPoint(stackedData);
  27659. }, true);
  27660. }
  27661. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  27662. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  27663. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  27664. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  27665. var x = Math.min(xExtent[0], xExtent[1]);
  27666. var y = Math.min(yExtent[0], yExtent[1]);
  27667. var width = Math.max(xExtent[0], xExtent[1]) - x;
  27668. var height = Math.max(yExtent[0], yExtent[1]) - y;
  27669. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  27670. // Expand clip shape to avoid clipping when line value exceeds axis
  27671. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  27672. if (isHorizontal) {
  27673. y -= expandSize;
  27674. height += expandSize * 2;
  27675. }
  27676. else {
  27677. x -= expandSize;
  27678. width += expandSize * 2;
  27679. }
  27680. var clipPath = new Rect({
  27681. shape: {
  27682. x: x,
  27683. y: y,
  27684. width: width,
  27685. height: height
  27686. }
  27687. });
  27688. if (hasAnimation) {
  27689. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  27690. initProps(clipPath, {
  27691. shape: {
  27692. width: width,
  27693. height: height
  27694. }
  27695. }, seriesModel);
  27696. }
  27697. return clipPath;
  27698. }
  27699. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  27700. var angleAxis = polar.getAngleAxis();
  27701. var radiusAxis = polar.getRadiusAxis();
  27702. var radiusExtent = radiusAxis.getExtent();
  27703. var angleExtent = angleAxis.getExtent();
  27704. var RADIAN = Math.PI / 180;
  27705. var clipPath = new Sector({
  27706. shape: {
  27707. cx: polar.cx,
  27708. cy: polar.cy,
  27709. r0: radiusExtent[0],
  27710. r: radiusExtent[1],
  27711. startAngle: -angleExtent[0] * RADIAN,
  27712. endAngle: -angleExtent[1] * RADIAN,
  27713. clockwise: angleAxis.inverse
  27714. }
  27715. });
  27716. if (hasAnimation) {
  27717. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  27718. initProps(clipPath, {
  27719. shape: {
  27720. endAngle: -angleExtent[1] * RADIAN
  27721. }
  27722. }, seriesModel);
  27723. }
  27724. return clipPath;
  27725. }
  27726. function createClipShape(coordSys, hasAnimation, seriesModel) {
  27727. return coordSys.type === 'polar'
  27728. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  27729. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  27730. }
  27731. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  27732. var baseAxis = coordSys.getBaseAxis();
  27733. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  27734. var stepPoints = [];
  27735. for (var i = 0; i < points.length - 1; i++) {
  27736. var nextPt = points[i + 1];
  27737. var pt = points[i];
  27738. stepPoints.push(pt);
  27739. var stepPt = [];
  27740. switch (stepTurnAt) {
  27741. case 'end':
  27742. stepPt[baseIndex] = nextPt[baseIndex];
  27743. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27744. // default is start
  27745. stepPoints.push(stepPt);
  27746. break;
  27747. case 'middle':
  27748. // default is start
  27749. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  27750. var stepPt2 = [];
  27751. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  27752. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27753. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  27754. stepPoints.push(stepPt);
  27755. stepPoints.push(stepPt2);
  27756. break;
  27757. default:
  27758. stepPt[baseIndex] = pt[baseIndex];
  27759. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  27760. // default is start
  27761. stepPoints.push(stepPt);
  27762. }
  27763. }
  27764. // Last points
  27765. points[i] && stepPoints.push(points[i]);
  27766. return stepPoints;
  27767. }
  27768. function getVisualGradient(data, coordSys) {
  27769. var visualMetaList = data.getVisual('visualMeta');
  27770. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  27771. // When data.count() is 0, gradient range can not be calculated.
  27772. return;
  27773. }
  27774. var visualMeta;
  27775. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  27776. // Can only be x or y
  27777. if (visualMetaList[i].dimension < 2) {
  27778. visualMeta = visualMetaList[i];
  27779. break;
  27780. }
  27781. }
  27782. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  27783. if (__DEV__) {
  27784. console.warn('Visual map on line style only support x or y dimension.');
  27785. }
  27786. return;
  27787. }
  27788. // If the area to be rendered is bigger than area defined by LinearGradient,
  27789. // the canvas spec prescribes that the color of the first stop and the last
  27790. // stop should be used. But if two stops are added at offset 0, in effect
  27791. // browsers use the color of the second stop to render area outside
  27792. // LinearGradient. So we can only infinitesimally extend area defined in
  27793. // LinearGradient to render `outerColors`.
  27794. var dimension = visualMeta.dimension;
  27795. var dimName = data.dimensions[dimension];
  27796. var axis = coordSys.getAxis(dimName);
  27797. // dataToCoor mapping may not be linear, but must be monotonic.
  27798. var colorStops = map(visualMeta.stops, function (stop) {
  27799. return {
  27800. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  27801. color: stop.color
  27802. };
  27803. });
  27804. var stopLen = colorStops.length;
  27805. var outerColors = visualMeta.outerColors.slice();
  27806. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  27807. colorStops.reverse();
  27808. outerColors.reverse();
  27809. }
  27810. var tinyExtent = 10; // Arbitrary value: 10px
  27811. var minCoord = colorStops[0].coord - tinyExtent;
  27812. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  27813. var coordSpan = maxCoord - minCoord;
  27814. if (coordSpan < 1e-3) {
  27815. return 'transparent';
  27816. }
  27817. each$1(colorStops, function (stop) {
  27818. stop.offset = (stop.coord - minCoord) / coordSpan;
  27819. });
  27820. colorStops.push({
  27821. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  27822. color: outerColors[1] || 'transparent'
  27823. });
  27824. colorStops.unshift({ // notice colorStops.length have been changed.
  27825. offset: stopLen ? colorStops[0].offset : 0.5,
  27826. color: outerColors[0] || 'transparent'
  27827. });
  27828. // zrUtil.each(colorStops, function (colorStop) {
  27829. // // Make sure each offset has rounded px to avoid not sharp edge
  27830. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  27831. // });
  27832. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  27833. gradient[dimName] = minCoord;
  27834. gradient[dimName + '2'] = maxCoord;
  27835. return gradient;
  27836. }
  27837. Chart.extend({
  27838. type: 'line',
  27839. init: function () {
  27840. var lineGroup = new Group();
  27841. var symbolDraw = new SymbolDraw();
  27842. this.group.add(symbolDraw.group);
  27843. this._symbolDraw = symbolDraw;
  27844. this._lineGroup = lineGroup;
  27845. },
  27846. render: function (seriesModel, ecModel, api) {
  27847. var coordSys = seriesModel.coordinateSystem;
  27848. var group = this.group;
  27849. var data = seriesModel.getData();
  27850. var lineStyleModel = seriesModel.getModel('lineStyle');
  27851. var areaStyleModel = seriesModel.getModel('areaStyle');
  27852. var points = data.mapArray(data.getItemLayout, true);
  27853. var isCoordSysPolar = coordSys.type === 'polar';
  27854. var prevCoordSys = this._coordSys;
  27855. var symbolDraw = this._symbolDraw;
  27856. var polyline = this._polyline;
  27857. var polygon = this._polygon;
  27858. var lineGroup = this._lineGroup;
  27859. var hasAnimation = seriesModel.get('animation');
  27860. var isAreaChart = !areaStyleModel.isEmpty();
  27861. var origin = areaStyleModel.get('origin');
  27862. var stackedOnPoints = getStackedOnPoints(seriesModel, coordSys, data, origin);
  27863. var showSymbol = seriesModel.get('showSymbol');
  27864. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  27865. && this._getSymbolIgnoreFunc(data, coordSys);
  27866. // Remove temporary symbols
  27867. var oldData = this._data;
  27868. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  27869. if (el.__temp) {
  27870. group.remove(el);
  27871. oldData.setItemGraphicEl(idx, null);
  27872. }
  27873. });
  27874. // Remove previous created symbols if showSymbol changed to false
  27875. if (!showSymbol) {
  27876. symbolDraw.remove();
  27877. }
  27878. group.add(lineGroup);
  27879. // FIXME step not support polar
  27880. var step = !isCoordSysPolar && seriesModel.get('step');
  27881. // Initialization animation or coordinate system changed
  27882. if (
  27883. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  27884. ) {
  27885. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  27886. if (step) {
  27887. // TODO If stacked series is not step
  27888. points = turnPointsIntoStep(points, coordSys, step);
  27889. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  27890. }
  27891. polyline = this._newPolyline(points, coordSys, hasAnimation);
  27892. if (isAreaChart) {
  27893. polygon = this._newPolygon(
  27894. points, stackedOnPoints,
  27895. coordSys, hasAnimation
  27896. );
  27897. }
  27898. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  27899. }
  27900. else {
  27901. if (isAreaChart && !polygon) {
  27902. // If areaStyle is added
  27903. polygon = this._newPolygon(
  27904. points, stackedOnPoints,
  27905. coordSys, hasAnimation
  27906. );
  27907. }
  27908. else if (polygon && !isAreaChart) {
  27909. // If areaStyle is removed
  27910. lineGroup.remove(polygon);
  27911. polygon = this._polygon = null;
  27912. }
  27913. // Update clipPath
  27914. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  27915. // Always update, or it is wrong in the case turning on legend
  27916. // because points are not changed
  27917. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  27918. // Stop symbol animation and sync with line points
  27919. // FIXME performance?
  27920. data.eachItemGraphicEl(function (el) {
  27921. el.stopAnimation(true);
  27922. });
  27923. // In the case data zoom triggerred refreshing frequently
  27924. // Data may not change if line has a category axis. So it should animate nothing
  27925. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  27926. || !isPointsSame(this._points, points)
  27927. ) {
  27928. if (hasAnimation) {
  27929. this._updateAnimation(
  27930. data, stackedOnPoints, coordSys, api, step
  27931. );
  27932. }
  27933. else {
  27934. // Not do it in update with animation
  27935. if (step) {
  27936. // TODO If stacked series is not step
  27937. points = turnPointsIntoStep(points, coordSys, step);
  27938. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  27939. }
  27940. polyline.setShape({
  27941. points: points
  27942. });
  27943. polygon && polygon.setShape({
  27944. points: points,
  27945. stackedOnPoints: stackedOnPoints
  27946. });
  27947. }
  27948. }
  27949. }
  27950. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  27951. polyline.useStyle(defaults(
  27952. // Use color in lineStyle first
  27953. lineStyleModel.getLineStyle(),
  27954. {
  27955. fill: 'none',
  27956. stroke: visualColor,
  27957. lineJoin: 'bevel'
  27958. }
  27959. ));
  27960. var smooth = seriesModel.get('smooth');
  27961. smooth = getSmooth(seriesModel.get('smooth'));
  27962. polyline.setShape({
  27963. smooth: smooth,
  27964. smoothMonotone: seriesModel.get('smoothMonotone'),
  27965. connectNulls: seriesModel.get('connectNulls')
  27966. });
  27967. if (polygon) {
  27968. var stackedOn = data.stackedOn;
  27969. var stackedOnSmooth = 0;
  27970. polygon.useStyle(defaults(
  27971. areaStyleModel.getAreaStyle(),
  27972. {
  27973. fill: visualColor,
  27974. opacity: 0.7,
  27975. lineJoin: 'bevel'
  27976. }
  27977. ));
  27978. if (stackedOn) {
  27979. var stackedOnSeries = stackedOn.hostModel;
  27980. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  27981. }
  27982. polygon.setShape({
  27983. smooth: smooth,
  27984. stackedOnSmooth: stackedOnSmooth,
  27985. smoothMonotone: seriesModel.get('smoothMonotone'),
  27986. connectNulls: seriesModel.get('connectNulls')
  27987. });
  27988. }
  27989. this._data = data;
  27990. // Save the coordinate system for transition animation when data changed
  27991. this._coordSys = coordSys;
  27992. this._stackedOnPoints = stackedOnPoints;
  27993. this._points = points;
  27994. this._step = step;
  27995. },
  27996. dispose: function () {},
  27997. highlight: function (seriesModel, ecModel, api, payload) {
  27998. var data = seriesModel.getData();
  27999. var dataIndex = queryDataIndex(data, payload);
  28000. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28001. var symbol = data.getItemGraphicEl(dataIndex);
  28002. if (!symbol) {
  28003. // Create a temporary symbol if it is not exists
  28004. var pt = data.getItemLayout(dataIndex);
  28005. if (!pt) {
  28006. // Null data
  28007. return;
  28008. }
  28009. symbol = new SymbolClz$1(data, dataIndex);
  28010. symbol.position = pt;
  28011. symbol.setZ(
  28012. seriesModel.get('zlevel'),
  28013. seriesModel.get('z')
  28014. );
  28015. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28016. symbol.__temp = true;
  28017. data.setItemGraphicEl(dataIndex, symbol);
  28018. // Stop scale animation
  28019. symbol.stopSymbolAnimation(true);
  28020. this.group.add(symbol);
  28021. }
  28022. symbol.highlight();
  28023. }
  28024. else {
  28025. // Highlight whole series
  28026. Chart.prototype.highlight.call(
  28027. this, seriesModel, ecModel, api, payload
  28028. );
  28029. }
  28030. },
  28031. downplay: function (seriesModel, ecModel, api, payload) {
  28032. var data = seriesModel.getData();
  28033. var dataIndex = queryDataIndex(data, payload);
  28034. if (dataIndex != null && dataIndex >= 0) {
  28035. var symbol = data.getItemGraphicEl(dataIndex);
  28036. if (symbol) {
  28037. if (symbol.__temp) {
  28038. data.setItemGraphicEl(dataIndex, null);
  28039. this.group.remove(symbol);
  28040. }
  28041. else {
  28042. symbol.downplay();
  28043. }
  28044. }
  28045. }
  28046. else {
  28047. // FIXME
  28048. // can not downplay completely.
  28049. // Downplay whole series
  28050. Chart.prototype.downplay.call(
  28051. this, seriesModel, ecModel, api, payload
  28052. );
  28053. }
  28054. },
  28055. /**
  28056. * @param {module:zrender/container/Group} group
  28057. * @param {Array.<Array.<number>>} points
  28058. * @private
  28059. */
  28060. _newPolyline: function (points) {
  28061. var polyline = this._polyline;
  28062. // Remove previous created polyline
  28063. if (polyline) {
  28064. this._lineGroup.remove(polyline);
  28065. }
  28066. polyline = new Polyline$1({
  28067. shape: {
  28068. points: points
  28069. },
  28070. silent: true,
  28071. z2: 10
  28072. });
  28073. this._lineGroup.add(polyline);
  28074. this._polyline = polyline;
  28075. return polyline;
  28076. },
  28077. /**
  28078. * @param {module:zrender/container/Group} group
  28079. * @param {Array.<Array.<number>>} stackedOnPoints
  28080. * @param {Array.<Array.<number>>} points
  28081. * @private
  28082. */
  28083. _newPolygon: function (points, stackedOnPoints) {
  28084. var polygon = this._polygon;
  28085. // Remove previous created polygon
  28086. if (polygon) {
  28087. this._lineGroup.remove(polygon);
  28088. }
  28089. polygon = new Polygon$1({
  28090. shape: {
  28091. points: points,
  28092. stackedOnPoints: stackedOnPoints
  28093. },
  28094. silent: true
  28095. });
  28096. this._lineGroup.add(polygon);
  28097. this._polygon = polygon;
  28098. return polygon;
  28099. },
  28100. /**
  28101. * @private
  28102. */
  28103. _getSymbolIgnoreFunc: function (data, coordSys) {
  28104. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28105. // `getLabelInterval` is provided by echarts/component/axis
  28106. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28107. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28108. }
  28109. },
  28110. /**
  28111. * @private
  28112. */
  28113. // FIXME Two value axis
  28114. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  28115. var polyline = this._polyline;
  28116. var polygon = this._polygon;
  28117. var seriesModel = data.hostModel;
  28118. var diff = lineAnimationDiff(
  28119. this._data, data,
  28120. this._stackedOnPoints, stackedOnPoints,
  28121. this._coordSys, coordSys
  28122. );
  28123. var current = diff.current;
  28124. var stackedOnCurrent = diff.stackedOnCurrent;
  28125. var next = diff.next;
  28126. var stackedOnNext = diff.stackedOnNext;
  28127. if (step) {
  28128. // TODO If stacked series is not step
  28129. current = turnPointsIntoStep(diff.current, coordSys, step);
  28130. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28131. next = turnPointsIntoStep(diff.next, coordSys, step);
  28132. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28133. }
  28134. // `diff.current` is subset of `current` (which should be ensured by
  28135. // turnPointsIntoStep), so points in `__points` can be updated when
  28136. // points in `current` are update during animation.
  28137. polyline.shape.__points = diff.current;
  28138. polyline.shape.points = current;
  28139. updateProps(polyline, {
  28140. shape: {
  28141. points: next
  28142. }
  28143. }, seriesModel);
  28144. if (polygon) {
  28145. polygon.setShape({
  28146. points: current,
  28147. stackedOnPoints: stackedOnCurrent
  28148. });
  28149. updateProps(polygon, {
  28150. shape: {
  28151. points: next,
  28152. stackedOnPoints: stackedOnNext
  28153. }
  28154. }, seriesModel);
  28155. }
  28156. var updatedDataInfo = [];
  28157. var diffStatus = diff.status;
  28158. for (var i = 0; i < diffStatus.length; i++) {
  28159. var cmd = diffStatus[i].cmd;
  28160. if (cmd === '=') {
  28161. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28162. if (el) {
  28163. updatedDataInfo.push({
  28164. el: el,
  28165. ptIdx: i // Index of points
  28166. });
  28167. }
  28168. }
  28169. }
  28170. if (polyline.animators && polyline.animators.length) {
  28171. polyline.animators[0].during(function () {
  28172. for (var i = 0; i < updatedDataInfo.length; i++) {
  28173. var el = updatedDataInfo[i].el;
  28174. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28175. }
  28176. });
  28177. }
  28178. },
  28179. remove: function (ecModel) {
  28180. var group = this.group;
  28181. var oldData = this._data;
  28182. this._lineGroup.removeAll();
  28183. this._symbolDraw.remove(true);
  28184. // Remove temporary created elements when highlighting
  28185. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28186. if (el.__temp) {
  28187. group.remove(el);
  28188. oldData.setItemGraphicEl(idx, null);
  28189. }
  28190. });
  28191. this._polyline =
  28192. this._polygon =
  28193. this._coordSys =
  28194. this._points =
  28195. this._stackedOnPoints =
  28196. this._data = null;
  28197. }
  28198. });
  28199. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28200. // Encoding visual for all series include which is filtered for legend drawing
  28201. return {
  28202. seriesType: seriesType,
  28203. performRawSeries: true,
  28204. reset: function (seriesModel, ecModel, api) {
  28205. var data = seriesModel.getData();
  28206. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28207. var symbolSize = seriesModel.get('symbolSize');
  28208. data.setVisual({
  28209. legendSymbol: legendSymbol || symbolType,
  28210. symbol: symbolType,
  28211. symbolSize: symbolSize
  28212. });
  28213. // Only visible series has each data be visual encoded
  28214. if (ecModel.isSeriesFiltered(seriesModel)) {
  28215. return;
  28216. }
  28217. var hasCallback = typeof symbolSize === 'function';
  28218. function dataEach(data, idx) {
  28219. if (typeof symbolSize === 'function') {
  28220. var rawValue = seriesModel.getRawValue(idx);
  28221. // FIXME
  28222. var params = seriesModel.getDataParams(idx);
  28223. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28224. }
  28225. if (data.hasItemOption) {
  28226. var itemModel = data.getItemModel(idx);
  28227. var itemSymbolType = itemModel.getShallow('symbol', true);
  28228. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28229. // If has item symbol
  28230. if (itemSymbolType != null) {
  28231. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28232. }
  28233. if (itemSymbolSize != null) {
  28234. // PENDING Transform symbolSize ?
  28235. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  28236. }
  28237. }
  28238. }
  28239. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  28240. }
  28241. };
  28242. };
  28243. var pointsLayout = function (seriesType) {
  28244. return {
  28245. seriesType: seriesType,
  28246. plan: createRenderPlanner(),
  28247. reset: function (seriesModel) {
  28248. var data = seriesModel.getData();
  28249. var coordSys = seriesModel.coordinateSystem;
  28250. var pipelineContext = seriesModel.pipelineContext;
  28251. var isLargeRender = pipelineContext.large;
  28252. if (!coordSys) {
  28253. return;
  28254. }
  28255. var dims = map(coordSys.dimensions, function (dim) {
  28256. return data.getDimension(data.mapDimension(dim));
  28257. }).slice(0, 2);
  28258. var dimLen = dims.length;
  28259. function progress(params, data) {
  28260. var segCount = params.end - params.start;
  28261. var points = isLargeRender && new Float32Array(segCount * dimLen);
  28262. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  28263. var point;
  28264. if (dimLen === 1) {
  28265. var x = data.get(dims[0], i, true);
  28266. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  28267. }
  28268. else {
  28269. var x = tmpIn[0] = data.get(dims[0], i, true);
  28270. var y = tmpIn[1] = data.get(dims[1], i, true);
  28271. // Also {Array.<number>}, not undefined to avoid if...else... statement
  28272. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  28273. }
  28274. if (isLargeRender) {
  28275. points[offset++] = point ? point[0] : NaN;
  28276. points[offset++] = point ? point[1] : NaN;
  28277. }
  28278. else {
  28279. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  28280. }
  28281. }
  28282. isLargeRender && data.setLayout('symbolPoints', points);
  28283. }
  28284. return dimLen && {progress: progress};
  28285. }
  28286. };
  28287. };
  28288. var samplers = {
  28289. average: function (frame) {
  28290. var sum = 0;
  28291. var count = 0;
  28292. for (var i = 0; i < frame.length; i++) {
  28293. if (!isNaN(frame[i])) {
  28294. sum += frame[i];
  28295. count++;
  28296. }
  28297. }
  28298. // Return NaN if count is 0
  28299. return count === 0 ? NaN : sum / count;
  28300. },
  28301. sum: function (frame) {
  28302. var sum = 0;
  28303. for (var i = 0; i < frame.length; i++) {
  28304. // Ignore NaN
  28305. sum += frame[i] || 0;
  28306. }
  28307. return sum;
  28308. },
  28309. max: function (frame) {
  28310. var max = -Infinity;
  28311. for (var i = 0; i < frame.length; i++) {
  28312. frame[i] > max && (max = frame[i]);
  28313. }
  28314. return max;
  28315. },
  28316. min: function (frame) {
  28317. var min = Infinity;
  28318. for (var i = 0; i < frame.length; i++) {
  28319. frame[i] < min && (min = frame[i]);
  28320. }
  28321. return min;
  28322. },
  28323. // TODO
  28324. // Median
  28325. nearest: function (frame) {
  28326. return frame[0];
  28327. }
  28328. };
  28329. var indexSampler = function (frame, value) {
  28330. return Math.round(frame.length / 2);
  28331. };
  28332. var dataSample = function (seriesType) {
  28333. return {
  28334. seriesType: seriesType,
  28335. reset: function (seriesModel, ecModel, api) {
  28336. var data = seriesModel.getData();
  28337. var sampling = seriesModel.get('sampling');
  28338. var coordSys = seriesModel.coordinateSystem;
  28339. // Only cartesian2d support down sampling
  28340. if (coordSys.type === 'cartesian2d' && sampling) {
  28341. var baseAxis = coordSys.getBaseAxis();
  28342. var valueAxis = coordSys.getOtherAxis(baseAxis);
  28343. var extent = baseAxis.getExtent();
  28344. // Coordinste system has been resized
  28345. var size = extent[1] - extent[0];
  28346. var rate = Math.round(data.count() / size);
  28347. if (rate > 1) {
  28348. var sampler;
  28349. if (typeof sampling === 'string') {
  28350. sampler = samplers[sampling];
  28351. }
  28352. else if (typeof sampling === 'function') {
  28353. sampler = sampling;
  28354. }
  28355. if (sampler) {
  28356. seriesModel.setData(data.downSample(
  28357. valueAxis.dim, 1 / rate, sampler, indexSampler
  28358. ));
  28359. }
  28360. }
  28361. }
  28362. }
  28363. };
  28364. };
  28365. /**
  28366. * Cartesian coordinate system
  28367. * @module echarts/coord/Cartesian
  28368. *
  28369. */
  28370. function dimAxisMapper(dim) {
  28371. return this._axes[dim];
  28372. }
  28373. /**
  28374. * @alias module:echarts/coord/Cartesian
  28375. * @constructor
  28376. */
  28377. var Cartesian = function (name) {
  28378. this._axes = {};
  28379. this._dimList = [];
  28380. /**
  28381. * @type {string}
  28382. */
  28383. this.name = name || '';
  28384. };
  28385. Cartesian.prototype = {
  28386. constructor: Cartesian,
  28387. type: 'cartesian',
  28388. /**
  28389. * Get axis
  28390. * @param {number|string} dim
  28391. * @return {module:echarts/coord/Cartesian~Axis}
  28392. */
  28393. getAxis: function (dim) {
  28394. return this._axes[dim];
  28395. },
  28396. /**
  28397. * Get axes list
  28398. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  28399. */
  28400. getAxes: function () {
  28401. return map(this._dimList, dimAxisMapper, this);
  28402. },
  28403. /**
  28404. * Get axes list by given scale type
  28405. */
  28406. getAxesByScale: function (scaleType) {
  28407. scaleType = scaleType.toLowerCase();
  28408. return filter(
  28409. this.getAxes(),
  28410. function (axis) {
  28411. return axis.scale.type === scaleType;
  28412. }
  28413. );
  28414. },
  28415. /**
  28416. * Add axis
  28417. * @param {module:echarts/coord/Cartesian.Axis}
  28418. */
  28419. addAxis: function (axis) {
  28420. var dim = axis.dim;
  28421. this._axes[dim] = axis;
  28422. this._dimList.push(dim);
  28423. },
  28424. /**
  28425. * Convert data to coord in nd space
  28426. * @param {Array.<number>|Object.<string, number>} val
  28427. * @return {Array.<number>|Object.<string, number>}
  28428. */
  28429. dataToCoord: function (val) {
  28430. return this._dataCoordConvert(val, 'dataToCoord');
  28431. },
  28432. /**
  28433. * Convert coord in nd space to data
  28434. * @param {Array.<number>|Object.<string, number>} val
  28435. * @return {Array.<number>|Object.<string, number>}
  28436. */
  28437. coordToData: function (val) {
  28438. return this._dataCoordConvert(val, 'coordToData');
  28439. },
  28440. _dataCoordConvert: function (input, method) {
  28441. var dimList = this._dimList;
  28442. var output = input instanceof Array ? [] : {};
  28443. for (var i = 0; i < dimList.length; i++) {
  28444. var dim = dimList[i];
  28445. var axis = this._axes[dim];
  28446. output[dim] = axis[method](input[dim]);
  28447. }
  28448. return output;
  28449. }
  28450. };
  28451. function Cartesian2D(name) {
  28452. Cartesian.call(this, name);
  28453. }
  28454. Cartesian2D.prototype = {
  28455. constructor: Cartesian2D,
  28456. type: 'cartesian2d',
  28457. /**
  28458. * @type {Array.<string>}
  28459. * @readOnly
  28460. */
  28461. dimensions: ['x', 'y'],
  28462. /**
  28463. * Base axis will be used on stacking.
  28464. *
  28465. * @return {module:echarts/coord/cartesian/Axis2D}
  28466. */
  28467. getBaseAxis: function () {
  28468. return this.getAxesByScale('ordinal')[0]
  28469. || this.getAxesByScale('time')[0]
  28470. || this.getAxis('x');
  28471. },
  28472. /**
  28473. * If contain point
  28474. * @param {Array.<number>} point
  28475. * @return {boolean}
  28476. */
  28477. containPoint: function (point) {
  28478. var axisX = this.getAxis('x');
  28479. var axisY = this.getAxis('y');
  28480. return axisX.contain(axisX.toLocalCoord(point[0]))
  28481. && axisY.contain(axisY.toLocalCoord(point[1]));
  28482. },
  28483. /**
  28484. * If contain data
  28485. * @param {Array.<number>} data
  28486. * @return {boolean}
  28487. */
  28488. containData: function (data) {
  28489. return this.getAxis('x').containData(data[0])
  28490. && this.getAxis('y').containData(data[1]);
  28491. },
  28492. /**
  28493. * @param {Array.<number>} data
  28494. * @param {Array.<number>} out
  28495. * @return {Array.<number>}
  28496. */
  28497. dataToPoint: function (data, reserved, out) {
  28498. var xAxis = this.getAxis('x');
  28499. var yAxis = this.getAxis('y');
  28500. out = out || [];
  28501. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  28502. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  28503. return out;
  28504. },
  28505. /**
  28506. * @param {Array.<number>} data
  28507. * @param {Array.<number>} out
  28508. * @return {Array.<number>}
  28509. */
  28510. clampData: function (data, out) {
  28511. var xAxisExtent = this.getAxis('x').scale.getExtent();
  28512. var yAxisExtent = this.getAxis('y').scale.getExtent();
  28513. out = out || [];
  28514. out[0] = Math.min(
  28515. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  28516. Math.max(xAxisExtent[0], xAxisExtent[1])
  28517. );
  28518. out[1] = Math.min(
  28519. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  28520. Math.max(yAxisExtent[0], yAxisExtent[1])
  28521. );
  28522. return out;
  28523. },
  28524. /**
  28525. * @param {Array.<number>} point
  28526. * @param {Array.<number>} out
  28527. * @return {Array.<number>}
  28528. */
  28529. pointToData: function (point, out) {
  28530. var xAxis = this.getAxis('x');
  28531. var yAxis = this.getAxis('y');
  28532. out = out || [];
  28533. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  28534. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  28535. return out;
  28536. },
  28537. /**
  28538. * Get other axis
  28539. * @param {module:echarts/coord/cartesian/Axis2D} axis
  28540. */
  28541. getOtherAxis: function (axis) {
  28542. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  28543. }
  28544. };
  28545. inherits(Cartesian2D, Cartesian);
  28546. /**
  28547. * Extend axis 2d
  28548. * @constructor module:echarts/coord/cartesian/Axis2D
  28549. * @extends {module:echarts/coord/cartesian/Axis}
  28550. * @param {string} dim
  28551. * @param {*} scale
  28552. * @param {Array.<number>} coordExtent
  28553. * @param {string} axisType
  28554. * @param {string} position
  28555. */
  28556. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  28557. Axis.call(this, dim, scale, coordExtent);
  28558. /**
  28559. * Axis type
  28560. * - 'category'
  28561. * - 'value'
  28562. * - 'time'
  28563. * - 'log'
  28564. * @type {string}
  28565. */
  28566. this.type = axisType || 'value';
  28567. /**
  28568. * Axis position
  28569. * - 'top'
  28570. * - 'bottom'
  28571. * - 'left'
  28572. * - 'right'
  28573. */
  28574. this.position = position || 'bottom';
  28575. };
  28576. Axis2D.prototype = {
  28577. constructor: Axis2D,
  28578. /**
  28579. * Index of axis, can be used as key
  28580. */
  28581. index: 0,
  28582. /**
  28583. * If axis is on the zero position of the other axis
  28584. * @type {boolean}
  28585. */
  28586. onZero: false,
  28587. /**
  28588. * Axis model
  28589. * @param {module:echarts/coord/cartesian/AxisModel}
  28590. */
  28591. model: null,
  28592. isHorizontal: function () {
  28593. var position = this.position;
  28594. return position === 'top' || position === 'bottom';
  28595. },
  28596. /**
  28597. * Each item cooresponds to this.getExtent(), which
  28598. * means globalExtent[0] may greater than globalExtent[1],
  28599. * unless `asc` is input.
  28600. *
  28601. * @param {boolean} [asc]
  28602. * @return {Array.<number>}
  28603. */
  28604. getGlobalExtent: function (asc) {
  28605. var ret = this.getExtent();
  28606. ret[0] = this.toGlobalCoord(ret[0]);
  28607. ret[1] = this.toGlobalCoord(ret[1]);
  28608. asc && ret[0] > ret[1] && ret.reverse();
  28609. return ret;
  28610. },
  28611. getOtherAxis: function () {
  28612. this.grid.getOtherAxis();
  28613. },
  28614. /**
  28615. * If label is ignored.
  28616. * Automatically used when axis is category and label can not be all shown
  28617. * @param {number} idx
  28618. * @return {boolean}
  28619. */
  28620. isLabelIgnored: function (idx) {
  28621. if (this.type === 'category') {
  28622. var labelInterval = this.getLabelInterval();
  28623. return ((typeof labelInterval === 'function')
  28624. && !labelInterval(idx, this.scale.getLabel(idx)))
  28625. || idx % (labelInterval + 1);
  28626. }
  28627. },
  28628. /**
  28629. * @override
  28630. */
  28631. pointToData: function (point, clamp) {
  28632. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  28633. },
  28634. /**
  28635. * Transform global coord to local coord,
  28636. * i.e. var localCoord = axis.toLocalCoord(80);
  28637. * designate by module:echarts/coord/cartesian/Grid.
  28638. * @type {Function}
  28639. */
  28640. toLocalCoord: null,
  28641. /**
  28642. * Transform global coord to local coord,
  28643. * i.e. var globalCoord = axis.toLocalCoord(40);
  28644. * designate by module:echarts/coord/cartesian/Grid.
  28645. * @type {Function}
  28646. */
  28647. toGlobalCoord: null
  28648. };
  28649. inherits(Axis2D, Axis);
  28650. var defaultOption = {
  28651. show: true,
  28652. zlevel: 0, // 一级层叠
  28653. z: 0, // 二级层叠
  28654. // 反向坐标轴
  28655. inverse: false,
  28656. // 坐标轴名字,默认为空
  28657. name: '',
  28658. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  28659. nameLocation: 'end',
  28660. // 坐标轴名字旋转,degree。
  28661. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  28662. nameTruncate: {
  28663. maxWidth: null,
  28664. ellipsis: '...',
  28665. placeholder: '.'
  28666. },
  28667. // 坐标轴文字样式,默认取全局样式
  28668. nameTextStyle: {},
  28669. // 文字与轴线距离
  28670. nameGap: 15,
  28671. silent: false, // Default false to support tooltip.
  28672. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  28673. tooltip: {
  28674. show: false
  28675. },
  28676. axisPointer: {},
  28677. // 坐标轴线
  28678. axisLine: {
  28679. // 默认显示,属性show控制显示与否
  28680. show: true,
  28681. onZero: true,
  28682. onZeroAxisIndex: null,
  28683. // 属性lineStyle控制线条样式
  28684. lineStyle: {
  28685. color: '#333',
  28686. width: 1,
  28687. type: 'solid'
  28688. },
  28689. // 坐标轴两端的箭头
  28690. symbol: ['none', 'none'],
  28691. symbolSize: [10, 15]
  28692. },
  28693. // 坐标轴小标记
  28694. axisTick: {
  28695. // 属性show控制显示与否,默认显示
  28696. show: true,
  28697. // 控制小标记是否在grid里
  28698. inside: false,
  28699. // 属性length控制线长
  28700. length: 5,
  28701. // 属性lineStyle控制线条样式
  28702. lineStyle: {
  28703. width: 1
  28704. }
  28705. },
  28706. // 坐标轴文本标签,详见axis.axisLabel
  28707. axisLabel: {
  28708. show: true,
  28709. // 控制文本标签是否在grid里
  28710. inside: false,
  28711. rotate: 0,
  28712. showMinLabel: null, // true | false | null (auto)
  28713. showMaxLabel: null, // true | false | null (auto)
  28714. margin: 8,
  28715. // formatter: null,
  28716. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  28717. fontSize: 12
  28718. },
  28719. // 分隔线
  28720. splitLine: {
  28721. // 默认显示,属性show控制显示与否
  28722. show: true,
  28723. // 属性lineStyle(详见lineStyle)控制线条样式
  28724. lineStyle: {
  28725. color: ['#ccc'],
  28726. width: 1,
  28727. type: 'solid'
  28728. }
  28729. },
  28730. // 分隔区域
  28731. splitArea: {
  28732. // 默认不显示,属性show控制显示与否
  28733. show: false,
  28734. // 属性areaStyle(详见areaStyle)控制区域样式
  28735. areaStyle: {
  28736. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  28737. }
  28738. }
  28739. };
  28740. var axisDefault = {};
  28741. axisDefault.categoryAxis = merge({
  28742. // 类目起始和结束两端空白策略
  28743. boundaryGap: true,
  28744. // Set false to faster category collection.
  28745. // Only usefull in the case like: category is
  28746. // ['2012-01-01', '2012-01-02', ...], where the input
  28747. // data has been ensured not duplicate and is large data.
  28748. // null means "auto":
  28749. // if axis.data provided, do not deduplication,
  28750. // else do deduplication.
  28751. deduplication: null,
  28752. // splitArea: {
  28753. // show: false
  28754. // },
  28755. splitLine: {
  28756. show: false
  28757. },
  28758. // 坐标轴小标记
  28759. axisTick: {
  28760. // If tick is align with label when boundaryGap is true
  28761. alignWithLabel: false,
  28762. interval: 'auto'
  28763. },
  28764. // 坐标轴文本标签,详见axis.axisLabel
  28765. axisLabel: {
  28766. interval: 'auto'
  28767. }
  28768. }, defaultOption);
  28769. axisDefault.valueAxis = merge({
  28770. // 数值起始和结束两端空白策略
  28771. boundaryGap: [0, 0],
  28772. // TODO
  28773. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  28774. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  28775. // min: null,
  28776. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  28777. // max: null,
  28778. // Readonly prop, specifies start value of the range when using data zoom.
  28779. // rangeStart: null
  28780. // Readonly prop, specifies end value of the range when using data zoom.
  28781. // rangeEnd: null
  28782. // 脱离0值比例,放大聚焦到最终_min,_max区间
  28783. // scale: false,
  28784. // 分割段数,默认为5
  28785. splitNumber: 5
  28786. // Minimum interval
  28787. // minInterval: null
  28788. // maxInterval: null
  28789. }, defaultOption);
  28790. // FIXME
  28791. axisDefault.timeAxis = defaults({
  28792. scale: true,
  28793. min: 'dataMin',
  28794. max: 'dataMax'
  28795. }, axisDefault.valueAxis);
  28796. axisDefault.logAxis = defaults({
  28797. scale: true,
  28798. logBase: 10
  28799. }, axisDefault.valueAxis);
  28800. // FIXME axisType is fixed ?
  28801. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  28802. /**
  28803. * Generate sub axis model class
  28804. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  28805. * @param {module:echarts/model/Component} BaseAxisModelClass
  28806. * @param {Function} axisTypeDefaulter
  28807. * @param {Object} [extraDefaultOption]
  28808. */
  28809. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  28810. each$1(AXIS_TYPES, function (axisType) {
  28811. BaseAxisModelClass.extend({
  28812. /**
  28813. * @readOnly
  28814. */
  28815. type: axisName + 'Axis.' + axisType,
  28816. mergeDefaultAndTheme: function (option, ecModel) {
  28817. var layoutMode = this.layoutMode;
  28818. var inputPositionParams = layoutMode
  28819. ? getLayoutParams(option) : {};
  28820. var themeModel = ecModel.getTheme();
  28821. merge(option, themeModel.get(axisType + 'Axis'));
  28822. merge(option, this.getDefaultOption());
  28823. option.type = axisTypeDefaulter(axisName, option);
  28824. if (layoutMode) {
  28825. mergeLayoutParam(option, inputPositionParams, layoutMode);
  28826. }
  28827. },
  28828. /**
  28829. * @override
  28830. */
  28831. optionUpdated: function () {
  28832. var thisOption = this.option;
  28833. if (thisOption.type === 'category') {
  28834. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  28835. }
  28836. },
  28837. /**
  28838. * Should not be called before all of 'getInitailData' finished.
  28839. * Because categories are collected during initializing data.
  28840. */
  28841. getCategories: function () {
  28842. // FIXME
  28843. // warning if called before all of 'getInitailData' finished.
  28844. if (this.option.type === 'category') {
  28845. return this.__ordinalMeta.categories;
  28846. }
  28847. },
  28848. getOrdinalMeta: function () {
  28849. return this.__ordinalMeta;
  28850. },
  28851. defaultOption: mergeAll(
  28852. [
  28853. {},
  28854. axisDefault[axisType + 'Axis'],
  28855. extraDefaultOption
  28856. ],
  28857. true
  28858. )
  28859. });
  28860. });
  28861. ComponentModel.registerSubTypeDefaulter(
  28862. axisName + 'Axis',
  28863. curry(axisTypeDefaulter, axisName)
  28864. );
  28865. };
  28866. var AxisModel = ComponentModel.extend({
  28867. type: 'cartesian2dAxis',
  28868. /**
  28869. * @type {module:echarts/coord/cartesian/Axis2D}
  28870. */
  28871. axis: null,
  28872. /**
  28873. * @override
  28874. */
  28875. init: function () {
  28876. AxisModel.superApply(this, 'init', arguments);
  28877. this.resetRange();
  28878. },
  28879. /**
  28880. * @override
  28881. */
  28882. mergeOption: function () {
  28883. AxisModel.superApply(this, 'mergeOption', arguments);
  28884. this.resetRange();
  28885. },
  28886. /**
  28887. * @override
  28888. */
  28889. restoreData: function () {
  28890. AxisModel.superApply(this, 'restoreData', arguments);
  28891. this.resetRange();
  28892. },
  28893. /**
  28894. * @override
  28895. * @return {module:echarts/model/Component}
  28896. */
  28897. getCoordSysModel: function () {
  28898. return this.ecModel.queryComponents({
  28899. mainType: 'grid',
  28900. index: this.option.gridIndex,
  28901. id: this.option.gridId
  28902. })[0];
  28903. }
  28904. });
  28905. function getAxisType(axisDim, option) {
  28906. // Default axis with data is category axis
  28907. return option.type || (option.data ? 'category' : 'value');
  28908. }
  28909. merge(AxisModel.prototype, axisModelCommonMixin);
  28910. var extraOption = {
  28911. // gridIndex: 0,
  28912. // gridId: '',
  28913. // Offset is for multiple axis on the same position
  28914. offset: 0
  28915. };
  28916. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  28917. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  28918. // Grid 是在有直角坐标系的时候必须要存在的
  28919. // 所以这里也要被 Cartesian2D 依赖
  28920. ComponentModel.extend({
  28921. type: 'grid',
  28922. dependencies: ['xAxis', 'yAxis'],
  28923. layoutMode: 'box',
  28924. /**
  28925. * @type {module:echarts/coord/cartesian/Grid}
  28926. */
  28927. coordinateSystem: null,
  28928. defaultOption: {
  28929. show: false,
  28930. zlevel: 0,
  28931. z: 0,
  28932. left: '10%',
  28933. top: 60,
  28934. right: '10%',
  28935. bottom: 60,
  28936. // If grid size contain label
  28937. containLabel: false,
  28938. // width: {totalWidth} - left - right,
  28939. // height: {totalHeight} - top - bottom,
  28940. backgroundColor: 'rgba(0,0,0,0)',
  28941. borderWidth: 1,
  28942. borderColor: '#ccc'
  28943. }
  28944. });
  28945. /**
  28946. * Grid is a region which contains at most 4 cartesian systems
  28947. *
  28948. * TODO Default cartesian
  28949. */
  28950. // Depends on GridModel, AxisModel, which performs preprocess.
  28951. var each$6 = each$1;
  28952. var ifAxisCrossZero$1 = ifAxisCrossZero;
  28953. var niceScaleExtent$1 = niceScaleExtent;
  28954. /**
  28955. * Check if the axis is used in the specified grid
  28956. * @inner
  28957. */
  28958. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  28959. return axisModel.getCoordSysModel() === gridModel;
  28960. }
  28961. function rotateTextRect(textRect, rotate) {
  28962. var rotateRadians = rotate * Math.PI / 180;
  28963. var boundingBox = textRect.plain();
  28964. var beforeWidth = boundingBox.width;
  28965. var beforeHeight = boundingBox.height;
  28966. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  28967. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  28968. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  28969. return rotatedRect;
  28970. }
  28971. function getLabelUnionRect(axis) {
  28972. var axisModel = axis.model;
  28973. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  28974. var axisLabelModel = axisModel.getModel('axisLabel');
  28975. var rect;
  28976. var step = 1;
  28977. var labelCount = labels.length;
  28978. if (labelCount > 40) {
  28979. // Simple optimization for large amount of labels
  28980. step = Math.ceil(labelCount / 40);
  28981. }
  28982. for (var i = 0; i < labelCount; i += step) {
  28983. if (!axis.isLabelIgnored(i)) {
  28984. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  28985. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  28986. rect ? rect.union(singleRect) : (rect = singleRect);
  28987. }
  28988. }
  28989. return rect;
  28990. }
  28991. function Grid(gridModel, ecModel, api) {
  28992. /**
  28993. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  28994. * @private
  28995. */
  28996. this._coordsMap = {};
  28997. /**
  28998. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  28999. * @private
  29000. */
  29001. this._coordsList = [];
  29002. /**
  29003. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29004. * @private
  29005. */
  29006. this._axesMap = {};
  29007. /**
  29008. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29009. * @private
  29010. */
  29011. this._axesList = [];
  29012. this._initCartesian(gridModel, ecModel, api);
  29013. this.model = gridModel;
  29014. }
  29015. var gridProto = Grid.prototype;
  29016. gridProto.type = 'grid';
  29017. gridProto.axisPointerEnabled = true;
  29018. gridProto.getRect = function () {
  29019. return this._rect;
  29020. };
  29021. gridProto.update = function (ecModel, api) {
  29022. var axesMap = this._axesMap;
  29023. this._updateScale(ecModel, this.model);
  29024. each$6(axesMap.x, function (xAxis) {
  29025. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29026. });
  29027. each$6(axesMap.y, function (yAxis) {
  29028. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29029. });
  29030. each$6(axesMap.x, function (xAxis) {
  29031. fixAxisOnZero(axesMap, 'y', xAxis);
  29032. });
  29033. each$6(axesMap.y, function (yAxis) {
  29034. fixAxisOnZero(axesMap, 'x', yAxis);
  29035. });
  29036. // Resize again if containLabel is enabled
  29037. // FIXME It may cause getting wrong grid size in data processing stage
  29038. this.resize(this.model, api);
  29039. };
  29040. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29041. // onZero can not be enabled in these two situations:
  29042. // 1. When any other axis is a category axis.
  29043. // 2. When no axis is cross 0 point.
  29044. var axes = axesMap[otherAxisDim];
  29045. if (!axis.onZero) {
  29046. return;
  29047. }
  29048. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29049. // If target axis is specified.
  29050. if (onZeroAxisIndex != null) {
  29051. var otherAxis = axes[onZeroAxisIndex];
  29052. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29053. axis.onZero = false;
  29054. }
  29055. return;
  29056. }
  29057. for (var idx in axes) {
  29058. if (axes.hasOwnProperty(idx)) {
  29059. var otherAxis = axes[idx];
  29060. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29061. onZeroAxisIndex = +idx;
  29062. break;
  29063. }
  29064. }
  29065. }
  29066. if (onZeroAxisIndex == null) {
  29067. axis.onZero = false;
  29068. }
  29069. axis.onZeroAxisIndex = onZeroAxisIndex;
  29070. }
  29071. function canNotOnZeroToAxis(axis) {
  29072. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29073. }
  29074. /**
  29075. * Resize the grid
  29076. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29077. * @param {module:echarts/ExtensionAPI} api
  29078. */
  29079. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29080. var gridRect = getLayoutRect(
  29081. gridModel.getBoxLayoutParams(), {
  29082. width: api.getWidth(),
  29083. height: api.getHeight()
  29084. });
  29085. this._rect = gridRect;
  29086. var axesList = this._axesList;
  29087. adjustAxes();
  29088. // Minus label size
  29089. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29090. each$6(axesList, function (axis) {
  29091. if (!axis.model.get('axisLabel.inside')) {
  29092. var labelUnionRect = getLabelUnionRect(axis);
  29093. if (labelUnionRect) {
  29094. var dim = axis.isHorizontal() ? 'height' : 'width';
  29095. var margin = axis.model.get('axisLabel.margin');
  29096. gridRect[dim] -= labelUnionRect[dim] + margin;
  29097. if (axis.position === 'top') {
  29098. gridRect.y += labelUnionRect.height + margin;
  29099. }
  29100. else if (axis.position === 'left') {
  29101. gridRect.x += labelUnionRect.width + margin;
  29102. }
  29103. }
  29104. }
  29105. });
  29106. adjustAxes();
  29107. }
  29108. function adjustAxes() {
  29109. each$6(axesList, function (axis) {
  29110. var isHorizontal = axis.isHorizontal();
  29111. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29112. var idx = axis.inverse ? 1 : 0;
  29113. axis.setExtent(extent[idx], extent[1 - idx]);
  29114. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29115. });
  29116. }
  29117. };
  29118. /**
  29119. * @param {string} axisType
  29120. * @param {number} [axisIndex]
  29121. */
  29122. gridProto.getAxis = function (axisType, axisIndex) {
  29123. var axesMapOnDim = this._axesMap[axisType];
  29124. if (axesMapOnDim != null) {
  29125. if (axisIndex == null) {
  29126. // Find first axis
  29127. for (var name in axesMapOnDim) {
  29128. if (axesMapOnDim.hasOwnProperty(name)) {
  29129. return axesMapOnDim[name];
  29130. }
  29131. }
  29132. }
  29133. return axesMapOnDim[axisIndex];
  29134. }
  29135. };
  29136. /**
  29137. * @return {Array.<module:echarts/coord/Axis>}
  29138. */
  29139. gridProto.getAxes = function () {
  29140. return this._axesList.slice();
  29141. };
  29142. /**
  29143. * Usage:
  29144. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29145. * grid.getCartesian(xAxisIndex);
  29146. * grid.getCartesian(null, yAxisIndex);
  29147. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29148. *
  29149. * @param {number|Object} [xAxisIndex]
  29150. * @param {number} [yAxisIndex]
  29151. */
  29152. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29153. if (xAxisIndex != null && yAxisIndex != null) {
  29154. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29155. return this._coordsMap[key];
  29156. }
  29157. if (isObject$1(xAxisIndex)) {
  29158. yAxisIndex = xAxisIndex.yAxisIndex;
  29159. xAxisIndex = xAxisIndex.xAxisIndex;
  29160. }
  29161. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29162. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29163. if (coordList[i].getAxis('x').index === xAxisIndex
  29164. || coordList[i].getAxis('y').index === yAxisIndex
  29165. ) {
  29166. return coordList[i];
  29167. }
  29168. }
  29169. };
  29170. gridProto.getCartesians = function () {
  29171. return this._coordsList.slice();
  29172. };
  29173. /**
  29174. * @implements
  29175. * see {module:echarts/CoodinateSystem}
  29176. */
  29177. gridProto.convertToPixel = function (ecModel, finder, value) {
  29178. var target = this._findConvertTarget(ecModel, finder);
  29179. return target.cartesian
  29180. ? target.cartesian.dataToPoint(value)
  29181. : target.axis
  29182. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29183. : null;
  29184. };
  29185. /**
  29186. * @implements
  29187. * see {module:echarts/CoodinateSystem}
  29188. */
  29189. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29190. var target = this._findConvertTarget(ecModel, finder);
  29191. return target.cartesian
  29192. ? target.cartesian.pointToData(value)
  29193. : target.axis
  29194. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29195. : null;
  29196. };
  29197. /**
  29198. * @inner
  29199. */
  29200. gridProto._findConvertTarget = function (ecModel, finder) {
  29201. var seriesModel = finder.seriesModel;
  29202. var xAxisModel = finder.xAxisModel
  29203. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29204. var yAxisModel = finder.yAxisModel
  29205. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29206. var gridModel = finder.gridModel;
  29207. var coordsList = this._coordsList;
  29208. var cartesian;
  29209. var axis;
  29210. if (seriesModel) {
  29211. cartesian = seriesModel.coordinateSystem;
  29212. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29213. }
  29214. else if (xAxisModel && yAxisModel) {
  29215. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29216. }
  29217. else if (xAxisModel) {
  29218. axis = this.getAxis('x', xAxisModel.componentIndex);
  29219. }
  29220. else if (yAxisModel) {
  29221. axis = this.getAxis('y', yAxisModel.componentIndex);
  29222. }
  29223. // Lowest priority.
  29224. else if (gridModel) {
  29225. var grid = gridModel.coordinateSystem;
  29226. if (grid === this) {
  29227. cartesian = this._coordsList[0];
  29228. }
  29229. }
  29230. return {cartesian: cartesian, axis: axis};
  29231. };
  29232. /**
  29233. * @implements
  29234. * see {module:echarts/CoodinateSystem}
  29235. */
  29236. gridProto.containPoint = function (point) {
  29237. var coord = this._coordsList[0];
  29238. if (coord) {
  29239. return coord.containPoint(point);
  29240. }
  29241. };
  29242. /**
  29243. * Initialize cartesian coordinate systems
  29244. * @private
  29245. */
  29246. gridProto._initCartesian = function (gridModel, ecModel, api) {
  29247. var axisPositionUsed = {
  29248. left: false,
  29249. right: false,
  29250. top: false,
  29251. bottom: false
  29252. };
  29253. var axesMap = {
  29254. x: {},
  29255. y: {}
  29256. };
  29257. var axesCount = {
  29258. x: 0,
  29259. y: 0
  29260. };
  29261. /// Create axis
  29262. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  29263. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  29264. if (!axesCount.x || !axesCount.y) {
  29265. // Roll back when there no either x or y axis
  29266. this._axesMap = {};
  29267. this._axesList = [];
  29268. return;
  29269. }
  29270. this._axesMap = axesMap;
  29271. /// Create cartesian2d
  29272. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  29273. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  29274. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29275. var cartesian = new Cartesian2D(key);
  29276. cartesian.grid = this;
  29277. cartesian.model = gridModel;
  29278. this._coordsMap[key] = cartesian;
  29279. this._coordsList.push(cartesian);
  29280. cartesian.addAxis(xAxis);
  29281. cartesian.addAxis(yAxis);
  29282. }, this);
  29283. }, this);
  29284. function createAxisCreator(axisType) {
  29285. return function (axisModel, idx) {
  29286. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  29287. return;
  29288. }
  29289. var axisPosition = axisModel.get('position');
  29290. if (axisType === 'x') {
  29291. // Fix position
  29292. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  29293. // Default bottom of X
  29294. axisPosition = 'bottom';
  29295. if (axisPositionUsed[axisPosition]) {
  29296. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  29297. }
  29298. }
  29299. }
  29300. else {
  29301. // Fix position
  29302. if (axisPosition !== 'left' && axisPosition !== 'right') {
  29303. // Default left of Y
  29304. axisPosition = 'left';
  29305. if (axisPositionUsed[axisPosition]) {
  29306. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  29307. }
  29308. }
  29309. }
  29310. axisPositionUsed[axisPosition] = true;
  29311. var axis = new Axis2D(
  29312. axisType, createScaleByModel(axisModel),
  29313. [0, 0],
  29314. axisModel.get('type'),
  29315. axisPosition
  29316. );
  29317. var isCategory = axis.type === 'category';
  29318. axis.onBand = isCategory && axisModel.get('boundaryGap');
  29319. axis.inverse = axisModel.get('inverse');
  29320. axis.onZero = axisModel.get('axisLine.onZero');
  29321. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  29322. // Inject axis into axisModel
  29323. axisModel.axis = axis;
  29324. // Inject axisModel into axis
  29325. axis.model = axisModel;
  29326. // Inject grid info axis
  29327. axis.grid = this;
  29328. // Index of axis, can be used as key
  29329. axis.index = idx;
  29330. this._axesList.push(axis);
  29331. axesMap[axisType][idx] = axis;
  29332. axesCount[axisType]++;
  29333. };
  29334. }
  29335. };
  29336. /**
  29337. * Update cartesian properties from series
  29338. * @param {module:echarts/model/Option} option
  29339. * @private
  29340. */
  29341. gridProto._updateScale = function (ecModel, gridModel) {
  29342. // Reset scale
  29343. each$1(this._axesList, function (axis) {
  29344. axis.scale.setExtent(Infinity, -Infinity);
  29345. });
  29346. ecModel.eachSeries(function (seriesModel) {
  29347. if (isCartesian2D(seriesModel)) {
  29348. var axesModels = findAxesModels(seriesModel, ecModel);
  29349. var xAxisModel = axesModels[0];
  29350. var yAxisModel = axesModels[1];
  29351. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  29352. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  29353. ) {
  29354. return;
  29355. }
  29356. var cartesian = this.getCartesian(
  29357. xAxisModel.componentIndex, yAxisModel.componentIndex
  29358. );
  29359. var data = seriesModel.getData();
  29360. var xAxis = cartesian.getAxis('x');
  29361. var yAxis = cartesian.getAxis('y');
  29362. if (data.type === 'list') {
  29363. unionExtent(data, xAxis, seriesModel);
  29364. unionExtent(data, yAxis, seriesModel);
  29365. }
  29366. }
  29367. }, this);
  29368. function unionExtent(data, axis, seriesModel) {
  29369. each$6(data.mapDimension(axis.dim, true), function (dim) {
  29370. axis.scale.unionExtentFromData(data, dim);
  29371. });
  29372. }
  29373. };
  29374. /**
  29375. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  29376. * @return {Object} {baseAxes: [], otherAxes: []}
  29377. */
  29378. gridProto.getTooltipAxes = function (dim) {
  29379. var baseAxes = [];
  29380. var otherAxes = [];
  29381. each$6(this.getCartesians(), function (cartesian) {
  29382. var baseAxis = (dim != null && dim !== 'auto')
  29383. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  29384. var otherAxis = cartesian.getOtherAxis(baseAxis);
  29385. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  29386. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  29387. });
  29388. return {baseAxes: baseAxes, otherAxes: otherAxes};
  29389. };
  29390. /**
  29391. * @inner
  29392. */
  29393. function updateAxisTransform(axis, coordBase) {
  29394. var axisExtent = axis.getExtent();
  29395. var axisExtentSum = axisExtent[0] + axisExtent[1];
  29396. // Fast transform
  29397. axis.toGlobalCoord = axis.dim === 'x'
  29398. ? function (coord) {
  29399. return coord + coordBase;
  29400. }
  29401. : function (coord) {
  29402. return axisExtentSum - coord + coordBase;
  29403. };
  29404. axis.toLocalCoord = axis.dim === 'x'
  29405. ? function (coord) {
  29406. return coord - coordBase;
  29407. }
  29408. : function (coord) {
  29409. return axisExtentSum - coord + coordBase;
  29410. };
  29411. }
  29412. var axesTypes = ['xAxis', 'yAxis'];
  29413. /**
  29414. * @inner
  29415. */
  29416. function findAxesModels(seriesModel, ecModel) {
  29417. return map(axesTypes, function (axisType) {
  29418. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  29419. if (__DEV__) {
  29420. if (!axisModel) {
  29421. throw new Error(axisType + ' "' + retrieve(
  29422. seriesModel.get(axisType + 'Index'),
  29423. seriesModel.get(axisType + 'Id'),
  29424. 0
  29425. ) + '" not found');
  29426. }
  29427. }
  29428. return axisModel;
  29429. });
  29430. }
  29431. /**
  29432. * @inner
  29433. */
  29434. function isCartesian2D(seriesModel) {
  29435. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  29436. }
  29437. Grid.create = function (ecModel, api) {
  29438. var grids = [];
  29439. ecModel.eachComponent('grid', function (gridModel, idx) {
  29440. var grid = new Grid(gridModel, ecModel, api);
  29441. grid.name = 'grid_' + idx;
  29442. // dataSampling requires axis extent, so resize
  29443. // should be performed in create stage.
  29444. grid.resize(gridModel, api, true);
  29445. gridModel.coordinateSystem = grid;
  29446. grids.push(grid);
  29447. });
  29448. // Inject the coordinateSystems into seriesModel
  29449. ecModel.eachSeries(function (seriesModel) {
  29450. if (!isCartesian2D(seriesModel)) {
  29451. return;
  29452. }
  29453. var axesModels = findAxesModels(seriesModel, ecModel);
  29454. var xAxisModel = axesModels[0];
  29455. var yAxisModel = axesModels[1];
  29456. var gridModel = xAxisModel.getCoordSysModel();
  29457. if (__DEV__) {
  29458. if (!gridModel) {
  29459. throw new Error(
  29460. 'Grid "' + retrieve(
  29461. xAxisModel.get('gridIndex'),
  29462. xAxisModel.get('gridId'),
  29463. 0
  29464. ) + '" not found'
  29465. );
  29466. }
  29467. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  29468. throw new Error('xAxis and yAxis must use the same grid');
  29469. }
  29470. }
  29471. var grid = gridModel.coordinateSystem;
  29472. seriesModel.coordinateSystem = grid.getCartesian(
  29473. xAxisModel.componentIndex, yAxisModel.componentIndex
  29474. );
  29475. });
  29476. return grids;
  29477. };
  29478. // For deciding which dimensions to use when creating list data
  29479. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  29480. CoordinateSystemManager.register('cartesian2d', Grid);
  29481. var PI$2 = Math.PI;
  29482. function makeAxisEventDataBase(axisModel) {
  29483. var eventData = {
  29484. componentType: axisModel.mainType
  29485. };
  29486. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  29487. return eventData;
  29488. }
  29489. /**
  29490. * A final axis is translated and rotated from a "standard axis".
  29491. * So opt.position and opt.rotation is required.
  29492. *
  29493. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  29494. * for example: (0, 0) ------------> (0, 50)
  29495. *
  29496. * nameDirection or tickDirection or labelDirection is 1 means tick
  29497. * or label is below the standard axis, whereas is -1 means above
  29498. * the standard axis. labelOffset means offset between label and axis,
  29499. * which is useful when 'onZero', where axisLabel is in the grid and
  29500. * label in outside grid.
  29501. *
  29502. * Tips: like always,
  29503. * positive rotation represents anticlockwise, and negative rotation
  29504. * represents clockwise.
  29505. * The direction of position coordinate is the same as the direction
  29506. * of screen coordinate.
  29507. *
  29508. * Do not need to consider axis 'inverse', which is auto processed by
  29509. * axis extent.
  29510. *
  29511. * @param {module:zrender/container/Group} group
  29512. * @param {Object} axisModel
  29513. * @param {Object} opt Standard axis parameters.
  29514. * @param {Array.<number>} opt.position [x, y]
  29515. * @param {number} opt.rotation by radian
  29516. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  29517. * @param {number} [opt.tickDirection=1] 1 or -1
  29518. * @param {number} [opt.labelDirection=1] 1 or -1
  29519. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  29520. * @param {string} [opt.axisLabelShow] default get from axisModel.
  29521. * @param {string} [opt.axisName] default get from axisModel.
  29522. * @param {number} [opt.axisNameAvailableWidth]
  29523. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  29524. * @param {number} [opt.labelInterval] Default label interval when label
  29525. * interval from model is null or 'auto'.
  29526. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  29527. * @param {number} [opt.nameTruncateMaxWidth]
  29528. */
  29529. var AxisBuilder = function (axisModel, opt) {
  29530. /**
  29531. * @readOnly
  29532. */
  29533. this.opt = opt;
  29534. /**
  29535. * @readOnly
  29536. */
  29537. this.axisModel = axisModel;
  29538. // Default value
  29539. defaults(
  29540. opt,
  29541. {
  29542. labelOffset: 0,
  29543. nameDirection: 1,
  29544. tickDirection: 1,
  29545. labelDirection: 1,
  29546. silent: true
  29547. }
  29548. );
  29549. /**
  29550. * @readOnly
  29551. */
  29552. this.group = new Group();
  29553. // FIXME Not use a seperate text group?
  29554. var dumbGroup = new Group({
  29555. position: opt.position.slice(),
  29556. rotation: opt.rotation
  29557. });
  29558. // this.group.add(dumbGroup);
  29559. // this._dumbGroup = dumbGroup;
  29560. dumbGroup.updateTransform();
  29561. this._transform = dumbGroup.transform;
  29562. this._dumbGroup = dumbGroup;
  29563. };
  29564. AxisBuilder.prototype = {
  29565. constructor: AxisBuilder,
  29566. hasBuilder: function (name) {
  29567. return !!builders[name];
  29568. },
  29569. add: function (name) {
  29570. builders[name].call(this);
  29571. },
  29572. getGroup: function () {
  29573. return this.group;
  29574. }
  29575. };
  29576. var builders = {
  29577. /**
  29578. * @private
  29579. */
  29580. axisLine: function () {
  29581. var opt = this.opt;
  29582. var axisModel = this.axisModel;
  29583. if (!axisModel.get('axisLine.show')) {
  29584. return;
  29585. }
  29586. var extent = this.axisModel.axis.getExtent();
  29587. var matrix = this._transform;
  29588. var pt1 = [extent[0], 0];
  29589. var pt2 = [extent[1], 0];
  29590. if (matrix) {
  29591. applyTransform(pt1, pt1, matrix);
  29592. applyTransform(pt2, pt2, matrix);
  29593. }
  29594. var lineStyle = extend(
  29595. {
  29596. lineCap: 'round'
  29597. },
  29598. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  29599. );
  29600. this.group.add(new Line(subPixelOptimizeLine({
  29601. // Id for animation
  29602. anid: 'line',
  29603. shape: {
  29604. x1: pt1[0],
  29605. y1: pt1[1],
  29606. x2: pt2[0],
  29607. y2: pt2[1]
  29608. },
  29609. style: lineStyle,
  29610. strokeContainThreshold: opt.strokeContainThreshold || 5,
  29611. silent: true,
  29612. z2: 1
  29613. })));
  29614. var arrows = axisModel.get('axisLine.symbol');
  29615. var arrowSize = axisModel.get('axisLine.symbolSize');
  29616. if (arrows != null) {
  29617. if (typeof arrows === 'string') {
  29618. // Use the same arrow for start and end point
  29619. arrows = [arrows, arrows];
  29620. }
  29621. if (typeof arrowSize === 'string'
  29622. || typeof arrowSize === 'number'
  29623. ) {
  29624. // Use the same size for width and height
  29625. arrowSize = [arrowSize, arrowSize];
  29626. }
  29627. var symbolWidth = arrowSize[0];
  29628. var symbolHeight = arrowSize[1];
  29629. each$1([
  29630. [opt.rotation + Math.PI / 2, pt1],
  29631. [opt.rotation - Math.PI / 2, pt2]
  29632. ], function (item, index) {
  29633. if (arrows[index] !== 'none' && arrows[index] != null) {
  29634. var symbol = createSymbol(
  29635. arrows[index],
  29636. -symbolWidth / 2,
  29637. -symbolHeight / 2,
  29638. symbolWidth,
  29639. symbolHeight,
  29640. lineStyle.stroke,
  29641. true
  29642. );
  29643. symbol.attr({
  29644. rotation: item[0],
  29645. position: item[1],
  29646. silent: true
  29647. });
  29648. this.group.add(symbol);
  29649. }
  29650. }, this);
  29651. }
  29652. },
  29653. /**
  29654. * @private
  29655. */
  29656. axisTickLabel: function () {
  29657. var axisModel = this.axisModel;
  29658. var opt = this.opt;
  29659. var tickEls = buildAxisTick(this, axisModel, opt);
  29660. var labelEls = buildAxisLabel(this, axisModel, opt);
  29661. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  29662. },
  29663. /**
  29664. * @private
  29665. */
  29666. axisName: function () {
  29667. var opt = this.opt;
  29668. var axisModel = this.axisModel;
  29669. var name = retrieve(opt.axisName, axisModel.get('name'));
  29670. if (!name) {
  29671. return;
  29672. }
  29673. var nameLocation = axisModel.get('nameLocation');
  29674. var nameDirection = opt.nameDirection;
  29675. var textStyleModel = axisModel.getModel('nameTextStyle');
  29676. var gap = axisModel.get('nameGap') || 0;
  29677. var extent = this.axisModel.axis.getExtent();
  29678. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  29679. var pos = [
  29680. nameLocation === 'start'
  29681. ? extent[0] - gapSignal * gap
  29682. : nameLocation === 'end'
  29683. ? extent[1] + gapSignal * gap
  29684. : (extent[0] + extent[1]) / 2, // 'middle'
  29685. // Reuse labelOffset.
  29686. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  29687. ];
  29688. var labelLayout;
  29689. var nameRotation = axisModel.get('nameRotate');
  29690. if (nameRotation != null) {
  29691. nameRotation = nameRotation * PI$2 / 180; // To radian.
  29692. }
  29693. var axisNameAvailableWidth;
  29694. if (isNameLocationCenter(nameLocation)) {
  29695. labelLayout = innerTextLayout(
  29696. opt.rotation,
  29697. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  29698. nameDirection
  29699. );
  29700. }
  29701. else {
  29702. labelLayout = endTextLayout(
  29703. opt, nameLocation, nameRotation || 0, extent
  29704. );
  29705. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  29706. if (axisNameAvailableWidth != null) {
  29707. axisNameAvailableWidth = Math.abs(
  29708. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  29709. );
  29710. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  29711. }
  29712. }
  29713. var textFont = textStyleModel.getFont();
  29714. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  29715. var ellipsis = truncateOpt.ellipsis;
  29716. var maxWidth = retrieve(
  29717. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  29718. );
  29719. // FIXME
  29720. // truncate rich text? (consider performance)
  29721. var truncatedText = (ellipsis != null && maxWidth != null)
  29722. ? truncateText$1(
  29723. name, maxWidth, textFont, ellipsis,
  29724. {minChar: 2, placeholder: truncateOpt.placeholder}
  29725. )
  29726. : name;
  29727. var tooltipOpt = axisModel.get('tooltip', true);
  29728. var mainType = axisModel.mainType;
  29729. var formatterParams = {
  29730. componentType: mainType,
  29731. name: name,
  29732. $vars: ['name']
  29733. };
  29734. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  29735. var textEl = new Text({
  29736. // Id for animation
  29737. anid: 'name',
  29738. __fullText: name,
  29739. __truncatedText: truncatedText,
  29740. position: pos,
  29741. rotation: labelLayout.rotation,
  29742. silent: isSilent(axisModel),
  29743. z2: 1,
  29744. tooltip: (tooltipOpt && tooltipOpt.show)
  29745. ? extend({
  29746. content: name,
  29747. formatter: function () {
  29748. return name;
  29749. },
  29750. formatterParams: formatterParams
  29751. }, tooltipOpt)
  29752. : null
  29753. });
  29754. setTextStyle(textEl.style, textStyleModel, {
  29755. text: truncatedText,
  29756. textFont: textFont,
  29757. textFill: textStyleModel.getTextColor()
  29758. || axisModel.get('axisLine.lineStyle.color'),
  29759. textAlign: labelLayout.textAlign,
  29760. textVerticalAlign: labelLayout.textVerticalAlign
  29761. });
  29762. if (axisModel.get('triggerEvent')) {
  29763. textEl.eventData = makeAxisEventDataBase(axisModel);
  29764. textEl.eventData.targetType = 'axisName';
  29765. textEl.eventData.name = name;
  29766. }
  29767. // FIXME
  29768. this._dumbGroup.add(textEl);
  29769. textEl.updateTransform();
  29770. this.group.add(textEl);
  29771. textEl.decomposeTransform();
  29772. }
  29773. };
  29774. /**
  29775. * @public
  29776. * @static
  29777. * @param {Object} opt
  29778. * @param {number} axisRotation in radian
  29779. * @param {number} textRotation in radian
  29780. * @param {number} direction
  29781. * @return {Object} {
  29782. * rotation, // according to axis
  29783. * textAlign,
  29784. * textVerticalAlign
  29785. * }
  29786. */
  29787. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  29788. var rotationDiff = remRadian(textRotation - axisRotation);
  29789. var textAlign;
  29790. var textVerticalAlign;
  29791. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  29792. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  29793. textAlign = 'center';
  29794. }
  29795. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  29796. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  29797. textAlign = 'center';
  29798. }
  29799. else {
  29800. textVerticalAlign = 'middle';
  29801. if (rotationDiff > 0 && rotationDiff < PI$2) {
  29802. textAlign = direction > 0 ? 'right' : 'left';
  29803. }
  29804. else {
  29805. textAlign = direction > 0 ? 'left' : 'right';
  29806. }
  29807. }
  29808. return {
  29809. rotation: rotationDiff,
  29810. textAlign: textAlign,
  29811. textVerticalAlign: textVerticalAlign
  29812. };
  29813. };
  29814. function endTextLayout(opt, textPosition, textRotate, extent) {
  29815. var rotationDiff = remRadian(textRotate - opt.rotation);
  29816. var textAlign;
  29817. var textVerticalAlign;
  29818. var inverse = extent[0] > extent[1];
  29819. var onLeft = (textPosition === 'start' && !inverse)
  29820. || (textPosition !== 'start' && inverse);
  29821. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  29822. textVerticalAlign = onLeft ? 'bottom' : 'top';
  29823. textAlign = 'center';
  29824. }
  29825. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  29826. textVerticalAlign = onLeft ? 'top' : 'bottom';
  29827. textAlign = 'center';
  29828. }
  29829. else {
  29830. textVerticalAlign = 'middle';
  29831. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  29832. textAlign = onLeft ? 'left' : 'right';
  29833. }
  29834. else {
  29835. textAlign = onLeft ? 'right' : 'left';
  29836. }
  29837. }
  29838. return {
  29839. rotation: rotationDiff,
  29840. textAlign: textAlign,
  29841. textVerticalAlign: textVerticalAlign
  29842. };
  29843. }
  29844. function isSilent(axisModel) {
  29845. var tooltipOpt = axisModel.get('tooltip');
  29846. return axisModel.get('silent')
  29847. // Consider mouse cursor, add these restrictions.
  29848. || !(
  29849. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  29850. );
  29851. }
  29852. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  29853. // If min or max are user set, we need to check
  29854. // If the tick on min(max) are overlap on their neighbour tick
  29855. // If they are overlapped, we need to hide the min(max) tick label
  29856. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29857. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29858. // FIXME
  29859. // Have not consider onBand yet, where tick els is more than label els.
  29860. labelEls = labelEls || [];
  29861. tickEls = tickEls || [];
  29862. var firstLabel = labelEls[0];
  29863. var nextLabel = labelEls[1];
  29864. var lastLabel = labelEls[labelEls.length - 1];
  29865. var prevLabel = labelEls[labelEls.length - 2];
  29866. var firstTick = tickEls[0];
  29867. var nextTick = tickEls[1];
  29868. var lastTick = tickEls[tickEls.length - 1];
  29869. var prevTick = tickEls[tickEls.length - 2];
  29870. if (showMinLabel === false) {
  29871. ignoreEl(firstLabel);
  29872. ignoreEl(firstTick);
  29873. }
  29874. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  29875. if (showMinLabel) {
  29876. ignoreEl(nextLabel);
  29877. ignoreEl(nextTick);
  29878. }
  29879. else {
  29880. ignoreEl(firstLabel);
  29881. ignoreEl(firstTick);
  29882. }
  29883. }
  29884. if (showMaxLabel === false) {
  29885. ignoreEl(lastLabel);
  29886. ignoreEl(lastTick);
  29887. }
  29888. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  29889. if (showMaxLabel) {
  29890. ignoreEl(prevLabel);
  29891. ignoreEl(prevTick);
  29892. }
  29893. else {
  29894. ignoreEl(lastLabel);
  29895. ignoreEl(lastTick);
  29896. }
  29897. }
  29898. }
  29899. function ignoreEl(el) {
  29900. el && (el.ignore = true);
  29901. }
  29902. function isTwoLabelOverlapped(current, next, labelLayout) {
  29903. // current and next has the same rotation.
  29904. var firstRect = current && current.getBoundingRect().clone();
  29905. var nextRect = next && next.getBoundingRect().clone();
  29906. if (!firstRect || !nextRect) {
  29907. return;
  29908. }
  29909. // When checking intersect of two rotated labels, we use mRotationBack
  29910. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  29911. var mRotationBack = identity([]);
  29912. rotate(mRotationBack, mRotationBack, -current.rotation);
  29913. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  29914. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  29915. return firstRect.intersect(nextRect);
  29916. }
  29917. function isNameLocationCenter(nameLocation) {
  29918. return nameLocation === 'middle' || nameLocation === 'center';
  29919. }
  29920. /**
  29921. * @static
  29922. */
  29923. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  29924. axis,
  29925. i,
  29926. interval,
  29927. ticksCnt,
  29928. showMinLabel,
  29929. showMaxLabel
  29930. ) {
  29931. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  29932. return false;
  29933. }
  29934. // FIXME
  29935. // Have not consider label overlap (if label is too long) yet.
  29936. var rawTick;
  29937. var scale$$1 = axis.scale;
  29938. return scale$$1.type === 'ordinal'
  29939. && (
  29940. typeof interval === 'function'
  29941. ? (
  29942. rawTick = scale$$1.getTicks()[i],
  29943. !interval(rawTick, scale$$1.getLabel(rawTick))
  29944. )
  29945. : i % (interval + 1)
  29946. );
  29947. };
  29948. /**
  29949. * @static
  29950. */
  29951. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  29952. var interval = model.get('interval');
  29953. if (interval == null || interval == 'auto') {
  29954. interval = labelInterval;
  29955. }
  29956. return interval;
  29957. };
  29958. function buildAxisTick(axisBuilder, axisModel, opt) {
  29959. var axis = axisModel.axis;
  29960. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  29961. return;
  29962. }
  29963. var tickModel = axisModel.getModel('axisTick');
  29964. var lineStyleModel = tickModel.getModel('lineStyle');
  29965. var tickLen = tickModel.get('length');
  29966. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  29967. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  29968. // FIXME
  29969. // Corresponds to ticksCoords ?
  29970. var ticks = axis.scale.getTicks();
  29971. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29972. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29973. var pt1 = [];
  29974. var pt2 = [];
  29975. var matrix = axisBuilder._transform;
  29976. var tickEls = [];
  29977. var ticksCnt = ticksCoords.length;
  29978. for (var i = 0; i < ticksCnt; i++) {
  29979. // Only ordinal scale support tick interval
  29980. if (ifIgnoreOnTick$1(
  29981. axis, i, tickInterval, ticksCnt,
  29982. showMinLabel, showMaxLabel
  29983. )) {
  29984. continue;
  29985. }
  29986. var tickCoord = ticksCoords[i];
  29987. pt1[0] = tickCoord;
  29988. pt1[1] = 0;
  29989. pt2[0] = tickCoord;
  29990. pt2[1] = opt.tickDirection * tickLen;
  29991. if (matrix) {
  29992. applyTransform(pt1, pt1, matrix);
  29993. applyTransform(pt2, pt2, matrix);
  29994. }
  29995. // Tick line, Not use group transform to have better line draw
  29996. var tickEl = new Line(subPixelOptimizeLine({
  29997. // Id for animation
  29998. anid: 'tick_' + ticks[i],
  29999. shape: {
  30000. x1: pt1[0],
  30001. y1: pt1[1],
  30002. x2: pt2[0],
  30003. y2: pt2[1]
  30004. },
  30005. style: defaults(
  30006. lineStyleModel.getLineStyle(),
  30007. {
  30008. stroke: axisModel.get('axisLine.lineStyle.color')
  30009. }
  30010. ),
  30011. z2: 2,
  30012. silent: true
  30013. }));
  30014. axisBuilder.group.add(tickEl);
  30015. tickEls.push(tickEl);
  30016. }
  30017. return tickEls;
  30018. }
  30019. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30020. var axis = axisModel.axis;
  30021. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30022. if (!show || axis.scale.isBlank()) {
  30023. return;
  30024. }
  30025. var labelModel = axisModel.getModel('axisLabel');
  30026. var labelMargin = labelModel.get('margin');
  30027. var ticks = axis.scale.getTicks();
  30028. var labels = axisModel.getFormattedLabels();
  30029. // Special label rotate.
  30030. var labelRotation = (
  30031. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30032. ) * PI$2 / 180;
  30033. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30034. var categoryData = axisModel.getCategories();
  30035. var labelEls = [];
  30036. var silent = isSilent(axisModel);
  30037. var triggerEvent = axisModel.get('triggerEvent');
  30038. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30039. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30040. each$1(ticks, function (tickVal, index) {
  30041. if (ifIgnoreOnTick$1(
  30042. axis, index, opt.labelInterval, ticks.length,
  30043. showMinLabel, showMaxLabel
  30044. )) {
  30045. return;
  30046. }
  30047. var itemLabelModel = labelModel;
  30048. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30049. itemLabelModel = new Model(
  30050. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30051. );
  30052. }
  30053. var textColor = itemLabelModel.getTextColor()
  30054. || axisModel.get('axisLine.lineStyle.color');
  30055. var tickCoord = axis.dataToCoord(tickVal);
  30056. var pos = [
  30057. tickCoord,
  30058. opt.labelOffset + opt.labelDirection * labelMargin
  30059. ];
  30060. var labelStr = axis.scale.getLabel(tickVal);
  30061. var textEl = new Text({
  30062. // Id for animation
  30063. anid: 'label_' + tickVal,
  30064. position: pos,
  30065. rotation: labelLayout.rotation,
  30066. silent: silent,
  30067. z2: 10
  30068. });
  30069. setTextStyle(textEl.style, itemLabelModel, {
  30070. text: labels[index],
  30071. textAlign: itemLabelModel.getShallow('align', true)
  30072. || labelLayout.textAlign,
  30073. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30074. || itemLabelModel.getShallow('baseline', true)
  30075. || labelLayout.textVerticalAlign,
  30076. textFill: typeof textColor === 'function'
  30077. ? textColor(
  30078. // (1) In category axis with data zoom, tick is not the original
  30079. // index of axis.data. So tick should not be exposed to user
  30080. // in category axis.
  30081. // (2) Compatible with previous version, which always returns labelStr.
  30082. // But in interval scale labelStr is like '223,445', which maked
  30083. // user repalce ','. So we modify it to return original val but remain
  30084. // it as 'string' to avoid error in replacing.
  30085. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30086. index
  30087. )
  30088. : textColor
  30089. });
  30090. // Pack data for mouse event
  30091. if (triggerEvent) {
  30092. textEl.eventData = makeAxisEventDataBase(axisModel);
  30093. textEl.eventData.targetType = 'axisLabel';
  30094. textEl.eventData.value = labelStr;
  30095. }
  30096. // FIXME
  30097. axisBuilder._dumbGroup.add(textEl);
  30098. textEl.updateTransform();
  30099. labelEls.push(textEl);
  30100. axisBuilder.group.add(textEl);
  30101. textEl.decomposeTransform();
  30102. });
  30103. return labelEls;
  30104. }
  30105. var each$7 = each$1;
  30106. var curry$1 = curry;
  30107. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30108. // allAxesInfo should be updated when setOption performed.
  30109. function collect(ecModel, api) {
  30110. var result = {
  30111. /**
  30112. * key: makeKey(axis.model)
  30113. * value: {
  30114. * axis,
  30115. * coordSys,
  30116. * axisPointerModel,
  30117. * triggerTooltip,
  30118. * involveSeries,
  30119. * snap,
  30120. * seriesModels,
  30121. * seriesDataCount
  30122. * }
  30123. */
  30124. axesInfo: {},
  30125. seriesInvolved: false,
  30126. /**
  30127. * key: makeKey(coordSys.model)
  30128. * value: Object: key makeKey(axis.model), value: axisInfo
  30129. */
  30130. coordSysAxesInfo: {},
  30131. coordSysMap: {}
  30132. };
  30133. collectAxesInfo(result, ecModel, api);
  30134. // Check seriesInvolved for performance, in case too many series in some chart.
  30135. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30136. return result;
  30137. }
  30138. function collectAxesInfo(result, ecModel, api) {
  30139. var globalTooltipModel = ecModel.getComponent('tooltip');
  30140. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30141. // links can only be set on global.
  30142. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30143. var linkGroups = [];
  30144. // Collect axes info.
  30145. each$7(api.getCoordinateSystems(), function (coordSys) {
  30146. // Some coordinate system do not support axes, like geo.
  30147. if (!coordSys.axisPointerEnabled) {
  30148. return;
  30149. }
  30150. var coordSysKey = makeKey(coordSys.model);
  30151. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30152. result.coordSysMap[coordSysKey] = coordSys;
  30153. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30154. // for user. So we enable seting tooltip on coordSys model.
  30155. var coordSysModel = coordSys.model;
  30156. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30157. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30158. // If axis tooltip used, choose tooltip axis for each coordSys.
  30159. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30160. if (coordSys.getTooltipAxes
  30161. && globalTooltipModel
  30162. // If tooltip.showContent is set as false, tooltip will not
  30163. // show but axisPointer will show as normal.
  30164. && baseTooltipModel.get('show')
  30165. ) {
  30166. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30167. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30168. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30169. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30170. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30171. if (triggerAxis || cross) {
  30172. each$7(tooltipAxes.baseAxes, curry$1(
  30173. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30174. ));
  30175. }
  30176. if (cross) {
  30177. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30178. }
  30179. }
  30180. // fromTooltip: true | false | 'cross'
  30181. // triggerTooltip: true | false | null
  30182. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30183. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30184. var axisPointerShow = axisPointerModel.get('show');
  30185. if (!axisPointerShow || (
  30186. axisPointerShow === 'auto'
  30187. && !fromTooltip
  30188. && !isHandleTrigger(axisPointerModel)
  30189. )) {
  30190. return;
  30191. }
  30192. if (triggerTooltip == null) {
  30193. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30194. }
  30195. axisPointerModel = fromTooltip
  30196. ? makeAxisPointerModel(
  30197. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30198. fromTooltip, triggerTooltip
  30199. )
  30200. : axisPointerModel;
  30201. var snap = axisPointerModel.get('snap');
  30202. var key = makeKey(axis.model);
  30203. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30204. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30205. var axisInfo = result.axesInfo[key] = {
  30206. key: key,
  30207. axis: axis,
  30208. coordSys: coordSys,
  30209. axisPointerModel: axisPointerModel,
  30210. triggerTooltip: triggerTooltip,
  30211. involveSeries: involveSeries,
  30212. snap: snap,
  30213. useHandle: isHandleTrigger(axisPointerModel),
  30214. seriesModels: []
  30215. };
  30216. axesInfoInCoordSys[key] = axisInfo;
  30217. result.seriesInvolved |= involveSeries;
  30218. var groupIndex = getLinkGroupIndex(linksOption, axis);
  30219. if (groupIndex != null) {
  30220. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  30221. linkGroup.axesInfo[key] = axisInfo;
  30222. linkGroup.mapper = linksOption[groupIndex].mapper;
  30223. axisInfo.linkGroup = linkGroup;
  30224. }
  30225. }
  30226. });
  30227. }
  30228. function makeAxisPointerModel(
  30229. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  30230. ) {
  30231. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  30232. var volatileOption = {};
  30233. each$7(
  30234. [
  30235. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  30236. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  30237. ],
  30238. function (field) {
  30239. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  30240. }
  30241. );
  30242. // category axis do not auto snap, otherwise some tick that do not
  30243. // has value can not be hovered. value/time/log axis default snap if
  30244. // triggered from tooltip and trigger tooltip.
  30245. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  30246. // Compatibel with previous behavior, tooltip axis do not show label by default.
  30247. // Only these properties can be overrided from tooltip to axisPointer.
  30248. if (tooltipAxisPointerModel.get('type') === 'cross') {
  30249. volatileOption.type = 'line';
  30250. }
  30251. var labelOption = volatileOption.label || (volatileOption.label = {});
  30252. // Follow the convention, do not show label when triggered by tooltip by default.
  30253. labelOption.show == null && (labelOption.show = false);
  30254. if (fromTooltip === 'cross') {
  30255. // When 'cross', both axes show labels.
  30256. labelOption.show = true;
  30257. // If triggerTooltip, this is a base axis, which should better not use cross style
  30258. // (cross style is dashed by default)
  30259. if (!triggerTooltip) {
  30260. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  30261. crossStyle && defaults(labelOption, crossStyle.textStyle);
  30262. }
  30263. }
  30264. return axis.model.getModel(
  30265. 'axisPointer',
  30266. new Model(volatileOption, globalAxisPointerModel, ecModel)
  30267. );
  30268. }
  30269. function collectSeriesInfo(result, ecModel) {
  30270. // Prepare data for axis trigger
  30271. ecModel.eachSeries(function (seriesModel) {
  30272. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  30273. var coordSys = seriesModel.coordinateSystem;
  30274. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  30275. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  30276. if (!coordSys
  30277. || seriesTooltipTrigger === 'none'
  30278. || seriesTooltipTrigger === false
  30279. || seriesTooltipTrigger === 'item'
  30280. || seriesTooltipShow === false
  30281. || seriesModel.get('axisPointer.show', true) === false
  30282. ) {
  30283. return;
  30284. }
  30285. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  30286. var axis = axisInfo.axis;
  30287. if (coordSys.getAxis(axis.dim) === axis) {
  30288. axisInfo.seriesModels.push(seriesModel);
  30289. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  30290. axisInfo.seriesDataCount += seriesModel.getData().count();
  30291. }
  30292. });
  30293. }, this);
  30294. }
  30295. /**
  30296. * For example:
  30297. * {
  30298. * axisPointer: {
  30299. * links: [{
  30300. * xAxisIndex: [2, 4],
  30301. * yAxisIndex: 'all'
  30302. * }, {
  30303. * xAxisId: ['a5', 'a7'],
  30304. * xAxisName: 'xxx'
  30305. * }]
  30306. * }
  30307. * }
  30308. */
  30309. function getLinkGroupIndex(linksOption, axis) {
  30310. var axisModel = axis.model;
  30311. var dim = axis.dim;
  30312. for (var i = 0; i < linksOption.length; i++) {
  30313. var linkOption = linksOption[i] || {};
  30314. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  30315. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  30316. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  30317. ) {
  30318. return i;
  30319. }
  30320. }
  30321. }
  30322. function checkPropInLink(linkPropValue, axisPropValue) {
  30323. return linkPropValue === 'all'
  30324. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  30325. || linkPropValue === axisPropValue;
  30326. }
  30327. function fixValue(axisModel) {
  30328. var axisInfo = getAxisInfo(axisModel);
  30329. if (!axisInfo) {
  30330. return;
  30331. }
  30332. var axisPointerModel = axisInfo.axisPointerModel;
  30333. var scale = axisInfo.axis.scale;
  30334. var option = axisPointerModel.option;
  30335. var status = axisPointerModel.get('status');
  30336. var value = axisPointerModel.get('value');
  30337. // Parse init value for category and time axis.
  30338. if (value != null) {
  30339. value = scale.parse(value);
  30340. }
  30341. var useHandle = isHandleTrigger(axisPointerModel);
  30342. // If `handle` used, `axisPointer` will always be displayed, so value
  30343. // and status should be initialized.
  30344. if (status == null) {
  30345. option.status = useHandle ? 'show' : 'hide';
  30346. }
  30347. var extent = scale.getExtent().slice();
  30348. extent[0] > extent[1] && extent.reverse();
  30349. if (// Pick a value on axis when initializing.
  30350. value == null
  30351. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  30352. // where we should re-pick a value to keep `handle` displaying normally.
  30353. || value > extent[1]
  30354. ) {
  30355. // Make handle displayed on the end of the axis when init, which looks better.
  30356. value = extent[1];
  30357. }
  30358. if (value < extent[0]) {
  30359. value = extent[0];
  30360. }
  30361. option.value = value;
  30362. if (useHandle) {
  30363. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  30364. }
  30365. }
  30366. function getAxisInfo(axisModel) {
  30367. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  30368. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  30369. }
  30370. function getAxisPointerModel(axisModel) {
  30371. var axisInfo = getAxisInfo(axisModel);
  30372. return axisInfo && axisInfo.axisPointerModel;
  30373. }
  30374. function isHandleTrigger(axisPointerModel) {
  30375. return !!axisPointerModel.get('handle.show');
  30376. }
  30377. /**
  30378. * @param {module:echarts/model/Model} model
  30379. * @return {string} unique key
  30380. */
  30381. function makeKey(model) {
  30382. return model.type + '||' + model.id;
  30383. }
  30384. /**
  30385. * Base class of AxisView.
  30386. */
  30387. var AxisView = extendComponentView({
  30388. type: 'axis',
  30389. /**
  30390. * @private
  30391. */
  30392. _axisPointer: null,
  30393. /**
  30394. * @protected
  30395. * @type {string}
  30396. */
  30397. axisPointerClass: null,
  30398. /**
  30399. * @override
  30400. */
  30401. render: function (axisModel, ecModel, api, payload) {
  30402. // FIXME
  30403. // This process should proformed after coordinate systems updated
  30404. // (axis scale updated), and should be performed each time update.
  30405. // So put it here temporarily, although it is not appropriate to
  30406. // put a model-writing procedure in `view`.
  30407. this.axisPointerClass && fixValue(axisModel);
  30408. AxisView.superApply(this, 'render', arguments);
  30409. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  30410. },
  30411. /**
  30412. * Action handler.
  30413. * @public
  30414. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30415. * @param {module:echarts/model/Global} ecModel
  30416. * @param {module:echarts/ExtensionAPI} api
  30417. * @param {Object} payload
  30418. */
  30419. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  30420. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  30421. },
  30422. /**
  30423. * @override
  30424. */
  30425. remove: function (ecModel, api) {
  30426. var axisPointer = this._axisPointer;
  30427. axisPointer && axisPointer.remove(api);
  30428. AxisView.superApply(this, 'remove', arguments);
  30429. },
  30430. /**
  30431. * @override
  30432. */
  30433. dispose: function (ecModel, api) {
  30434. disposeAxisPointer(this, api);
  30435. AxisView.superApply(this, 'dispose', arguments);
  30436. }
  30437. });
  30438. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  30439. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  30440. if (!Clazz) {
  30441. return;
  30442. }
  30443. var axisPointerModel = getAxisPointerModel(axisModel);
  30444. axisPointerModel
  30445. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  30446. .render(axisModel, axisPointerModel, api, forceRender)
  30447. : disposeAxisPointer(axisView, api);
  30448. }
  30449. function disposeAxisPointer(axisView, ecModel, api) {
  30450. var axisPointer = axisView._axisPointer;
  30451. axisPointer && axisPointer.dispose(ecModel, api);
  30452. axisView._axisPointer = null;
  30453. }
  30454. var axisPointerClazz = [];
  30455. AxisView.registerAxisPointerClass = function (type, clazz) {
  30456. if (__DEV__) {
  30457. if (axisPointerClazz[type]) {
  30458. throw new Error('axisPointer ' + type + ' exists');
  30459. }
  30460. }
  30461. axisPointerClazz[type] = clazz;
  30462. };
  30463. AxisView.getAxisPointerClass = function (type) {
  30464. return type && axisPointerClazz[type];
  30465. };
  30466. /**
  30467. * @param {Object} opt {labelInside}
  30468. * @return {Object} {
  30469. * position, rotation, labelDirection, labelOffset,
  30470. * tickDirection, labelRotate, labelInterval, z2
  30471. * }
  30472. */
  30473. function layout$1(gridModel, axisModel, opt) {
  30474. opt = opt || {};
  30475. var grid = gridModel.coordinateSystem;
  30476. var axis = axisModel.axis;
  30477. var layout = {};
  30478. var rawAxisPosition = axis.position;
  30479. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  30480. var axisDim = axis.dim;
  30481. var rect = grid.getRect();
  30482. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  30483. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  30484. var axisOffset = axisModel.get('offset') || 0;
  30485. var posBound = axisDim === 'x'
  30486. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  30487. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  30488. if (axis.onZero) {
  30489. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  30490. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  30491. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  30492. }
  30493. // Axis position
  30494. layout.position = [
  30495. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  30496. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  30497. ];
  30498. // Axis rotation
  30499. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  30500. // Tick and label direction, x y is axisDim
  30501. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  30502. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  30503. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  30504. if (axisModel.get('axisTick.inside')) {
  30505. layout.tickDirection = -layout.tickDirection;
  30506. }
  30507. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  30508. layout.labelDirection = -layout.labelDirection;
  30509. }
  30510. // Special label rotation
  30511. var labelRotate = axisModel.get('axisLabel.rotate');
  30512. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  30513. // label interval when auto mode.
  30514. layout.labelInterval = axis.getLabelInterval();
  30515. // Over splitLine and splitArea
  30516. layout.z2 = 1;
  30517. return layout;
  30518. }
  30519. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  30520. var getInterval = AxisBuilder.getInterval;
  30521. var axisBuilderAttrs = [
  30522. 'axisLine', 'axisTickLabel', 'axisName'
  30523. ];
  30524. var selfBuilderAttrs = [
  30525. 'splitArea', 'splitLine'
  30526. ];
  30527. // function getAlignWithLabel(model, axisModel) {
  30528. // var alignWithLabel = model.get('alignWithLabel');
  30529. // if (alignWithLabel === 'auto') {
  30530. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  30531. // }
  30532. // return alignWithLabel;
  30533. // }
  30534. var CartesianAxisView = AxisView.extend({
  30535. type: 'cartesianAxis',
  30536. axisPointerClass: 'CartesianAxisPointer',
  30537. /**
  30538. * @override
  30539. */
  30540. render: function (axisModel, ecModel, api, payload) {
  30541. this.group.removeAll();
  30542. var oldAxisGroup = this._axisGroup;
  30543. this._axisGroup = new Group();
  30544. this.group.add(this._axisGroup);
  30545. if (!axisModel.get('show')) {
  30546. return;
  30547. }
  30548. var gridModel = axisModel.getCoordSysModel();
  30549. var layout = layout$1(gridModel, axisModel);
  30550. var axisBuilder = new AxisBuilder(axisModel, layout);
  30551. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  30552. this._axisGroup.add(axisBuilder.getGroup());
  30553. each$1(selfBuilderAttrs, function (name) {
  30554. if (axisModel.get(name + '.show')) {
  30555. this['_' + name](axisModel, gridModel, layout.labelInterval);
  30556. }
  30557. }, this);
  30558. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  30559. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  30560. },
  30561. /**
  30562. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30563. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30564. * @param {number|Function} labelInterval
  30565. * @private
  30566. */
  30567. _splitLine: function (axisModel, gridModel, labelInterval) {
  30568. var axis = axisModel.axis;
  30569. if (axis.scale.isBlank()) {
  30570. return;
  30571. }
  30572. var splitLineModel = axisModel.getModel('splitLine');
  30573. var lineStyleModel = splitLineModel.getModel('lineStyle');
  30574. var lineColors = lineStyleModel.get('color');
  30575. var lineInterval = getInterval(splitLineModel, labelInterval);
  30576. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  30577. var gridRect = gridModel.coordinateSystem.getRect();
  30578. var isHorizontal = axis.isHorizontal();
  30579. var lineCount = 0;
  30580. var ticksCoords = axis.getTicksCoords(
  30581. // splitLineModel.get('alignWithLabel')
  30582. );
  30583. var ticks = axis.scale.getTicks();
  30584. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30585. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30586. var p1 = [];
  30587. var p2 = [];
  30588. // Simple optimization
  30589. // Batching the lines if color are the same
  30590. var lineStyle = lineStyleModel.getLineStyle();
  30591. for (var i = 0; i < ticksCoords.length; i++) {
  30592. if (ifIgnoreOnTick(
  30593. axis, i, lineInterval, ticksCoords.length,
  30594. showMinLabel, showMaxLabel
  30595. )) {
  30596. continue;
  30597. }
  30598. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30599. if (isHorizontal) {
  30600. p1[0] = tickCoord;
  30601. p1[1] = gridRect.y;
  30602. p2[0] = tickCoord;
  30603. p2[1] = gridRect.y + gridRect.height;
  30604. }
  30605. else {
  30606. p1[0] = gridRect.x;
  30607. p1[1] = tickCoord;
  30608. p2[0] = gridRect.x + gridRect.width;
  30609. p2[1] = tickCoord;
  30610. }
  30611. var colorIndex = (lineCount++) % lineColors.length;
  30612. this._axisGroup.add(new Line(subPixelOptimizeLine({
  30613. anid: 'line_' + ticks[i],
  30614. shape: {
  30615. x1: p1[0],
  30616. y1: p1[1],
  30617. x2: p2[0],
  30618. y2: p2[1]
  30619. },
  30620. style: defaults({
  30621. stroke: lineColors[colorIndex]
  30622. }, lineStyle),
  30623. silent: true
  30624. })));
  30625. }
  30626. },
  30627. /**
  30628. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30629. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30630. * @param {number|Function} labelInterval
  30631. * @private
  30632. */
  30633. _splitArea: function (axisModel, gridModel, labelInterval) {
  30634. var axis = axisModel.axis;
  30635. if (axis.scale.isBlank()) {
  30636. return;
  30637. }
  30638. var splitAreaModel = axisModel.getModel('splitArea');
  30639. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  30640. var areaColors = areaStyleModel.get('color');
  30641. var gridRect = gridModel.coordinateSystem.getRect();
  30642. var ticksCoords = axis.getTicksCoords(
  30643. // splitAreaModel.get('alignWithLabel')
  30644. );
  30645. var ticks = axis.scale.getTicks();
  30646. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  30647. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  30648. var count = 0;
  30649. var areaInterval = getInterval(splitAreaModel, labelInterval);
  30650. var areaStyle = areaStyleModel.getAreaStyle();
  30651. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  30652. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30653. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30654. for (var i = 1; i < ticksCoords.length; i++) {
  30655. if (ifIgnoreOnTick(
  30656. axis, i, areaInterval, ticksCoords.length,
  30657. showMinLabel, showMaxLabel
  30658. )) {
  30659. continue;
  30660. }
  30661. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30662. var x;
  30663. var y;
  30664. var width;
  30665. var height;
  30666. if (axis.isHorizontal()) {
  30667. x = prevX;
  30668. y = gridRect.y;
  30669. width = tickCoord - x;
  30670. height = gridRect.height;
  30671. }
  30672. else {
  30673. x = gridRect.x;
  30674. y = prevY;
  30675. width = gridRect.width;
  30676. height = tickCoord - y;
  30677. }
  30678. var colorIndex = (count++) % areaColors.length;
  30679. this._axisGroup.add(new Rect({
  30680. anid: 'area_' + ticks[i],
  30681. shape: {
  30682. x: x,
  30683. y: y,
  30684. width: width,
  30685. height: height
  30686. },
  30687. style: defaults({
  30688. fill: areaColors[colorIndex]
  30689. }, areaStyle),
  30690. silent: true
  30691. }));
  30692. prevX = x + width;
  30693. prevY = y + height;
  30694. }
  30695. }
  30696. });
  30697. CartesianAxisView.extend({
  30698. type: 'xAxis'
  30699. });
  30700. CartesianAxisView.extend({
  30701. type: 'yAxis'
  30702. });
  30703. // Grid view
  30704. extendComponentView({
  30705. type: 'grid',
  30706. render: function (gridModel, ecModel) {
  30707. this.group.removeAll();
  30708. if (gridModel.get('show')) {
  30709. this.group.add(new Rect({
  30710. shape: gridModel.coordinateSystem.getRect(),
  30711. style: defaults({
  30712. fill: gridModel.get('backgroundColor')
  30713. }, gridModel.getItemStyle()),
  30714. silent: true,
  30715. z2: -1
  30716. }));
  30717. }
  30718. }
  30719. });
  30720. registerPreprocessor(function (option) {
  30721. // Only create grid when need
  30722. if (option.xAxis && option.yAxis && !option.grid) {
  30723. option.grid = {};
  30724. }
  30725. });
  30726. // In case developer forget to include grid component
  30727. registerVisual(visualSymbol('line', 'circle', 'line'));
  30728. registerLayout(pointsLayout('line'));
  30729. // Down sample after filter
  30730. registerProcessor(
  30731. PRIORITY.PROCESSOR.STATISTIC,
  30732. dataSample('line')
  30733. );
  30734. var BaseBarSeries = SeriesModel.extend({
  30735. type: 'series.__base_bar__',
  30736. getInitialData: function (option, ecModel) {
  30737. return createListFromArray(this.getSource(), this);
  30738. },
  30739. getMarkerPosition: function (value) {
  30740. var coordSys = this.coordinateSystem;
  30741. if (coordSys) {
  30742. // PENDING if clamp ?
  30743. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  30744. var data = this.getData();
  30745. var offset = data.getLayout('offset');
  30746. var size = data.getLayout('size');
  30747. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  30748. pt[offsetIndex] += offset + size / 2;
  30749. return pt;
  30750. }
  30751. return [NaN, NaN];
  30752. },
  30753. defaultOption: {
  30754. zlevel: 0, // 一级层叠
  30755. z: 2, // 二级层叠
  30756. coordinateSystem: 'cartesian2d',
  30757. legendHoverLink: true,
  30758. // stack: null
  30759. // Cartesian coordinate system
  30760. // xAxisIndex: 0,
  30761. // yAxisIndex: 0,
  30762. // 最小高度改为0
  30763. barMinHeight: 0,
  30764. // 最小角度为0,仅对极坐标系下的柱状图有效
  30765. barMinAngle: 0,
  30766. // cursor: null,
  30767. // barMaxWidth: null,
  30768. // 默认自适应
  30769. // barWidth: null,
  30770. // 柱间距离,默认为柱形宽度的30%,可设固定值
  30771. // barGap: '30%',
  30772. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  30773. // barCategoryGap: '20%',
  30774. // label: {
  30775. // show: false
  30776. // },
  30777. itemStyle: {},
  30778. emphasis: {}
  30779. }
  30780. });
  30781. BaseBarSeries.extend({
  30782. type: 'series.bar',
  30783. dependencies: ['grid', 'polar'],
  30784. brushSelector: 'rect'
  30785. });
  30786. function setLabel(
  30787. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  30788. ) {
  30789. var labelModel = itemModel.getModel('label');
  30790. var hoverLabelModel = itemModel.getModel('emphasis.label');
  30791. setLabelStyle(
  30792. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  30793. {
  30794. labelFetcher: seriesModel,
  30795. labelDataIndex: dataIndex,
  30796. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  30797. isRectText: true,
  30798. autoColor: color
  30799. }
  30800. );
  30801. fixPosition(normalStyle);
  30802. fixPosition(hoverStyle);
  30803. }
  30804. function fixPosition(style, labelPositionOutside) {
  30805. if (style.textPosition === 'outside') {
  30806. style.textPosition = labelPositionOutside;
  30807. }
  30808. }
  30809. var getBarItemStyle = makeStyleMapper(
  30810. [
  30811. ['fill', 'color'],
  30812. ['stroke', 'borderColor'],
  30813. ['lineWidth', 'borderWidth'],
  30814. // Compatitable with 2
  30815. ['stroke', 'barBorderColor'],
  30816. ['lineWidth', 'barBorderWidth'],
  30817. ['opacity'],
  30818. ['shadowBlur'],
  30819. ['shadowOffsetX'],
  30820. ['shadowOffsetY'],
  30821. ['shadowColor']
  30822. ]
  30823. );
  30824. var barItemStyle = {
  30825. getBarItemStyle: function (excludes) {
  30826. var style = getBarItemStyle(this, excludes);
  30827. if (this.getBorderLineDash) {
  30828. var lineDash = this.getBorderLineDash();
  30829. lineDash && (style.lineDash = lineDash);
  30830. }
  30831. return style;
  30832. }
  30833. };
  30834. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  30835. // FIXME
  30836. // Just for compatible with ec2.
  30837. extend(Model.prototype, barItemStyle);
  30838. extendChartView({
  30839. type: 'bar',
  30840. render: function (seriesModel, ecModel, api) {
  30841. var coordinateSystemType = seriesModel.get('coordinateSystem');
  30842. if (coordinateSystemType === 'cartesian2d'
  30843. || coordinateSystemType === 'polar'
  30844. ) {
  30845. this._render(seriesModel, ecModel, api);
  30846. }
  30847. else if (__DEV__) {
  30848. console.warn('Only cartesian2d and polar supported for bar.');
  30849. }
  30850. return this.group;
  30851. },
  30852. dispose: noop,
  30853. _render: function (seriesModel, ecModel, api) {
  30854. var group = this.group;
  30855. var data = seriesModel.getData();
  30856. var oldData = this._data;
  30857. var coord = seriesModel.coordinateSystem;
  30858. var baseAxis = coord.getBaseAxis();
  30859. var isHorizontalOrRadial;
  30860. if (coord.type === 'cartesian2d') {
  30861. isHorizontalOrRadial = baseAxis.isHorizontal();
  30862. }
  30863. else if (coord.type === 'polar') {
  30864. isHorizontalOrRadial = baseAxis.dim === 'angle';
  30865. }
  30866. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  30867. data.diff(oldData)
  30868. .add(function (dataIndex) {
  30869. if (!data.hasValue(dataIndex)) {
  30870. return;
  30871. }
  30872. var itemModel = data.getItemModel(dataIndex);
  30873. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  30874. var el = elementCreator[coord.type](
  30875. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  30876. );
  30877. data.setItemGraphicEl(dataIndex, el);
  30878. group.add(el);
  30879. updateStyle(
  30880. el, data, dataIndex, itemModel, layout,
  30881. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30882. );
  30883. })
  30884. .update(function (newIndex, oldIndex) {
  30885. var el = oldData.getItemGraphicEl(oldIndex);
  30886. if (!data.hasValue(newIndex)) {
  30887. group.remove(el);
  30888. return;
  30889. }
  30890. var itemModel = data.getItemModel(newIndex);
  30891. var layout = getLayout[coord.type](data, newIndex, itemModel);
  30892. if (el) {
  30893. updateProps(el, {shape: layout}, animationModel, newIndex);
  30894. }
  30895. else {
  30896. el = elementCreator[coord.type](
  30897. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  30898. );
  30899. }
  30900. data.setItemGraphicEl(newIndex, el);
  30901. // Add back
  30902. group.add(el);
  30903. updateStyle(
  30904. el, data, newIndex, itemModel, layout,
  30905. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30906. );
  30907. })
  30908. .remove(function (dataIndex) {
  30909. var el = oldData.getItemGraphicEl(dataIndex);
  30910. if (coord.type === 'cartesian2d') {
  30911. el && removeRect(dataIndex, animationModel, el);
  30912. }
  30913. else {
  30914. el && removeSector(dataIndex, animationModel, el);
  30915. }
  30916. })
  30917. .execute();
  30918. this._data = data;
  30919. },
  30920. remove: function (ecModel, api) {
  30921. var group = this.group;
  30922. var data = this._data;
  30923. if (ecModel.get('animation')) {
  30924. if (data) {
  30925. data.eachItemGraphicEl(function (el) {
  30926. if (el.type === 'sector') {
  30927. removeSector(el.dataIndex, ecModel, el);
  30928. }
  30929. else {
  30930. removeRect(el.dataIndex, ecModel, el);
  30931. }
  30932. });
  30933. }
  30934. }
  30935. else {
  30936. group.removeAll();
  30937. }
  30938. }
  30939. });
  30940. var elementCreator = {
  30941. cartesian2d: function (
  30942. data, dataIndex, itemModel, layout, isHorizontal,
  30943. animationModel, isUpdate
  30944. ) {
  30945. var rect = new Rect({shape: extend({}, layout)});
  30946. // Animation
  30947. if (animationModel) {
  30948. var rectShape = rect.shape;
  30949. var animateProperty = isHorizontal ? 'height' : 'width';
  30950. var animateTarget = {};
  30951. rectShape[animateProperty] = 0;
  30952. animateTarget[animateProperty] = layout[animateProperty];
  30953. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  30954. shape: animateTarget
  30955. }, animationModel, dataIndex);
  30956. }
  30957. return rect;
  30958. },
  30959. polar: function (
  30960. data, dataIndex, itemModel, layout, isRadial,
  30961. animationModel, isUpdate
  30962. ) {
  30963. var sector = new Sector({shape: extend({}, layout)});
  30964. // Animation
  30965. if (animationModel) {
  30966. var sectorShape = sector.shape;
  30967. var animateProperty = isRadial ? 'r' : 'endAngle';
  30968. var animateTarget = {};
  30969. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  30970. animateTarget[animateProperty] = layout[animateProperty];
  30971. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  30972. shape: animateTarget
  30973. }, animationModel, dataIndex);
  30974. }
  30975. return sector;
  30976. }
  30977. };
  30978. function removeRect(dataIndex, animationModel, el) {
  30979. // Not show text when animating
  30980. el.style.text = null;
  30981. updateProps(el, {
  30982. shape: {
  30983. width: 0
  30984. }
  30985. }, animationModel, dataIndex, function () {
  30986. el.parent && el.parent.remove(el);
  30987. });
  30988. }
  30989. function removeSector(dataIndex, animationModel, el) {
  30990. // Not show text when animating
  30991. el.style.text = null;
  30992. updateProps(el, {
  30993. shape: {
  30994. r: el.shape.r0
  30995. }
  30996. }, animationModel, dataIndex, function () {
  30997. el.parent && el.parent.remove(el);
  30998. });
  30999. }
  31000. var getLayout = {
  31001. cartesian2d: function (data, dataIndex, itemModel) {
  31002. var layout = data.getItemLayout(dataIndex);
  31003. var fixedLineWidth = getLineWidth(itemModel, layout);
  31004. // fix layout with lineWidth
  31005. var signX = layout.width > 0 ? 1 : -1;
  31006. var signY = layout.height > 0 ? 1 : -1;
  31007. return {
  31008. x: layout.x + signX * fixedLineWidth / 2,
  31009. y: layout.y + signY * fixedLineWidth / 2,
  31010. width: layout.width - signX * fixedLineWidth,
  31011. height: layout.height - signY * fixedLineWidth
  31012. };
  31013. },
  31014. polar: function (data, dataIndex, itemModel) {
  31015. var layout = data.getItemLayout(dataIndex);
  31016. return {
  31017. cx: layout.cx,
  31018. cy: layout.cy,
  31019. r0: layout.r0,
  31020. r: layout.r,
  31021. startAngle: layout.startAngle,
  31022. endAngle: layout.endAngle
  31023. };
  31024. }
  31025. };
  31026. function updateStyle(
  31027. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31028. ) {
  31029. var color = data.getItemVisual(dataIndex, 'color');
  31030. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31031. var itemStyleModel = itemModel.getModel('itemStyle');
  31032. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31033. if (!isPolar) {
  31034. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31035. }
  31036. el.useStyle(defaults(
  31037. {
  31038. fill: color,
  31039. opacity: opacity
  31040. },
  31041. itemStyleModel.getBarItemStyle()
  31042. ));
  31043. var cursorStyle = itemModel.getShallow('cursor');
  31044. cursorStyle && el.attr('cursor', cursorStyle);
  31045. var labelPositionOutside = isHorizontal
  31046. ? (layout.height > 0 ? 'bottom' : 'top')
  31047. : (layout.width > 0 ? 'left' : 'right');
  31048. if (!isPolar) {
  31049. setLabel(
  31050. el.style, hoverStyle, itemModel, color,
  31051. seriesModel, dataIndex, labelPositionOutside
  31052. );
  31053. }
  31054. setHoverStyle(el, hoverStyle);
  31055. }
  31056. // In case width or height are too small.
  31057. function getLineWidth(itemModel, rawLayout) {
  31058. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31059. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31060. }
  31061. // In case developer forget to include grid component
  31062. registerLayout(curry(layout, 'bar'));
  31063. // Visual coding for legend
  31064. registerVisual(function (ecModel) {
  31065. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31066. var data = seriesModel.getData();
  31067. data.setVisual('legendSymbol', 'roundRect');
  31068. });
  31069. });
  31070. /**
  31071. * [Usage]:
  31072. * (1)
  31073. * createListSimply(seriesModel, ['value']);
  31074. * (2)
  31075. * createListSimply(seriesModel, {
  31076. * coordDimensions: ['value'],
  31077. * dimensionsCount: 5
  31078. * });
  31079. *
  31080. * @param {module:echarts/model/Series} seriesModel
  31081. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31082. * The options in opt, see `echarts/data/helper/createDimensions`
  31083. * @param {Array.<string>} [nameList]
  31084. * @return {module:echarts/data/List}
  31085. */
  31086. var createListSimply = function (seriesModel, opt, nameList) {
  31087. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31088. var source = seriesModel.getSource();
  31089. var dimensionsInfo = createDimensions(source, opt);
  31090. var list = new List(dimensionsInfo, seriesModel);
  31091. list.initData(source, nameList);
  31092. return list;
  31093. };
  31094. /**
  31095. * Data selectable mixin for chart series.
  31096. * To eanble data select, option of series must have `selectedMode`.
  31097. * And each data item will use `selected` to toggle itself selected status
  31098. */
  31099. var dataSelectableMixin = {
  31100. /**
  31101. * @param {Array.<Object>|module:echars/data/List} targetList
  31102. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31103. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31104. */
  31105. updateSelectedMap: function (targetList) {
  31106. if (isArray(targetList)) {
  31107. this._targetList = targetList.slice();
  31108. }
  31109. else {
  31110. var ecList = targetList;
  31111. var valueDim = ecList.mapDimension('value');
  31112. var targetList = this._targetList = [];
  31113. for (var i = 0, len = ecList.count(); i < len; i++) {
  31114. targetList.push({
  31115. name: ecList.getName(i),
  31116. value: ecList.get(valueDim, i),
  31117. selected: retrieveRawAttr(ecList, i, 'selected')
  31118. });
  31119. }
  31120. }
  31121. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31122. targetMap.set(target.name, target);
  31123. return targetMap;
  31124. }, createHashMap());
  31125. },
  31126. /**
  31127. * Either name or id should be passed as input here.
  31128. * If both of them are defined, id is used.
  31129. *
  31130. * @param {string|undefined} name name of data
  31131. * @param {number|undefined} id dataIndex of data
  31132. */
  31133. // PENGING If selectedMode is null ?
  31134. select: function (name, id) {
  31135. var target = id != null
  31136. ? this._targetList[id]
  31137. : this._selectTargetMap.get(name);
  31138. var selectedMode = this.get('selectedMode');
  31139. if (selectedMode === 'single') {
  31140. this._selectTargetMap.each(function (target) {
  31141. target.selected = false;
  31142. });
  31143. }
  31144. target && (target.selected = true);
  31145. },
  31146. /**
  31147. * Either name or id should be passed as input here.
  31148. * If both of them are defined, id is used.
  31149. *
  31150. * @param {string|undefined} name name of data
  31151. * @param {number|undefined} id dataIndex of data
  31152. */
  31153. unSelect: function (name, id) {
  31154. var target = id != null
  31155. ? this._targetList[id]
  31156. : this._selectTargetMap.get(name);
  31157. // var selectedMode = this.get('selectedMode');
  31158. // selectedMode !== 'single' && target && (target.selected = false);
  31159. target && (target.selected = false);
  31160. },
  31161. /**
  31162. * Either name or id should be passed as input here.
  31163. * If both of them are defined, id is used.
  31164. *
  31165. * @param {string|undefined} name name of data
  31166. * @param {number|undefined} id dataIndex of data
  31167. */
  31168. toggleSelected: function (name, id) {
  31169. var target = id != null
  31170. ? this._targetList[id]
  31171. : this._selectTargetMap.get(name);
  31172. if (target != null) {
  31173. this[target.selected ? 'unSelect' : 'select'](name, id);
  31174. return target.selected;
  31175. }
  31176. },
  31177. /**
  31178. * Either name or id should be passed as input here.
  31179. * If both of them are defined, id is used.
  31180. *
  31181. * @param {string|undefined} name name of data
  31182. * @param {number|undefined} id dataIndex of data
  31183. */
  31184. isSelected: function (name, id) {
  31185. var target = id != null
  31186. ? this._targetList[id]
  31187. : this._selectTargetMap.get(name);
  31188. return target && target.selected;
  31189. }
  31190. };
  31191. var PieSeries = extendSeriesModel({
  31192. type: 'series.pie',
  31193. // Overwrite
  31194. init: function (option) {
  31195. PieSeries.superApply(this, 'init', arguments);
  31196. // Enable legend selection for each data item
  31197. // Use a function instead of direct access because data reference may changed
  31198. this.legendDataProvider = function () {
  31199. return this.getRawData();
  31200. };
  31201. this.updateSelectedMap(this.getRawData());
  31202. this._defaultLabelLine(option);
  31203. },
  31204. // Overwrite
  31205. mergeOption: function (newOption) {
  31206. PieSeries.superCall(this, 'mergeOption', newOption);
  31207. this.updateSelectedMap(this.getRawData());
  31208. },
  31209. getInitialData: function (option, ecModel) {
  31210. return createListSimply(this, ['value']);
  31211. },
  31212. // Overwrite
  31213. getDataParams: function (dataIndex) {
  31214. var data = this.getData();
  31215. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  31216. // FIXME toFixed?
  31217. var valueList = [];
  31218. data.each(data.mapDimension('value'), function (value) {
  31219. valueList.push(value);
  31220. });
  31221. params.percent = getPercentWithPrecision(
  31222. valueList,
  31223. dataIndex,
  31224. data.hostModel.get('percentPrecision')
  31225. );
  31226. params.$vars.push('percent');
  31227. return params;
  31228. },
  31229. _defaultLabelLine: function (option) {
  31230. // Extend labelLine emphasis
  31231. defaultEmphasis(option, 'labelLine', ['show']);
  31232. var labelLineNormalOpt = option.labelLine;
  31233. var labelLineEmphasisOpt = option.emphasis.labelLine;
  31234. // Not show label line if `label.normal.show = false`
  31235. labelLineNormalOpt.show = labelLineNormalOpt.show
  31236. && option.label.show;
  31237. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  31238. && option.emphasis.label.show;
  31239. },
  31240. defaultOption: {
  31241. zlevel: 0,
  31242. z: 2,
  31243. legendHoverLink: true,
  31244. hoverAnimation: true,
  31245. // 默认全局居中
  31246. center: ['50%', '50%'],
  31247. radius: [0, '75%'],
  31248. // 默认顺时针
  31249. clockwise: true,
  31250. startAngle: 90,
  31251. // 最小角度改为0
  31252. minAngle: 0,
  31253. // 选中时扇区偏移量
  31254. selectedOffset: 10,
  31255. // 高亮扇区偏移量
  31256. hoverOffset: 10,
  31257. // If use strategy to avoid label overlapping
  31258. avoidLabelOverlap: true,
  31259. // 选择模式,默认关闭,可选single,multiple
  31260. // selectedMode: false,
  31261. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  31262. // roseType: null,
  31263. percentPrecision: 2,
  31264. // If still show when all data zero.
  31265. stillShowZeroSum: true,
  31266. // cursor: null,
  31267. label: {
  31268. // If rotate around circle
  31269. rotate: false,
  31270. show: true,
  31271. // 'outer', 'inside', 'center'
  31272. position: 'outer'
  31273. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  31274. // 默认使用全局文本样式,详见TEXTSTYLE
  31275. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  31276. },
  31277. // Enabled when label.normal.position is 'outer'
  31278. labelLine: {
  31279. show: true,
  31280. // 引导线两段中的第一段长度
  31281. length: 15,
  31282. // 引导线两段中的第二段长度
  31283. length2: 15,
  31284. smooth: false,
  31285. lineStyle: {
  31286. // color: 各异,
  31287. width: 1,
  31288. type: 'solid'
  31289. }
  31290. },
  31291. itemStyle: {
  31292. borderWidth: 1
  31293. },
  31294. // Animation type canbe expansion, scale
  31295. animationType: 'expansion',
  31296. animationEasing: 'cubicOut'
  31297. }
  31298. });
  31299. mixin(PieSeries, dataSelectableMixin);
  31300. /**
  31301. * @param {module:echarts/model/Series} seriesModel
  31302. * @param {boolean} hasAnimation
  31303. * @inner
  31304. */
  31305. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  31306. var data = seriesModel.getData();
  31307. var dataIndex = this.dataIndex;
  31308. var name = data.getName(dataIndex);
  31309. var selectedOffset = seriesModel.get('selectedOffset');
  31310. api.dispatchAction({
  31311. type: 'pieToggleSelect',
  31312. from: uid,
  31313. name: name,
  31314. seriesId: seriesModel.id
  31315. });
  31316. data.each(function (idx) {
  31317. toggleItemSelected(
  31318. data.getItemGraphicEl(idx),
  31319. data.getItemLayout(idx),
  31320. seriesModel.isSelected(data.getName(idx)),
  31321. selectedOffset,
  31322. hasAnimation
  31323. );
  31324. });
  31325. }
  31326. /**
  31327. * @param {module:zrender/graphic/Sector} el
  31328. * @param {Object} layout
  31329. * @param {boolean} isSelected
  31330. * @param {number} selectedOffset
  31331. * @param {boolean} hasAnimation
  31332. * @inner
  31333. */
  31334. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  31335. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31336. var dx = Math.cos(midAngle);
  31337. var dy = Math.sin(midAngle);
  31338. var offset = isSelected ? selectedOffset : 0;
  31339. var position = [dx * offset, dy * offset];
  31340. hasAnimation
  31341. // animateTo will stop revious animation like update transition
  31342. ? el.animate()
  31343. .when(200, {
  31344. position: position
  31345. })
  31346. .start('bounceOut')
  31347. : el.attr('position', position);
  31348. }
  31349. /**
  31350. * Piece of pie including Sector, Label, LabelLine
  31351. * @constructor
  31352. * @extends {module:zrender/graphic/Group}
  31353. */
  31354. function PiePiece(data, idx) {
  31355. Group.call(this);
  31356. var sector = new Sector({
  31357. z2: 2
  31358. });
  31359. var polyline = new Polyline();
  31360. var text = new Text();
  31361. this.add(sector);
  31362. this.add(polyline);
  31363. this.add(text);
  31364. this.updateData(data, idx, true);
  31365. // Hover to change label and labelLine
  31366. function onEmphasis() {
  31367. polyline.ignore = polyline.hoverIgnore;
  31368. text.ignore = text.hoverIgnore;
  31369. }
  31370. function onNormal() {
  31371. polyline.ignore = polyline.normalIgnore;
  31372. text.ignore = text.normalIgnore;
  31373. }
  31374. this.on('emphasis', onEmphasis)
  31375. .on('normal', onNormal)
  31376. .on('mouseover', onEmphasis)
  31377. .on('mouseout', onNormal);
  31378. }
  31379. var piePieceProto = PiePiece.prototype;
  31380. piePieceProto.updateData = function (data, idx, firstCreate) {
  31381. var sector = this.childAt(0);
  31382. var seriesModel = data.hostModel;
  31383. var itemModel = data.getItemModel(idx);
  31384. var layout = data.getItemLayout(idx);
  31385. var sectorShape = extend({}, layout);
  31386. sectorShape.label = null;
  31387. if (firstCreate) {
  31388. sector.setShape(sectorShape);
  31389. var animationType = seriesModel.getShallow('animationType');
  31390. if (animationType === 'scale') {
  31391. sector.shape.r = layout.r0;
  31392. initProps(sector, {
  31393. shape: {
  31394. r: layout.r
  31395. }
  31396. }, seriesModel, idx);
  31397. }
  31398. // Expansion
  31399. else {
  31400. sector.shape.endAngle = layout.startAngle;
  31401. updateProps(sector, {
  31402. shape: {
  31403. endAngle: layout.endAngle
  31404. }
  31405. }, seriesModel, idx);
  31406. }
  31407. }
  31408. else {
  31409. updateProps(sector, {
  31410. shape: sectorShape
  31411. }, seriesModel, idx);
  31412. }
  31413. // Update common style
  31414. var visualColor = data.getItemVisual(idx, 'color');
  31415. sector.useStyle(
  31416. defaults(
  31417. {
  31418. lineJoin: 'bevel',
  31419. fill: visualColor
  31420. },
  31421. itemModel.getModel('itemStyle').getItemStyle()
  31422. )
  31423. );
  31424. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  31425. var cursorStyle = itemModel.getShallow('cursor');
  31426. cursorStyle && sector.attr('cursor', cursorStyle);
  31427. // Toggle selected
  31428. toggleItemSelected(
  31429. this,
  31430. data.getItemLayout(idx),
  31431. seriesModel.isSelected(null, idx),
  31432. seriesModel.get('selectedOffset'),
  31433. seriesModel.get('animation')
  31434. );
  31435. function onEmphasis() {
  31436. // Sector may has animation of updating data. Force to move to the last frame
  31437. // Or it may stopped on the wrong shape
  31438. sector.stopAnimation(true);
  31439. sector.animateTo({
  31440. shape: {
  31441. r: layout.r + seriesModel.get('hoverOffset')
  31442. }
  31443. }, 300, 'elasticOut');
  31444. }
  31445. function onNormal() {
  31446. sector.stopAnimation(true);
  31447. sector.animateTo({
  31448. shape: {
  31449. r: layout.r
  31450. }
  31451. }, 300, 'elasticOut');
  31452. }
  31453. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  31454. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  31455. sector
  31456. .on('mouseover', onEmphasis)
  31457. .on('mouseout', onNormal)
  31458. .on('emphasis', onEmphasis)
  31459. .on('normal', onNormal);
  31460. }
  31461. this._updateLabel(data, idx);
  31462. setHoverStyle(this);
  31463. };
  31464. piePieceProto._updateLabel = function (data, idx) {
  31465. var labelLine = this.childAt(1);
  31466. var labelText = this.childAt(2);
  31467. var seriesModel = data.hostModel;
  31468. var itemModel = data.getItemModel(idx);
  31469. var layout = data.getItemLayout(idx);
  31470. var labelLayout = layout.label;
  31471. var visualColor = data.getItemVisual(idx, 'color');
  31472. updateProps(labelLine, {
  31473. shape: {
  31474. points: labelLayout.linePoints || [
  31475. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  31476. ]
  31477. }
  31478. }, seriesModel, idx);
  31479. updateProps(labelText, {
  31480. style: {
  31481. x: labelLayout.x,
  31482. y: labelLayout.y
  31483. }
  31484. }, seriesModel, idx);
  31485. labelText.attr({
  31486. rotation: labelLayout.rotation,
  31487. origin: [labelLayout.x, labelLayout.y],
  31488. z2: 10
  31489. });
  31490. var labelModel = itemModel.getModel('label');
  31491. var labelHoverModel = itemModel.getModel('emphasis.label');
  31492. var labelLineModel = itemModel.getModel('labelLine');
  31493. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  31494. var visualColor = data.getItemVisual(idx, 'color');
  31495. setLabelStyle(
  31496. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  31497. {
  31498. labelFetcher: data.hostModel,
  31499. labelDataIndex: idx,
  31500. defaultText: data.getName(idx),
  31501. autoColor: visualColor,
  31502. useInsideStyle: !!labelLayout.inside
  31503. },
  31504. {
  31505. textAlign: labelLayout.textAlign,
  31506. textVerticalAlign: labelLayout.verticalAlign,
  31507. opacity: data.getItemVisual(idx, 'opacity')
  31508. }
  31509. );
  31510. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  31511. labelText.hoverIgnore = !labelHoverModel.get('show');
  31512. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  31513. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  31514. // Default use item visual color
  31515. labelLine.setStyle({
  31516. stroke: visualColor,
  31517. opacity: data.getItemVisual(idx, 'opacity')
  31518. });
  31519. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  31520. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  31521. var smooth = labelLineModel.get('smooth');
  31522. if (smooth && smooth === true) {
  31523. smooth = 0.4;
  31524. }
  31525. labelLine.setShape({
  31526. smooth: smooth
  31527. });
  31528. };
  31529. inherits(PiePiece, Group);
  31530. // Pie view
  31531. var PieView = Chart.extend({
  31532. type: 'pie',
  31533. init: function () {
  31534. var sectorGroup = new Group();
  31535. this._sectorGroup = sectorGroup;
  31536. },
  31537. render: function (seriesModel, ecModel, api, payload) {
  31538. if (payload && (payload.from === this.uid)) {
  31539. return;
  31540. }
  31541. var data = seriesModel.getData();
  31542. var oldData = this._data;
  31543. var group = this.group;
  31544. var hasAnimation = ecModel.get('animation');
  31545. var isFirstRender = !oldData;
  31546. var animationType = seriesModel.get('animationType');
  31547. var onSectorClick = curry(
  31548. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  31549. );
  31550. var selectedMode = seriesModel.get('selectedMode');
  31551. data.diff(oldData)
  31552. .add(function (idx) {
  31553. var piePiece = new PiePiece(data, idx);
  31554. // Default expansion animation
  31555. if (isFirstRender && animationType !== 'scale') {
  31556. piePiece.eachChild(function (child) {
  31557. child.stopAnimation(true);
  31558. });
  31559. }
  31560. selectedMode && piePiece.on('click', onSectorClick);
  31561. data.setItemGraphicEl(idx, piePiece);
  31562. group.add(piePiece);
  31563. })
  31564. .update(function (newIdx, oldIdx) {
  31565. var piePiece = oldData.getItemGraphicEl(oldIdx);
  31566. piePiece.updateData(data, newIdx);
  31567. piePiece.off('click');
  31568. selectedMode && piePiece.on('click', onSectorClick);
  31569. group.add(piePiece);
  31570. data.setItemGraphicEl(newIdx, piePiece);
  31571. })
  31572. .remove(function (idx) {
  31573. var piePiece = oldData.getItemGraphicEl(idx);
  31574. group.remove(piePiece);
  31575. })
  31576. .execute();
  31577. if (
  31578. hasAnimation && isFirstRender && data.count() > 0
  31579. // Default expansion animation
  31580. && animationType !== 'scale'
  31581. ) {
  31582. var shape = data.getItemLayout(0);
  31583. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  31584. var removeClipPath = bind(group.removeClipPath, group);
  31585. group.setClipPath(this._createClipPath(
  31586. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  31587. ));
  31588. }
  31589. this._data = data;
  31590. },
  31591. dispose: function () {},
  31592. _createClipPath: function (
  31593. cx, cy, r, startAngle, clockwise, cb, seriesModel
  31594. ) {
  31595. var clipPath = new Sector({
  31596. shape: {
  31597. cx: cx,
  31598. cy: cy,
  31599. r0: 0,
  31600. r: r,
  31601. startAngle: startAngle,
  31602. endAngle: startAngle,
  31603. clockwise: clockwise
  31604. }
  31605. });
  31606. initProps(clipPath, {
  31607. shape: {
  31608. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  31609. }
  31610. }, seriesModel, cb);
  31611. return clipPath;
  31612. },
  31613. /**
  31614. * @implement
  31615. */
  31616. containPoint: function (point, seriesModel) {
  31617. var data = seriesModel.getData();
  31618. var itemLayout = data.getItemLayout(0);
  31619. if (itemLayout) {
  31620. var dx = point[0] - itemLayout.cx;
  31621. var dy = point[1] - itemLayout.cy;
  31622. var radius = Math.sqrt(dx * dx + dy * dy);
  31623. return radius <= itemLayout.r && radius >= itemLayout.r0;
  31624. }
  31625. }
  31626. });
  31627. var createDataSelectAction = function (seriesType, actionInfos) {
  31628. each$1(actionInfos, function (actionInfo) {
  31629. actionInfo.update = 'updateView';
  31630. /**
  31631. * @payload
  31632. * @property {string} seriesName
  31633. * @property {string} name
  31634. */
  31635. registerAction(actionInfo, function (payload, ecModel) {
  31636. var selected = {};
  31637. ecModel.eachComponent(
  31638. {mainType: 'series', subType: seriesType, query: payload},
  31639. function (seriesModel) {
  31640. if (seriesModel[actionInfo.method]) {
  31641. seriesModel[actionInfo.method](
  31642. payload.name,
  31643. payload.dataIndex
  31644. );
  31645. }
  31646. var data = seriesModel.getData();
  31647. // Create selected map
  31648. data.each(function (idx) {
  31649. var name = data.getName(idx);
  31650. selected[name] = seriesModel.isSelected(name)
  31651. || false;
  31652. });
  31653. }
  31654. );
  31655. return {
  31656. name: payload.name,
  31657. selected: selected
  31658. };
  31659. });
  31660. });
  31661. };
  31662. // Pick color from palette for each data item.
  31663. // Applicable for charts that require applying color palette
  31664. // in data level (like pie, funnel, chord).
  31665. var dataColor = function (seriesType) {
  31666. return {
  31667. getTargetSeries: function (ecModel) {
  31668. // Pie and funnel may use diferrent scope
  31669. var paletteScope = {};
  31670. var seiresModelMap = createHashMap();
  31671. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31672. seriesModel.__paletteScope = paletteScope;
  31673. seiresModelMap.set(seriesModel.uid, seriesModel);
  31674. });
  31675. return seiresModelMap;
  31676. },
  31677. reset: function (seriesModel, ecModel) {
  31678. var dataAll = seriesModel.getRawData();
  31679. var idxMap = {};
  31680. var data = seriesModel.getData();
  31681. data.each(function (idx) {
  31682. var rawIdx = data.getRawIndex(idx);
  31683. idxMap[rawIdx] = idx;
  31684. });
  31685. dataAll.each(function (rawIdx) {
  31686. var filteredIdx = idxMap[rawIdx];
  31687. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  31688. var singleDataColor = filteredIdx != null
  31689. && data.getItemVisual(filteredIdx, 'color', true);
  31690. if (!singleDataColor) {
  31691. // FIXME Performance
  31692. var itemModel = dataAll.getItemModel(rawIdx);
  31693. var color = itemModel.get('itemStyle.color')
  31694. || seriesModel.getColorFromPalette(
  31695. dataAll.getName(rawIdx), seriesModel.__paletteScope,
  31696. dataAll.count()
  31697. );
  31698. // Legend may use the visual info in data before processed
  31699. dataAll.setItemVisual(rawIdx, 'color', color);
  31700. // Data is not filtered
  31701. if (filteredIdx != null) {
  31702. data.setItemVisual(filteredIdx, 'color', color);
  31703. }
  31704. }
  31705. else {
  31706. // Set data all color for legend
  31707. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  31708. }
  31709. });
  31710. }
  31711. };
  31712. };
  31713. // FIXME emphasis label position is not same with normal label position
  31714. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  31715. list.sort(function (a, b) {
  31716. return a.y - b.y;
  31717. });
  31718. // 压
  31719. function shiftDown(start, end, delta, dir) {
  31720. for (var j = start; j < end; j++) {
  31721. list[j].y += delta;
  31722. if (j > start
  31723. && j + 1 < end
  31724. && list[j + 1].y > list[j].y + list[j].height
  31725. ) {
  31726. shiftUp(j, delta / 2);
  31727. return;
  31728. }
  31729. }
  31730. shiftUp(end - 1, delta / 2);
  31731. }
  31732. // 弹
  31733. function shiftUp(end, delta) {
  31734. for (var j = end; j >= 0; j--) {
  31735. list[j].y -= delta;
  31736. if (j > 0
  31737. && list[j].y > list[j - 1].y + list[j - 1].height
  31738. ) {
  31739. break;
  31740. }
  31741. }
  31742. }
  31743. function changeX(list, isDownList, cx, cy, r, dir) {
  31744. var lastDeltaX = dir > 0
  31745. ? isDownList // 右侧
  31746. ? Number.MAX_VALUE // 下
  31747. : 0 // 上
  31748. : isDownList // 左侧
  31749. ? Number.MAX_VALUE // 下
  31750. : 0; // 上
  31751. for (var i = 0, l = list.length; i < l; i++) {
  31752. // Not change x for center label
  31753. if (list[i].position === 'center') {
  31754. continue;
  31755. }
  31756. var deltaY = Math.abs(list[i].y - cy);
  31757. var length = list[i].len;
  31758. var length2 = list[i].len2;
  31759. var deltaX = (deltaY < r + length)
  31760. ? Math.sqrt(
  31761. (r + length + length2) * (r + length + length2)
  31762. - deltaY * deltaY
  31763. )
  31764. : Math.abs(list[i].x - cx);
  31765. if (isDownList && deltaX >= lastDeltaX) {
  31766. // 右下,左下
  31767. deltaX = lastDeltaX - 10;
  31768. }
  31769. if (!isDownList && deltaX <= lastDeltaX) {
  31770. // 右上,左上
  31771. deltaX = lastDeltaX + 10;
  31772. }
  31773. list[i].x = cx + deltaX * dir;
  31774. lastDeltaX = deltaX;
  31775. }
  31776. }
  31777. var lastY = 0;
  31778. var delta;
  31779. var len = list.length;
  31780. var upList = [];
  31781. var downList = [];
  31782. for (var i = 0; i < len; i++) {
  31783. delta = list[i].y - lastY;
  31784. if (delta < 0) {
  31785. shiftDown(i, len, -delta, dir);
  31786. }
  31787. lastY = list[i].y + list[i].height;
  31788. }
  31789. if (viewHeight - lastY < 0) {
  31790. shiftUp(len - 1, lastY - viewHeight);
  31791. }
  31792. for (var i = 0; i < len; i++) {
  31793. if (list[i].y >= cy) {
  31794. downList.push(list[i]);
  31795. }
  31796. else {
  31797. upList.push(list[i]);
  31798. }
  31799. }
  31800. changeX(upList, false, cx, cy, r, dir);
  31801. changeX(downList, true, cx, cy, r, dir);
  31802. }
  31803. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  31804. var leftList = [];
  31805. var rightList = [];
  31806. for (var i = 0; i < labelLayoutList.length; i++) {
  31807. if (labelLayoutList[i].x < cx) {
  31808. leftList.push(labelLayoutList[i]);
  31809. }
  31810. else {
  31811. rightList.push(labelLayoutList[i]);
  31812. }
  31813. }
  31814. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  31815. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  31816. for (var i = 0; i < labelLayoutList.length; i++) {
  31817. var linePoints = labelLayoutList[i].linePoints;
  31818. if (linePoints) {
  31819. var dist = linePoints[1][0] - linePoints[2][0];
  31820. if (labelLayoutList[i].x < cx) {
  31821. linePoints[2][0] = labelLayoutList[i].x + 3;
  31822. }
  31823. else {
  31824. linePoints[2][0] = labelLayoutList[i].x - 3;
  31825. }
  31826. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  31827. linePoints[1][0] = linePoints[2][0] + dist;
  31828. }
  31829. }
  31830. }
  31831. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  31832. var data = seriesModel.getData();
  31833. var labelLayoutList = [];
  31834. var cx;
  31835. var cy;
  31836. var hasLabelRotate = false;
  31837. data.each(function (idx) {
  31838. var layout = data.getItemLayout(idx);
  31839. var itemModel = data.getItemModel(idx);
  31840. var labelModel = itemModel.getModel('label');
  31841. // Use position in normal or emphasis
  31842. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  31843. var labelLineModel = itemModel.getModel('labelLine');
  31844. var labelLineLen = labelLineModel.get('length');
  31845. var labelLineLen2 = labelLineModel.get('length2');
  31846. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31847. var dx = Math.cos(midAngle);
  31848. var dy = Math.sin(midAngle);
  31849. var textX;
  31850. var textY;
  31851. var linePoints;
  31852. var textAlign;
  31853. cx = layout.cx;
  31854. cy = layout.cy;
  31855. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  31856. if (labelPosition === 'center') {
  31857. textX = layout.cx;
  31858. textY = layout.cy;
  31859. textAlign = 'center';
  31860. }
  31861. else {
  31862. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  31863. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  31864. textX = x1 + dx * 3;
  31865. textY = y1 + dy * 3;
  31866. if (!isLabelInside) {
  31867. // For roseType
  31868. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  31869. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  31870. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  31871. var y3 = y2;
  31872. textX = x3 + (dx < 0 ? -5 : 5);
  31873. textY = y3;
  31874. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  31875. }
  31876. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  31877. }
  31878. var font = labelModel.getFont();
  31879. var labelRotate = labelModel.get('rotate')
  31880. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  31881. var text = seriesModel.getFormattedLabel(idx, 'normal')
  31882. || data.getName(idx);
  31883. var textRect = getBoundingRect(
  31884. text, font, textAlign, 'top'
  31885. );
  31886. hasLabelRotate = !!labelRotate;
  31887. layout.label = {
  31888. x: textX,
  31889. y: textY,
  31890. position: labelPosition,
  31891. height: textRect.height,
  31892. len: labelLineLen,
  31893. len2: labelLineLen2,
  31894. linePoints: linePoints,
  31895. textAlign: textAlign,
  31896. verticalAlign: 'middle',
  31897. rotation: labelRotate,
  31898. inside: isLabelInside
  31899. };
  31900. // Not layout the inside label
  31901. if (!isLabelInside) {
  31902. labelLayoutList.push(layout.label);
  31903. }
  31904. });
  31905. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  31906. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  31907. }
  31908. };
  31909. var PI2$4 = Math.PI * 2;
  31910. var RADIAN = Math.PI / 180;
  31911. var pieLayout = function (seriesType, ecModel, api, payload) {
  31912. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31913. var data = seriesModel.getData();
  31914. var valueDim = data.mapDimension('value');
  31915. var center = seriesModel.get('center');
  31916. var radius = seriesModel.get('radius');
  31917. if (!isArray(radius)) {
  31918. radius = [0, radius];
  31919. }
  31920. if (!isArray(center)) {
  31921. center = [center, center];
  31922. }
  31923. var width = api.getWidth();
  31924. var height = api.getHeight();
  31925. var size = Math.min(width, height);
  31926. var cx = parsePercent$1(center[0], width);
  31927. var cy = parsePercent$1(center[1], height);
  31928. var r0 = parsePercent$1(radius[0], size / 2);
  31929. var r = parsePercent$1(radius[1], size / 2);
  31930. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  31931. var minAngle = seriesModel.get('minAngle') * RADIAN;
  31932. var validDataCount = 0;
  31933. data.each(valueDim, function (value) {
  31934. !isNaN(value) && validDataCount++;
  31935. });
  31936. var sum = data.getSum(valueDim);
  31937. // Sum may be 0
  31938. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  31939. var clockwise = seriesModel.get('clockwise');
  31940. var roseType = seriesModel.get('roseType');
  31941. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  31942. // [0...max]
  31943. var extent = data.getDataExtent(valueDim);
  31944. extent[0] = 0;
  31945. // In the case some sector angle is smaller than minAngle
  31946. var restAngle = PI2$4;
  31947. var valueSumLargerThanMinAngle = 0;
  31948. var currentAngle = startAngle;
  31949. var dir = clockwise ? 1 : -1;
  31950. data.each(valueDim, function (value, idx) {
  31951. var angle;
  31952. if (isNaN(value)) {
  31953. data.setItemLayout(idx, {
  31954. angle: NaN,
  31955. startAngle: NaN,
  31956. endAngle: NaN,
  31957. clockwise: clockwise,
  31958. cx: cx,
  31959. cy: cy,
  31960. r0: r0,
  31961. r: roseType
  31962. ? NaN
  31963. : r
  31964. });
  31965. return;
  31966. }
  31967. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  31968. if (roseType !== 'area') {
  31969. angle = (sum === 0 && stillShowZeroSum)
  31970. ? unitRadian : (value * unitRadian);
  31971. }
  31972. else {
  31973. angle = PI2$4 / validDataCount;
  31974. }
  31975. if (angle < minAngle) {
  31976. angle = minAngle;
  31977. restAngle -= minAngle;
  31978. }
  31979. else {
  31980. valueSumLargerThanMinAngle += value;
  31981. }
  31982. var endAngle = currentAngle + dir * angle;
  31983. data.setItemLayout(idx, {
  31984. angle: angle,
  31985. startAngle: currentAngle,
  31986. endAngle: endAngle,
  31987. clockwise: clockwise,
  31988. cx: cx,
  31989. cy: cy,
  31990. r0: r0,
  31991. r: roseType
  31992. ? linearMap(value, extent, [r0, r])
  31993. : r
  31994. });
  31995. currentAngle = endAngle;
  31996. }, true);
  31997. // Some sector is constrained by minAngle
  31998. // Rest sectors needs recalculate angle
  31999. if (restAngle < PI2$4 && validDataCount) {
  32000. // Average the angle if rest angle is not enough after all angles is
  32001. // Constrained by minAngle
  32002. if (restAngle <= 1e-3) {
  32003. var angle = PI2$4 / validDataCount;
  32004. data.each(valueDim, function (value, idx) {
  32005. if (!isNaN(value)) {
  32006. var layout = data.getItemLayout(idx);
  32007. layout.angle = angle;
  32008. layout.startAngle = startAngle + dir * idx * angle;
  32009. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32010. }
  32011. });
  32012. }
  32013. else {
  32014. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32015. currentAngle = startAngle;
  32016. data.each(valueDim, function (value, idx) {
  32017. if (!isNaN(value)) {
  32018. var layout = data.getItemLayout(idx);
  32019. var angle = layout.angle === minAngle
  32020. ? minAngle : value * unitRadian;
  32021. layout.startAngle = currentAngle;
  32022. layout.endAngle = currentAngle + dir * angle;
  32023. currentAngle += dir * angle;
  32024. }
  32025. });
  32026. }
  32027. }
  32028. labelLayout(seriesModel, r, width, height);
  32029. });
  32030. };
  32031. var dataFilter = function (seriesType) {
  32032. return {
  32033. seriesType: seriesType,
  32034. reset: function (seriesModel, ecModel) {
  32035. var legendModels = ecModel.findComponents({
  32036. mainType: 'legend'
  32037. });
  32038. if (!legendModels || !legendModels.length) {
  32039. return;
  32040. }
  32041. var data = seriesModel.getData();
  32042. data.filterSelf(function (idx) {
  32043. var name = data.getName(idx);
  32044. // If in any legend component the status is not selected.
  32045. for (var i = 0; i < legendModels.length; i++) {
  32046. if (!legendModels[i].isSelected(name)) {
  32047. return false;
  32048. }
  32049. }
  32050. return true;
  32051. }, this);
  32052. }
  32053. };
  32054. };
  32055. createDataSelectAction('pie', [{
  32056. type: 'pieToggleSelect',
  32057. event: 'pieselectchanged',
  32058. method: 'toggleSelected'
  32059. }, {
  32060. type: 'pieSelect',
  32061. event: 'pieselected',
  32062. method: 'select'
  32063. }, {
  32064. type: 'pieUnSelect',
  32065. event: 'pieunselected',
  32066. method: 'unSelect'
  32067. }]);
  32068. registerVisual(dataColor('pie'));
  32069. registerLayout(curry(pieLayout, 'pie'));
  32070. registerProcessor(dataFilter('pie'));
  32071. SeriesModel.extend({
  32072. type: 'series.scatter',
  32073. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32074. getInitialData: function (option, ecModel) {
  32075. return createListFromArray(this.getSource(), this);
  32076. },
  32077. brushSelector: 'point',
  32078. getProgressive: function () {
  32079. var progressive = this.option.progressive;
  32080. if (progressive == null) {
  32081. // PENDING
  32082. return this.option.large ? 5e3 : this.get('progressive');
  32083. }
  32084. return progressive;
  32085. },
  32086. getProgressiveThreshold: function () {
  32087. var progressiveThreshold = this.option.progressiveThreshold;
  32088. if (progressiveThreshold == null) {
  32089. // PENDING
  32090. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32091. }
  32092. return progressiveThreshold;
  32093. },
  32094. defaultOption: {
  32095. coordinateSystem: 'cartesian2d',
  32096. zlevel: 0,
  32097. z: 2,
  32098. legendHoverLink: true,
  32099. hoverAnimation: true,
  32100. // Cartesian coordinate system
  32101. // xAxisIndex: 0,
  32102. // yAxisIndex: 0,
  32103. // Polar coordinate system
  32104. // polarIndex: 0,
  32105. // Geo coordinate system
  32106. // geoIndex: 0,
  32107. // symbol: null, // 图形类型
  32108. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32109. // symbolRotate: null, // 图形旋转控制
  32110. large: false,
  32111. // Available when large is true
  32112. largeThreshold: 2000,
  32113. // cursor: null,
  32114. // label: {
  32115. // show: false
  32116. // distance: 5,
  32117. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32118. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32119. // 'inside'|'left'|'right'|'top'|'bottom'
  32120. // 默认使用全局文本样式,详见TEXTSTYLE
  32121. // },
  32122. itemStyle: {
  32123. opacity: 0.8
  32124. // color: 各异
  32125. },
  32126. progressive: null
  32127. }
  32128. });
  32129. // TODO Batch by color
  32130. var BOOST_SIZE_THRESHOLD = 4;
  32131. var LargeSymbolPath = extendShape({
  32132. shape: {
  32133. points: null
  32134. },
  32135. symbolProxy: null,
  32136. buildPath: function (path, shape) {
  32137. var points = shape.points;
  32138. var size = shape.size;
  32139. var symbolProxy = this.symbolProxy;
  32140. var symbolProxyShape = symbolProxy.shape;
  32141. var ctx = path.getContext ? path.getContext() : path;
  32142. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32143. // Do draw in afterBrush.
  32144. if (canBoost) {
  32145. return;
  32146. }
  32147. for (var i = 0; i < points.length;) {
  32148. var x = points[i++];
  32149. var y = points[i++];
  32150. if (isNaN(x) || isNaN(y)) {
  32151. continue;
  32152. }
  32153. symbolProxyShape.x = x - size[0] / 2;
  32154. symbolProxyShape.y = y - size[1] / 2;
  32155. symbolProxyShape.width = size[0];
  32156. symbolProxyShape.height = size[1];
  32157. symbolProxy.buildPath(path, symbolProxyShape, true);
  32158. }
  32159. },
  32160. afterBrush: function (ctx) {
  32161. var shape = this.shape;
  32162. var points = shape.points;
  32163. var size = shape.size;
  32164. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32165. if (!canBoost) {
  32166. return;
  32167. }
  32168. this.setTransform(ctx);
  32169. // PENDING If style or other canvas status changed?
  32170. for (var i = 0; i < points.length;) {
  32171. var x = points[i++];
  32172. var y = points[i++];
  32173. if (isNaN(x) || isNaN(y)) {
  32174. continue;
  32175. }
  32176. // fillRect is faster than building a rect path and draw.
  32177. // And it support light globalCompositeOperation.
  32178. ctx.fillRect(
  32179. x - size[0] / 2, y - size[1] / 2,
  32180. size[0], size[1]
  32181. );
  32182. }
  32183. this.restoreTransform(ctx);
  32184. },
  32185. findDataIndex: function (x, y) {
  32186. // TODO ???
  32187. // Consider transform
  32188. var shape = this.shape;
  32189. var points = shape.points;
  32190. var size = shape.size;
  32191. var w = Math.max(size[0], 4);
  32192. var h = Math.max(size[1], 4);
  32193. // Not consider transform
  32194. // Treat each element as a rect
  32195. // top down traverse
  32196. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32197. var i = idx * 2;
  32198. var x0 = points[i] - w / 2;
  32199. var y0 = points[i + 1] - h / 2;
  32200. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32201. return idx;
  32202. }
  32203. }
  32204. return -1;
  32205. }
  32206. });
  32207. function LargeSymbolDraw() {
  32208. this.group = new Group();
  32209. }
  32210. var largeSymbolProto = LargeSymbolDraw.prototype;
  32211. largeSymbolProto.isPersistent = function () {
  32212. return !this._incremental;
  32213. };
  32214. /**
  32215. * Update symbols draw by new data
  32216. * @param {module:echarts/data/List} data
  32217. */
  32218. largeSymbolProto.updateData = function (data) {
  32219. this.group.removeAll();
  32220. var symbolEl = new LargeSymbolPath({
  32221. rectHover: true,
  32222. cursor: 'default'
  32223. });
  32224. symbolEl.setShape({
  32225. points: data.getLayout('symbolPoints')
  32226. });
  32227. this._setCommon(symbolEl, data);
  32228. this.group.add(symbolEl);
  32229. this._incremental = null;
  32230. };
  32231. largeSymbolProto.updateLayout = function (data) {
  32232. if (this._incremental) {
  32233. return;
  32234. }
  32235. var points = data.getLayout('symbolPoints');
  32236. this.group.eachChild(function (child) {
  32237. if (child.startIndex != null) {
  32238. var len = (child.endIndex - child.startIndex) * 2;
  32239. var byteOffset = child.startIndex * 4 * 2;
  32240. points = new Float32Array(points.buffer, byteOffset, len);
  32241. }
  32242. child.setShape('points', points);
  32243. });
  32244. };
  32245. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  32246. this.group.removeAll();
  32247. this._clearIncremental();
  32248. // Only use incremental displayables when data amount is larger than 2 million.
  32249. // PENDING Incremental data?
  32250. if (data.count() > 2e6) {
  32251. if (!this._incremental) {
  32252. this._incremental = new IncrementalDisplayble({
  32253. silent: true
  32254. });
  32255. }
  32256. this.group.add(this._incremental);
  32257. }
  32258. else {
  32259. this._incremental = null;
  32260. }
  32261. };
  32262. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  32263. var symbolEl;
  32264. if (this._incremental) {
  32265. symbolEl = new LargeSymbolPath();
  32266. this._incremental.addDisplayable(symbolEl, true);
  32267. }
  32268. else {
  32269. symbolEl = new LargeSymbolPath({
  32270. rectHover: true,
  32271. cursor: 'default',
  32272. startIndex: taskParams.start,
  32273. endIndex: taskParams.end
  32274. });
  32275. symbolEl.incremental = true;
  32276. this.group.add(symbolEl);
  32277. }
  32278. symbolEl.setShape({
  32279. points: data.getLayout('symbolPoints')
  32280. });
  32281. this._setCommon(symbolEl, data, !!this._incremental);
  32282. };
  32283. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  32284. var hostModel = data.hostModel;
  32285. // TODO
  32286. // if (data.hasItemVisual.symbolSize) {
  32287. // // TODO typed array?
  32288. // symbolEl.setShape('sizes', data.mapArray(
  32289. // function (idx) {
  32290. // var size = data.getItemVisual(idx, 'symbolSize');
  32291. // return (size instanceof Array) ? size : [size, size];
  32292. // }
  32293. // ));
  32294. // }
  32295. // else {
  32296. var size = data.getVisual('symbolSize');
  32297. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  32298. // }
  32299. // Create symbolProxy to build path for each data
  32300. symbolEl.symbolProxy = createSymbol(
  32301. data.getVisual('symbol'), 0, 0, 0, 0
  32302. );
  32303. // Use symbolProxy setColor method
  32304. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  32305. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  32306. symbolEl.useStyle(
  32307. // Draw shadow when doing fillRect is extremely slow.
  32308. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  32309. );
  32310. var visualColor = data.getVisual('color');
  32311. if (visualColor) {
  32312. symbolEl.setColor(visualColor);
  32313. }
  32314. if (!isIncremental) {
  32315. // Enable tooltip
  32316. // PENDING May have performance issue when path is extremely large
  32317. symbolEl.seriesIndex = hostModel.seriesIndex;
  32318. symbolEl.on('mousemove', function (e) {
  32319. symbolEl.dataIndex = null;
  32320. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  32321. if (dataIndex >= 0) {
  32322. // Provide dataIndex for tooltip
  32323. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  32324. }
  32325. });
  32326. }
  32327. };
  32328. largeSymbolProto.remove = function () {
  32329. this._clearIncremental();
  32330. this._incremental = null;
  32331. this.group.removeAll();
  32332. };
  32333. largeSymbolProto._clearIncremental = function () {
  32334. var incremental = this._incremental;
  32335. if (incremental) {
  32336. incremental.clearDisplaybles();
  32337. }
  32338. };
  32339. extendChartView({
  32340. type: 'scatter',
  32341. render: function (seriesModel, ecModel, api) {
  32342. var data = seriesModel.getData();
  32343. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32344. symbolDraw.updateData(data);
  32345. this._finished = true;
  32346. },
  32347. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  32348. var data = seriesModel.getData();
  32349. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32350. symbolDraw.incrementalPrepareUpdate(data);
  32351. this._finished = false;
  32352. },
  32353. incrementalRender: function (taskParams, seriesModel, ecModel) {
  32354. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  32355. this._finished = taskParams.end === seriesModel.getData().count();
  32356. },
  32357. updateTransform: function (seriesModel, ecModel, api) {
  32358. var data = seriesModel.getData();
  32359. // Must mark group dirty and make sure the incremental layer will be cleared
  32360. // PENDING
  32361. this.group.dirty();
  32362. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  32363. return {
  32364. update: true
  32365. };
  32366. }
  32367. else {
  32368. var res = pointsLayout().reset(seriesModel);
  32369. if (res.progress) {
  32370. res.progress({ start: 0, end: data.count() }, data);
  32371. }
  32372. this._symbolDraw.updateLayout(data);
  32373. }
  32374. },
  32375. _updateSymbolDraw: function (data, seriesModel) {
  32376. var symbolDraw = this._symbolDraw;
  32377. var pipelineContext = seriesModel.pipelineContext;
  32378. var isLargeDraw = pipelineContext.large;
  32379. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  32380. symbolDraw && symbolDraw.remove();
  32381. symbolDraw = this._symbolDraw = isLargeDraw
  32382. ? new LargeSymbolDraw()
  32383. : new SymbolDraw();
  32384. this._isLargeDraw = isLargeDraw;
  32385. this.group.removeAll();
  32386. }
  32387. this.group.add(symbolDraw.group);
  32388. return symbolDraw;
  32389. },
  32390. remove: function (ecModel, api) {
  32391. this._symbolDraw && this._symbolDraw.remove(true);
  32392. this._symbolDraw = null;
  32393. },
  32394. dispose: function () {}
  32395. });
  32396. // import * as zrUtil from 'zrender/src/core/util';
  32397. // In case developer forget to include grid component
  32398. registerVisual(visualSymbol('scatter', 'circle'));
  32399. registerLayout(pointsLayout('scatter'));
  32400. // echarts.registerProcessor(function (ecModel, api) {
  32401. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  32402. // var data = seriesModel.getData();
  32403. // var coordSys = seriesModel.coordinateSystem;
  32404. // if (coordSys.type !== 'geo') {
  32405. // return;
  32406. // }
  32407. // var startPt = coordSys.pointToData([0, 0]);
  32408. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  32409. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  32410. // return data.mapDimension(dim);
  32411. // });
  32412. // var range = {};
  32413. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  32414. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  32415. // data.selectRange(range);
  32416. // });
  32417. // });
  32418. // -------------
  32419. // Preprocessor
  32420. // -------------
  32421. registerPreprocessor(function (option) {
  32422. var graphicOption = option.graphic;
  32423. // Convert
  32424. // {graphic: [{left: 10, type: 'circle'}, ...]}
  32425. // or
  32426. // {graphic: {left: 10, type: 'circle'}}
  32427. // to
  32428. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  32429. if (isArray(graphicOption)) {
  32430. if (!graphicOption[0] || !graphicOption[0].elements) {
  32431. option.graphic = [{elements: graphicOption}];
  32432. }
  32433. else {
  32434. // Only one graphic instance can be instantiated. (We dont
  32435. // want that too many views are created in echarts._viewMap)
  32436. option.graphic = [option.graphic[0]];
  32437. }
  32438. }
  32439. else if (graphicOption && !graphicOption.elements) {
  32440. option.graphic = [{elements: [graphicOption]}];
  32441. }
  32442. });
  32443. // ------
  32444. // Model
  32445. // ------
  32446. var GraphicModel = extendComponentModel({
  32447. type: 'graphic',
  32448. defaultOption: {
  32449. // Extra properties for each elements:
  32450. //
  32451. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  32452. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  32453. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  32454. // This mechanism is useful when you want to position a group/element
  32455. // against the right side or the center of this container.
  32456. //
  32457. // width/height: (can only be pixel value, default 0)
  32458. // Only be used to specify contianer(group) size, if needed. And
  32459. // can not be percentage value (like '33%'). See the reason in the
  32460. // layout algorithm below.
  32461. //
  32462. // bounding: (enum: 'all' (default) | 'raw')
  32463. // Specify how to calculate boundingRect when locating.
  32464. // 'all': Get uioned and transformed boundingRect
  32465. // from both itself and its descendants.
  32466. // This mode simplies confining a group of elements in the bounding
  32467. // of their ancester container (e.g., using 'right: 0').
  32468. // 'raw': Only use the boundingRect of itself and before transformed.
  32469. // This mode is similar to css behavior, which is useful when you
  32470. // want an element to be able to overflow its container. (Consider
  32471. // a rotated circle needs to be located in a corner.)
  32472. // Note: elements is always behind its ancestors in this elements array.
  32473. elements: [],
  32474. parentId: null
  32475. },
  32476. /**
  32477. * Save el options for the sake of the performance (only update modified graphics).
  32478. * The order is the same as those in option. (ancesters -> descendants)
  32479. *
  32480. * @private
  32481. * @type {Array.<Object>}
  32482. */
  32483. _elOptionsToUpdate: null,
  32484. /**
  32485. * @override
  32486. */
  32487. mergeOption: function (option) {
  32488. // Prevent default merge to elements
  32489. var elements = this.option.elements;
  32490. this.option.elements = null;
  32491. GraphicModel.superApply(this, 'mergeOption', arguments);
  32492. this.option.elements = elements;
  32493. },
  32494. /**
  32495. * @override
  32496. */
  32497. optionUpdated: function (newOption, isInit) {
  32498. var thisOption = this.option;
  32499. var newList = (isInit ? thisOption : newOption).elements;
  32500. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  32501. var flattenedList = [];
  32502. this._flatten(newList, flattenedList);
  32503. var mappingResult = mappingToExists(existList, flattenedList);
  32504. makeIdAndName(mappingResult);
  32505. // Clear elOptionsToUpdate
  32506. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  32507. each$1(mappingResult, function (resultItem, index) {
  32508. var newElOption = resultItem.option;
  32509. if (__DEV__) {
  32510. assert$1(
  32511. isObject$1(newElOption) || resultItem.exist,
  32512. 'Empty graphic option definition'
  32513. );
  32514. }
  32515. if (!newElOption) {
  32516. return;
  32517. }
  32518. elOptionsToUpdate.push(newElOption);
  32519. setKeyInfoToNewElOption(resultItem, newElOption);
  32520. mergeNewElOptionToExist(existList, index, newElOption);
  32521. setLayoutInfoToExist(existList[index], newElOption);
  32522. }, this);
  32523. // Clean
  32524. for (var i = existList.length - 1; i >= 0; i--) {
  32525. if (existList[i] == null) {
  32526. existList.splice(i, 1);
  32527. }
  32528. else {
  32529. // $action should be volatile, otherwise option gotten from
  32530. // `getOption` will contain unexpected $action.
  32531. delete existList[i].$action;
  32532. }
  32533. }
  32534. },
  32535. /**
  32536. * Convert
  32537. * [{
  32538. * type: 'group',
  32539. * id: 'xx',
  32540. * children: [{type: 'circle'}, {type: 'polygon'}]
  32541. * }]
  32542. * to
  32543. * [
  32544. * {type: 'group', id: 'xx'},
  32545. * {type: 'circle', parentId: 'xx'},
  32546. * {type: 'polygon', parentId: 'xx'}
  32547. * ]
  32548. *
  32549. * @private
  32550. * @param {Array.<Object>} optionList option list
  32551. * @param {Array.<Object>} result result of flatten
  32552. * @param {Object} parentOption parent option
  32553. */
  32554. _flatten: function (optionList, result, parentOption) {
  32555. each$1(optionList, function (option) {
  32556. if (!option) {
  32557. return;
  32558. }
  32559. if (parentOption) {
  32560. option.parentOption = parentOption;
  32561. }
  32562. result.push(option);
  32563. var children = option.children;
  32564. if (option.type === 'group' && children) {
  32565. this._flatten(children, result, option);
  32566. }
  32567. // Deleting for JSON output, and for not affecting group creation.
  32568. delete option.children;
  32569. }, this);
  32570. },
  32571. // FIXME
  32572. // Pass to view using payload? setOption has a payload?
  32573. useElOptionsToUpdate: function () {
  32574. var els = this._elOptionsToUpdate;
  32575. // Clear to avoid render duplicately when zooming.
  32576. this._elOptionsToUpdate = null;
  32577. return els;
  32578. }
  32579. });
  32580. // -----
  32581. // View
  32582. // -----
  32583. extendComponentView({
  32584. type: 'graphic',
  32585. /**
  32586. * @override
  32587. */
  32588. init: function (ecModel, api) {
  32589. /**
  32590. * @private
  32591. * @type {module:zrender/core/util.HashMap}
  32592. */
  32593. this._elMap = createHashMap();
  32594. /**
  32595. * @private
  32596. * @type {module:echarts/graphic/GraphicModel}
  32597. */
  32598. this._lastGraphicModel;
  32599. },
  32600. /**
  32601. * @override
  32602. */
  32603. render: function (graphicModel, ecModel, api) {
  32604. // Having leveraged between use cases and algorithm complexity, a very
  32605. // simple layout mechanism is used:
  32606. // The size(width/height) can be determined by itself or its parent (not
  32607. // implemented yet), but can not by its children. (Top-down travel)
  32608. // The location(x/y) can be determined by the bounding rect of itself
  32609. // (can including its descendants or not) and the size of its parent.
  32610. // (Bottom-up travel)
  32611. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  32612. // view will be reused.
  32613. if (graphicModel !== this._lastGraphicModel) {
  32614. this._clear();
  32615. }
  32616. this._lastGraphicModel = graphicModel;
  32617. this._updateElements(graphicModel, api);
  32618. this._relocate(graphicModel, api);
  32619. },
  32620. /**
  32621. * Update graphic elements.
  32622. *
  32623. * @private
  32624. * @param {Object} graphicModel graphic model
  32625. * @param {module:echarts/ExtensionAPI} api extension API
  32626. */
  32627. _updateElements: function (graphicModel, api) {
  32628. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  32629. if (!elOptionsToUpdate) {
  32630. return;
  32631. }
  32632. var elMap = this._elMap;
  32633. var rootGroup = this.group;
  32634. // Top-down tranverse to assign graphic settings to each elements.
  32635. each$1(elOptionsToUpdate, function (elOption) {
  32636. var $action = elOption.$action;
  32637. var id = elOption.id;
  32638. var existEl = elMap.get(id);
  32639. var parentId = elOption.parentId;
  32640. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  32641. if (elOption.type === 'text') {
  32642. var elOptionStyle = elOption.style;
  32643. // In top/bottom mode, textVerticalAlign should not be used, which cause
  32644. // inaccurately locating.
  32645. if (elOption.hv && elOption.hv[1]) {
  32646. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  32647. }
  32648. // Compatible with previous setting: both support fill and textFill,
  32649. // stroke and textStroke.
  32650. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  32651. elOptionStyle.textFill = elOptionStyle.fill
  32652. );
  32653. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  32654. elOptionStyle.textStroke = elOptionStyle.stroke
  32655. );
  32656. }
  32657. // Remove unnecessary props to avoid potential problems.
  32658. var elOptionCleaned = getCleanedElOption(elOption);
  32659. // For simple, do not support parent change, otherwise reorder is needed.
  32660. if (__DEV__) {
  32661. existEl && assert$1(
  32662. targetElParent === existEl.parent,
  32663. 'Changing parent is not supported.'
  32664. );
  32665. }
  32666. if (!$action || $action === 'merge') {
  32667. existEl
  32668. ? existEl.attr(elOptionCleaned)
  32669. : createEl(id, targetElParent, elOptionCleaned, elMap);
  32670. }
  32671. else if ($action === 'replace') {
  32672. removeEl(existEl, elMap);
  32673. createEl(id, targetElParent, elOptionCleaned, elMap);
  32674. }
  32675. else if ($action === 'remove') {
  32676. removeEl(existEl, elMap);
  32677. }
  32678. var el = elMap.get(id);
  32679. if (el) {
  32680. el.__ecGraphicWidth = elOption.width;
  32681. el.__ecGraphicHeight = elOption.height;
  32682. }
  32683. });
  32684. },
  32685. /**
  32686. * Locate graphic elements.
  32687. *
  32688. * @private
  32689. * @param {Object} graphicModel graphic model
  32690. * @param {module:echarts/ExtensionAPI} api extension API
  32691. */
  32692. _relocate: function (graphicModel, api) {
  32693. var elOptions = graphicModel.option.elements;
  32694. var rootGroup = this.group;
  32695. var elMap = this._elMap;
  32696. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  32697. for (var i = elOptions.length - 1; i >= 0; i--) {
  32698. var elOption = elOptions[i];
  32699. var el = elMap.get(elOption.id);
  32700. if (!el) {
  32701. continue;
  32702. }
  32703. var parentEl = el.parent;
  32704. var containerInfo = parentEl === rootGroup
  32705. ? {
  32706. width: api.getWidth(),
  32707. height: api.getHeight()
  32708. }
  32709. : { // Like 'position:absolut' in css, default 0.
  32710. width: parentEl.__ecGraphicWidth || 0,
  32711. height: parentEl.__ecGraphicHeight || 0
  32712. };
  32713. positionElement(
  32714. el, elOption, containerInfo, null,
  32715. {hv: elOption.hv, boundingMode: elOption.bounding}
  32716. );
  32717. }
  32718. },
  32719. /**
  32720. * Clear all elements.
  32721. *
  32722. * @private
  32723. */
  32724. _clear: function () {
  32725. var elMap = this._elMap;
  32726. elMap.each(function (el) {
  32727. removeEl(el, elMap);
  32728. });
  32729. this._elMap = createHashMap();
  32730. },
  32731. /**
  32732. * @override
  32733. */
  32734. dispose: function () {
  32735. this._clear();
  32736. }
  32737. });
  32738. function createEl(id, targetElParent, elOption, elMap) {
  32739. var graphicType = elOption.type;
  32740. if (__DEV__) {
  32741. assert$1(graphicType, 'graphic type MUST be set');
  32742. }
  32743. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  32744. if (__DEV__) {
  32745. assert$1(Clz, 'graphic type can not be found');
  32746. }
  32747. var el = new Clz(elOption);
  32748. targetElParent.add(el);
  32749. elMap.set(id, el);
  32750. el.__ecGraphicId = id;
  32751. }
  32752. function removeEl(existEl, elMap) {
  32753. var existElParent = existEl && existEl.parent;
  32754. if (existElParent) {
  32755. existEl.type === 'group' && existEl.traverse(function (el) {
  32756. removeEl(el, elMap);
  32757. });
  32758. elMap.removeKey(existEl.__ecGraphicId);
  32759. existElParent.remove(existEl);
  32760. }
  32761. }
  32762. // Remove unnecessary props to avoid potential problems.
  32763. function getCleanedElOption(elOption) {
  32764. elOption = extend({}, elOption);
  32765. each$1(
  32766. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  32767. function (name) {
  32768. delete elOption[name];
  32769. }
  32770. );
  32771. return elOption;
  32772. }
  32773. function isSetLoc(obj, props) {
  32774. var isSet;
  32775. each$1(props, function (prop) {
  32776. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  32777. });
  32778. return isSet;
  32779. }
  32780. function setKeyInfoToNewElOption(resultItem, newElOption) {
  32781. var existElOption = resultItem.exist;
  32782. // Set id and type after id assigned.
  32783. newElOption.id = resultItem.keyInfo.id;
  32784. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  32785. // Set parent id if not specified
  32786. if (newElOption.parentId == null) {
  32787. var newElParentOption = newElOption.parentOption;
  32788. if (newElParentOption) {
  32789. newElOption.parentId = newElParentOption.id;
  32790. }
  32791. else if (existElOption) {
  32792. newElOption.parentId = existElOption.parentId;
  32793. }
  32794. }
  32795. // Clear
  32796. newElOption.parentOption = null;
  32797. }
  32798. function mergeNewElOptionToExist(existList, index, newElOption) {
  32799. // Update existing options, for `getOption` feature.
  32800. var newElOptCopy = extend({}, newElOption);
  32801. var existElOption = existList[index];
  32802. var $action = newElOption.$action || 'merge';
  32803. if ($action === 'merge') {
  32804. if (existElOption) {
  32805. if (__DEV__) {
  32806. var newType = newElOption.type;
  32807. assert$1(
  32808. !newType || existElOption.type === newType,
  32809. 'Please set $action: "replace" to change `type`'
  32810. );
  32811. }
  32812. // We can ensure that newElOptCopy and existElOption are not
  32813. // the same object, so `merge` will not change newElOptCopy.
  32814. merge(existElOption, newElOptCopy, true);
  32815. // Rigid body, use ignoreSize.
  32816. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  32817. // Will be used in render.
  32818. copyLayoutParams(newElOption, existElOption);
  32819. }
  32820. else {
  32821. existList[index] = newElOptCopy;
  32822. }
  32823. }
  32824. else if ($action === 'replace') {
  32825. existList[index] = newElOptCopy;
  32826. }
  32827. else if ($action === 'remove') {
  32828. // null will be cleaned later.
  32829. existElOption && (existList[index] = null);
  32830. }
  32831. }
  32832. function setLayoutInfoToExist(existItem, newElOption) {
  32833. if (!existItem) {
  32834. return;
  32835. }
  32836. existItem.hv = newElOption.hv = [
  32837. // Rigid body, dont care `width`.
  32838. isSetLoc(newElOption, ['left', 'right']),
  32839. // Rigid body, dont care `height`.
  32840. isSetLoc(newElOption, ['top', 'bottom'])
  32841. ];
  32842. // Give default group size. Otherwise layout error may occur.
  32843. if (existItem.type === 'group') {
  32844. existItem.width == null && (existItem.width = newElOption.width = 0);
  32845. existItem.height == null && (existItem.height = newElOption.height = 0);
  32846. }
  32847. }
  32848. /**
  32849. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  32850. * @param {module:echarts/model/Global} ecModel
  32851. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  32852. */
  32853. var findPointFromSeries = function (finder, ecModel) {
  32854. var point = [];
  32855. var seriesIndex = finder.seriesIndex;
  32856. var seriesModel;
  32857. if (seriesIndex == null || !(
  32858. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  32859. )) {
  32860. return {point: []};
  32861. }
  32862. var data = seriesModel.getData();
  32863. var dataIndex = queryDataIndex(data, finder);
  32864. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  32865. return {point: []};
  32866. }
  32867. var el = data.getItemGraphicEl(dataIndex);
  32868. var coordSys = seriesModel.coordinateSystem;
  32869. if (seriesModel.getTooltipPosition) {
  32870. point = seriesModel.getTooltipPosition(dataIndex) || [];
  32871. }
  32872. else if (coordSys && coordSys.dataToPoint) {
  32873. point = coordSys.dataToPoint(
  32874. data.getValues(
  32875. map(coordSys.dimensions, function (dim) {
  32876. return data.mapDimension(dim);
  32877. }), dataIndex, true
  32878. )
  32879. ) || [];
  32880. }
  32881. else if (el) {
  32882. // Use graphic bounding rect
  32883. var rect = el.getBoundingRect().clone();
  32884. rect.applyTransform(el.transform);
  32885. point = [
  32886. rect.x + rect.width / 2,
  32887. rect.y + rect.height / 2
  32888. ];
  32889. }
  32890. return {point: point, el: el};
  32891. };
  32892. var each$8 = each$1;
  32893. var curry$2 = curry;
  32894. var inner$6 = makeInner();
  32895. /**
  32896. * Basic logic: check all axis, if they do not demand show/highlight,
  32897. * then hide/downplay them.
  32898. *
  32899. * @param {Object} coordSysAxesInfo
  32900. * @param {Object} payload
  32901. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  32902. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  32903. * trigger axisPointer and tooltip.
  32904. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  32905. * trigger axisPointer and tooltip.
  32906. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  32907. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  32908. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  32909. * [{
  32910. * axisDim: 'x'|'y'|'angle'|...,
  32911. * axisIndex: ...,
  32912. * value: ...
  32913. * }, ...]
  32914. * @param {Function} [payload.dispatchAction]
  32915. * @param {Object} [payload.tooltipOption]
  32916. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  32917. * which can be specified in dispatchAction
  32918. * @param {module:echarts/model/Global} ecModel
  32919. * @param {module:echarts/ExtensionAPI} api
  32920. * @return {Object} content of event obj for echarts.connect.
  32921. */
  32922. var axisTrigger = function (payload, ecModel, api) {
  32923. var currTrigger = payload.currTrigger;
  32924. var point = [payload.x, payload.y];
  32925. var finder = payload;
  32926. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  32927. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  32928. // Pending
  32929. // See #6121. But we are not able to reproduce it yet.
  32930. if (!coordSysAxesInfo) {
  32931. return;
  32932. }
  32933. if (illegalPoint(point)) {
  32934. // Used in the default behavior of `connection`: use the sample seriesIndex
  32935. // and dataIndex. And also used in the tooltipView trigger.
  32936. point = findPointFromSeries({
  32937. seriesIndex: finder.seriesIndex,
  32938. // Do not use dataIndexInside from other ec instance.
  32939. // FIXME: auto detect it?
  32940. dataIndex: finder.dataIndex
  32941. }, ecModel).point;
  32942. }
  32943. var isIllegalPoint = illegalPoint(point);
  32944. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  32945. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  32946. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  32947. // and dataIndex.
  32948. var inputAxesInfo = finder.axesInfo;
  32949. var axesInfo = coordSysAxesInfo.axesInfo;
  32950. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  32951. var outputFinder = {};
  32952. var showValueMap = {};
  32953. var dataByCoordSys = {list: [], map: {}};
  32954. var updaters = {
  32955. showPointer: curry$2(showPointer, showValueMap),
  32956. showTooltip: curry$2(showTooltip, dataByCoordSys)
  32957. };
  32958. // Process for triggered axes.
  32959. each$8(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  32960. // If a point given, it must be contained by the coordinate system.
  32961. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  32962. each$8(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  32963. var axis = axisInfo.axis;
  32964. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  32965. // If no inputAxesInfo, no axis is restricted.
  32966. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  32967. var val = inputAxisInfo && inputAxisInfo.value;
  32968. if (val == null && !isIllegalPoint) {
  32969. val = axis.pointToData(point);
  32970. }
  32971. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  32972. }
  32973. });
  32974. });
  32975. // Process for linked axes.
  32976. var linkTriggers = {};
  32977. each$8(axesInfo, function (tarAxisInfo, tarKey) {
  32978. var linkGroup = tarAxisInfo.linkGroup;
  32979. // If axis has been triggered in the previous stage, it should not be triggered by link.
  32980. if (linkGroup && !showValueMap[tarKey]) {
  32981. each$8(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  32982. var srcValItem = showValueMap[srcKey];
  32983. // If srcValItem exist, source axis is triggered, so link to target axis.
  32984. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  32985. var val = srcValItem.value;
  32986. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  32987. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  32988. )));
  32989. linkTriggers[tarAxisInfo.key] = val;
  32990. }
  32991. });
  32992. }
  32993. });
  32994. each$8(linkTriggers, function (val, tarKey) {
  32995. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  32996. });
  32997. updateModelActually(showValueMap, axesInfo, outputFinder);
  32998. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  32999. dispatchHighDownActually(axesInfo, dispatchAction, api);
  33000. return outputFinder;
  33001. };
  33002. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  33003. var axis = axisInfo.axis;
  33004. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  33005. return;
  33006. }
  33007. if (!axisInfo.involveSeries) {
  33008. updaters.showPointer(axisInfo, newValue);
  33009. return;
  33010. }
  33011. // Heavy calculation. So put it after axis.containData checking.
  33012. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  33013. var payloadBatch = payloadInfo.payloadBatch;
  33014. var snapToValue = payloadInfo.snapToValue;
  33015. // Fill content of event obj for echarts.connect.
  33016. // By defualt use the first involved series data as a sample to connect.
  33017. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  33018. extend(outputFinder, payloadBatch[0]);
  33019. }
  33020. // If no linkSource input, this process is for collecting link
  33021. // target, where snap should not be accepted.
  33022. if (!dontSnap && axisInfo.snap) {
  33023. if (axis.containData(snapToValue) && snapToValue != null) {
  33024. newValue = snapToValue;
  33025. }
  33026. }
  33027. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  33028. // Tooltip should always be snapToValue, otherwise there will be
  33029. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  33030. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  33031. }
  33032. function buildPayloadsBySeries(value, axisInfo) {
  33033. var axis = axisInfo.axis;
  33034. var dim = axis.dim;
  33035. var snapToValue = value;
  33036. var payloadBatch = [];
  33037. var minDist = Number.MAX_VALUE;
  33038. var minDiff = -1;
  33039. each$8(axisInfo.seriesModels, function (series, idx) {
  33040. var dataDim = series.getData().mapDimension(dim, true);
  33041. var seriesNestestValue;
  33042. var dataIndices;
  33043. if (series.getAxisTooltipData) {
  33044. var result = series.getAxisTooltipData(dataDim, value, axis);
  33045. dataIndices = result.dataIndices;
  33046. seriesNestestValue = result.nestestValue;
  33047. }
  33048. else {
  33049. dataIndices = series.getData().indicesOfNearest(
  33050. dataDim[0],
  33051. value,
  33052. // Add a threshold to avoid find the wrong dataIndex
  33053. // when data length is not same.
  33054. false, axis.type === 'category' ? 0.5 : null
  33055. );
  33056. if (!dataIndices.length) {
  33057. return;
  33058. }
  33059. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  33060. }
  33061. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  33062. return;
  33063. }
  33064. var diff = value - seriesNestestValue;
  33065. var dist = Math.abs(diff);
  33066. // Consider category case
  33067. if (dist <= minDist) {
  33068. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  33069. minDist = dist;
  33070. minDiff = diff;
  33071. snapToValue = seriesNestestValue;
  33072. payloadBatch.length = 0;
  33073. }
  33074. each$8(dataIndices, function (dataIndex) {
  33075. payloadBatch.push({
  33076. seriesIndex: series.seriesIndex,
  33077. dataIndexInside: dataIndex,
  33078. dataIndex: series.getData().getRawIndex(dataIndex)
  33079. });
  33080. });
  33081. }
  33082. });
  33083. return {
  33084. payloadBatch: payloadBatch,
  33085. snapToValue: snapToValue
  33086. };
  33087. }
  33088. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  33089. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  33090. }
  33091. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  33092. var payloadBatch = payloadInfo.payloadBatch;
  33093. var axis = axisInfo.axis;
  33094. var axisModel = axis.model;
  33095. var axisPointerModel = axisInfo.axisPointerModel;
  33096. // If no data, do not create anything in dataByCoordSys,
  33097. // whose length will be used to judge whether dispatch action.
  33098. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  33099. return;
  33100. }
  33101. var coordSysModel = axisInfo.coordSys.model;
  33102. var coordSysKey = makeKey(coordSysModel);
  33103. var coordSysItem = dataByCoordSys.map[coordSysKey];
  33104. if (!coordSysItem) {
  33105. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  33106. coordSysId: coordSysModel.id,
  33107. coordSysIndex: coordSysModel.componentIndex,
  33108. coordSysType: coordSysModel.type,
  33109. coordSysMainType: coordSysModel.mainType,
  33110. dataByAxis: []
  33111. };
  33112. dataByCoordSys.list.push(coordSysItem);
  33113. }
  33114. coordSysItem.dataByAxis.push({
  33115. axisDim: axis.dim,
  33116. axisIndex: axisModel.componentIndex,
  33117. axisType: axisModel.type,
  33118. axisId: axisModel.id,
  33119. value: value,
  33120. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  33121. // depends that all models have been updated. So it should not be performed
  33122. // here. Considering axisPointerModel used here is volatile, which is hard
  33123. // to be retrieve in TooltipView, we prepare parameters here.
  33124. valueLabelOpt: {
  33125. precision: axisPointerModel.get('label.precision'),
  33126. formatter: axisPointerModel.get('label.formatter')
  33127. },
  33128. seriesDataIndices: payloadBatch.slice()
  33129. });
  33130. }
  33131. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  33132. var outputAxesInfo = outputFinder.axesInfo = [];
  33133. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  33134. each$8(axesInfo, function (axisInfo, key) {
  33135. var option = axisInfo.axisPointerModel.option;
  33136. var valItem = showValueMap[key];
  33137. if (valItem) {
  33138. !axisInfo.useHandle && (option.status = 'show');
  33139. option.value = valItem.value;
  33140. // For label formatter param and highlight.
  33141. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  33142. }
  33143. // When always show (e.g., handle used), remain
  33144. // original value and status.
  33145. else {
  33146. // If hide, value still need to be set, consider
  33147. // click legend to toggle axis blank.
  33148. !axisInfo.useHandle && (option.status = 'hide');
  33149. }
  33150. // If status is 'hide', should be no info in payload.
  33151. option.status === 'show' && outputAxesInfo.push({
  33152. axisDim: axisInfo.axis.dim,
  33153. axisIndex: axisInfo.axis.model.componentIndex,
  33154. value: option.value
  33155. });
  33156. });
  33157. }
  33158. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  33159. // Basic logic: If no showTip required, hideTip will be dispatched.
  33160. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  33161. dispatchAction({type: 'hideTip'});
  33162. return;
  33163. }
  33164. // In most case only one axis (or event one series is used). It is
  33165. // convinient to fetch payload.seriesIndex and payload.dataIndex
  33166. // dirtectly. So put the first seriesIndex and dataIndex of the first
  33167. // axis on the payload.
  33168. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  33169. dispatchAction({
  33170. type: 'showTip',
  33171. escapeConnect: true,
  33172. x: point[0],
  33173. y: point[1],
  33174. tooltipOption: payload.tooltipOption,
  33175. position: payload.position,
  33176. dataIndexInside: sampleItem.dataIndexInside,
  33177. dataIndex: sampleItem.dataIndex,
  33178. seriesIndex: sampleItem.seriesIndex,
  33179. dataByCoordSys: dataByCoordSys.list
  33180. });
  33181. }
  33182. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  33183. // FIXME
  33184. // highlight status modification shoule be a stage of main process?
  33185. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  33186. var zr = api.getZr();
  33187. var highDownKey = 'axisPointerLastHighlights';
  33188. var lastHighlights = inner$6(zr)[highDownKey] || {};
  33189. var newHighlights = inner$6(zr)[highDownKey] = {};
  33190. // Update highlight/downplay status according to axisPointer model.
  33191. // Build hash map and remove duplicate incidentally.
  33192. each$8(axesInfo, function (axisInfo, key) {
  33193. var option = axisInfo.axisPointerModel.option;
  33194. option.status === 'show' && each$8(option.seriesDataIndices, function (batchItem) {
  33195. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  33196. newHighlights[key] = batchItem;
  33197. });
  33198. });
  33199. // Diff.
  33200. var toHighlight = [];
  33201. var toDownplay = [];
  33202. each$1(lastHighlights, function (batchItem, key) {
  33203. !newHighlights[key] && toDownplay.push(batchItem);
  33204. });
  33205. each$1(newHighlights, function (batchItem, key) {
  33206. !lastHighlights[key] && toHighlight.push(batchItem);
  33207. });
  33208. toDownplay.length && api.dispatchAction({
  33209. type: 'downplay', escapeConnect: true, batch: toDownplay
  33210. });
  33211. toHighlight.length && api.dispatchAction({
  33212. type: 'highlight', escapeConnect: true, batch: toHighlight
  33213. });
  33214. }
  33215. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  33216. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  33217. var inputAxisInfo = inputAxesInfo[i];
  33218. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  33219. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  33220. ) {
  33221. return inputAxisInfo;
  33222. }
  33223. }
  33224. }
  33225. function makeMapperParam(axisInfo) {
  33226. var axisModel = axisInfo.axis.model;
  33227. var item = {};
  33228. var dim = item.axisDim = axisInfo.axis.dim;
  33229. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  33230. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  33231. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  33232. return item;
  33233. }
  33234. function illegalPoint(point) {
  33235. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  33236. }
  33237. var AxisPointerModel = extendComponentModel({
  33238. type: 'axisPointer',
  33239. coordSysAxesInfo: null,
  33240. defaultOption: {
  33241. // 'auto' means that show when triggered by tooltip or handle.
  33242. show: 'auto',
  33243. // 'click' | 'mousemove' | 'none'
  33244. triggerOn: null, // set default in AxisPonterView.js
  33245. zlevel: 0,
  33246. z: 50,
  33247. type: 'line',
  33248. // axispointer triggered by tootip determine snap automatically,
  33249. // see `modelHelper`.
  33250. snap: false,
  33251. triggerTooltip: true,
  33252. value: null,
  33253. status: null, // Init value depends on whether handle is used.
  33254. // [group0, group1, ...]
  33255. // Each group can be: {
  33256. // mapper: function () {},
  33257. // singleTooltip: 'multiple', // 'multiple' or 'single'
  33258. // xAxisId: ...,
  33259. // yAxisName: ...,
  33260. // angleAxisIndex: ...
  33261. // }
  33262. // mapper: can be ignored.
  33263. // input: {axisInfo, value}
  33264. // output: {axisInfo, value}
  33265. link: [],
  33266. // Do not set 'auto' here, otherwise global animation: false
  33267. // will not effect at this axispointer.
  33268. animation: null,
  33269. animationDurationUpdate: 200,
  33270. lineStyle: {
  33271. color: '#aaa',
  33272. width: 1,
  33273. type: 'solid'
  33274. },
  33275. shadowStyle: {
  33276. color: 'rgba(150,150,150,0.3)'
  33277. },
  33278. label: {
  33279. show: true,
  33280. formatter: null, // string | Function
  33281. precision: 'auto', // Or a number like 0, 1, 2 ...
  33282. margin: 3,
  33283. color: '#fff',
  33284. padding: [5, 7, 5, 7],
  33285. backgroundColor: 'auto', // default: axis line color
  33286. borderColor: null,
  33287. borderWidth: 0,
  33288. shadowBlur: 3,
  33289. shadowColor: '#aaa'
  33290. // Considering applicability, common style should
  33291. // better not have shadowOffset.
  33292. // shadowOffsetX: 0,
  33293. // shadowOffsetY: 2
  33294. },
  33295. handle: {
  33296. show: false,
  33297. 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
  33298. size: 45,
  33299. // handle margin is from symbol center to axis, which is stable when circular move.
  33300. margin: 50,
  33301. // color: '#1b8bbd'
  33302. // color: '#2f4554'
  33303. color: '#333',
  33304. shadowBlur: 3,
  33305. shadowColor: '#aaa',
  33306. shadowOffsetX: 0,
  33307. shadowOffsetY: 2,
  33308. // For mobile performance
  33309. throttle: 40
  33310. }
  33311. }
  33312. });
  33313. var inner$7 = makeInner();
  33314. var each$9 = each$1;
  33315. /**
  33316. * @param {string} key
  33317. * @param {module:echarts/ExtensionAPI} api
  33318. * @param {Function} handler
  33319. * param: {string} currTrigger
  33320. * param: {Array.<number>} point
  33321. */
  33322. function register(key, api, handler) {
  33323. if (env$1.node) {
  33324. return;
  33325. }
  33326. var zr = api.getZr();
  33327. inner$7(zr).records || (inner$7(zr).records = {});
  33328. initGlobalListeners(zr, api);
  33329. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  33330. record.handler = handler;
  33331. }
  33332. function initGlobalListeners(zr, api) {
  33333. if (inner$7(zr).initialized) {
  33334. return;
  33335. }
  33336. inner$7(zr).initialized = true;
  33337. useHandler('click', curry(doEnter, 'click'));
  33338. useHandler('mousemove', curry(doEnter, 'mousemove'));
  33339. // useHandler('mouseout', onLeave);
  33340. useHandler('globalout', onLeave);
  33341. function useHandler(eventType, cb) {
  33342. zr.on(eventType, function (e) {
  33343. var dis = makeDispatchAction(api);
  33344. each$9(inner$7(zr).records, function (record) {
  33345. record && cb(record, e, dis.dispatchAction);
  33346. });
  33347. dispatchTooltipFinally(dis.pendings, api);
  33348. });
  33349. }
  33350. }
  33351. function dispatchTooltipFinally(pendings, api) {
  33352. var showLen = pendings.showTip.length;
  33353. var hideLen = pendings.hideTip.length;
  33354. var actuallyPayload;
  33355. if (showLen) {
  33356. actuallyPayload = pendings.showTip[showLen - 1];
  33357. }
  33358. else if (hideLen) {
  33359. actuallyPayload = pendings.hideTip[hideLen - 1];
  33360. }
  33361. if (actuallyPayload) {
  33362. actuallyPayload.dispatchAction = null;
  33363. api.dispatchAction(actuallyPayload);
  33364. }
  33365. }
  33366. function onLeave(record, e, dispatchAction) {
  33367. record.handler('leave', null, dispatchAction);
  33368. }
  33369. function doEnter(currTrigger, record, e, dispatchAction) {
  33370. record.handler(currTrigger, e, dispatchAction);
  33371. }
  33372. function makeDispatchAction(api) {
  33373. var pendings = {
  33374. showTip: [],
  33375. hideTip: []
  33376. };
  33377. // FIXME
  33378. // better approach?
  33379. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  33380. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  33381. // So we have to add "final stage" to merge those dispatched actions.
  33382. var dispatchAction = function (payload) {
  33383. var pendingList = pendings[payload.type];
  33384. if (pendingList) {
  33385. pendingList.push(payload);
  33386. }
  33387. else {
  33388. payload.dispatchAction = dispatchAction;
  33389. api.dispatchAction(payload);
  33390. }
  33391. };
  33392. return {
  33393. dispatchAction: dispatchAction,
  33394. pendings: pendings
  33395. };
  33396. }
  33397. /**
  33398. * @param {string} key
  33399. * @param {module:echarts/ExtensionAPI} api
  33400. */
  33401. function unregister(key, api) {
  33402. if (env$1.node) {
  33403. return;
  33404. }
  33405. var zr = api.getZr();
  33406. var record = (inner$7(zr).records || {})[key];
  33407. if (record) {
  33408. inner$7(zr).records[key] = null;
  33409. }
  33410. }
  33411. var AxisPointerView = extendComponentView({
  33412. type: 'axisPointer',
  33413. render: function (globalAxisPointerModel, ecModel, api) {
  33414. var globalTooltipModel = ecModel.getComponent('tooltip');
  33415. var triggerOn = globalAxisPointerModel.get('triggerOn')
  33416. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  33417. // Register global listener in AxisPointerView to enable
  33418. // AxisPointerView to be independent to Tooltip.
  33419. register(
  33420. 'axisPointer',
  33421. api,
  33422. function (currTrigger, e, dispatchAction) {
  33423. // If 'none', it is not controlled by mouse totally.
  33424. if (triggerOn !== 'none'
  33425. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  33426. ) {
  33427. dispatchAction({
  33428. type: 'updateAxisPointer',
  33429. currTrigger: currTrigger,
  33430. x: e && e.offsetX,
  33431. y: e && e.offsetY
  33432. });
  33433. }
  33434. }
  33435. );
  33436. },
  33437. /**
  33438. * @override
  33439. */
  33440. remove: function (ecModel, api) {
  33441. unregister(api.getZr(), 'axisPointer');
  33442. AxisPointerView.superApply(this._model, 'remove', arguments);
  33443. },
  33444. /**
  33445. * @override
  33446. */
  33447. dispose: function (ecModel, api) {
  33448. unregister('axisPointer', api);
  33449. AxisPointerView.superApply(this._model, 'dispose', arguments);
  33450. }
  33451. });
  33452. var inner$8 = makeInner();
  33453. var clone$4 = clone;
  33454. var bind$1 = bind;
  33455. /**
  33456. * Base axis pointer class in 2D.
  33457. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  33458. */
  33459. function BaseAxisPointer () {
  33460. }
  33461. BaseAxisPointer.prototype = {
  33462. /**
  33463. * @private
  33464. */
  33465. _group: null,
  33466. /**
  33467. * @private
  33468. */
  33469. _lastGraphicKey: null,
  33470. /**
  33471. * @private
  33472. */
  33473. _handle: null,
  33474. /**
  33475. * @private
  33476. */
  33477. _dragging: false,
  33478. /**
  33479. * @private
  33480. */
  33481. _lastValue: null,
  33482. /**
  33483. * @private
  33484. */
  33485. _lastStatus: null,
  33486. /**
  33487. * @private
  33488. */
  33489. _payloadInfo: null,
  33490. /**
  33491. * In px, arbitrary value. Do not set too small,
  33492. * no animation is ok for most cases.
  33493. * @protected
  33494. */
  33495. animationThreshold: 15,
  33496. /**
  33497. * @implement
  33498. */
  33499. render: function (axisModel, axisPointerModel, api, forceRender) {
  33500. var value = axisPointerModel.get('value');
  33501. var status = axisPointerModel.get('status');
  33502. // Bind them to `this`, not in closure, otherwise they will not
  33503. // be replaced when user calling setOption in not merge mode.
  33504. this._axisModel = axisModel;
  33505. this._axisPointerModel = axisPointerModel;
  33506. this._api = api;
  33507. // Optimize: `render` will be called repeatly during mouse move.
  33508. // So it is power consuming if performing `render` each time,
  33509. // especially on mobile device.
  33510. if (!forceRender
  33511. && this._lastValue === value
  33512. && this._lastStatus === status
  33513. ) {
  33514. return;
  33515. }
  33516. this._lastValue = value;
  33517. this._lastStatus = status;
  33518. var group = this._group;
  33519. var handle = this._handle;
  33520. if (!status || status === 'hide') {
  33521. // Do not clear here, for animation better.
  33522. group && group.hide();
  33523. handle && handle.hide();
  33524. return;
  33525. }
  33526. group && group.show();
  33527. handle && handle.show();
  33528. // Otherwise status is 'show'
  33529. var elOption = {};
  33530. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  33531. // Enable change axis pointer type.
  33532. var graphicKey = elOption.graphicKey;
  33533. if (graphicKey !== this._lastGraphicKey) {
  33534. this.clear(api);
  33535. }
  33536. this._lastGraphicKey = graphicKey;
  33537. var moveAnimation = this._moveAnimation =
  33538. this.determineAnimation(axisModel, axisPointerModel);
  33539. if (!group) {
  33540. group = this._group = new Group();
  33541. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  33542. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  33543. api.getZr().add(group);
  33544. }
  33545. else {
  33546. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  33547. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  33548. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  33549. }
  33550. updateMandatoryProps(group, axisPointerModel, true);
  33551. this._renderHandle(value);
  33552. },
  33553. /**
  33554. * @implement
  33555. */
  33556. remove: function (api) {
  33557. this.clear(api);
  33558. },
  33559. /**
  33560. * @implement
  33561. */
  33562. dispose: function (api) {
  33563. this.clear(api);
  33564. },
  33565. /**
  33566. * @protected
  33567. */
  33568. determineAnimation: function (axisModel, axisPointerModel) {
  33569. var animation = axisPointerModel.get('animation');
  33570. var axis = axisModel.axis;
  33571. var isCategoryAxis = axis.type === 'category';
  33572. var useSnap = axisPointerModel.get('snap');
  33573. // Value axis without snap always do not snap.
  33574. if (!useSnap && !isCategoryAxis) {
  33575. return false;
  33576. }
  33577. if (animation === 'auto' || animation == null) {
  33578. var animationThreshold = this.animationThreshold;
  33579. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  33580. return true;
  33581. }
  33582. // It is important to auto animation when snap used. Consider if there is
  33583. // a dataZoom, animation will be disabled when too many points exist, while
  33584. // it will be enabled for better visual effect when little points exist.
  33585. if (useSnap) {
  33586. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  33587. var axisExtent = axis.getExtent();
  33588. // Approximate band width
  33589. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  33590. }
  33591. return false;
  33592. }
  33593. return animation === true;
  33594. },
  33595. /**
  33596. * add {pointer, label, graphicKey} to elOption
  33597. * @protected
  33598. */
  33599. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  33600. // Shoule be implemenented by sub-class.
  33601. },
  33602. /**
  33603. * @protected
  33604. */
  33605. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  33606. var pointerOption = elOption.pointer;
  33607. if (pointerOption) {
  33608. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  33609. clone$4(elOption.pointer)
  33610. );
  33611. group.add(pointerEl);
  33612. }
  33613. },
  33614. /**
  33615. * @protected
  33616. */
  33617. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  33618. if (elOption.label) {
  33619. var labelEl = inner$8(group).labelEl = new Rect(
  33620. clone$4(elOption.label)
  33621. );
  33622. group.add(labelEl);
  33623. updateLabelShowHide(labelEl, axisPointerModel);
  33624. }
  33625. },
  33626. /**
  33627. * @protected
  33628. */
  33629. updatePointerEl: function (group, elOption, updateProps$$1) {
  33630. var pointerEl = inner$8(group).pointerEl;
  33631. if (pointerEl) {
  33632. pointerEl.setStyle(elOption.pointer.style);
  33633. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  33634. }
  33635. },
  33636. /**
  33637. * @protected
  33638. */
  33639. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  33640. var labelEl = inner$8(group).labelEl;
  33641. if (labelEl) {
  33642. labelEl.setStyle(elOption.label.style);
  33643. updateProps$$1(labelEl, {
  33644. // Consider text length change in vertical axis, animation should
  33645. // be used on shape, otherwise the effect will be weird.
  33646. shape: elOption.label.shape,
  33647. position: elOption.label.position
  33648. });
  33649. updateLabelShowHide(labelEl, axisPointerModel);
  33650. }
  33651. },
  33652. /**
  33653. * @private
  33654. */
  33655. _renderHandle: function (value) {
  33656. if (this._dragging || !this.updateHandleTransform) {
  33657. return;
  33658. }
  33659. var axisPointerModel = this._axisPointerModel;
  33660. var zr = this._api.getZr();
  33661. var handle = this._handle;
  33662. var handleModel = axisPointerModel.getModel('handle');
  33663. var status = axisPointerModel.get('status');
  33664. if (!handleModel.get('show') || !status || status === 'hide') {
  33665. handle && zr.remove(handle);
  33666. this._handle = null;
  33667. return;
  33668. }
  33669. var isInit;
  33670. if (!this._handle) {
  33671. isInit = true;
  33672. handle = this._handle = createIcon(
  33673. handleModel.get('icon'),
  33674. {
  33675. cursor: 'move',
  33676. draggable: true,
  33677. onmousemove: function (e) {
  33678. // Fot mobile devicem, prevent screen slider on the button.
  33679. stop(e.event);
  33680. },
  33681. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  33682. drift: bind$1(this._onHandleDragMove, this),
  33683. ondragend: bind$1(this._onHandleDragEnd, this)
  33684. }
  33685. );
  33686. zr.add(handle);
  33687. }
  33688. updateMandatoryProps(handle, axisPointerModel, false);
  33689. // update style
  33690. var includeStyles = [
  33691. 'color', 'borderColor', 'borderWidth', 'opacity',
  33692. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  33693. ];
  33694. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  33695. // update position
  33696. var handleSize = handleModel.get('size');
  33697. if (!isArray(handleSize)) {
  33698. handleSize = [handleSize, handleSize];
  33699. }
  33700. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  33701. createOrUpdate(
  33702. this,
  33703. '_doDispatchAxisPointer',
  33704. handleModel.get('throttle') || 0,
  33705. 'fixRate'
  33706. );
  33707. this._moveHandleToValue(value, isInit);
  33708. },
  33709. /**
  33710. * @private
  33711. */
  33712. _moveHandleToValue: function (value, isInit) {
  33713. updateProps$1(
  33714. this._axisPointerModel,
  33715. !isInit && this._moveAnimation,
  33716. this._handle,
  33717. getHandleTransProps(this.getHandleTransform(
  33718. value, this._axisModel, this._axisPointerModel
  33719. ))
  33720. );
  33721. },
  33722. /**
  33723. * @private
  33724. */
  33725. _onHandleDragMove: function (dx, dy) {
  33726. var handle = this._handle;
  33727. if (!handle) {
  33728. return;
  33729. }
  33730. this._dragging = true;
  33731. // Persistent for throttle.
  33732. var trans = this.updateHandleTransform(
  33733. getHandleTransProps(handle),
  33734. [dx, dy],
  33735. this._axisModel,
  33736. this._axisPointerModel
  33737. );
  33738. this._payloadInfo = trans;
  33739. handle.stopAnimation();
  33740. handle.attr(getHandleTransProps(trans));
  33741. inner$8(handle).lastProp = null;
  33742. this._doDispatchAxisPointer();
  33743. },
  33744. /**
  33745. * Throttled method.
  33746. * @private
  33747. */
  33748. _doDispatchAxisPointer: function () {
  33749. var handle = this._handle;
  33750. if (!handle) {
  33751. return;
  33752. }
  33753. var payloadInfo = this._payloadInfo;
  33754. var axisModel = this._axisModel;
  33755. this._api.dispatchAction({
  33756. type: 'updateAxisPointer',
  33757. x: payloadInfo.cursorPoint[0],
  33758. y: payloadInfo.cursorPoint[1],
  33759. tooltipOption: payloadInfo.tooltipOption,
  33760. axesInfo: [{
  33761. axisDim: axisModel.axis.dim,
  33762. axisIndex: axisModel.componentIndex
  33763. }]
  33764. });
  33765. },
  33766. /**
  33767. * @private
  33768. */
  33769. _onHandleDragEnd: function (moveAnimation) {
  33770. this._dragging = false;
  33771. var handle = this._handle;
  33772. if (!handle) {
  33773. return;
  33774. }
  33775. var value = this._axisPointerModel.get('value');
  33776. // Consider snap or categroy axis, handle may be not consistent with
  33777. // axisPointer. So move handle to align the exact value position when
  33778. // drag ended.
  33779. this._moveHandleToValue(value);
  33780. // For the effect: tooltip will be shown when finger holding on handle
  33781. // button, and will be hidden after finger left handle button.
  33782. this._api.dispatchAction({
  33783. type: 'hideTip'
  33784. });
  33785. },
  33786. /**
  33787. * Should be implemenented by sub-class if support `handle`.
  33788. * @protected
  33789. * @param {number} value
  33790. * @param {module:echarts/model/Model} axisModel
  33791. * @param {module:echarts/model/Model} axisPointerModel
  33792. * @return {Object} {position: [x, y], rotation: 0}
  33793. */
  33794. getHandleTransform: null,
  33795. /**
  33796. * * Should be implemenented by sub-class if support `handle`.
  33797. * @protected
  33798. * @param {Object} transform {position, rotation}
  33799. * @param {Array.<number>} delta [dx, dy]
  33800. * @param {module:echarts/model/Model} axisModel
  33801. * @param {module:echarts/model/Model} axisPointerModel
  33802. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  33803. */
  33804. updateHandleTransform: null,
  33805. /**
  33806. * @private
  33807. */
  33808. clear: function (api) {
  33809. this._lastValue = null;
  33810. this._lastStatus = null;
  33811. var zr = api.getZr();
  33812. var group = this._group;
  33813. var handle = this._handle;
  33814. if (zr && group) {
  33815. this._lastGraphicKey = null;
  33816. group && zr.remove(group);
  33817. handle && zr.remove(handle);
  33818. this._group = null;
  33819. this._handle = null;
  33820. this._payloadInfo = null;
  33821. }
  33822. },
  33823. /**
  33824. * @protected
  33825. */
  33826. doClear: function () {
  33827. // Implemented by sub-class if necessary.
  33828. },
  33829. /**
  33830. * @protected
  33831. * @param {Array.<number>} xy
  33832. * @param {Array.<number>} wh
  33833. * @param {number} [xDimIndex=0] or 1
  33834. */
  33835. buildLabel: function (xy, wh, xDimIndex) {
  33836. xDimIndex = xDimIndex || 0;
  33837. return {
  33838. x: xy[xDimIndex],
  33839. y: xy[1 - xDimIndex],
  33840. width: wh[xDimIndex],
  33841. height: wh[1 - xDimIndex]
  33842. };
  33843. }
  33844. };
  33845. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  33846. function updateProps$1(animationModel, moveAnimation, el, props) {
  33847. // Animation optimize.
  33848. if (!propsEqual(inner$8(el).lastProp, props)) {
  33849. inner$8(el).lastProp = props;
  33850. moveAnimation
  33851. ? updateProps(el, props, animationModel)
  33852. : (el.stopAnimation(), el.attr(props));
  33853. }
  33854. }
  33855. function propsEqual(lastProps, newProps) {
  33856. if (isObject$1(lastProps) && isObject$1(newProps)) {
  33857. var equals = true;
  33858. each$1(newProps, function (item, key) {
  33859. equals = equals && propsEqual(lastProps[key], item);
  33860. });
  33861. return !!equals;
  33862. }
  33863. else {
  33864. return lastProps === newProps;
  33865. }
  33866. }
  33867. function updateLabelShowHide(labelEl, axisPointerModel) {
  33868. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  33869. }
  33870. function getHandleTransProps(trans) {
  33871. return {
  33872. position: trans.position.slice(),
  33873. rotation: trans.rotation || 0
  33874. };
  33875. }
  33876. function updateMandatoryProps(group, axisPointerModel, silent) {
  33877. var z = axisPointerModel.get('z');
  33878. var zlevel = axisPointerModel.get('zlevel');
  33879. group && group.traverse(function (el) {
  33880. if (el.type !== 'group') {
  33881. z != null && (el.z = z);
  33882. zlevel != null && (el.zlevel = zlevel);
  33883. el.silent = silent;
  33884. }
  33885. });
  33886. }
  33887. enableClassExtend(BaseAxisPointer);
  33888. /**
  33889. * @param {module:echarts/model/Model} axisPointerModel
  33890. */
  33891. function buildElStyle(axisPointerModel) {
  33892. var axisPointerType = axisPointerModel.get('type');
  33893. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  33894. var style;
  33895. if (axisPointerType === 'line') {
  33896. style = styleModel.getLineStyle();
  33897. style.fill = null;
  33898. }
  33899. else if (axisPointerType === 'shadow') {
  33900. style = styleModel.getAreaStyle();
  33901. style.stroke = null;
  33902. }
  33903. return style;
  33904. }
  33905. /**
  33906. * @param {Function} labelPos {align, verticalAlign, position}
  33907. */
  33908. function buildLabelElOption(
  33909. elOption, axisModel, axisPointerModel, api, labelPos
  33910. ) {
  33911. var value = axisPointerModel.get('value');
  33912. var text = getValueLabel(
  33913. value, axisModel.axis, axisModel.ecModel,
  33914. axisPointerModel.get('seriesDataIndices'),
  33915. {
  33916. precision: axisPointerModel.get('label.precision'),
  33917. formatter: axisPointerModel.get('label.formatter')
  33918. }
  33919. );
  33920. var labelModel = axisPointerModel.getModel('label');
  33921. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  33922. var font = labelModel.getFont();
  33923. var textRect = getBoundingRect(text, font);
  33924. var position = labelPos.position;
  33925. var width = textRect.width + paddings[1] + paddings[3];
  33926. var height = textRect.height + paddings[0] + paddings[2];
  33927. // Adjust by align.
  33928. var align = labelPos.align;
  33929. align === 'right' && (position[0] -= width);
  33930. align === 'center' && (position[0] -= width / 2);
  33931. var verticalAlign = labelPos.verticalAlign;
  33932. verticalAlign === 'bottom' && (position[1] -= height);
  33933. verticalAlign === 'middle' && (position[1] -= height / 2);
  33934. // Not overflow ec container
  33935. confineInContainer(position, width, height, api);
  33936. var bgColor = labelModel.get('backgroundColor');
  33937. if (!bgColor || bgColor === 'auto') {
  33938. bgColor = axisModel.get('axisLine.lineStyle.color');
  33939. }
  33940. elOption.label = {
  33941. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  33942. position: position.slice(),
  33943. // TODO: rich
  33944. style: {
  33945. text: text,
  33946. textFont: font,
  33947. textFill: labelModel.getTextColor(),
  33948. textPosition: 'inside',
  33949. fill: bgColor,
  33950. stroke: labelModel.get('borderColor') || 'transparent',
  33951. lineWidth: labelModel.get('borderWidth') || 0,
  33952. shadowBlur: labelModel.get('shadowBlur'),
  33953. shadowColor: labelModel.get('shadowColor'),
  33954. shadowOffsetX: labelModel.get('shadowOffsetX'),
  33955. shadowOffsetY: labelModel.get('shadowOffsetY')
  33956. },
  33957. // Lable should be over axisPointer.
  33958. z2: 10
  33959. };
  33960. }
  33961. // Do not overflow ec container
  33962. function confineInContainer(position, width, height, api) {
  33963. var viewWidth = api.getWidth();
  33964. var viewHeight = api.getHeight();
  33965. position[0] = Math.min(position[0] + width, viewWidth) - width;
  33966. position[1] = Math.min(position[1] + height, viewHeight) - height;
  33967. position[0] = Math.max(position[0], 0);
  33968. position[1] = Math.max(position[1], 0);
  33969. }
  33970. /**
  33971. * @param {number} value
  33972. * @param {module:echarts/coord/Axis} axis
  33973. * @param {module:echarts/model/Global} ecModel
  33974. * @param {Object} opt
  33975. * @param {Array.<Object>} seriesDataIndices
  33976. * @param {number|string} opt.precision 'auto' or a number
  33977. * @param {string|Function} opt.formatter label formatter
  33978. */
  33979. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  33980. var text = axis.scale.getLabel(
  33981. // If `precision` is set, width can be fixed (like '12.00500'), which
  33982. // helps to debounce when when moving label.
  33983. value, {precision: opt.precision}
  33984. );
  33985. var formatter = opt.formatter;
  33986. if (formatter) {
  33987. var params = {
  33988. value: getAxisRawValue(axis, value),
  33989. seriesData: []
  33990. };
  33991. each$1(seriesDataIndices, function (idxItem) {
  33992. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  33993. var dataIndex = idxItem.dataIndexInside;
  33994. var dataParams = series && series.getDataParams(dataIndex);
  33995. dataParams && params.seriesData.push(dataParams);
  33996. });
  33997. if (isString(formatter)) {
  33998. text = formatter.replace('{value}', text);
  33999. }
  34000. else if (isFunction$1(formatter)) {
  34001. text = formatter(params);
  34002. }
  34003. }
  34004. return text;
  34005. }
  34006. /**
  34007. * @param {module:echarts/coord/Axis} axis
  34008. * @param {number} value
  34009. * @param {Object} layoutInfo {
  34010. * rotation, position, labelOffset, labelDirection, labelMargin
  34011. * }
  34012. */
  34013. function getTransformedPosition (axis, value, layoutInfo) {
  34014. var transform = create$1();
  34015. rotate(transform, transform, layoutInfo.rotation);
  34016. translate(transform, transform, layoutInfo.position);
  34017. return applyTransform$1([
  34018. axis.dataToCoord(value),
  34019. (layoutInfo.labelOffset || 0)
  34020. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  34021. ], transform);
  34022. }
  34023. function buildCartesianSingleLabelElOption(
  34024. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34025. ) {
  34026. var textLayout = AxisBuilder.innerTextLayout(
  34027. layoutInfo.rotation, 0, layoutInfo.labelDirection
  34028. );
  34029. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  34030. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  34031. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34032. align: textLayout.textAlign,
  34033. verticalAlign: textLayout.textVerticalAlign
  34034. });
  34035. }
  34036. /**
  34037. * @param {Array.<number>} p1
  34038. * @param {Array.<number>} p2
  34039. * @param {number} [xDimIndex=0] or 1
  34040. */
  34041. function makeLineShape(p1, p2, xDimIndex) {
  34042. xDimIndex = xDimIndex || 0;
  34043. return {
  34044. x1: p1[xDimIndex],
  34045. y1: p1[1 - xDimIndex],
  34046. x2: p2[xDimIndex],
  34047. y2: p2[1 - xDimIndex]
  34048. };
  34049. }
  34050. /**
  34051. * @param {Array.<number>} xy
  34052. * @param {Array.<number>} wh
  34053. * @param {number} [xDimIndex=0] or 1
  34054. */
  34055. function makeRectShape(xy, wh, xDimIndex) {
  34056. xDimIndex = xDimIndex || 0;
  34057. return {
  34058. x: xy[xDimIndex],
  34059. y: xy[1 - xDimIndex],
  34060. width: wh[xDimIndex],
  34061. height: wh[1 - xDimIndex]
  34062. };
  34063. }
  34064. var CartesianAxisPointer = BaseAxisPointer.extend({
  34065. /**
  34066. * @override
  34067. */
  34068. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34069. var axis = axisModel.axis;
  34070. var grid = axis.grid;
  34071. var axisPointerType = axisPointerModel.get('type');
  34072. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34073. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  34074. if (axisPointerType && axisPointerType !== 'none') {
  34075. var elStyle = buildElStyle(axisPointerModel);
  34076. var pointerOption = pointerShapeBuilder[axisPointerType](
  34077. axis, pixelValue, otherExtent, elStyle
  34078. );
  34079. pointerOption.style = elStyle;
  34080. elOption.graphicKey = pointerOption.type;
  34081. elOption.pointer = pointerOption;
  34082. }
  34083. var layoutInfo = layout$1(grid.model, axisModel);
  34084. buildCartesianSingleLabelElOption(
  34085. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34086. );
  34087. },
  34088. /**
  34089. * @override
  34090. */
  34091. getHandleTransform: function (value, axisModel, axisPointerModel) {
  34092. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  34093. labelInside: false
  34094. });
  34095. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  34096. return {
  34097. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34098. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  34099. };
  34100. },
  34101. /**
  34102. * @override
  34103. */
  34104. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  34105. var axis = axisModel.axis;
  34106. var grid = axis.grid;
  34107. var axisExtent = axis.getGlobalExtent(true);
  34108. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34109. var dimIndex = axis.dim === 'x' ? 0 : 1;
  34110. var currPosition = transform.position;
  34111. currPosition[dimIndex] += delta[dimIndex];
  34112. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  34113. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  34114. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  34115. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  34116. cursorPoint[dimIndex] = currPosition[dimIndex];
  34117. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  34118. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  34119. return {
  34120. position: currPosition,
  34121. rotation: transform.rotation,
  34122. cursorPoint: cursorPoint,
  34123. tooltipOption: tooltipOptions[dimIndex]
  34124. };
  34125. }
  34126. });
  34127. function getCartesian(grid, axis) {
  34128. var opt = {};
  34129. opt[axis.dim + 'AxisIndex'] = axis.index;
  34130. return grid.getCartesian(opt);
  34131. }
  34132. var pointerShapeBuilder = {
  34133. line: function (axis, pixelValue, otherExtent, elStyle) {
  34134. var targetShape = makeLineShape(
  34135. [pixelValue, otherExtent[0]],
  34136. [pixelValue, otherExtent[1]],
  34137. getAxisDimIndex(axis)
  34138. );
  34139. subPixelOptimizeLine({
  34140. shape: targetShape,
  34141. style: elStyle
  34142. });
  34143. return {
  34144. type: 'Line',
  34145. shape: targetShape
  34146. };
  34147. },
  34148. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  34149. var bandWidth = axis.getBandWidth();
  34150. var span = otherExtent[1] - otherExtent[0];
  34151. return {
  34152. type: 'Rect',
  34153. shape: makeRectShape(
  34154. [pixelValue - bandWidth / 2, otherExtent[0]],
  34155. [bandWidth, span],
  34156. getAxisDimIndex(axis)
  34157. )
  34158. };
  34159. }
  34160. };
  34161. function getAxisDimIndex(axis) {
  34162. return axis.dim === 'x' ? 0 : 1;
  34163. }
  34164. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  34165. // CartesianAxisPointer is not supposed to be required here. But consider
  34166. // echarts.simple.js and online build tooltip, which only require gridSimple,
  34167. // CartesianAxisPointer should be able to required somewhere.
  34168. registerPreprocessor(function (option) {
  34169. // Always has a global axisPointerModel for default setting.
  34170. if (option) {
  34171. (!option.axisPointer || option.axisPointer.length === 0)
  34172. && (option.axisPointer = {});
  34173. var link = option.axisPointer.link;
  34174. // Normalize to array to avoid object mergin. But if link
  34175. // is not set, remain null/undefined, otherwise it will
  34176. // override existent link setting.
  34177. if (link && !isArray(link)) {
  34178. option.axisPointer.link = [link];
  34179. }
  34180. }
  34181. });
  34182. // This process should proformed after coordinate systems created
  34183. // and series data processed. So put it on statistic processing stage.
  34184. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  34185. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34186. // allAxesInfo should be updated when setOption performed.
  34187. ecModel.getComponent('axisPointer').coordSysAxesInfo
  34188. = collect(ecModel, api);
  34189. });
  34190. // Broadcast to all views.
  34191. registerAction({
  34192. type: 'updateAxisPointer',
  34193. event: 'updateAxisPointer',
  34194. update: ':updateAxisPointer'
  34195. }, axisTrigger);
  34196. extendComponentModel({
  34197. type: 'tooltip',
  34198. dependencies: ['axisPointer'],
  34199. defaultOption: {
  34200. zlevel: 0,
  34201. z: 8,
  34202. show: true,
  34203. // tooltip主体内容
  34204. showContent: true,
  34205. // 'trigger' only works on coordinate system.
  34206. // 'item' | 'axis' | 'none'
  34207. trigger: 'item',
  34208. // 'click' | 'mousemove' | 'none'
  34209. triggerOn: 'mousemove|click',
  34210. alwaysShowContent: false,
  34211. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  34212. // 位置 {Array} | {Function}
  34213. // position: null
  34214. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  34215. // align: null,
  34216. // verticalAlign: null,
  34217. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  34218. confine: false,
  34219. // 内容格式器:{string}(Template) ¦ {Function}
  34220. // formatter: null
  34221. showDelay: 0,
  34222. // 隐藏延迟,单位ms
  34223. hideDelay: 100,
  34224. // 动画变换时间,单位s
  34225. transitionDuration: 0.4,
  34226. enterable: false,
  34227. // 提示背景颜色,默认为透明度为0.7的黑色
  34228. backgroundColor: 'rgba(50,50,50,0.7)',
  34229. // 提示边框颜色
  34230. borderColor: '#333',
  34231. // 提示边框圆角,单位px,默认为4
  34232. borderRadius: 4,
  34233. // 提示边框线宽,单位px,默认为0(无边框)
  34234. borderWidth: 0,
  34235. // 提示内边距,单位px,默认各方向内边距为5,
  34236. // 接受数组分别设定上右下左边距,同css
  34237. padding: 5,
  34238. // Extra css text
  34239. extraCssText: '',
  34240. // 坐标轴指示器,坐标轴触发有效
  34241. axisPointer: {
  34242. // 默认为直线
  34243. // 可选为:'line' | 'shadow' | 'cross'
  34244. type: 'line',
  34245. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  34246. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  34247. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  34248. // 极坐标系会默认选择 angle 轴
  34249. axis: 'auto',
  34250. animation: 'auto',
  34251. animationDurationUpdate: 200,
  34252. animationEasingUpdate: 'exponentialOut',
  34253. crossStyle: {
  34254. color: '#999',
  34255. width: 1,
  34256. type: 'dashed',
  34257. // TODO formatter
  34258. textStyle: {}
  34259. }
  34260. // lineStyle and shadowStyle should not be specified here,
  34261. // otherwise it will always override those styles on option.axisPointer.
  34262. },
  34263. textStyle: {
  34264. color: '#fff',
  34265. fontSize: 14
  34266. }
  34267. }
  34268. });
  34269. var each$11 = each$1;
  34270. var toCamelCase$1 = toCamelCase;
  34271. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  34272. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  34273. /**
  34274. * @param {number} duration
  34275. * @return {string}
  34276. * @inner
  34277. */
  34278. function assembleTransition(duration) {
  34279. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  34280. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  34281. + 'top ' + duration + 's ' + transitionCurve;
  34282. return map(vendors, function (vendorPrefix) {
  34283. return vendorPrefix + 'transition:' + transitionText;
  34284. }).join(';');
  34285. }
  34286. /**
  34287. * @param {Object} textStyle
  34288. * @return {string}
  34289. * @inner
  34290. */
  34291. function assembleFont(textStyleModel) {
  34292. var cssText = [];
  34293. var fontSize = textStyleModel.get('fontSize');
  34294. var color = textStyleModel.getTextColor();
  34295. color && cssText.push('color:' + color);
  34296. cssText.push('font:' + textStyleModel.getFont());
  34297. fontSize &&
  34298. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  34299. each$11(['decoration', 'align'], function (name) {
  34300. var val = textStyleModel.get(name);
  34301. val && cssText.push('text-' + name + ':' + val);
  34302. });
  34303. return cssText.join(';');
  34304. }
  34305. /**
  34306. * @param {Object} tooltipModel
  34307. * @return {string}
  34308. * @inner
  34309. */
  34310. function assembleCssText(tooltipModel) {
  34311. var cssText = [];
  34312. var transitionDuration = tooltipModel.get('transitionDuration');
  34313. var backgroundColor = tooltipModel.get('backgroundColor');
  34314. var textStyleModel = tooltipModel.getModel('textStyle');
  34315. var padding = tooltipModel.get('padding');
  34316. // Animation transition. Do not animate when transitionDuration is 0.
  34317. transitionDuration &&
  34318. cssText.push(assembleTransition(transitionDuration));
  34319. if (backgroundColor) {
  34320. if (env$1.canvasSupported) {
  34321. cssText.push('background-Color:' + backgroundColor);
  34322. }
  34323. else {
  34324. // for ie
  34325. cssText.push(
  34326. 'background-Color:#' + toHex(backgroundColor)
  34327. );
  34328. cssText.push('filter:alpha(opacity=70)');
  34329. }
  34330. }
  34331. // Border style
  34332. each$11(['width', 'color', 'radius'], function (name) {
  34333. var borderName = 'border-' + name;
  34334. var camelCase = toCamelCase$1(borderName);
  34335. var val = tooltipModel.get(camelCase);
  34336. val != null &&
  34337. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  34338. });
  34339. // Text style
  34340. cssText.push(assembleFont(textStyleModel));
  34341. // Padding
  34342. if (padding != null) {
  34343. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  34344. }
  34345. return cssText.join(';') + ';';
  34346. }
  34347. /**
  34348. * @alias module:echarts/component/tooltip/TooltipContent
  34349. * @constructor
  34350. */
  34351. function TooltipContent(container, api) {
  34352. if (env$1.wxa) {
  34353. return null;
  34354. }
  34355. var el = document.createElement('div');
  34356. var zr = this._zr = api.getZr();
  34357. this.el = el;
  34358. this._x = api.getWidth() / 2;
  34359. this._y = api.getHeight() / 2;
  34360. container.appendChild(el);
  34361. this._container = container;
  34362. this._show = false;
  34363. /**
  34364. * @private
  34365. */
  34366. this._hideTimeout;
  34367. var self = this;
  34368. el.onmouseenter = function () {
  34369. // clear the timeout in hideLater and keep showing tooltip
  34370. if (self._enterable) {
  34371. clearTimeout(self._hideTimeout);
  34372. self._show = true;
  34373. }
  34374. self._inContent = true;
  34375. };
  34376. el.onmousemove = function (e) {
  34377. e = e || window.event;
  34378. if (!self._enterable) {
  34379. // Try trigger zrender event to avoid mouse
  34380. // in and out shape too frequently
  34381. var handler = zr.handler;
  34382. normalizeEvent(container, e, true);
  34383. handler.dispatch('mousemove', e);
  34384. }
  34385. };
  34386. el.onmouseleave = function () {
  34387. if (self._enterable) {
  34388. if (self._show) {
  34389. self.hideLater(self._hideDelay);
  34390. }
  34391. }
  34392. self._inContent = false;
  34393. };
  34394. }
  34395. TooltipContent.prototype = {
  34396. constructor: TooltipContent,
  34397. /**
  34398. * @private
  34399. * @type {boolean}
  34400. */
  34401. _enterable: true,
  34402. /**
  34403. * Update when tooltip is rendered
  34404. */
  34405. update: function () {
  34406. // FIXME
  34407. // Move this logic to ec main?
  34408. var container = this._container;
  34409. var stl = container.currentStyle
  34410. || document.defaultView.getComputedStyle(container);
  34411. var domStyle = container.style;
  34412. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  34413. domStyle.position = 'relative';
  34414. }
  34415. // Hide the tooltip
  34416. // PENDING
  34417. // this.hide();
  34418. },
  34419. show: function (tooltipModel) {
  34420. clearTimeout(this._hideTimeout);
  34421. var el = this.el;
  34422. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  34423. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  34424. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  34425. + (tooltipModel.get('extraCssText') || '');
  34426. el.style.display = el.innerHTML ? 'block' : 'none';
  34427. this._show = true;
  34428. },
  34429. setContent: function (content) {
  34430. this.el.innerHTML = content == null ? '' : content;
  34431. },
  34432. setEnterable: function (enterable) {
  34433. this._enterable = enterable;
  34434. },
  34435. getSize: function () {
  34436. var el = this.el;
  34437. return [el.clientWidth, el.clientHeight];
  34438. },
  34439. moveTo: function (x, y) {
  34440. // xy should be based on canvas root. But tooltipContent is
  34441. // the sibling of canvas root. So padding of ec container
  34442. // should be considered here.
  34443. var zr = this._zr;
  34444. var viewportRootOffset;
  34445. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  34446. x += viewportRootOffset.offsetLeft;
  34447. y += viewportRootOffset.offsetTop;
  34448. }
  34449. var style = this.el.style;
  34450. style.left = x + 'px';
  34451. style.top = y + 'px';
  34452. this._x = x;
  34453. this._y = y;
  34454. },
  34455. hide: function () {
  34456. this.el.style.display = 'none';
  34457. this._show = false;
  34458. },
  34459. hideLater: function (time) {
  34460. if (this._show && !(this._inContent && this._enterable)) {
  34461. if (time) {
  34462. this._hideDelay = time;
  34463. // Set show false to avoid invoke hideLater mutiple times
  34464. this._show = false;
  34465. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  34466. }
  34467. else {
  34468. this.hide();
  34469. }
  34470. }
  34471. },
  34472. isShow: function () {
  34473. return this._show;
  34474. }
  34475. };
  34476. var bind$2 = bind;
  34477. var each$10 = each$1;
  34478. var parsePercent$2 = parsePercent$1;
  34479. var proxyRect = new Rect({
  34480. shape: {x: -1, y: -1, width: 2, height: 2}
  34481. });
  34482. extendComponentView({
  34483. type: 'tooltip',
  34484. init: function (ecModel, api) {
  34485. if (env$1.node) {
  34486. return;
  34487. }
  34488. var tooltipContent = new TooltipContent(api.getDom(), api);
  34489. this._tooltipContent = tooltipContent;
  34490. },
  34491. render: function (tooltipModel, ecModel, api) {
  34492. if (env$1.node || env$1.wxa) {
  34493. return;
  34494. }
  34495. // Reset
  34496. this.group.removeAll();
  34497. /**
  34498. * @private
  34499. * @type {module:echarts/component/tooltip/TooltipModel}
  34500. */
  34501. this._tooltipModel = tooltipModel;
  34502. /**
  34503. * @private
  34504. * @type {module:echarts/model/Global}
  34505. */
  34506. this._ecModel = ecModel;
  34507. /**
  34508. * @private
  34509. * @type {module:echarts/ExtensionAPI}
  34510. */
  34511. this._api = api;
  34512. /**
  34513. * Should be cleaned when render.
  34514. * @private
  34515. * @type {Array.<Array.<Object>>}
  34516. */
  34517. this._lastDataByCoordSys = null;
  34518. /**
  34519. * @private
  34520. * @type {boolean}
  34521. */
  34522. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  34523. var tooltipContent = this._tooltipContent;
  34524. tooltipContent.update();
  34525. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  34526. this._initGlobalListener();
  34527. this._keepShow();
  34528. },
  34529. _initGlobalListener: function () {
  34530. var tooltipModel = this._tooltipModel;
  34531. var triggerOn = tooltipModel.get('triggerOn');
  34532. register(
  34533. 'itemTooltip',
  34534. this._api,
  34535. bind$2(function (currTrigger, e, dispatchAction) {
  34536. // If 'none', it is not controlled by mouse totally.
  34537. if (triggerOn !== 'none') {
  34538. if (triggerOn.indexOf(currTrigger) >= 0) {
  34539. this._tryShow(e, dispatchAction);
  34540. }
  34541. else if (currTrigger === 'leave') {
  34542. this._hide(dispatchAction);
  34543. }
  34544. }
  34545. }, this)
  34546. );
  34547. },
  34548. _keepShow: function () {
  34549. var tooltipModel = this._tooltipModel;
  34550. var ecModel = this._ecModel;
  34551. var api = this._api;
  34552. // Try to keep the tooltip show when refreshing
  34553. if (this._lastX != null
  34554. && this._lastY != null
  34555. // When user is willing to control tooltip totally using API,
  34556. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  34557. // which is not expected.
  34558. && tooltipModel.get('triggerOn') !== 'none'
  34559. ) {
  34560. var self = this;
  34561. clearTimeout(this._refreshUpdateTimeout);
  34562. this._refreshUpdateTimeout = setTimeout(function () {
  34563. // Show tip next tick after other charts are rendered
  34564. // In case highlight action has wrong result
  34565. // FIXME
  34566. self.manuallyShowTip(tooltipModel, ecModel, api, {
  34567. x: self._lastX,
  34568. y: self._lastY
  34569. });
  34570. });
  34571. }
  34572. },
  34573. /**
  34574. * Show tip manually by
  34575. * dispatchAction({
  34576. * type: 'showTip',
  34577. * x: 10,
  34578. * y: 10
  34579. * });
  34580. * Or
  34581. * dispatchAction({
  34582. * type: 'showTip',
  34583. * seriesIndex: 0,
  34584. * dataIndex or dataIndexInside or name
  34585. * });
  34586. *
  34587. * TODO Batch
  34588. */
  34589. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  34590. if (payload.from === this.uid || env$1.node) {
  34591. return;
  34592. }
  34593. var dispatchAction = makeDispatchAction$1(payload, api);
  34594. // Reset ticket
  34595. this._ticket = '';
  34596. // When triggered from axisPointer.
  34597. var dataByCoordSys = payload.dataByCoordSys;
  34598. if (payload.tooltip && payload.x != null && payload.y != null) {
  34599. var el = proxyRect;
  34600. el.position = [payload.x, payload.y];
  34601. el.update();
  34602. el.tooltip = payload.tooltip;
  34603. // Manually show tooltip while view is not using zrender elements.
  34604. this._tryShow({
  34605. offsetX: payload.x,
  34606. offsetY: payload.y,
  34607. target: el
  34608. }, dispatchAction);
  34609. }
  34610. else if (dataByCoordSys) {
  34611. this._tryShow({
  34612. offsetX: payload.x,
  34613. offsetY: payload.y,
  34614. position: payload.position,
  34615. event: {},
  34616. dataByCoordSys: payload.dataByCoordSys,
  34617. tooltipOption: payload.tooltipOption
  34618. }, dispatchAction);
  34619. }
  34620. else if (payload.seriesIndex != null) {
  34621. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  34622. return;
  34623. }
  34624. var pointInfo = findPointFromSeries(payload, ecModel);
  34625. var cx = pointInfo.point[0];
  34626. var cy = pointInfo.point[1];
  34627. if (cx != null && cy != null) {
  34628. this._tryShow({
  34629. offsetX: cx,
  34630. offsetY: cy,
  34631. position: payload.position,
  34632. target: pointInfo.el,
  34633. event: {}
  34634. }, dispatchAction);
  34635. }
  34636. }
  34637. else if (payload.x != null && payload.y != null) {
  34638. // FIXME
  34639. // should wrap dispatchAction like `axisPointer/globalListener` ?
  34640. api.dispatchAction({
  34641. type: 'updateAxisPointer',
  34642. x: payload.x,
  34643. y: payload.y
  34644. });
  34645. this._tryShow({
  34646. offsetX: payload.x,
  34647. offsetY: payload.y,
  34648. position: payload.position,
  34649. target: api.getZr().findHover(payload.x, payload.y).target,
  34650. event: {}
  34651. }, dispatchAction);
  34652. }
  34653. },
  34654. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  34655. var tooltipContent = this._tooltipContent;
  34656. if (!this._alwaysShowContent && this._tooltipModel) {
  34657. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  34658. }
  34659. this._lastX = this._lastY = null;
  34660. if (payload.from !== this.uid) {
  34661. this._hide(makeDispatchAction$1(payload, api));
  34662. }
  34663. },
  34664. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  34665. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  34666. // and tooltip.
  34667. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  34668. var seriesIndex = payload.seriesIndex;
  34669. var dataIndex = payload.dataIndex;
  34670. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  34671. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  34672. return;
  34673. }
  34674. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  34675. if (!seriesModel) {
  34676. return;
  34677. }
  34678. var data = seriesModel.getData();
  34679. var tooltipModel = buildTooltipModel([
  34680. data.getItemModel(dataIndex),
  34681. seriesModel,
  34682. (seriesModel.coordinateSystem || {}).model,
  34683. tooltipModel
  34684. ]);
  34685. if (tooltipModel.get('trigger') !== 'axis') {
  34686. return;
  34687. }
  34688. api.dispatchAction({
  34689. type: 'updateAxisPointer',
  34690. seriesIndex: seriesIndex,
  34691. dataIndex: dataIndex,
  34692. position: payload.position
  34693. });
  34694. return true;
  34695. },
  34696. _tryShow: function (e, dispatchAction) {
  34697. var el = e.target;
  34698. var tooltipModel = this._tooltipModel;
  34699. if (!tooltipModel) {
  34700. return;
  34701. }
  34702. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  34703. this._lastX = e.offsetX;
  34704. this._lastY = e.offsetY;
  34705. var dataByCoordSys = e.dataByCoordSys;
  34706. if (dataByCoordSys && dataByCoordSys.length) {
  34707. this._showAxisTooltip(dataByCoordSys, e);
  34708. }
  34709. // Always show item tooltip if mouse is on the element with dataIndex
  34710. else if (el && el.dataIndex != null) {
  34711. this._lastDataByCoordSys = null;
  34712. this._showSeriesItemTooltip(e, el, dispatchAction);
  34713. }
  34714. // Tooltip provided directly. Like legend.
  34715. else if (el && el.tooltip) {
  34716. this._lastDataByCoordSys = null;
  34717. this._showComponentItemTooltip(e, el, dispatchAction);
  34718. }
  34719. else {
  34720. this._lastDataByCoordSys = null;
  34721. this._hide(dispatchAction);
  34722. }
  34723. },
  34724. _showOrMove: function (tooltipModel, cb) {
  34725. // showDelay is used in this case: tooltip.enterable is set
  34726. // as true. User intent to move mouse into tooltip and click
  34727. // something. `showDelay` makes it easyer to enter the content
  34728. // but tooltip do not move immediately.
  34729. var delay = tooltipModel.get('showDelay');
  34730. cb = bind(cb, this);
  34731. clearTimeout(this._showTimout);
  34732. delay > 0
  34733. ? (this._showTimout = setTimeout(cb, delay))
  34734. : cb();
  34735. },
  34736. _showAxisTooltip: function (dataByCoordSys, e) {
  34737. var ecModel = this._ecModel;
  34738. var globalTooltipModel = this._tooltipModel;
  34739. var point = [e.offsetX, e.offsetY];
  34740. var singleDefaultHTML = [];
  34741. var singleParamsList = [];
  34742. var singleTooltipModel = buildTooltipModel([
  34743. e.tooltipOption,
  34744. globalTooltipModel
  34745. ]);
  34746. each$10(dataByCoordSys, function (itemCoordSys) {
  34747. // var coordParamList = [];
  34748. // var coordDefaultHTML = [];
  34749. // var coordTooltipModel = buildTooltipModel([
  34750. // e.tooltipOption,
  34751. // itemCoordSys.tooltipOption,
  34752. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  34753. // globalTooltipModel
  34754. // ]);
  34755. // var displayMode = coordTooltipModel.get('displayMode');
  34756. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  34757. each$10(itemCoordSys.dataByAxis, function (item) {
  34758. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  34759. var axisValue = item.value;
  34760. var seriesDefaultHTML = [];
  34761. if (!axisModel || axisValue == null) {
  34762. return;
  34763. }
  34764. var valueLabel = getValueLabel(
  34765. axisValue, axisModel.axis, ecModel,
  34766. item.seriesDataIndices,
  34767. item.valueLabelOpt
  34768. );
  34769. each$1(item.seriesDataIndices, function (idxItem) {
  34770. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  34771. var dataIndex = idxItem.dataIndexInside;
  34772. var dataParams = series && series.getDataParams(dataIndex);
  34773. dataParams.axisDim = item.axisDim;
  34774. dataParams.axisIndex = item.axisIndex;
  34775. dataParams.axisType = item.axisType;
  34776. dataParams.axisId = item.axisId;
  34777. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  34778. dataParams.axisValueLabel = valueLabel;
  34779. if (dataParams) {
  34780. singleParamsList.push(dataParams);
  34781. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  34782. }
  34783. });
  34784. // Default tooltip content
  34785. // FIXME
  34786. // (1) shold be the first data which has name?
  34787. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  34788. var firstLine = valueLabel;
  34789. singleDefaultHTML.push(
  34790. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  34791. + seriesDefaultHTML.join('<br />')
  34792. );
  34793. });
  34794. }, this);
  34795. // In most case, the second axis is shown upper than the first one.
  34796. singleDefaultHTML.reverse();
  34797. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  34798. var positionExpr = e.position;
  34799. this._showOrMove(singleTooltipModel, function () {
  34800. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  34801. this._updatePosition(
  34802. singleTooltipModel,
  34803. positionExpr,
  34804. point[0], point[1],
  34805. this._tooltipContent,
  34806. singleParamsList
  34807. );
  34808. }
  34809. else {
  34810. this._showTooltipContent(
  34811. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  34812. point[0], point[1], positionExpr
  34813. );
  34814. }
  34815. });
  34816. // Do not trigger events here, because this branch only be entered
  34817. // from dispatchAction.
  34818. },
  34819. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  34820. var ecModel = this._ecModel;
  34821. // Use dataModel in element if possible
  34822. // Used when mouseover on a element like markPoint or edge
  34823. // In which case, the data is not main data in series.
  34824. var seriesIndex = el.seriesIndex;
  34825. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  34826. // For example, graph link.
  34827. var dataModel = el.dataModel || seriesModel;
  34828. var dataIndex = el.dataIndex;
  34829. var dataType = el.dataType;
  34830. var data = dataModel.getData();
  34831. var tooltipModel = buildTooltipModel([
  34832. data.getItemModel(dataIndex),
  34833. dataModel,
  34834. seriesModel && (seriesModel.coordinateSystem || {}).model,
  34835. this._tooltipModel
  34836. ]);
  34837. var tooltipTrigger = tooltipModel.get('trigger');
  34838. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  34839. return;
  34840. }
  34841. var params = dataModel.getDataParams(dataIndex, dataType);
  34842. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  34843. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  34844. this._showOrMove(tooltipModel, function () {
  34845. this._showTooltipContent(
  34846. tooltipModel, defaultHtml, params, asyncTicket,
  34847. e.offsetX, e.offsetY, e.position, e.target
  34848. );
  34849. });
  34850. // FIXME
  34851. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  34852. dispatchAction({
  34853. type: 'showTip',
  34854. dataIndexInside: dataIndex,
  34855. dataIndex: data.getRawIndex(dataIndex),
  34856. seriesIndex: seriesIndex,
  34857. from: this.uid
  34858. });
  34859. },
  34860. _showComponentItemTooltip: function (e, el, dispatchAction) {
  34861. var tooltipOpt = el.tooltip;
  34862. if (typeof tooltipOpt === 'string') {
  34863. var content = tooltipOpt;
  34864. tooltipOpt = {
  34865. content: content,
  34866. // Fixed formatter
  34867. formatter: content
  34868. };
  34869. }
  34870. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  34871. var defaultHtml = subTooltipModel.get('content');
  34872. var asyncTicket = Math.random();
  34873. // Do not check whether `trigger` is 'none' here, because `trigger`
  34874. // only works on cooridinate system. In fact, we have not found case
  34875. // that requires setting `trigger` nothing on component yet.
  34876. this._showOrMove(subTooltipModel, function () {
  34877. this._showTooltipContent(
  34878. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  34879. asyncTicket, e.offsetX, e.offsetY, e.position, el
  34880. );
  34881. });
  34882. // If not dispatch showTip, tip may be hide triggered by axis.
  34883. dispatchAction({
  34884. type: 'showTip',
  34885. from: this.uid
  34886. });
  34887. },
  34888. _showTooltipContent: function (
  34889. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  34890. ) {
  34891. // Reset ticket
  34892. this._ticket = '';
  34893. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  34894. return;
  34895. }
  34896. var tooltipContent = this._tooltipContent;
  34897. var formatter = tooltipModel.get('formatter');
  34898. positionExpr = positionExpr || tooltipModel.get('position');
  34899. var html = defaultHtml;
  34900. if (formatter && typeof formatter === 'string') {
  34901. html = formatTpl(formatter, params, true);
  34902. }
  34903. else if (typeof formatter === 'function') {
  34904. var callback = bind$2(function (cbTicket, html) {
  34905. if (cbTicket === this._ticket) {
  34906. tooltipContent.setContent(html);
  34907. this._updatePosition(
  34908. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  34909. );
  34910. }
  34911. }, this);
  34912. this._ticket = asyncTicket;
  34913. html = formatter(params, asyncTicket, callback);
  34914. }
  34915. tooltipContent.setContent(html);
  34916. tooltipContent.show(tooltipModel);
  34917. this._updatePosition(
  34918. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  34919. );
  34920. },
  34921. /**
  34922. * @param {string|Function|Array.<number>|Object} positionExpr
  34923. * @param {number} x Mouse x
  34924. * @param {number} y Mouse y
  34925. * @param {boolean} confine Whether confine tooltip content in view rect.
  34926. * @param {Object|<Array.<Object>} params
  34927. * @param {module:zrender/Element} el target element
  34928. * @param {module:echarts/ExtensionAPI} api
  34929. * @return {Array.<number>}
  34930. */
  34931. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  34932. var viewWidth = this._api.getWidth();
  34933. var viewHeight = this._api.getHeight();
  34934. positionExpr = positionExpr || tooltipModel.get('position');
  34935. var contentSize = content.getSize();
  34936. var align = tooltipModel.get('align');
  34937. var vAlign = tooltipModel.get('verticalAlign');
  34938. var rect = el && el.getBoundingRect().clone();
  34939. el && rect.applyTransform(el.transform);
  34940. if (typeof positionExpr === 'function') {
  34941. // Callback of position can be an array or a string specify the position
  34942. positionExpr = positionExpr([x, y], params, content.el, rect, {
  34943. viewSize: [viewWidth, viewHeight],
  34944. contentSize: contentSize.slice()
  34945. });
  34946. }
  34947. if (isArray(positionExpr)) {
  34948. x = parsePercent$2(positionExpr[0], viewWidth);
  34949. y = parsePercent$2(positionExpr[1], viewHeight);
  34950. }
  34951. else if (isObject$1(positionExpr)) {
  34952. positionExpr.width = contentSize[0];
  34953. positionExpr.height = contentSize[1];
  34954. var layoutRect = getLayoutRect(
  34955. positionExpr, {width: viewWidth, height: viewHeight}
  34956. );
  34957. x = layoutRect.x;
  34958. y = layoutRect.y;
  34959. align = null;
  34960. // When positionExpr is left/top/right/bottom,
  34961. // align and verticalAlign will not work.
  34962. vAlign = null;
  34963. }
  34964. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  34965. else if (typeof positionExpr === 'string' && el) {
  34966. var pos = calcTooltipPosition(
  34967. positionExpr, rect, contentSize
  34968. );
  34969. x = pos[0];
  34970. y = pos[1];
  34971. }
  34972. else {
  34973. var pos = refixTooltipPosition(
  34974. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  34975. );
  34976. x = pos[0];
  34977. y = pos[1];
  34978. }
  34979. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  34980. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  34981. if (tooltipModel.get('confine')) {
  34982. var pos = confineTooltipPosition(
  34983. x, y, content.el, viewWidth, viewHeight
  34984. );
  34985. x = pos[0];
  34986. y = pos[1];
  34987. }
  34988. content.moveTo(x, y);
  34989. },
  34990. // FIXME
  34991. // Should we remove this but leave this to user?
  34992. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  34993. var lastCoordSys = this._lastDataByCoordSys;
  34994. var contentNotChanged = !!lastCoordSys
  34995. && lastCoordSys.length === dataByCoordSys.length;
  34996. contentNotChanged && each$10(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  34997. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  34998. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  34999. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  35000. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  35001. contentNotChanged && each$10(lastDataByAxis, function (lastItem, indexAxis) {
  35002. var thisItem = thisDataByAxis[indexAxis] || {};
  35003. var lastIndices = lastItem.seriesDataIndices || [];
  35004. var newIndices = thisItem.seriesDataIndices || [];
  35005. contentNotChanged &=
  35006. lastItem.value === thisItem.value
  35007. && lastItem.axisType === thisItem.axisType
  35008. && lastItem.axisId === thisItem.axisId
  35009. && lastIndices.length === newIndices.length;
  35010. contentNotChanged && each$10(lastIndices, function (lastIdxItem, j) {
  35011. var newIdxItem = newIndices[j];
  35012. contentNotChanged &=
  35013. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  35014. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  35015. });
  35016. });
  35017. });
  35018. this._lastDataByCoordSys = dataByCoordSys;
  35019. return !!contentNotChanged;
  35020. },
  35021. _hide: function (dispatchAction) {
  35022. // Do not directly hideLater here, because this behavior may be prevented
  35023. // in dispatchAction when showTip is dispatched.
  35024. // FIXME
  35025. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  35026. this._lastDataByCoordSys = null;
  35027. dispatchAction({
  35028. type: 'hideTip',
  35029. from: this.uid
  35030. });
  35031. },
  35032. dispose: function (ecModel, api) {
  35033. if (env$1.node) {
  35034. return;
  35035. }
  35036. this._tooltipContent.hide();
  35037. unregister('itemTooltip', api);
  35038. }
  35039. });
  35040. /**
  35041. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  35042. * From top to bottom. (the last one should be globalTooltipModel);
  35043. */
  35044. function buildTooltipModel(modelCascade) {
  35045. var resultModel = modelCascade.pop();
  35046. while (modelCascade.length) {
  35047. var tooltipOpt = modelCascade.pop();
  35048. if (tooltipOpt) {
  35049. if (Model.isInstance(tooltipOpt)) {
  35050. tooltipOpt = tooltipOpt.get('tooltip', true);
  35051. }
  35052. // In each data item tooltip can be simply write:
  35053. // {
  35054. // value: 10,
  35055. // tooltip: 'Something you need to know'
  35056. // }
  35057. if (typeof tooltipOpt === 'string') {
  35058. tooltipOpt = {formatter: tooltipOpt};
  35059. }
  35060. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  35061. }
  35062. }
  35063. return resultModel;
  35064. }
  35065. function makeDispatchAction$1(payload, api) {
  35066. return payload.dispatchAction || bind(api.dispatchAction, api);
  35067. }
  35068. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  35069. var size = getOuterSize(el);
  35070. var width = size.width;
  35071. var height = size.height;
  35072. if (gapH != null) {
  35073. if (x + width + gapH > viewWidth) {
  35074. x -= width + gapH;
  35075. }
  35076. else {
  35077. x += gapH;
  35078. }
  35079. }
  35080. if (gapV != null) {
  35081. if (y + height + gapV > viewHeight) {
  35082. y -= height + gapV;
  35083. }
  35084. else {
  35085. y += gapV;
  35086. }
  35087. }
  35088. return [x, y];
  35089. }
  35090. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  35091. var size = getOuterSize(el);
  35092. var width = size.width;
  35093. var height = size.height;
  35094. x = Math.min(x + width, viewWidth) - width;
  35095. y = Math.min(y + height, viewHeight) - height;
  35096. x = Math.max(x, 0);
  35097. y = Math.max(y, 0);
  35098. return [x, y];
  35099. }
  35100. function getOuterSize(el) {
  35101. var width = el.clientWidth;
  35102. var height = el.clientHeight;
  35103. // Consider browser compatibility.
  35104. // IE8 does not support getComputedStyle.
  35105. if (document.defaultView && document.defaultView.getComputedStyle) {
  35106. var stl = document.defaultView.getComputedStyle(el);
  35107. if (stl) {
  35108. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  35109. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  35110. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  35111. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  35112. }
  35113. }
  35114. return {width: width, height: height};
  35115. }
  35116. function calcTooltipPosition(position, rect, contentSize) {
  35117. var domWidth = contentSize[0];
  35118. var domHeight = contentSize[1];
  35119. var gap = 5;
  35120. var x = 0;
  35121. var y = 0;
  35122. var rectWidth = rect.width;
  35123. var rectHeight = rect.height;
  35124. switch (position) {
  35125. case 'inside':
  35126. x = rect.x + rectWidth / 2 - domWidth / 2;
  35127. y = rect.y + rectHeight / 2 - domHeight / 2;
  35128. break;
  35129. case 'top':
  35130. x = rect.x + rectWidth / 2 - domWidth / 2;
  35131. y = rect.y - domHeight - gap;
  35132. break;
  35133. case 'bottom':
  35134. x = rect.x + rectWidth / 2 - domWidth / 2;
  35135. y = rect.y + rectHeight + gap;
  35136. break;
  35137. case 'left':
  35138. x = rect.x - domWidth - gap;
  35139. y = rect.y + rectHeight / 2 - domHeight / 2;
  35140. break;
  35141. case 'right':
  35142. x = rect.x + rectWidth + gap;
  35143. y = rect.y + rectHeight / 2 - domHeight / 2;
  35144. }
  35145. return [x, y];
  35146. }
  35147. function isCenterAlign(align) {
  35148. return align === 'center' || align === 'middle';
  35149. }
  35150. // FIXME Better way to pack data in graphic element
  35151. /**
  35152. * @action
  35153. * @property {string} type
  35154. * @property {number} seriesIndex
  35155. * @property {number} dataIndex
  35156. * @property {number} [x]
  35157. * @property {number} [y]
  35158. */
  35159. registerAction(
  35160. {
  35161. type: 'showTip',
  35162. event: 'showTip',
  35163. update: 'tooltip:manuallyShowTip'
  35164. },
  35165. // noop
  35166. function () {}
  35167. );
  35168. registerAction(
  35169. {
  35170. type: 'hideTip',
  35171. event: 'hideTip',
  35172. update: 'tooltip:manuallyHideTip'
  35173. },
  35174. // noop
  35175. function () {}
  35176. );
  35177. var LegendModel = extendComponentModel({
  35178. type: 'legend.plain',
  35179. dependencies: ['series'],
  35180. layoutMode: {
  35181. type: 'box',
  35182. // legend.width/height are maxWidth/maxHeight actually,
  35183. // whereas realy width/height is calculated by its content.
  35184. // (Setting {left: 10, right: 10} does not make sense).
  35185. // So consider the case:
  35186. // `setOption({legend: {left: 10});`
  35187. // then `setOption({legend: {right: 10});`
  35188. // The previous `left` should be cleared by setting `ignoreSize`.
  35189. ignoreSize: true
  35190. },
  35191. init: function (option, parentModel, ecModel) {
  35192. this.mergeDefaultAndTheme(option, ecModel);
  35193. option.selected = option.selected || {};
  35194. },
  35195. mergeOption: function (option) {
  35196. LegendModel.superCall(this, 'mergeOption', option);
  35197. },
  35198. optionUpdated: function () {
  35199. this._updateData(this.ecModel);
  35200. var legendData = this._data;
  35201. // If selectedMode is single, try to select one
  35202. if (legendData[0] && this.get('selectedMode') === 'single') {
  35203. var hasSelected = false;
  35204. // If has any selected in option.selected
  35205. for (var i = 0; i < legendData.length; i++) {
  35206. var name = legendData[i].get('name');
  35207. if (this.isSelected(name)) {
  35208. // Force to unselect others
  35209. this.select(name);
  35210. hasSelected = true;
  35211. break;
  35212. }
  35213. }
  35214. // Try select the first if selectedMode is single
  35215. !hasSelected && this.select(legendData[0].get('name'));
  35216. }
  35217. },
  35218. _updateData: function (ecModel) {
  35219. var potentialData = [];
  35220. var availableNames = [];
  35221. ecModel.eachRawSeries(function (seriesModel) {
  35222. var seriesName = seriesModel.name;
  35223. availableNames.push(seriesName);
  35224. var potentialSeriesName;
  35225. if (seriesModel.legendDataProvider) {
  35226. var data = seriesModel.legendDataProvider();
  35227. var names = data.mapArray(data.getName);
  35228. if (!ecModel.isSeriesFiltered(seriesModel)) {
  35229. availableNames = availableNames.concat(names);
  35230. }
  35231. if (names.length) {
  35232. potentialData = potentialData.concat(names);
  35233. }
  35234. else {
  35235. potentialSeriesName = seriesName;
  35236. }
  35237. }
  35238. else {
  35239. potentialSeriesName = seriesName;
  35240. }
  35241. if (potentialSeriesName && potentialSeriesName !== DEFAULT_COMPONENT_NAME) {
  35242. potentialData.push(potentialSeriesName);
  35243. }
  35244. });
  35245. /**
  35246. * @type {Array.<string>}
  35247. * @private
  35248. */
  35249. this._availableNames = availableNames;
  35250. // If legend.data not specified in option, use availableNames as data,
  35251. // which is convinient for user preparing option.
  35252. var rawData = this.get('data') || potentialData;
  35253. var legendData = map(rawData, function (dataItem) {
  35254. // Can be string or number
  35255. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  35256. dataItem = {
  35257. name: dataItem
  35258. };
  35259. }
  35260. return new Model(dataItem, this, this.ecModel);
  35261. }, this);
  35262. /**
  35263. * @type {Array.<module:echarts/model/Model>}
  35264. * @private
  35265. */
  35266. this._data = legendData;
  35267. },
  35268. /**
  35269. * @return {Array.<module:echarts/model/Model>}
  35270. */
  35271. getData: function () {
  35272. return this._data;
  35273. },
  35274. /**
  35275. * @param {string} name
  35276. */
  35277. select: function (name) {
  35278. var selected = this.option.selected;
  35279. var selectedMode = this.get('selectedMode');
  35280. if (selectedMode === 'single') {
  35281. var data = this._data;
  35282. each$1(data, function (dataItem) {
  35283. selected[dataItem.get('name')] = false;
  35284. });
  35285. }
  35286. selected[name] = true;
  35287. },
  35288. /**
  35289. * @param {string} name
  35290. */
  35291. unSelect: function (name) {
  35292. if (this.get('selectedMode') !== 'single') {
  35293. this.option.selected[name] = false;
  35294. }
  35295. },
  35296. /**
  35297. * @param {string} name
  35298. */
  35299. toggleSelected: function (name) {
  35300. var selected = this.option.selected;
  35301. // Default is true
  35302. if (!selected.hasOwnProperty(name)) {
  35303. selected[name] = true;
  35304. }
  35305. this[selected[name] ? 'unSelect' : 'select'](name);
  35306. },
  35307. /**
  35308. * @param {string} name
  35309. */
  35310. isSelected: function (name) {
  35311. var selected = this.option.selected;
  35312. return !(selected.hasOwnProperty(name) && !selected[name])
  35313. && indexOf(this._availableNames, name) >= 0;
  35314. },
  35315. defaultOption: {
  35316. // 一级层叠
  35317. zlevel: 0,
  35318. // 二级层叠
  35319. z: 4,
  35320. show: true,
  35321. // 布局方式,默认为水平布局,可选为:
  35322. // 'horizontal' | 'vertical'
  35323. orient: 'horizontal',
  35324. left: 'center',
  35325. // right: 'center',
  35326. top: 0,
  35327. // bottom: null,
  35328. // 水平对齐
  35329. // 'auto' | 'left' | 'right'
  35330. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  35331. align: 'auto',
  35332. backgroundColor: 'rgba(0,0,0,0)',
  35333. // 图例边框颜色
  35334. borderColor: '#ccc',
  35335. borderRadius: 0,
  35336. // 图例边框线宽,单位px,默认为0(无边框)
  35337. borderWidth: 0,
  35338. // 图例内边距,单位px,默认各方向内边距为5,
  35339. // 接受数组分别设定上右下左边距,同css
  35340. padding: 5,
  35341. // 各个item之间的间隔,单位px,默认为10,
  35342. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  35343. itemGap: 10,
  35344. // 图例图形宽度
  35345. itemWidth: 25,
  35346. // 图例图形高度
  35347. itemHeight: 14,
  35348. // 图例关闭时候的颜色
  35349. inactiveColor: '#ccc',
  35350. textStyle: {
  35351. // 图例文字颜色
  35352. color: '#333'
  35353. },
  35354. // formatter: '',
  35355. // 选择模式,默认开启图例开关
  35356. selectedMode: true,
  35357. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  35358. // selected: null,
  35359. // 图例内容(详见legend.data,数组中每一项代表一个item
  35360. // data: [],
  35361. // Tooltip 相关配置
  35362. tooltip: {
  35363. show: false
  35364. }
  35365. }
  35366. });
  35367. function legendSelectActionHandler(methodName, payload, ecModel) {
  35368. var selectedMap = {};
  35369. var isToggleSelect = methodName === 'toggleSelected';
  35370. var isSelected;
  35371. // Update all legend components
  35372. ecModel.eachComponent('legend', function (legendModel) {
  35373. if (isToggleSelect && isSelected != null) {
  35374. // Force other legend has same selected status
  35375. // Or the first is toggled to true and other are toggled to false
  35376. // In the case one legend has some item unSelected in option. And if other legend
  35377. // doesn't has the item, they will assume it is selected.
  35378. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  35379. }
  35380. else {
  35381. legendModel[methodName](payload.name);
  35382. isSelected = legendModel.isSelected(payload.name);
  35383. }
  35384. var legendData = legendModel.getData();
  35385. each$1(legendData, function (model) {
  35386. var name = model.get('name');
  35387. // Wrap element
  35388. if (name === '\n' || name === '') {
  35389. return;
  35390. }
  35391. var isItemSelected = legendModel.isSelected(name);
  35392. if (selectedMap.hasOwnProperty(name)) {
  35393. // Unselected if any legend is unselected
  35394. selectedMap[name] = selectedMap[name] && isItemSelected;
  35395. }
  35396. else {
  35397. selectedMap[name] = isItemSelected;
  35398. }
  35399. });
  35400. });
  35401. // Return the event explicitly
  35402. return {
  35403. name: payload.name,
  35404. selected: selectedMap
  35405. };
  35406. }
  35407. /**
  35408. * @event legendToggleSelect
  35409. * @type {Object}
  35410. * @property {string} type 'legendToggleSelect'
  35411. * @property {string} [from]
  35412. * @property {string} name Series name or data item name
  35413. */
  35414. registerAction(
  35415. 'legendToggleSelect', 'legendselectchanged',
  35416. curry(legendSelectActionHandler, 'toggleSelected')
  35417. );
  35418. /**
  35419. * @event legendSelect
  35420. * @type {Object}
  35421. * @property {string} type 'legendSelect'
  35422. * @property {string} name Series name or data item name
  35423. */
  35424. registerAction(
  35425. 'legendSelect', 'legendselected',
  35426. curry(legendSelectActionHandler, 'select')
  35427. );
  35428. /**
  35429. * @event legendUnSelect
  35430. * @type {Object}
  35431. * @property {string} type 'legendUnSelect'
  35432. * @property {string} name Series name or data item name
  35433. */
  35434. registerAction(
  35435. 'legendUnSelect', 'legendunselected',
  35436. curry(legendSelectActionHandler, 'unSelect')
  35437. );
  35438. /**
  35439. * Layout list like component.
  35440. * It will box layout each items in group of component and then position the whole group in the viewport
  35441. * @param {module:zrender/group/Group} group
  35442. * @param {module:echarts/model/Component} componentModel
  35443. * @param {module:echarts/ExtensionAPI}
  35444. */
  35445. function layout$2(group, componentModel, api) {
  35446. var boxLayoutParams = componentModel.getBoxLayoutParams();
  35447. var padding = componentModel.get('padding');
  35448. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  35449. var rect = getLayoutRect(
  35450. boxLayoutParams,
  35451. viewportSize,
  35452. padding
  35453. );
  35454. box(
  35455. componentModel.get('orient'),
  35456. group,
  35457. componentModel.get('itemGap'),
  35458. rect.width,
  35459. rect.height
  35460. );
  35461. positionElement(
  35462. group,
  35463. boxLayoutParams,
  35464. viewportSize,
  35465. padding
  35466. );
  35467. }
  35468. function makeBackground(rect, componentModel) {
  35469. var padding = normalizeCssArray$1(
  35470. componentModel.get('padding')
  35471. );
  35472. var style = componentModel.getItemStyle(['color', 'opacity']);
  35473. style.fill = componentModel.get('backgroundColor');
  35474. var rect = new Rect({
  35475. shape: {
  35476. x: rect.x - padding[3],
  35477. y: rect.y - padding[0],
  35478. width: rect.width + padding[1] + padding[3],
  35479. height: rect.height + padding[0] + padding[2],
  35480. r: componentModel.get('borderRadius')
  35481. },
  35482. style: style,
  35483. silent: true,
  35484. z2: -1
  35485. });
  35486. // FIXME
  35487. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  35488. // and background rect when setting like `left: 0`, `top: 0`.
  35489. // graphic.subPixelOptimizeRect(rect);
  35490. return rect;
  35491. }
  35492. var curry$3 = curry;
  35493. var each$12 = each$1;
  35494. var Group$2 = Group;
  35495. var LegendView = extendComponentView({
  35496. type: 'legend.plain',
  35497. newlineDisabled: false,
  35498. /**
  35499. * @override
  35500. */
  35501. init: function () {
  35502. /**
  35503. * @private
  35504. * @type {module:zrender/container/Group}
  35505. */
  35506. this.group.add(this._contentGroup = new Group$2());
  35507. /**
  35508. * @private
  35509. * @type {module:zrender/Element}
  35510. */
  35511. this._backgroundEl;
  35512. },
  35513. /**
  35514. * @protected
  35515. */
  35516. getContentGroup: function () {
  35517. return this._contentGroup;
  35518. },
  35519. /**
  35520. * @override
  35521. */
  35522. render: function (legendModel, ecModel, api) {
  35523. this.resetInner();
  35524. if (!legendModel.get('show', true)) {
  35525. return;
  35526. }
  35527. var itemAlign = legendModel.get('align');
  35528. if (!itemAlign || itemAlign === 'auto') {
  35529. itemAlign = (
  35530. legendModel.get('left') === 'right'
  35531. && legendModel.get('orient') === 'vertical'
  35532. ) ? 'right' : 'left';
  35533. }
  35534. this.renderInner(itemAlign, legendModel, ecModel, api);
  35535. // Perform layout.
  35536. var positionInfo = legendModel.getBoxLayoutParams();
  35537. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  35538. var padding = legendModel.get('padding');
  35539. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  35540. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  35541. // Place mainGroup, based on the calculated `mainRect`.
  35542. var layoutRect = getLayoutRect(
  35543. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  35544. viewportSize,
  35545. padding
  35546. );
  35547. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  35548. // Render background after group is layout.
  35549. this.group.add(
  35550. this._backgroundEl = makeBackground(mainRect, legendModel)
  35551. );
  35552. },
  35553. /**
  35554. * @protected
  35555. */
  35556. resetInner: function () {
  35557. this.getContentGroup().removeAll();
  35558. this._backgroundEl && this.group.remove(this._backgroundEl);
  35559. },
  35560. /**
  35561. * @protected
  35562. */
  35563. renderInner: function (itemAlign, legendModel, ecModel, api) {
  35564. var contentGroup = this.getContentGroup();
  35565. var legendDrawnMap = createHashMap();
  35566. var selectMode = legendModel.get('selectedMode');
  35567. each$12(legendModel.getData(), function (itemModel, dataIndex) {
  35568. var name = itemModel.get('name');
  35569. // Use empty string or \n as a newline string
  35570. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  35571. contentGroup.add(new Group$2({
  35572. newline: true
  35573. }));
  35574. return;
  35575. }
  35576. var seriesModel = ecModel.getSeriesByName(name)[0];
  35577. if (legendDrawnMap.get(name)) {
  35578. // Have been drawed
  35579. return;
  35580. }
  35581. // Series legend
  35582. if (seriesModel) {
  35583. var data = seriesModel.getData();
  35584. var color = data.getVisual('color');
  35585. // If color is a callback function
  35586. if (typeof color === 'function') {
  35587. // Use the first data
  35588. color = color(seriesModel.getDataParams(0));
  35589. }
  35590. // Using rect symbol defaultly
  35591. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  35592. var symbolType = data.getVisual('symbol');
  35593. var itemGroup = this._createItem(
  35594. name, dataIndex, itemModel, legendModel,
  35595. legendSymbolType, symbolType,
  35596. itemAlign, color,
  35597. selectMode
  35598. );
  35599. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  35600. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, null, api))
  35601. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, null, api));
  35602. legendDrawnMap.set(name, true);
  35603. }
  35604. else {
  35605. // Data legend of pie, funnel
  35606. ecModel.eachRawSeries(function (seriesModel) {
  35607. // In case multiple series has same data name
  35608. if (legendDrawnMap.get(name)) {
  35609. return;
  35610. }
  35611. if (seriesModel.legendDataProvider) {
  35612. var data = seriesModel.legendDataProvider();
  35613. var idx = data.indexOfName(name);
  35614. if (idx < 0) {
  35615. return;
  35616. }
  35617. var color = data.getItemVisual(idx, 'color');
  35618. var legendSymbolType = 'roundRect';
  35619. var itemGroup = this._createItem(
  35620. name, dataIndex, itemModel, legendModel,
  35621. legendSymbolType, null,
  35622. itemAlign, color,
  35623. selectMode
  35624. );
  35625. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  35626. // FIXME Should not specify the series name
  35627. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, name, api))
  35628. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, name, api));
  35629. legendDrawnMap.set(name, true);
  35630. }
  35631. }, this);
  35632. }
  35633. if (__DEV__) {
  35634. if (!legendDrawnMap.get(name)) {
  35635. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  35636. }
  35637. }
  35638. }, this);
  35639. },
  35640. _createItem: function (
  35641. name, dataIndex, itemModel, legendModel,
  35642. legendSymbolType, symbolType,
  35643. itemAlign, color, selectMode
  35644. ) {
  35645. var itemWidth = legendModel.get('itemWidth');
  35646. var itemHeight = legendModel.get('itemHeight');
  35647. var inactiveColor = legendModel.get('inactiveColor');
  35648. var isSelected = legendModel.isSelected(name);
  35649. var itemGroup = new Group$2();
  35650. var textStyleModel = itemModel.getModel('textStyle');
  35651. var itemIcon = itemModel.get('icon');
  35652. var tooltipModel = itemModel.getModel('tooltip');
  35653. var legendGlobalTooltipModel = tooltipModel.parentModel;
  35654. // Use user given icon first
  35655. legendSymbolType = itemIcon || legendSymbolType;
  35656. itemGroup.add(createSymbol(
  35657. legendSymbolType,
  35658. 0,
  35659. 0,
  35660. itemWidth,
  35661. itemHeight,
  35662. isSelected ? color : inactiveColor,
  35663. true
  35664. ));
  35665. // Compose symbols
  35666. // PENDING
  35667. if (!itemIcon && symbolType
  35668. // At least show one symbol, can't be all none
  35669. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  35670. ) {
  35671. var size = itemHeight * 0.8;
  35672. if (symbolType === 'none') {
  35673. symbolType = 'circle';
  35674. }
  35675. // Put symbol in the center
  35676. itemGroup.add(createSymbol(
  35677. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  35678. isSelected ? color : inactiveColor
  35679. ));
  35680. }
  35681. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  35682. var textAlign = itemAlign;
  35683. var formatter = legendModel.get('formatter');
  35684. var content = name;
  35685. if (typeof formatter === 'string' && formatter) {
  35686. content = formatter.replace('{name}', name != null ? name : '');
  35687. }
  35688. else if (typeof formatter === 'function') {
  35689. content = formatter(name);
  35690. }
  35691. itemGroup.add(new Text({
  35692. style: setTextStyle({}, textStyleModel, {
  35693. text: content,
  35694. x: textX,
  35695. y: itemHeight / 2,
  35696. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  35697. textAlign: textAlign,
  35698. textVerticalAlign: 'middle'
  35699. })
  35700. }));
  35701. // Add a invisible rect to increase the area of mouse hover
  35702. var hitRect = new Rect({
  35703. shape: itemGroup.getBoundingRect(),
  35704. invisible: true,
  35705. tooltip: tooltipModel.get('show') ? extend({
  35706. content: name,
  35707. // Defaul formatter
  35708. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  35709. return name;
  35710. },
  35711. formatterParams: {
  35712. componentType: 'legend',
  35713. legendIndex: legendModel.componentIndex,
  35714. name: name,
  35715. $vars: ['name']
  35716. }
  35717. }, tooltipModel.option) : null
  35718. });
  35719. itemGroup.add(hitRect);
  35720. itemGroup.eachChild(function (child) {
  35721. child.silent = true;
  35722. });
  35723. hitRect.silent = !selectMode;
  35724. this.getContentGroup().add(itemGroup);
  35725. setHoverStyle(itemGroup);
  35726. itemGroup.__legendDataIndex = dataIndex;
  35727. return itemGroup;
  35728. },
  35729. /**
  35730. * @protected
  35731. */
  35732. layoutInner: function (legendModel, itemAlign, maxSize) {
  35733. var contentGroup = this.getContentGroup();
  35734. // Place items in contentGroup.
  35735. box(
  35736. legendModel.get('orient'),
  35737. contentGroup,
  35738. legendModel.get('itemGap'),
  35739. maxSize.width,
  35740. maxSize.height
  35741. );
  35742. var contentRect = contentGroup.getBoundingRect();
  35743. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  35744. return this.group.getBoundingRect();
  35745. }
  35746. });
  35747. function dispatchSelectAction(name, api) {
  35748. api.dispatchAction({
  35749. type: 'legendToggleSelect',
  35750. name: name
  35751. });
  35752. }
  35753. function dispatchHighlightAction(seriesModel, dataName, api) {
  35754. // If element hover will move to a hoverLayer.
  35755. var el = api.getZr().storage.getDisplayList()[0];
  35756. if (!(el && el.useHoverLayer)) {
  35757. seriesModel.get('legendHoverLink') && api.dispatchAction({
  35758. type: 'highlight',
  35759. seriesName: seriesModel.name,
  35760. name: dataName
  35761. });
  35762. }
  35763. }
  35764. function dispatchDownplayAction(seriesModel, dataName, api) {
  35765. // If element hover will move to a hoverLayer.
  35766. var el = api.getZr().storage.getDisplayList()[0];
  35767. if (!(el && el.useHoverLayer)) {
  35768. seriesModel.get('legendHoverLink') && api.dispatchAction({
  35769. type: 'downplay',
  35770. seriesName: seriesModel.name,
  35771. name: dataName
  35772. });
  35773. }
  35774. }
  35775. var legendFilter = function (ecModel) {
  35776. var legendModels = ecModel.findComponents({
  35777. mainType: 'legend'
  35778. });
  35779. if (legendModels && legendModels.length) {
  35780. ecModel.filterSeries(function (series) {
  35781. // If in any legend component the status is not selected.
  35782. // Because in legend series is assumed selected when it is not in the legend data.
  35783. for (var i = 0; i < legendModels.length; i++) {
  35784. if (!legendModels[i].isSelected(series.name)) {
  35785. return false;
  35786. }
  35787. }
  35788. return true;
  35789. });
  35790. }
  35791. };
  35792. // Do not contain scrollable legend, for sake of file size.
  35793. // Series Filter
  35794. registerProcessor(legendFilter);
  35795. ComponentModel.registerSubTypeDefaulter('legend', function () {
  35796. // Default 'plain' when no type specified.
  35797. return 'plain';
  35798. });
  35799. var ScrollableLegendModel = LegendModel.extend({
  35800. type: 'legend.scroll',
  35801. /**
  35802. * @param {number} scrollDataIndex
  35803. */
  35804. setScrollDataIndex: function (scrollDataIndex) {
  35805. this.option.scrollDataIndex = scrollDataIndex;
  35806. },
  35807. defaultOption: {
  35808. scrollDataIndex: 0,
  35809. pageButtonItemGap: 5,
  35810. pageButtonGap: null,
  35811. pageButtonPosition: 'end', // 'start' or 'end'
  35812. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  35813. pageIcons: {
  35814. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  35815. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  35816. },
  35817. pageIconColor: '#2f4554',
  35818. pageIconInactiveColor: '#aaa',
  35819. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  35820. pageTextStyle: {
  35821. color: '#333'
  35822. },
  35823. animationDurationUpdate: 800
  35824. },
  35825. /**
  35826. * @override
  35827. */
  35828. init: function (option, parentModel, ecModel, extraOpt) {
  35829. var inputPositionParams = getLayoutParams(option);
  35830. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  35831. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  35832. },
  35833. /**
  35834. * @override
  35835. */
  35836. mergeOption: function (option, extraOpt) {
  35837. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  35838. mergeAndNormalizeLayoutParams(this, this.option, option);
  35839. },
  35840. getOrient: function () {
  35841. return this.get('orient') === 'vertical'
  35842. ? {index: 1, name: 'vertical'}
  35843. : {index: 0, name: 'horizontal'};
  35844. }
  35845. });
  35846. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  35847. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  35848. var orient = legendModel.getOrient();
  35849. var ignoreSize = [1, 1];
  35850. ignoreSize[orient.index] = 0;
  35851. mergeLayoutParam(target, raw, {
  35852. type: 'box', ignoreSize: ignoreSize
  35853. });
  35854. }
  35855. /**
  35856. * Separate legend and scrollable legend to reduce package size.
  35857. */
  35858. var Group$3 = Group;
  35859. var WH = ['width', 'height'];
  35860. var XY = ['x', 'y'];
  35861. var ScrollableLegendView = LegendView.extend({
  35862. type: 'legend.scroll',
  35863. newlineDisabled: true,
  35864. init: function () {
  35865. ScrollableLegendView.superCall(this, 'init');
  35866. /**
  35867. * @private
  35868. * @type {number} For `scroll`.
  35869. */
  35870. this._currentIndex = 0;
  35871. /**
  35872. * @private
  35873. * @type {module:zrender/container/Group}
  35874. */
  35875. this.group.add(this._containerGroup = new Group$3());
  35876. this._containerGroup.add(this.getContentGroup());
  35877. /**
  35878. * @private
  35879. * @type {module:zrender/container/Group}
  35880. */
  35881. this.group.add(this._controllerGroup = new Group$3());
  35882. /**
  35883. *
  35884. * @private
  35885. */
  35886. this._showController;
  35887. },
  35888. /**
  35889. * @override
  35890. */
  35891. resetInner: function () {
  35892. ScrollableLegendView.superCall(this, 'resetInner');
  35893. this._controllerGroup.removeAll();
  35894. this._containerGroup.removeClipPath();
  35895. this._containerGroup.__rectSize = null;
  35896. },
  35897. /**
  35898. * @override
  35899. */
  35900. renderInner: function (itemAlign, legendModel, ecModel, api) {
  35901. var me = this;
  35902. // Render content items.
  35903. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  35904. var controllerGroup = this._controllerGroup;
  35905. var pageIconSize = legendModel.get('pageIconSize', true);
  35906. if (!isArray(pageIconSize)) {
  35907. pageIconSize = [pageIconSize, pageIconSize];
  35908. }
  35909. createPageButton('pagePrev', 0);
  35910. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  35911. controllerGroup.add(new Text({
  35912. name: 'pageText',
  35913. style: {
  35914. textFill: pageTextStyleModel.getTextColor(),
  35915. font: pageTextStyleModel.getFont(),
  35916. textVerticalAlign: 'middle',
  35917. textAlign: 'center'
  35918. },
  35919. silent: true
  35920. }));
  35921. createPageButton('pageNext', 1);
  35922. function createPageButton(name, iconIdx) {
  35923. var pageDataIndexName = name + 'DataIndex';
  35924. var icon = createIcon(
  35925. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  35926. {
  35927. // Buttons will be created in each render, so we do not need
  35928. // to worry about avoiding using legendModel kept in scope.
  35929. onclick: bind(
  35930. me._pageGo, me, pageDataIndexName, legendModel, api
  35931. )
  35932. },
  35933. {
  35934. x: -pageIconSize[0] / 2,
  35935. y: -pageIconSize[1] / 2,
  35936. width: pageIconSize[0],
  35937. height: pageIconSize[1]
  35938. }
  35939. );
  35940. icon.name = name;
  35941. controllerGroup.add(icon);
  35942. }
  35943. },
  35944. /**
  35945. * @override
  35946. */
  35947. layoutInner: function (legendModel, itemAlign, maxSize) {
  35948. var contentGroup = this.getContentGroup();
  35949. var containerGroup = this._containerGroup;
  35950. var controllerGroup = this._controllerGroup;
  35951. var orientIdx = legendModel.getOrient().index;
  35952. var wh = WH[orientIdx];
  35953. var hw = WH[1 - orientIdx];
  35954. var yx = XY[1 - orientIdx];
  35955. // Place items in contentGroup.
  35956. box(
  35957. legendModel.get('orient'),
  35958. contentGroup,
  35959. legendModel.get('itemGap'),
  35960. !orientIdx ? null : maxSize.width,
  35961. orientIdx ? null : maxSize.height
  35962. );
  35963. box(
  35964. // Buttons in controller are layout always horizontally.
  35965. 'horizontal',
  35966. controllerGroup,
  35967. legendModel.get('pageButtonItemGap', true)
  35968. );
  35969. var contentRect = contentGroup.getBoundingRect();
  35970. var controllerRect = controllerGroup.getBoundingRect();
  35971. var showController = this._showController = contentRect[wh] > maxSize[wh];
  35972. var contentPos = [-contentRect.x, -contentRect.y];
  35973. // Remain contentPos when scroll animation perfroming.
  35974. contentPos[orientIdx] = contentGroup.position[orientIdx];
  35975. // Layout container group based on 0.
  35976. var containerPos = [0, 0];
  35977. var controllerPos = [-controllerRect.x, -controllerRect.y];
  35978. var pageButtonGap = retrieve2(
  35979. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  35980. );
  35981. // Place containerGroup and controllerGroup and contentGroup.
  35982. if (showController) {
  35983. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  35984. // controller is on the right / bottom.
  35985. if (pageButtonPosition === 'end') {
  35986. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  35987. }
  35988. // controller is on the left / top.
  35989. else {
  35990. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  35991. }
  35992. }
  35993. // Always align controller to content as 'middle'.
  35994. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  35995. contentGroup.attr('position', contentPos);
  35996. containerGroup.attr('position', containerPos);
  35997. controllerGroup.attr('position', controllerPos);
  35998. // Calculate `mainRect` and set `clipPath`.
  35999. // mainRect should not be calculated by `this.group.getBoundingRect()`
  36000. // for sake of the overflow.
  36001. var mainRect = this.group.getBoundingRect();
  36002. var mainRect = {x: 0, y: 0};
  36003. // Consider content may be overflow (should be clipped).
  36004. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  36005. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  36006. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  36007. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  36008. containerGroup.__rectSize = maxSize[wh];
  36009. if (showController) {
  36010. var clipShape = {x: 0, y: 0};
  36011. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  36012. clipShape[hw] = mainRect[hw];
  36013. containerGroup.setClipPath(new Rect({shape: clipShape}));
  36014. // Consider content may be larger than container, container rect
  36015. // can not be obtained from `containerGroup.getBoundingRect()`.
  36016. containerGroup.__rectSize = clipShape[wh];
  36017. }
  36018. else {
  36019. // Do not remove or ignore controller. Keep them set as place holders.
  36020. controllerGroup.eachChild(function (child) {
  36021. child.attr({invisible: true, silent: true});
  36022. });
  36023. }
  36024. // Content translate animation.
  36025. var pageInfo = this._getPageInfo(legendModel);
  36026. pageInfo.pageIndex != null && updateProps(
  36027. contentGroup,
  36028. {position: pageInfo.contentPosition},
  36029. // When switch from "show controller" to "not show controller", view should be
  36030. // updated immediately without animation, otherwise causes weird efffect.
  36031. showController ? legendModel : false
  36032. );
  36033. this._updatePageInfoView(legendModel, pageInfo);
  36034. return mainRect;
  36035. },
  36036. _pageGo: function (to, legendModel, api) {
  36037. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  36038. scrollDataIndex != null && api.dispatchAction({
  36039. type: 'legendScroll',
  36040. scrollDataIndex: scrollDataIndex,
  36041. legendId: legendModel.id
  36042. });
  36043. },
  36044. _updatePageInfoView: function (legendModel, pageInfo) {
  36045. var controllerGroup = this._controllerGroup;
  36046. each$1(['pagePrev', 'pageNext'], function (name) {
  36047. var canJump = pageInfo[name + 'DataIndex'] != null;
  36048. var icon = controllerGroup.childOfName(name);
  36049. if (icon) {
  36050. icon.setStyle(
  36051. 'fill',
  36052. canJump
  36053. ? legendModel.get('pageIconColor', true)
  36054. : legendModel.get('pageIconInactiveColor', true)
  36055. );
  36056. icon.cursor = canJump ? 'pointer' : 'default';
  36057. }
  36058. });
  36059. var pageText = controllerGroup.childOfName('pageText');
  36060. var pageFormatter = legendModel.get('pageFormatter');
  36061. var pageIndex = pageInfo.pageIndex;
  36062. var current = pageIndex != null ? pageIndex + 1 : 0;
  36063. var total = pageInfo.pageCount;
  36064. pageText && pageFormatter && pageText.setStyle(
  36065. 'text',
  36066. isString(pageFormatter)
  36067. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  36068. : pageFormatter({current: current, total: total})
  36069. );
  36070. },
  36071. /**
  36072. * @param {module:echarts/model/Model} legendModel
  36073. * @return {Object} {
  36074. * contentPosition: Array.<number>, null when data item not found.
  36075. * pageIndex: number, null when data item not found.
  36076. * pageCount: number, always be a number, can be 0.
  36077. * pagePrevDataIndex: number, null when no next page.
  36078. * pageNextDataIndex: number, null when no previous page.
  36079. * }
  36080. */
  36081. _getPageInfo: function (legendModel) {
  36082. // Align left or top by the current dataIndex.
  36083. var currDataIndex = legendModel.get('scrollDataIndex', true);
  36084. var contentGroup = this.getContentGroup();
  36085. var contentRect = contentGroup.getBoundingRect();
  36086. var containerRectSize = this._containerGroup.__rectSize;
  36087. var orientIdx = legendModel.getOrient().index;
  36088. var wh = WH[orientIdx];
  36089. var hw = WH[1 - orientIdx];
  36090. var xy = XY[orientIdx];
  36091. var contentPos = contentGroup.position.slice();
  36092. var pageIndex;
  36093. var pagePrevDataIndex;
  36094. var pageNextDataIndex;
  36095. var targetItemGroup;
  36096. if (this._showController) {
  36097. contentGroup.eachChild(function (child) {
  36098. if (child.__legendDataIndex === currDataIndex) {
  36099. targetItemGroup = child;
  36100. }
  36101. });
  36102. }
  36103. else {
  36104. targetItemGroup = contentGroup.childAt(0);
  36105. }
  36106. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  36107. if (targetItemGroup) {
  36108. var itemRect = targetItemGroup.getBoundingRect();
  36109. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  36110. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  36111. pageIndex = Math.floor(
  36112. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  36113. );
  36114. pageIndex = (contentRect[wh] && pageCount)
  36115. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  36116. : -1;
  36117. var winRect = {x: 0, y: 0};
  36118. winRect[wh] = containerRectSize;
  36119. winRect[hw] = contentRect[hw];
  36120. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  36121. var startIdx;
  36122. var children = contentGroup.children();
  36123. contentGroup.eachChild(function (child, index) {
  36124. var itemRect = getItemRect(child);
  36125. if (itemRect.intersect(winRect)) {
  36126. startIdx == null && (startIdx = index);
  36127. // It is user-friendly that the last item shown in the
  36128. // current window is shown at the begining of next window.
  36129. pageNextDataIndex = child.__legendDataIndex;
  36130. }
  36131. // If the last item is shown entirely, no next page.
  36132. if (index === children.length - 1
  36133. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  36134. ) {
  36135. pageNextDataIndex = null;
  36136. }
  36137. });
  36138. // Always align based on the left/top most item, so the left/top most
  36139. // item in the previous window is needed to be found here.
  36140. if (startIdx != null) {
  36141. var startItem = children[startIdx];
  36142. var startRect = getItemRect(startItem);
  36143. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  36144. // If the first item is shown entirely, no previous page.
  36145. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  36146. pagePrevDataIndex = null;
  36147. }
  36148. else {
  36149. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  36150. startIdx--;
  36151. }
  36152. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  36153. }
  36154. }
  36155. }
  36156. return {
  36157. contentPosition: contentPos,
  36158. pageIndex: pageIndex,
  36159. pageCount: pageCount,
  36160. pagePrevDataIndex: pagePrevDataIndex,
  36161. pageNextDataIndex: pageNextDataIndex
  36162. };
  36163. function getItemRect(el) {
  36164. var itemRect = el.getBoundingRect().clone();
  36165. itemRect[xy] += el.position[orientIdx];
  36166. return itemRect;
  36167. }
  36168. }
  36169. });
  36170. /**
  36171. * @event legendScroll
  36172. * @type {Object}
  36173. * @property {string} type 'legendScroll'
  36174. * @property {string} scrollDataIndex
  36175. */
  36176. registerAction(
  36177. 'legendScroll', 'legendscroll',
  36178. function (payload, ecModel) {
  36179. var scrollDataIndex = payload.scrollDataIndex;
  36180. scrollDataIndex != null && ecModel.eachComponent(
  36181. {mainType: 'legend', subType: 'scroll', query: payload},
  36182. function (legendModel) {
  36183. legendModel.setScrollDataIndex(scrollDataIndex);
  36184. }
  36185. );
  36186. }
  36187. );
  36188. /**
  36189. * Legend component entry file8
  36190. */
  36191. // Model
  36192. extendComponentModel({
  36193. type: 'title',
  36194. layoutMode: {type: 'box', ignoreSize: true},
  36195. defaultOption: {
  36196. // 一级层叠
  36197. zlevel: 0,
  36198. // 二级层叠
  36199. z: 6,
  36200. show: true,
  36201. text: '',
  36202. // 超链接跳转
  36203. // link: null,
  36204. // 仅支持self | blank
  36205. target: 'blank',
  36206. subtext: '',
  36207. // 超链接跳转
  36208. // sublink: null,
  36209. // 仅支持self | blank
  36210. subtarget: 'blank',
  36211. // 'center' ¦ 'left' ¦ 'right'
  36212. // ¦ {number}(x坐标,单位px)
  36213. left: 0,
  36214. // 'top' ¦ 'bottom' ¦ 'center'
  36215. // ¦ {number}(y坐标,单位px)
  36216. top: 0,
  36217. // 水平对齐
  36218. // 'auto' | 'left' | 'right' | 'center'
  36219. // 默认根据 left 的位置判断是左对齐还是右对齐
  36220. // textAlign: null
  36221. //
  36222. // 垂直对齐
  36223. // 'auto' | 'top' | 'bottom' | 'middle'
  36224. // 默认根据 top 位置判断是上对齐还是下对齐
  36225. // textBaseline: null
  36226. backgroundColor: 'rgba(0,0,0,0)',
  36227. // 标题边框颜色
  36228. borderColor: '#ccc',
  36229. // 标题边框线宽,单位px,默认为0(无边框)
  36230. borderWidth: 0,
  36231. // 标题内边距,单位px,默认各方向内边距为5,
  36232. // 接受数组分别设定上右下左边距,同css
  36233. padding: 5,
  36234. // 主副标题纵向间隔,单位px,默认为10,
  36235. itemGap: 10,
  36236. textStyle: {
  36237. fontSize: 18,
  36238. fontWeight: 'bolder',
  36239. color: '#333'
  36240. },
  36241. subtextStyle: {
  36242. color: '#aaa'
  36243. }
  36244. }
  36245. });
  36246. // View
  36247. extendComponentView({
  36248. type: 'title',
  36249. render: function (titleModel, ecModel, api) {
  36250. this.group.removeAll();
  36251. if (!titleModel.get('show')) {
  36252. return;
  36253. }
  36254. var group = this.group;
  36255. var textStyleModel = titleModel.getModel('textStyle');
  36256. var subtextStyleModel = titleModel.getModel('subtextStyle');
  36257. var textAlign = titleModel.get('textAlign');
  36258. var textBaseline = titleModel.get('textBaseline');
  36259. var textEl = new Text({
  36260. style: setTextStyle({}, textStyleModel, {
  36261. text: titleModel.get('text'),
  36262. textFill: textStyleModel.getTextColor()
  36263. }, {disableBox: true}),
  36264. z2: 10
  36265. });
  36266. var textRect = textEl.getBoundingRect();
  36267. var subText = titleModel.get('subtext');
  36268. var subTextEl = new Text({
  36269. style: setTextStyle({}, subtextStyleModel, {
  36270. text: subText,
  36271. textFill: subtextStyleModel.getTextColor(),
  36272. y: textRect.height + titleModel.get('itemGap'),
  36273. textVerticalAlign: 'top'
  36274. }, {disableBox: true}),
  36275. z2: 10
  36276. });
  36277. var link = titleModel.get('link');
  36278. var sublink = titleModel.get('sublink');
  36279. textEl.silent = !link;
  36280. subTextEl.silent = !sublink;
  36281. if (link) {
  36282. textEl.on('click', function () {
  36283. window.open(link, '_' + titleModel.get('target'));
  36284. });
  36285. }
  36286. if (sublink) {
  36287. subTextEl.on('click', function () {
  36288. window.open(sublink, '_' + titleModel.get('subtarget'));
  36289. });
  36290. }
  36291. group.add(textEl);
  36292. subText && group.add(subTextEl);
  36293. // If no subText, but add subTextEl, there will be an empty line.
  36294. var groupRect = group.getBoundingRect();
  36295. var layoutOption = titleModel.getBoxLayoutParams();
  36296. layoutOption.width = groupRect.width;
  36297. layoutOption.height = groupRect.height;
  36298. var layoutRect = getLayoutRect(
  36299. layoutOption, {
  36300. width: api.getWidth(),
  36301. height: api.getHeight()
  36302. }, titleModel.get('padding')
  36303. );
  36304. // Adjust text align based on position
  36305. if (!textAlign) {
  36306. // Align left if title is on the left. center and right is same
  36307. textAlign = titleModel.get('left') || titleModel.get('right');
  36308. if (textAlign === 'middle') {
  36309. textAlign = 'center';
  36310. }
  36311. // Adjust layout by text align
  36312. if (textAlign === 'right') {
  36313. layoutRect.x += layoutRect.width;
  36314. }
  36315. else if (textAlign === 'center') {
  36316. layoutRect.x += layoutRect.width / 2;
  36317. }
  36318. }
  36319. if (!textBaseline) {
  36320. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  36321. if (textBaseline === 'center') {
  36322. textBaseline = 'middle';
  36323. }
  36324. if (textBaseline === 'bottom') {
  36325. layoutRect.y += layoutRect.height;
  36326. }
  36327. else if (textBaseline === 'middle') {
  36328. layoutRect.y += layoutRect.height / 2;
  36329. }
  36330. textBaseline = textBaseline || 'top';
  36331. }
  36332. group.attr('position', [layoutRect.x, layoutRect.y]);
  36333. var alignStyle = {
  36334. textAlign: textAlign,
  36335. textVerticalAlign: textBaseline
  36336. };
  36337. textEl.setStyle(alignStyle);
  36338. subTextEl.setStyle(alignStyle);
  36339. // Render background
  36340. // Get groupRect again because textAlign has been changed
  36341. groupRect = group.getBoundingRect();
  36342. var padding = layoutRect.margin;
  36343. var style = titleModel.getItemStyle(['color', 'opacity']);
  36344. style.fill = titleModel.get('backgroundColor');
  36345. var rect = new Rect({
  36346. shape: {
  36347. x: groupRect.x - padding[3],
  36348. y: groupRect.y - padding[0],
  36349. width: groupRect.width + padding[1] + padding[3],
  36350. height: groupRect.height + padding[0] + padding[2],
  36351. r: titleModel.get('borderRadius')
  36352. },
  36353. style: style,
  36354. silent: true
  36355. });
  36356. subPixelOptimizeRect(rect);
  36357. group.add(rect);
  36358. }
  36359. });
  36360. var addCommas$1 = addCommas;
  36361. var encodeHTML$1 = encodeHTML;
  36362. function fillLabel(opt) {
  36363. defaultEmphasis(opt, 'label', ['show']);
  36364. }
  36365. var MarkerModel = extendComponentModel({
  36366. type: 'marker',
  36367. dependencies: ['series', 'grid', 'polar', 'geo'],
  36368. /**
  36369. * @overrite
  36370. */
  36371. init: function (option, parentModel, ecModel, extraOpt) {
  36372. if (__DEV__) {
  36373. if (this.type === 'marker') {
  36374. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  36375. }
  36376. }
  36377. this.mergeDefaultAndTheme(option, ecModel);
  36378. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  36379. },
  36380. /**
  36381. * @return {boolean}
  36382. */
  36383. isAnimationEnabled: function () {
  36384. if (env$1.node) {
  36385. return false;
  36386. }
  36387. var hostSeries = this.__hostSeries;
  36388. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  36389. },
  36390. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  36391. var MarkerModel = this.constructor;
  36392. var modelPropName = this.mainType + 'Model';
  36393. if (!createdBySelf) {
  36394. ecModel.eachSeries(function (seriesModel) {
  36395. var markerOpt = seriesModel.get(this.mainType);
  36396. var markerModel = seriesModel[modelPropName];
  36397. if (!markerOpt || !markerOpt.data) {
  36398. seriesModel[modelPropName] = null;
  36399. return;
  36400. }
  36401. if (!markerModel) {
  36402. if (isInit) {
  36403. // Default label emphasis `position` and `show`
  36404. fillLabel(markerOpt);
  36405. }
  36406. each$1(markerOpt.data, function (item) {
  36407. // FIXME Overwrite fillLabel method ?
  36408. if (item instanceof Array) {
  36409. fillLabel(item[0]);
  36410. fillLabel(item[1]);
  36411. }
  36412. else {
  36413. fillLabel(item);
  36414. }
  36415. });
  36416. markerModel = new MarkerModel(
  36417. markerOpt, this, ecModel
  36418. );
  36419. extend(markerModel, {
  36420. mainType: this.mainType,
  36421. // Use the same series index and name
  36422. seriesIndex: seriesModel.seriesIndex,
  36423. name: seriesModel.name,
  36424. createdBySelf: true
  36425. });
  36426. markerModel.__hostSeries = seriesModel;
  36427. }
  36428. else {
  36429. markerModel.mergeOption(markerOpt, ecModel, true);
  36430. }
  36431. seriesModel[modelPropName] = markerModel;
  36432. }, this);
  36433. }
  36434. },
  36435. formatTooltip: function (dataIndex) {
  36436. var data = this.getData();
  36437. var value = this.getRawValue(dataIndex);
  36438. var formattedValue = isArray(value)
  36439. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  36440. var name = data.getName(dataIndex);
  36441. var html = encodeHTML$1(this.name);
  36442. if (value != null || name) {
  36443. html += '<br />';
  36444. }
  36445. if (name) {
  36446. html += encodeHTML$1(name);
  36447. if (value != null) {
  36448. html += ' : ';
  36449. }
  36450. }
  36451. if (value != null) {
  36452. html += encodeHTML$1(formattedValue);
  36453. }
  36454. return html;
  36455. },
  36456. getData: function () {
  36457. return this._data;
  36458. },
  36459. setData: function (data) {
  36460. this._data = data;
  36461. }
  36462. });
  36463. mixin(MarkerModel, dataFormatMixin);
  36464. MarkerModel.extend({
  36465. type: 'markPoint',
  36466. defaultOption: {
  36467. zlevel: 0,
  36468. z: 5,
  36469. symbol: 'pin',
  36470. symbolSize: 50,
  36471. //symbolRotate: 0,
  36472. //symbolOffset: [0, 0]
  36473. tooltip: {
  36474. trigger: 'item'
  36475. },
  36476. label: {
  36477. show: true,
  36478. position: 'inside'
  36479. },
  36480. itemStyle: {
  36481. borderWidth: 2
  36482. },
  36483. emphasis: {
  36484. label: {
  36485. show: true
  36486. }
  36487. }
  36488. }
  36489. });
  36490. var indexOf$1 = indexOf;
  36491. function hasXOrY(item) {
  36492. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  36493. }
  36494. function hasXAndY(item) {
  36495. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  36496. }
  36497. function getPrecision$1(data, valueAxisDim, dataIndex) {
  36498. var precision = -1;
  36499. do {
  36500. precision = Math.max(
  36501. getPrecision(data.get(
  36502. valueAxisDim, dataIndex
  36503. )),
  36504. precision
  36505. );
  36506. data = data.stackedOn;
  36507. } while (data);
  36508. return precision;
  36509. }
  36510. function markerTypeCalculatorWithExtent(
  36511. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  36512. ) {
  36513. var coordArr = [];
  36514. var value = numCalculate(data, targetDataDim, mlType);
  36515. var dataIndex = data.indicesOfNearest(targetDataDim, value, true)[0];
  36516. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex, true);
  36517. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex, true);
  36518. var precision = getPrecision$1(data, targetDataDim, dataIndex);
  36519. precision = Math.min(precision, 20);
  36520. if (precision >= 0) {
  36521. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  36522. }
  36523. return coordArr;
  36524. }
  36525. var curry$4 = curry;
  36526. // TODO Specified percent
  36527. var markerTypeCalculator = {
  36528. /**
  36529. * @method
  36530. * @param {module:echarts/data/List} data
  36531. * @param {string} baseAxisDim
  36532. * @param {string} valueAxisDim
  36533. */
  36534. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  36535. /**
  36536. * @method
  36537. * @param {module:echarts/data/List} data
  36538. * @param {string} baseAxisDim
  36539. * @param {string} valueAxisDim
  36540. */
  36541. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  36542. /**
  36543. * @method
  36544. * @param {module:echarts/data/List} data
  36545. * @param {string} baseAxisDim
  36546. * @param {string} valueAxisDim
  36547. */
  36548. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  36549. };
  36550. /**
  36551. * Transform markPoint data item to format used in List by do the following
  36552. * 1. Calculate statistic like `max`, `min`, `average`
  36553. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  36554. * @param {module:echarts/model/Series} seriesModel
  36555. * @param {module:echarts/coord/*} [coordSys]
  36556. * @param {Object} item
  36557. * @return {Object}
  36558. */
  36559. function dataTransform(seriesModel, item) {
  36560. var data = seriesModel.getData();
  36561. var coordSys = seriesModel.coordinateSystem;
  36562. // 1. If not specify the position with pixel directly
  36563. // 2. If `coord` is not a data array. Which uses `xAxis`,
  36564. // `yAxis` to specify the coord on each dimension
  36565. // parseFloat first because item.x and item.y can be percent string like '20%'
  36566. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  36567. var dims = coordSys.dimensions;
  36568. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  36569. // Clone the option
  36570. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  36571. item = clone(item);
  36572. if (item.type
  36573. && markerTypeCalculator[item.type]
  36574. && axisInfo.baseAxis && axisInfo.valueAxis
  36575. ) {
  36576. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  36577. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  36578. item.coord = markerTypeCalculator[item.type](
  36579. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  36580. otherCoordIndex, targetCoordIndex
  36581. );
  36582. // Force to use the value of calculated value.
  36583. item.value = item.coord[targetCoordIndex];
  36584. }
  36585. else {
  36586. // FIXME Only has one of xAxis and yAxis.
  36587. var coord = [
  36588. item.xAxis != null ? item.xAxis : item.radiusAxis,
  36589. item.yAxis != null ? item.yAxis : item.angleAxis
  36590. ];
  36591. // Each coord support max, min, average
  36592. for (var i = 0; i < 2; i++) {
  36593. if (markerTypeCalculator[coord[i]]) {
  36594. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  36595. }
  36596. }
  36597. item.coord = coord;
  36598. }
  36599. }
  36600. return item;
  36601. }
  36602. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  36603. var ret = {};
  36604. if (item.valueIndex != null || item.valueDim != null) {
  36605. ret.valueDataDim = item.valueIndex != null
  36606. ? data.getDimension(item.valueIndex) : item.valueDim;
  36607. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  36608. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  36609. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  36610. }
  36611. else {
  36612. ret.baseAxis = seriesModel.getBaseAxis();
  36613. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  36614. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  36615. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  36616. }
  36617. return ret;
  36618. }
  36619. function dataDimToCoordDim(seriesModel, dataDim) {
  36620. var data = seriesModel.getData();
  36621. var dimensions = data.dimensions;
  36622. dataDim = data.getDimension(dataDim);
  36623. for (var i = 0; i < dimensions.length; i++) {
  36624. var dimItem = data.getDimensionInfo(dimensions[i]);
  36625. if (dimItem.name === dataDim) {
  36626. return dimItem.coordDim;
  36627. }
  36628. }
  36629. }
  36630. /**
  36631. * Filter data which is out of coordinateSystem range
  36632. * [dataFilter description]
  36633. * @param {module:echarts/coord/*} [coordSys]
  36634. * @param {Object} item
  36635. * @return {boolean}
  36636. */
  36637. function dataFilter$1(coordSys, item) {
  36638. // Alwalys return true if there is no coordSys
  36639. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  36640. ? coordSys.containData(item.coord) : true;
  36641. }
  36642. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  36643. // x, y, radius, angle
  36644. if (dimIndex < 2) {
  36645. return item.coord && item.coord[dimIndex];
  36646. }
  36647. return item.value;
  36648. }
  36649. function numCalculate(data, valueDataDim, type) {
  36650. if (type === 'average') {
  36651. var sum = 0;
  36652. var count = 0;
  36653. data.each(valueDataDim, function (val, idx) {
  36654. if (!isNaN(val)) {
  36655. sum += val;
  36656. count++;
  36657. }
  36658. }, true);
  36659. return sum / count;
  36660. }
  36661. else {
  36662. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  36663. }
  36664. }
  36665. var MarkerView = extendComponentView({
  36666. type: 'marker',
  36667. init: function () {
  36668. /**
  36669. * Markline grouped by series
  36670. * @private
  36671. * @type {module:zrender/core/util.HashMap}
  36672. */
  36673. this.markerGroupMap = createHashMap();
  36674. },
  36675. render: function (markerModel, ecModel, api) {
  36676. var markerGroupMap = this.markerGroupMap;
  36677. markerGroupMap.each(function (item) {
  36678. item.__keep = false;
  36679. });
  36680. var markerModelKey = this.type + 'Model';
  36681. ecModel.eachSeries(function (seriesModel) {
  36682. var markerModel = seriesModel[markerModelKey];
  36683. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  36684. }, this);
  36685. markerGroupMap.each(function (item) {
  36686. !item.__keep && this.group.remove(item.group);
  36687. }, this);
  36688. },
  36689. renderSeries: function () {}
  36690. });
  36691. function updateMarkerLayout(mpData, seriesModel, api) {
  36692. var coordSys = seriesModel.coordinateSystem;
  36693. mpData.each(function (idx) {
  36694. var itemModel = mpData.getItemModel(idx);
  36695. var point;
  36696. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  36697. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  36698. if (!isNaN(xPx) && !isNaN(yPx)) {
  36699. point = [xPx, yPx];
  36700. }
  36701. // Chart like bar may have there own marker positioning logic
  36702. else if (seriesModel.getMarkerPosition) {
  36703. // Use the getMarkerPoisition
  36704. point = seriesModel.getMarkerPosition(
  36705. mpData.getValues(mpData.dimensions, idx)
  36706. );
  36707. }
  36708. else if (coordSys) {
  36709. var x = mpData.get(coordSys.dimensions[0], idx);
  36710. var y = mpData.get(coordSys.dimensions[1], idx);
  36711. point = coordSys.dataToPoint([x, y]);
  36712. }
  36713. // Use x, y if has any
  36714. if (!isNaN(xPx)) {
  36715. point[0] = xPx;
  36716. }
  36717. if (!isNaN(yPx)) {
  36718. point[1] = yPx;
  36719. }
  36720. mpData.setItemLayout(idx, point);
  36721. });
  36722. }
  36723. MarkerView.extend({
  36724. type: 'markPoint',
  36725. // updateLayout: function (markPointModel, ecModel, api) {
  36726. // ecModel.eachSeries(function (seriesModel) {
  36727. // var mpModel = seriesModel.markPointModel;
  36728. // if (mpModel) {
  36729. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36730. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  36731. // }
  36732. // }, this);
  36733. // },
  36734. updateTransform: function (markPointModel, ecModel, api) {
  36735. ecModel.eachSeries(function (seriesModel) {
  36736. var mpModel = seriesModel.markPointModel;
  36737. if (mpModel) {
  36738. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36739. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  36740. }
  36741. }, this);
  36742. },
  36743. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  36744. var coordSys = seriesModel.coordinateSystem;
  36745. var seriesId = seriesModel.id;
  36746. var seriesData = seriesModel.getData();
  36747. var symbolDrawMap = this.markerGroupMap;
  36748. var symbolDraw = symbolDrawMap.get(seriesId)
  36749. || symbolDrawMap.set(seriesId, new SymbolDraw());
  36750. var mpData = createList$1(coordSys, seriesModel, mpModel);
  36751. // FIXME
  36752. mpModel.setData(mpData);
  36753. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  36754. mpData.each(function (idx) {
  36755. var itemModel = mpData.getItemModel(idx);
  36756. var symbolSize = itemModel.getShallow('symbolSize');
  36757. if (typeof symbolSize === 'function') {
  36758. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  36759. symbolSize = symbolSize(
  36760. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  36761. );
  36762. }
  36763. mpData.setItemVisual(idx, {
  36764. symbolSize: symbolSize,
  36765. color: itemModel.get('itemStyle.color')
  36766. || seriesData.getVisual('color'),
  36767. symbol: itemModel.getShallow('symbol')
  36768. });
  36769. });
  36770. // TODO Text are wrong
  36771. symbolDraw.updateData(mpData);
  36772. this.group.add(symbolDraw.group);
  36773. // Set host model for tooltip
  36774. // FIXME
  36775. mpData.eachItemGraphicEl(function (el) {
  36776. el.traverse(function (child) {
  36777. child.dataModel = mpModel;
  36778. });
  36779. });
  36780. symbolDraw.__keep = true;
  36781. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  36782. }
  36783. });
  36784. /**
  36785. * @inner
  36786. * @param {module:echarts/coord/*} [coordSys]
  36787. * @param {module:echarts/model/Series} seriesModel
  36788. * @param {module:echarts/model/Model} mpModel
  36789. */
  36790. function createList$1(coordSys, seriesModel, mpModel) {
  36791. var coordDimsInfos;
  36792. if (coordSys) {
  36793. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  36794. var info = seriesModel.getData().getDimensionInfo(
  36795. seriesModel.getData().mapDimension(coordDim)
  36796. ) || {};
  36797. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  36798. return defaults({name: coordDim, isSysCoord: true}, info);
  36799. });
  36800. }
  36801. else {
  36802. coordDimsInfos =[{
  36803. name: 'value',
  36804. type: 'float',
  36805. isSysCoord: true
  36806. }];
  36807. }
  36808. var mpData = new List(coordDimsInfos, mpModel);
  36809. var dataOpt = map(mpModel.get('data'), curry(
  36810. dataTransform, seriesModel
  36811. ));
  36812. if (coordSys) {
  36813. dataOpt = filter(
  36814. dataOpt, curry(dataFilter$1, coordSys)
  36815. );
  36816. }
  36817. mpData.initData(dataOpt, null,
  36818. coordSys ? dimValueGetter : function (item) {
  36819. return item.value;
  36820. }
  36821. );
  36822. return mpData;
  36823. }
  36824. // HINT Markpoint can't be used too much
  36825. registerPreprocessor(function (opt) {
  36826. // Make sure markPoint component is enabled
  36827. opt.markPoint = opt.markPoint || {};
  36828. });
  36829. MarkerModel.extend({
  36830. type: 'markLine',
  36831. defaultOption: {
  36832. zlevel: 0,
  36833. z: 5,
  36834. symbol: ['circle', 'arrow'],
  36835. symbolSize: [8, 16],
  36836. //symbolRotate: 0,
  36837. precision: 2,
  36838. tooltip: {
  36839. trigger: 'item'
  36840. },
  36841. label: {
  36842. show: true,
  36843. position: 'end'
  36844. },
  36845. lineStyle: {
  36846. type: 'dashed'
  36847. },
  36848. emphasis: {
  36849. label: {
  36850. show: true
  36851. },
  36852. lineStyle: {
  36853. width: 3
  36854. }
  36855. },
  36856. animationEasing: 'linear'
  36857. }
  36858. });
  36859. /**
  36860. * Line path for bezier and straight line draw
  36861. */
  36862. var straightLineProto = Line.prototype;
  36863. var bezierCurveProto = BezierCurve.prototype;
  36864. function isLine(shape) {
  36865. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  36866. }
  36867. var LinePath = extendShape({
  36868. type: 'ec-line',
  36869. style: {
  36870. stroke: '#000',
  36871. fill: null
  36872. },
  36873. shape: {
  36874. x1: 0,
  36875. y1: 0,
  36876. x2: 0,
  36877. y2: 0,
  36878. percent: 1,
  36879. cpx1: null,
  36880. cpy1: null
  36881. },
  36882. buildPath: function (ctx, shape) {
  36883. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  36884. },
  36885. pointAt: function (t) {
  36886. return isLine(this.shape)
  36887. ? straightLineProto.pointAt.call(this, t)
  36888. : bezierCurveProto.pointAt.call(this, t);
  36889. },
  36890. tangentAt: function (t) {
  36891. var shape = this.shape;
  36892. var p = isLine(shape)
  36893. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  36894. : bezierCurveProto.tangentAt.call(this, t);
  36895. return normalize(p, p);
  36896. }
  36897. });
  36898. /**
  36899. * @module echarts/chart/helper/Line
  36900. */
  36901. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  36902. function makeSymbolTypeKey(symbolCategory) {
  36903. return '_' + symbolCategory + 'Type';
  36904. }
  36905. /**
  36906. * @inner
  36907. */
  36908. function createSymbol$1(name, lineData, idx) {
  36909. var color = lineData.getItemVisual(idx, 'color');
  36910. var symbolType = lineData.getItemVisual(idx, name);
  36911. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  36912. if (!symbolType || symbolType === 'none') {
  36913. return;
  36914. }
  36915. if (!isArray(symbolSize)) {
  36916. symbolSize = [symbolSize, symbolSize];
  36917. }
  36918. var symbolPath = createSymbol(
  36919. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  36920. symbolSize[0], symbolSize[1], color
  36921. );
  36922. symbolPath.name = name;
  36923. return symbolPath;
  36924. }
  36925. function createLine(points) {
  36926. var line = new LinePath({
  36927. name: 'line'
  36928. });
  36929. setLinePoints(line.shape, points);
  36930. return line;
  36931. }
  36932. function setLinePoints(targetShape, points) {
  36933. var p1 = points[0];
  36934. var p2 = points[1];
  36935. var cp1 = points[2];
  36936. targetShape.x1 = p1[0];
  36937. targetShape.y1 = p1[1];
  36938. targetShape.x2 = p2[0];
  36939. targetShape.y2 = p2[1];
  36940. targetShape.percent = 1;
  36941. if (cp1) {
  36942. targetShape.cpx1 = cp1[0];
  36943. targetShape.cpy1 = cp1[1];
  36944. }
  36945. else {
  36946. targetShape.cpx1 = NaN;
  36947. targetShape.cpy1 = NaN;
  36948. }
  36949. }
  36950. function updateSymbolAndLabelBeforeLineUpdate () {
  36951. var lineGroup = this;
  36952. var symbolFrom = lineGroup.childOfName('fromSymbol');
  36953. var symbolTo = lineGroup.childOfName('toSymbol');
  36954. var label = lineGroup.childOfName('label');
  36955. // Quick reject
  36956. if (!symbolFrom && !symbolTo && label.ignore) {
  36957. return;
  36958. }
  36959. var invScale = 1;
  36960. var parentNode = this.parent;
  36961. while (parentNode) {
  36962. if (parentNode.scale) {
  36963. invScale /= parentNode.scale[0];
  36964. }
  36965. parentNode = parentNode.parent;
  36966. }
  36967. var line = lineGroup.childOfName('line');
  36968. // If line not changed
  36969. // FIXME Parent scale changed
  36970. if (!this.__dirty && !line.__dirty) {
  36971. return;
  36972. }
  36973. var percent = line.shape.percent;
  36974. var fromPos = line.pointAt(0);
  36975. var toPos = line.pointAt(percent);
  36976. var d = sub([], toPos, fromPos);
  36977. normalize(d, d);
  36978. if (symbolFrom) {
  36979. symbolFrom.attr('position', fromPos);
  36980. var tangent = line.tangentAt(0);
  36981. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  36982. tangent[1], tangent[0]
  36983. ));
  36984. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  36985. }
  36986. if (symbolTo) {
  36987. symbolTo.attr('position', toPos);
  36988. var tangent = line.tangentAt(1);
  36989. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  36990. tangent[1], tangent[0]
  36991. ));
  36992. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  36993. }
  36994. if (!label.ignore) {
  36995. label.attr('position', toPos);
  36996. var textPosition;
  36997. var textAlign;
  36998. var textVerticalAlign;
  36999. var distance$$1 = 5 * invScale;
  37000. // End
  37001. if (label.__position === 'end') {
  37002. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  37003. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  37004. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  37005. }
  37006. // Middle
  37007. else if (label.__position === 'middle') {
  37008. var halfPercent = percent / 2;
  37009. var tangent = line.tangentAt(halfPercent);
  37010. var n = [tangent[1], -tangent[0]];
  37011. var cp = line.pointAt(halfPercent);
  37012. if (n[1] > 0) {
  37013. n[0] = -n[0];
  37014. n[1] = -n[1];
  37015. }
  37016. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  37017. textAlign = 'center';
  37018. textVerticalAlign = 'bottom';
  37019. var rotation = -Math.atan2(tangent[1], tangent[0]);
  37020. if (toPos[0] < fromPos[0]) {
  37021. rotation = Math.PI + rotation;
  37022. }
  37023. label.attr('rotation', rotation);
  37024. }
  37025. // Start
  37026. else {
  37027. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  37028. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  37029. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  37030. }
  37031. label.attr({
  37032. style: {
  37033. // Use the user specified text align and baseline first
  37034. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  37035. textAlign: label.__textAlign || textAlign
  37036. },
  37037. position: textPosition,
  37038. scale: [invScale, invScale]
  37039. });
  37040. }
  37041. }
  37042. /**
  37043. * @constructor
  37044. * @extends {module:zrender/graphic/Group}
  37045. * @alias {module:echarts/chart/helper/Line}
  37046. */
  37047. function Line$1(lineData, idx, seriesScope) {
  37048. Group.call(this);
  37049. this._createLine(lineData, idx, seriesScope);
  37050. }
  37051. var lineProto = Line$1.prototype;
  37052. // Update symbol position and rotation
  37053. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  37054. lineProto._createLine = function (lineData, idx, seriesScope) {
  37055. var seriesModel = lineData.hostModel;
  37056. var linePoints = lineData.getItemLayout(idx);
  37057. var line = createLine(linePoints);
  37058. line.shape.percent = 0;
  37059. initProps(line, {
  37060. shape: {
  37061. percent: 1
  37062. }
  37063. }, seriesModel, idx);
  37064. this.add(line);
  37065. var label = new Text({
  37066. name: 'label'
  37067. });
  37068. this.add(label);
  37069. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37070. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37071. // symbols must added after line to make sure
  37072. // it will be updated after line#update.
  37073. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  37074. this.add(symbol);
  37075. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  37076. }, this);
  37077. this._updateCommonStl(lineData, idx, seriesScope);
  37078. };
  37079. lineProto.updateData = function (lineData, idx, seriesScope) {
  37080. var seriesModel = lineData.hostModel;
  37081. var line = this.childOfName('line');
  37082. var linePoints = lineData.getItemLayout(idx);
  37083. var target = {
  37084. shape: {}
  37085. };
  37086. setLinePoints(target.shape, linePoints);
  37087. updateProps(line, target, seriesModel, idx);
  37088. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37089. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  37090. var key = makeSymbolTypeKey(symbolCategory);
  37091. // Symbol changed
  37092. if (this[key] !== symbolType) {
  37093. this.remove(this.childOfName(symbolCategory));
  37094. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37095. this.add(symbol);
  37096. }
  37097. this[key] = symbolType;
  37098. }, this);
  37099. this._updateCommonStl(lineData, idx, seriesScope);
  37100. };
  37101. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  37102. var seriesModel = lineData.hostModel;
  37103. var line = this.childOfName('line');
  37104. var lineStyle = seriesScope && seriesScope.lineStyle;
  37105. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  37106. var labelModel = seriesScope && seriesScope.labelModel;
  37107. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  37108. // Optimization for large dataset
  37109. if (!seriesScope || lineData.hasItemOption) {
  37110. var itemModel = lineData.getItemModel(idx);
  37111. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  37112. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  37113. labelModel = itemModel.getModel('label');
  37114. hoverLabelModel = itemModel.getModel('emphasis.label');
  37115. }
  37116. var visualColor = lineData.getItemVisual(idx, 'color');
  37117. var visualOpacity = retrieve3(
  37118. lineData.getItemVisual(idx, 'opacity'),
  37119. lineStyle.opacity,
  37120. 1
  37121. );
  37122. line.useStyle(defaults(
  37123. {
  37124. strokeNoScale: true,
  37125. fill: 'none',
  37126. stroke: visualColor,
  37127. opacity: visualOpacity
  37128. },
  37129. lineStyle
  37130. ));
  37131. line.hoverStyle = hoverLineStyle;
  37132. // Update symbol
  37133. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37134. var symbol = this.childOfName(symbolCategory);
  37135. if (symbol) {
  37136. symbol.setColor(visualColor);
  37137. symbol.setStyle({
  37138. opacity: visualOpacity
  37139. });
  37140. }
  37141. }, this);
  37142. var showLabel = labelModel.getShallow('show');
  37143. var hoverShowLabel = hoverLabelModel.getShallow('show');
  37144. var label = this.childOfName('label');
  37145. var defaultLabelColor;
  37146. var normalText;
  37147. var emphasisText;
  37148. if (showLabel || hoverShowLabel) {
  37149. defaultLabelColor = visualColor || '#000';
  37150. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  37151. if (normalText == null) {
  37152. var rawVal = seriesModel.getRawValue(idx);
  37153. normalText = rawVal == null
  37154. ? lineData.getName(idx)
  37155. : isFinite(rawVal)
  37156. ? round$1(rawVal)
  37157. : rawVal;
  37158. }
  37159. emphasisText = retrieve2(
  37160. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  37161. normalText
  37162. );
  37163. }
  37164. // label.afterUpdate = lineAfterUpdate;
  37165. if (showLabel) {
  37166. var labelStyle = setTextStyle(label.style, labelModel, {
  37167. text: normalText
  37168. }, {
  37169. autoColor: defaultLabelColor
  37170. });
  37171. label.__textAlign = labelStyle.textAlign;
  37172. label.__verticalAlign = labelStyle.textVerticalAlign;
  37173. // 'start', 'middle', 'end'
  37174. label.__position = labelModel.get('position') || 'middle';
  37175. }
  37176. else {
  37177. label.setStyle('text', null);
  37178. }
  37179. if (hoverShowLabel) {
  37180. // Only these properties supported in this emphasis style here.
  37181. label.hoverStyle = {
  37182. text: emphasisText,
  37183. textFill: hoverLabelModel.getTextColor(true),
  37184. // For merging hover style to normal style, do not use
  37185. // `hoverLabelModel.getFont()` here.
  37186. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  37187. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  37188. fontSize: hoverLabelModel.getShallow('fontSize'),
  37189. fontFamily: hoverLabelModel.getShallow('fontFamily')
  37190. };
  37191. }
  37192. else {
  37193. label.hoverStyle = {
  37194. text: null
  37195. };
  37196. }
  37197. label.ignore = !showLabel && !hoverShowLabel;
  37198. setHoverStyle(this);
  37199. };
  37200. lineProto.highlight = function () {
  37201. this.trigger('emphasis');
  37202. };
  37203. lineProto.downplay = function () {
  37204. this.trigger('normal');
  37205. };
  37206. lineProto.updateLayout = function (lineData, idx) {
  37207. this.setLinePoints(lineData.getItemLayout(idx));
  37208. };
  37209. lineProto.setLinePoints = function (points) {
  37210. var linePath = this.childOfName('line');
  37211. setLinePoints(linePath.shape, points);
  37212. linePath.dirty();
  37213. };
  37214. inherits(Line$1, Group);
  37215. /**
  37216. * @module echarts/chart/helper/LineDraw
  37217. */
  37218. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  37219. /**
  37220. * @alias module:echarts/component/marker/LineDraw
  37221. * @constructor
  37222. */
  37223. function LineDraw(ctor) {
  37224. this._ctor = ctor || Line$1;
  37225. this.group = new Group();
  37226. }
  37227. var lineDrawProto = LineDraw.prototype;
  37228. lineDrawProto.isPersistent = function () {
  37229. return true;
  37230. };
  37231. /**
  37232. * @param {module:echarts/data/List} lineData
  37233. */
  37234. lineDrawProto.updateData = function (lineData) {
  37235. var lineDraw = this;
  37236. var group = lineDraw.group;
  37237. var oldLineData = lineDraw._lineData;
  37238. lineDraw._lineData = lineData;
  37239. // There is no oldLineData only when first rendering or switching from
  37240. // stream mode to normal mode, where previous elements should be removed.
  37241. if (!oldLineData) {
  37242. group.removeAll();
  37243. }
  37244. var seriesScope = makeSeriesScope$1(lineData);
  37245. lineData.diff(oldLineData)
  37246. .add(function (idx) {
  37247. doAdd(lineDraw, lineData, idx, seriesScope);
  37248. })
  37249. .update(function (newIdx, oldIdx) {
  37250. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  37251. })
  37252. .remove(function (idx) {
  37253. group.remove(oldLineData.getItemGraphicEl(idx));
  37254. })
  37255. .execute();
  37256. };
  37257. function doAdd(lineDraw, lineData, idx, seriesScope) {
  37258. var itemLayout = lineData.getItemLayout(idx);
  37259. if (!lineNeedsDraw(itemLayout)) {
  37260. return;
  37261. }
  37262. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  37263. lineData.setItemGraphicEl(idx, el);
  37264. lineDraw.group.add(el);
  37265. }
  37266. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  37267. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  37268. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  37269. lineDraw.group.remove(itemEl);
  37270. return;
  37271. }
  37272. if (!itemEl) {
  37273. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  37274. }
  37275. else {
  37276. itemEl.updateData(newLineData, newIdx, seriesScope);
  37277. }
  37278. newLineData.setItemGraphicEl(newIdx, itemEl);
  37279. lineDraw.group.add(itemEl);
  37280. }
  37281. lineDrawProto.updateLayout = function () {
  37282. var lineData = this._lineData;
  37283. lineData.eachItemGraphicEl(function (el, idx) {
  37284. el.updateLayout(lineData, idx);
  37285. }, this);
  37286. };
  37287. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  37288. this._seriesScope = makeSeriesScope$1(lineData);
  37289. this._lineData = null;
  37290. this.group.removeAll();
  37291. };
  37292. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  37293. function updateIncrementalAndHover(el) {
  37294. if (!el.isGroup) {
  37295. el.incremental = el.useHoverLayer = true;
  37296. }
  37297. }
  37298. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  37299. var itemLayout = lineData.getItemLayout(idx);
  37300. if (lineNeedsDraw(itemLayout)) {
  37301. var el = new this._ctor(lineData, idx, this._seriesScope);
  37302. el.traverse(updateIncrementalAndHover);
  37303. this.group.add(el);
  37304. }
  37305. }
  37306. };
  37307. function makeSeriesScope$1(lineData) {
  37308. var hostModel = lineData.hostModel;
  37309. return {
  37310. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  37311. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  37312. labelModel: hostModel.getModel('label'),
  37313. hoverLabelModel: hostModel.getModel('emphasis.label')
  37314. };
  37315. }
  37316. lineDrawProto.remove = function () {
  37317. this._clearIncremental();
  37318. this._incremental = null;
  37319. this.group.removeAll();
  37320. };
  37321. lineDrawProto._clearIncremental = function () {
  37322. var incremental = this._incremental;
  37323. if (incremental) {
  37324. incremental.clearDisplaybles();
  37325. }
  37326. };
  37327. function isPointNaN(pt) {
  37328. return isNaN(pt[0]) || isNaN(pt[1]);
  37329. }
  37330. function lineNeedsDraw(pts) {
  37331. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  37332. }
  37333. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  37334. var data = seriesModel.getData();
  37335. // Special type markLine like 'min', 'max', 'average'
  37336. var mlType = item.type;
  37337. if (!isArray(item)
  37338. && (
  37339. mlType === 'min' || mlType === 'max' || mlType === 'average'
  37340. // In case
  37341. // data: [{
  37342. // yAxis: 10
  37343. // }]
  37344. || (item.xAxis != null || item.yAxis != null)
  37345. )
  37346. ) {
  37347. var valueAxis;
  37348. var valueDataDim;
  37349. var value;
  37350. if (item.yAxis != null || item.xAxis != null) {
  37351. valueDataDim = item.yAxis != null ? 'y' : 'x';
  37352. valueAxis = coordSys.getAxis(valueDataDim);
  37353. value = retrieve(item.yAxis, item.xAxis);
  37354. }
  37355. else {
  37356. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  37357. valueDataDim = axisInfo.valueDataDim;
  37358. valueAxis = axisInfo.valueAxis;
  37359. value = numCalculate(data, valueDataDim, mlType);
  37360. }
  37361. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  37362. var baseIndex = 1 - valueIndex;
  37363. var mlFrom = clone(item);
  37364. var mlTo = {};
  37365. mlFrom.type = null;
  37366. mlFrom.coord = [];
  37367. mlTo.coord = [];
  37368. mlFrom.coord[baseIndex] = -Infinity;
  37369. mlTo.coord[baseIndex] = Infinity;
  37370. var precision = mlModel.get('precision');
  37371. if (precision >= 0 && typeof value === 'number') {
  37372. value = +value.toFixed(Math.min(precision, 20));
  37373. }
  37374. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  37375. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  37376. type: mlType,
  37377. valueIndex: item.valueIndex,
  37378. // Force to use the value of calculated value.
  37379. value: value
  37380. }];
  37381. }
  37382. item = [
  37383. dataTransform(seriesModel, item[0]),
  37384. dataTransform(seriesModel, item[1]),
  37385. extend({}, item[2])
  37386. ];
  37387. // Avoid line data type is extended by from(to) data type
  37388. item[2].type = item[2].type || '';
  37389. // Merge from option and to option into line option
  37390. merge(item[2], item[0]);
  37391. merge(item[2], item[1]);
  37392. return item;
  37393. };
  37394. function isInifinity(val) {
  37395. return !isNaN(val) && !isFinite(val);
  37396. }
  37397. // If a markLine has one dim
  37398. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  37399. var otherDimIndex = 1 - dimIndex;
  37400. var dimName = coordSys.dimensions[dimIndex];
  37401. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  37402. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  37403. }
  37404. function markLineFilter(coordSys, item) {
  37405. if (coordSys.type === 'cartesian2d') {
  37406. var fromCoord = item[0].coord;
  37407. var toCoord = item[1].coord;
  37408. // In case
  37409. // {
  37410. // markLine: {
  37411. // data: [{ yAxis: 2 }]
  37412. // }
  37413. // }
  37414. if (
  37415. fromCoord && toCoord &&
  37416. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  37417. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  37418. ) {
  37419. return true;
  37420. }
  37421. }
  37422. return dataFilter$1(coordSys, item[0])
  37423. && dataFilter$1(coordSys, item[1]);
  37424. }
  37425. function updateSingleMarkerEndLayout(
  37426. data, idx, isFrom, seriesModel, api
  37427. ) {
  37428. var coordSys = seriesModel.coordinateSystem;
  37429. var itemModel = data.getItemModel(idx);
  37430. var point;
  37431. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  37432. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  37433. if (!isNaN(xPx) && !isNaN(yPx)) {
  37434. point = [xPx, yPx];
  37435. }
  37436. else {
  37437. // Chart like bar may have there own marker positioning logic
  37438. if (seriesModel.getMarkerPosition) {
  37439. // Use the getMarkerPoisition
  37440. point = seriesModel.getMarkerPosition(
  37441. data.getValues(data.dimensions, idx)
  37442. );
  37443. }
  37444. else {
  37445. var dims = coordSys.dimensions;
  37446. var x = data.get(dims[0], idx);
  37447. var y = data.get(dims[1], idx);
  37448. point = coordSys.dataToPoint([x, y]);
  37449. }
  37450. // Expand line to the edge of grid if value on one axis is Inifnity
  37451. // In case
  37452. // markLine: {
  37453. // data: [{
  37454. // yAxis: 2
  37455. // // or
  37456. // type: 'average'
  37457. // }]
  37458. // }
  37459. if (coordSys.type === 'cartesian2d') {
  37460. var xAxis = coordSys.getAxis('x');
  37461. var yAxis = coordSys.getAxis('y');
  37462. var dims = coordSys.dimensions;
  37463. if (isInifinity(data.get(dims[0], idx))) {
  37464. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  37465. }
  37466. else if (isInifinity(data.get(dims[1], idx))) {
  37467. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  37468. }
  37469. }
  37470. // Use x, y if has any
  37471. if (!isNaN(xPx)) {
  37472. point[0] = xPx;
  37473. }
  37474. if (!isNaN(yPx)) {
  37475. point[1] = yPx;
  37476. }
  37477. }
  37478. data.setItemLayout(idx, point);
  37479. }
  37480. MarkerView.extend({
  37481. type: 'markLine',
  37482. // updateLayout: function (markLineModel, ecModel, api) {
  37483. // ecModel.eachSeries(function (seriesModel) {
  37484. // var mlModel = seriesModel.markLineModel;
  37485. // if (mlModel) {
  37486. // var mlData = mlModel.getData();
  37487. // var fromData = mlModel.__from;
  37488. // var toData = mlModel.__to;
  37489. // // Update visual and layout of from symbol and to symbol
  37490. // fromData.each(function (idx) {
  37491. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  37492. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  37493. // });
  37494. // // Update layout of line
  37495. // mlData.each(function (idx) {
  37496. // mlData.setItemLayout(idx, [
  37497. // fromData.getItemLayout(idx),
  37498. // toData.getItemLayout(idx)
  37499. // ]);
  37500. // });
  37501. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  37502. // }
  37503. // }, this);
  37504. // },
  37505. updateTransform: function (markLineModel, ecModel, api) {
  37506. ecModel.eachSeries(function (seriesModel) {
  37507. var mlModel = seriesModel.markLineModel;
  37508. if (mlModel) {
  37509. var mlData = mlModel.getData();
  37510. var fromData = mlModel.__from;
  37511. var toData = mlModel.__to;
  37512. // Update visual and layout of from symbol and to symbol
  37513. fromData.each(function (idx) {
  37514. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  37515. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  37516. });
  37517. // Update layout of line
  37518. mlData.each(function (idx) {
  37519. mlData.setItemLayout(idx, [
  37520. fromData.getItemLayout(idx),
  37521. toData.getItemLayout(idx)
  37522. ]);
  37523. });
  37524. this.markerGroupMap.get(seriesModel.id).updateLayout();
  37525. }
  37526. }, this);
  37527. },
  37528. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  37529. var coordSys = seriesModel.coordinateSystem;
  37530. var seriesId = seriesModel.id;
  37531. var seriesData = seriesModel.getData();
  37532. var lineDrawMap = this.markerGroupMap;
  37533. var lineDraw = lineDrawMap.get(seriesId)
  37534. || lineDrawMap.set(seriesId, new LineDraw());
  37535. this.group.add(lineDraw.group);
  37536. var mlData = createList$2(coordSys, seriesModel, mlModel);
  37537. var fromData = mlData.from;
  37538. var toData = mlData.to;
  37539. var lineData = mlData.line;
  37540. mlModel.__from = fromData;
  37541. mlModel.__to = toData;
  37542. // Line data for tooltip and formatter
  37543. mlModel.setData(lineData);
  37544. var symbolType = mlModel.get('symbol');
  37545. var symbolSize = mlModel.get('symbolSize');
  37546. if (!isArray(symbolType)) {
  37547. symbolType = [symbolType, symbolType];
  37548. }
  37549. if (typeof symbolSize === 'number') {
  37550. symbolSize = [symbolSize, symbolSize];
  37551. }
  37552. // Update visual and layout of from symbol and to symbol
  37553. mlData.from.each(function (idx) {
  37554. updateDataVisualAndLayout(fromData, idx, true);
  37555. updateDataVisualAndLayout(toData, idx, false);
  37556. });
  37557. // Update visual and layout of line
  37558. lineData.each(function (idx) {
  37559. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  37560. lineData.setItemVisual(idx, {
  37561. color: lineColor || fromData.getItemVisual(idx, 'color')
  37562. });
  37563. lineData.setItemLayout(idx, [
  37564. fromData.getItemLayout(idx),
  37565. toData.getItemLayout(idx)
  37566. ]);
  37567. lineData.setItemVisual(idx, {
  37568. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  37569. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  37570. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  37571. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  37572. });
  37573. });
  37574. lineDraw.updateData(lineData);
  37575. // Set host model for tooltip
  37576. // FIXME
  37577. mlData.line.eachItemGraphicEl(function (el, idx) {
  37578. el.traverse(function (child) {
  37579. child.dataModel = mlModel;
  37580. });
  37581. });
  37582. function updateDataVisualAndLayout(data, idx, isFrom) {
  37583. var itemModel = data.getItemModel(idx);
  37584. updateSingleMarkerEndLayout(
  37585. data, idx, isFrom, seriesModel, api
  37586. );
  37587. data.setItemVisual(idx, {
  37588. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  37589. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  37590. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  37591. });
  37592. }
  37593. lineDraw.__keep = true;
  37594. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  37595. }
  37596. });
  37597. /**
  37598. * @inner
  37599. * @param {module:echarts/coord/*} coordSys
  37600. * @param {module:echarts/model/Series} seriesModel
  37601. * @param {module:echarts/model/Model} mpModel
  37602. */
  37603. function createList$2(coordSys, seriesModel, mlModel) {
  37604. var coordDimsInfos;
  37605. if (coordSys) {
  37606. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37607. var info = seriesModel.getData().getDimensionInfo(
  37608. seriesModel.getData().mapDimension(coordDim)
  37609. ) || {};
  37610. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37611. return defaults({name: coordDim}, info);
  37612. });
  37613. }
  37614. else {
  37615. coordDimsInfos =[{
  37616. name: 'value',
  37617. type: 'float'
  37618. }];
  37619. }
  37620. var fromData = new List(coordDimsInfos, mlModel);
  37621. var toData = new List(coordDimsInfos, mlModel);
  37622. // No dimensions
  37623. var lineData = new List([], mlModel);
  37624. var optData = map(mlModel.get('data'), curry(
  37625. markLineTransform, seriesModel, coordSys, mlModel
  37626. ));
  37627. if (coordSys) {
  37628. optData = filter(
  37629. optData, curry(markLineFilter, coordSys)
  37630. );
  37631. }
  37632. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  37633. return item.value;
  37634. };
  37635. fromData.initData(
  37636. map(optData, function (item) { return item[0]; }),
  37637. null, dimValueGetter$$1
  37638. );
  37639. toData.initData(
  37640. map(optData, function (item) { return item[1]; }),
  37641. null, dimValueGetter$$1
  37642. );
  37643. lineData.initData(
  37644. map(optData, function (item) { return item[2]; })
  37645. );
  37646. lineData.hasItemOption = true;
  37647. return {
  37648. from: fromData,
  37649. to: toData,
  37650. line: lineData
  37651. };
  37652. }
  37653. registerPreprocessor(function (opt) {
  37654. // Make sure markLine component is enabled
  37655. opt.markLine = opt.markLine || {};
  37656. });
  37657. MarkerModel.extend({
  37658. type: 'markArea',
  37659. defaultOption: {
  37660. zlevel: 0,
  37661. // PENDING
  37662. z: 1,
  37663. tooltip: {
  37664. trigger: 'item'
  37665. },
  37666. // markArea should fixed on the coordinate system
  37667. animation: false,
  37668. label: {
  37669. show: true,
  37670. position: 'top'
  37671. },
  37672. itemStyle: {
  37673. // color and borderColor default to use color from series
  37674. // color: 'auto'
  37675. // borderColor: 'auto'
  37676. borderWidth: 0
  37677. },
  37678. emphasis: {
  37679. label: {
  37680. show: true,
  37681. position: 'top'
  37682. }
  37683. }
  37684. }
  37685. });
  37686. // TODO Better on polar
  37687. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  37688. var lt = dataTransform(seriesModel, item[0]);
  37689. var rb = dataTransform(seriesModel, item[1]);
  37690. var retrieve$$1 = retrieve;
  37691. // FIXME make sure lt is less than rb
  37692. var ltCoord = lt.coord;
  37693. var rbCoord = rb.coord;
  37694. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  37695. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  37696. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  37697. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  37698. // Merge option into one
  37699. var result = mergeAll([{}, lt, rb]);
  37700. result.coord = [
  37701. lt.coord, rb.coord
  37702. ];
  37703. result.x0 = lt.x;
  37704. result.y0 = lt.y;
  37705. result.x1 = rb.x;
  37706. result.y1 = rb.y;
  37707. return result;
  37708. };
  37709. function isInifinity$1(val) {
  37710. return !isNaN(val) && !isFinite(val);
  37711. }
  37712. // If a markArea has one dim
  37713. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  37714. var otherDimIndex = 1 - dimIndex;
  37715. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  37716. }
  37717. function markAreaFilter(coordSys, item) {
  37718. var fromCoord = item.coord[0];
  37719. var toCoord = item.coord[1];
  37720. if (coordSys.type === 'cartesian2d') {
  37721. // In case
  37722. // {
  37723. // markArea: {
  37724. // data: [{ yAxis: 2 }]
  37725. // }
  37726. // }
  37727. if (
  37728. fromCoord && toCoord &&
  37729. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  37730. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  37731. ) {
  37732. return true;
  37733. }
  37734. }
  37735. return dataFilter$1(coordSys, {
  37736. coord: fromCoord,
  37737. x: item.x0,
  37738. y: item.y0
  37739. })
  37740. || dataFilter$1(coordSys, {
  37741. coord: toCoord,
  37742. x: item.x1,
  37743. y: item.y1
  37744. });
  37745. }
  37746. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  37747. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  37748. var coordSys = seriesModel.coordinateSystem;
  37749. var itemModel = data.getItemModel(idx);
  37750. var point;
  37751. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  37752. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  37753. if (!isNaN(xPx) && !isNaN(yPx)) {
  37754. point = [xPx, yPx];
  37755. }
  37756. else {
  37757. // Chart like bar may have there own marker positioning logic
  37758. if (seriesModel.getMarkerPosition) {
  37759. // Use the getMarkerPoisition
  37760. point = seriesModel.getMarkerPosition(
  37761. data.getValues(dims, idx)
  37762. );
  37763. }
  37764. else {
  37765. var x = data.get(dims[0], idx);
  37766. var y = data.get(dims[1], idx);
  37767. var pt = [x, y];
  37768. coordSys.clampData && coordSys.clampData(pt, pt);
  37769. point = coordSys.dataToPoint(pt, true);
  37770. }
  37771. if (coordSys.type === 'cartesian2d') {
  37772. var xAxis = coordSys.getAxis('x');
  37773. var yAxis = coordSys.getAxis('y');
  37774. var x = data.get(dims[0], idx);
  37775. var y = data.get(dims[1], idx);
  37776. if (isInifinity$1(x)) {
  37777. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  37778. }
  37779. else if (isInifinity$1(y)) {
  37780. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  37781. }
  37782. }
  37783. // Use x, y if has any
  37784. if (!isNaN(xPx)) {
  37785. point[0] = xPx;
  37786. }
  37787. if (!isNaN(yPx)) {
  37788. point[1] = yPx;
  37789. }
  37790. }
  37791. return point;
  37792. }
  37793. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  37794. MarkerView.extend({
  37795. type: 'markArea',
  37796. // updateLayout: function (markAreaModel, ecModel, api) {
  37797. // ecModel.eachSeries(function (seriesModel) {
  37798. // var maModel = seriesModel.markAreaModel;
  37799. // if (maModel) {
  37800. // var areaData = maModel.getData();
  37801. // areaData.each(function (idx) {
  37802. // var points = zrUtil.map(dimPermutations, function (dim) {
  37803. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37804. // });
  37805. // // Layout
  37806. // areaData.setItemLayout(idx, points);
  37807. // var el = areaData.getItemGraphicEl(idx);
  37808. // el.setShape('points', points);
  37809. // });
  37810. // }
  37811. // }, this);
  37812. // },
  37813. updateTransform: function (markAreaModel, ecModel, api) {
  37814. ecModel.eachSeries(function (seriesModel) {
  37815. var maModel = seriesModel.markAreaModel;
  37816. if (maModel) {
  37817. var areaData = maModel.getData();
  37818. areaData.each(function (idx) {
  37819. var points = map(dimPermutations, function (dim) {
  37820. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37821. });
  37822. // Layout
  37823. areaData.setItemLayout(idx, points);
  37824. var el = areaData.getItemGraphicEl(idx);
  37825. el.setShape('points', points);
  37826. });
  37827. }
  37828. }, this);
  37829. },
  37830. renderSeries: function (seriesModel, maModel, ecModel, api) {
  37831. var coordSys = seriesModel.coordinateSystem;
  37832. var seriesName = seriesModel.name;
  37833. var seriesData = seriesModel.getData();
  37834. var areaGroupMap = this.markerGroupMap;
  37835. var polygonGroup = areaGroupMap.get(seriesName)
  37836. || areaGroupMap.set(seriesName, {group: new Group()});
  37837. this.group.add(polygonGroup.group);
  37838. polygonGroup.__keep = true;
  37839. var areaData = createList$3(coordSys, seriesModel, maModel);
  37840. // Line data for tooltip and formatter
  37841. maModel.setData(areaData);
  37842. // Update visual and layout of line
  37843. areaData.each(function (idx) {
  37844. // Layout
  37845. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  37846. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  37847. }));
  37848. // Visual
  37849. areaData.setItemVisual(idx, {
  37850. color: seriesData.getVisual('color')
  37851. });
  37852. });
  37853. areaData.diff(polygonGroup.__data)
  37854. .add(function (idx) {
  37855. var polygon = new Polygon({
  37856. shape: {
  37857. points: areaData.getItemLayout(idx)
  37858. }
  37859. });
  37860. areaData.setItemGraphicEl(idx, polygon);
  37861. polygonGroup.group.add(polygon);
  37862. })
  37863. .update(function (newIdx, oldIdx) {
  37864. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  37865. updateProps(polygon, {
  37866. shape: {
  37867. points: areaData.getItemLayout(newIdx)
  37868. }
  37869. }, maModel, newIdx);
  37870. polygonGroup.group.add(polygon);
  37871. areaData.setItemGraphicEl(newIdx, polygon);
  37872. })
  37873. .remove(function (idx) {
  37874. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  37875. polygonGroup.group.remove(polygon);
  37876. })
  37877. .execute();
  37878. areaData.eachItemGraphicEl(function (polygon, idx) {
  37879. var itemModel = areaData.getItemModel(idx);
  37880. var labelModel = itemModel.getModel('label');
  37881. var labelHoverModel = itemModel.getModel('emphasis.label');
  37882. var color = areaData.getItemVisual(idx, 'color');
  37883. polygon.useStyle(
  37884. defaults(
  37885. itemModel.getModel('itemStyle').getItemStyle(),
  37886. {
  37887. fill: modifyAlpha(color, 0.4),
  37888. stroke: color
  37889. }
  37890. )
  37891. );
  37892. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  37893. setLabelStyle(
  37894. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  37895. {
  37896. labelFetcher: maModel,
  37897. labelDataIndex: idx,
  37898. defaultText: areaData.getName(idx) || '',
  37899. isRectText: true,
  37900. autoColor: color
  37901. }
  37902. );
  37903. setHoverStyle(polygon, {});
  37904. polygon.dataModel = maModel;
  37905. });
  37906. polygonGroup.__data = areaData;
  37907. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  37908. }
  37909. });
  37910. /**
  37911. * @inner
  37912. * @param {module:echarts/coord/*} coordSys
  37913. * @param {module:echarts/model/Series} seriesModel
  37914. * @param {module:echarts/model/Model} mpModel
  37915. */
  37916. function createList$3(coordSys, seriesModel, maModel) {
  37917. var coordDimsInfos;
  37918. var areaData;
  37919. var dims = ['x0', 'y0', 'x1', 'y1'];
  37920. if (coordSys) {
  37921. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37922. var data = seriesModel.getData();
  37923. var info = data.getDimensionInfo(
  37924. data.mapDimension(coordDim)
  37925. ) || {};
  37926. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37927. return defaults({name: coordDim}, info);
  37928. });
  37929. areaData = new List(map(dims, function (dim, idx) {
  37930. return {
  37931. name: dim,
  37932. type: coordDimsInfos[idx % 2].type
  37933. };
  37934. }), maModel);
  37935. }
  37936. else {
  37937. coordDimsInfos =[{
  37938. name: 'value',
  37939. type: 'float'
  37940. }];
  37941. areaData = new List(coordDimsInfos, maModel);
  37942. }
  37943. var optData = map(maModel.get('data'), curry(
  37944. markAreaTransform, seriesModel, coordSys, maModel
  37945. ));
  37946. if (coordSys) {
  37947. optData = filter(
  37948. optData, curry(markAreaFilter, coordSys)
  37949. );
  37950. }
  37951. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  37952. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  37953. } : function (item) {
  37954. return item.value;
  37955. };
  37956. areaData.initData(optData, null, dimValueGetter$$1);
  37957. areaData.hasItemOption = true;
  37958. return areaData;
  37959. }
  37960. registerPreprocessor(function (opt) {
  37961. // Make sure markArea component is enabled
  37962. opt.markArea = opt.markArea || {};
  37963. });
  37964. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  37965. // Default 'slider' when no type specified.
  37966. return 'slider';
  37967. });
  37968. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  37969. // Supported coords.
  37970. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  37971. /**
  37972. * @param {string} coordType
  37973. * @return {boolean}
  37974. */
  37975. function isCoordSupported(coordType) {
  37976. return indexOf(COORDS, coordType) >= 0;
  37977. }
  37978. /**
  37979. * Create "each" method to iterate names.
  37980. *
  37981. * @pubilc
  37982. * @param {Array.<string>} names
  37983. * @param {Array.<string>=} attrs
  37984. * @return {Function}
  37985. */
  37986. function createNameEach(names, attrs) {
  37987. names = names.slice();
  37988. var capitalNames = map(names, capitalFirst);
  37989. attrs = (attrs || []).slice();
  37990. var capitalAttrs = map(attrs, capitalFirst);
  37991. return function (callback, context) {
  37992. each$1(names, function (name, index) {
  37993. var nameObj = {name: name, capital: capitalNames[index]};
  37994. for (var j = 0; j < attrs.length; j++) {
  37995. nameObj[attrs[j]] = name + capitalAttrs[j];
  37996. }
  37997. callback.call(context, nameObj);
  37998. });
  37999. };
  38000. }
  38001. /**
  38002. * Iterate each dimension name.
  38003. *
  38004. * @public
  38005. * @param {Function} callback The parameter is like:
  38006. * {
  38007. * name: 'angle',
  38008. * capital: 'Angle',
  38009. * axis: 'angleAxis',
  38010. * axisIndex: 'angleAixs',
  38011. * index: 'angleIndex'
  38012. * }
  38013. * @param {Object} context
  38014. */
  38015. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  38016. /**
  38017. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  38018. * dataZoomModels and 'links' make up one or more graphics.
  38019. * This function finds the graphic where the source dataZoomModel is in.
  38020. *
  38021. * @public
  38022. * @param {Function} forEachNode Node iterator.
  38023. * @param {Function} forEachEdgeType edgeType iterator
  38024. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  38025. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  38026. */
  38027. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  38028. return function (sourceNode) {
  38029. var result = {
  38030. nodes: [],
  38031. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  38032. };
  38033. forEachEdgeType(function (edgeType) {
  38034. result.records[edgeType.name] = {};
  38035. });
  38036. if (!sourceNode) {
  38037. return result;
  38038. }
  38039. absorb(sourceNode, result);
  38040. var existsLink;
  38041. do {
  38042. existsLink = false;
  38043. forEachNode(processSingleNode);
  38044. }
  38045. while (existsLink);
  38046. function processSingleNode(node) {
  38047. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  38048. absorb(node, result);
  38049. existsLink = true;
  38050. }
  38051. }
  38052. return result;
  38053. };
  38054. function isNodeAbsorded(node, result) {
  38055. return indexOf(result.nodes, node) >= 0;
  38056. }
  38057. function isLinked(node, result) {
  38058. var hasLink = false;
  38059. forEachEdgeType(function (edgeType) {
  38060. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38061. result.records[edgeType.name][edgeId] && (hasLink = true);
  38062. });
  38063. });
  38064. return hasLink;
  38065. }
  38066. function absorb(node, result) {
  38067. result.nodes.push(node);
  38068. forEachEdgeType(function (edgeType) {
  38069. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38070. result.records[edgeType.name][edgeId] = true;
  38071. });
  38072. });
  38073. }
  38074. }
  38075. var each$14 = each$1;
  38076. var asc$1 = asc;
  38077. /**
  38078. * Operate single axis.
  38079. * One axis can only operated by one axis operator.
  38080. * Different dataZoomModels may be defined to operate the same axis.
  38081. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  38082. * So dataZoomModels share one axisProxy in that case.
  38083. *
  38084. * @class
  38085. */
  38086. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  38087. /**
  38088. * @private
  38089. * @type {string}
  38090. */
  38091. this._dimName = dimName;
  38092. /**
  38093. * @private
  38094. */
  38095. this._axisIndex = axisIndex;
  38096. /**
  38097. * @private
  38098. * @type {Array.<number>}
  38099. */
  38100. this._valueWindow;
  38101. /**
  38102. * @private
  38103. * @type {Array.<number>}
  38104. */
  38105. this._percentWindow;
  38106. /**
  38107. * @private
  38108. * @type {Array.<number>}
  38109. */
  38110. this._dataExtent;
  38111. /**
  38112. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  38113. * @private
  38114. * @type {Object}
  38115. */
  38116. this._minMaxSpan;
  38117. /**
  38118. * @readOnly
  38119. * @type {module: echarts/model/Global}
  38120. */
  38121. this.ecModel = ecModel;
  38122. /**
  38123. * @private
  38124. * @type {module: echarts/component/dataZoom/DataZoomModel}
  38125. */
  38126. this._dataZoomModel = dataZoomModel;
  38127. /**
  38128. * @readOnly
  38129. * @private
  38130. */
  38131. this.hasSeriesStacked;
  38132. };
  38133. AxisProxy.prototype = {
  38134. constructor: AxisProxy,
  38135. /**
  38136. * Whether the axisProxy is hosted by dataZoomModel.
  38137. *
  38138. * @public
  38139. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38140. * @return {boolean}
  38141. */
  38142. hostedBy: function (dataZoomModel) {
  38143. return this._dataZoomModel === dataZoomModel;
  38144. },
  38145. /**
  38146. * @return {Array.<number>} Value can only be NaN or finite value.
  38147. */
  38148. getDataValueWindow: function () {
  38149. return this._valueWindow.slice();
  38150. },
  38151. /**
  38152. * @return {Array.<number>}
  38153. */
  38154. getDataPercentWindow: function () {
  38155. return this._percentWindow.slice();
  38156. },
  38157. /**
  38158. * @public
  38159. * @param {number} axisIndex
  38160. * @return {Array} seriesModels
  38161. */
  38162. getTargetSeriesModels: function () {
  38163. var seriesModels = [];
  38164. var ecModel = this.ecModel;
  38165. ecModel.eachSeries(function (seriesModel) {
  38166. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  38167. var dimName = this._dimName;
  38168. var axisModel = ecModel.queryComponents({
  38169. mainType: dimName + 'Axis',
  38170. index: seriesModel.get(dimName + 'AxisIndex'),
  38171. id: seriesModel.get(dimName + 'AxisId')
  38172. })[0];
  38173. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  38174. seriesModels.push(seriesModel);
  38175. }
  38176. }
  38177. }, this);
  38178. return seriesModels;
  38179. },
  38180. getAxisModel: function () {
  38181. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  38182. },
  38183. getOtherAxisModel: function () {
  38184. var axisDim = this._dimName;
  38185. var ecModel = this.ecModel;
  38186. var axisModel = this.getAxisModel();
  38187. var isCartesian = axisDim === 'x' || axisDim === 'y';
  38188. var otherAxisDim;
  38189. var coordSysIndexName;
  38190. if (isCartesian) {
  38191. coordSysIndexName = 'gridIndex';
  38192. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  38193. }
  38194. else {
  38195. coordSysIndexName = 'polarIndex';
  38196. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  38197. }
  38198. var foundOtherAxisModel;
  38199. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  38200. if ((otherAxisModel.get(coordSysIndexName) || 0)
  38201. === (axisModel.get(coordSysIndexName) || 0)
  38202. ) {
  38203. foundOtherAxisModel = otherAxisModel;
  38204. }
  38205. });
  38206. return foundOtherAxisModel;
  38207. },
  38208. getMinMaxSpan: function () {
  38209. return clone(this._minMaxSpan);
  38210. },
  38211. /**
  38212. * Only calculate by given range and this._dataExtent, do not change anything.
  38213. *
  38214. * @param {Object} opt
  38215. * @param {number} [opt.start]
  38216. * @param {number} [opt.end]
  38217. * @param {number} [opt.startValue]
  38218. * @param {number} [opt.endValue]
  38219. */
  38220. calculateDataWindow: function (opt) {
  38221. var dataExtent = this._dataExtent;
  38222. var axisModel = this.getAxisModel();
  38223. var scale = axisModel.axis.scale;
  38224. var rangePropMode = this._dataZoomModel.getRangePropMode();
  38225. var percentExtent = [0, 100];
  38226. var percentWindow = [
  38227. opt.start,
  38228. opt.end
  38229. ];
  38230. var valueWindow = [];
  38231. each$14(['startValue', 'endValue'], function (prop) {
  38232. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  38233. });
  38234. // Normalize bound.
  38235. each$14([0, 1], function (idx) {
  38236. var boundValue = valueWindow[idx];
  38237. var boundPercent = percentWindow[idx];
  38238. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  38239. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  38240. // for cases that a dataZoom component controls multiple axes with different
  38241. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  38242. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  38243. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  38244. // accurately (because all of values that are overflow the `dataExtent` will
  38245. // be calculated to percent '100%'). So we have to use
  38246. // `dataZoom.getRangePropMode()` to mark which prop is used.
  38247. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  38248. // it remains its original value.
  38249. if (rangePropMode[idx] === 'percent') {
  38250. if (boundPercent == null) {
  38251. boundPercent = percentExtent[idx];
  38252. }
  38253. // Use scale.parse to math round for category or time axis.
  38254. boundValue = scale.parse(linearMap(
  38255. boundPercent, percentExtent, dataExtent, true
  38256. ));
  38257. }
  38258. else {
  38259. // Calculating `percent` from `value` may be not accurate, because
  38260. // This calculation can not be inversed, because all of values that
  38261. // are overflow the `dataExtent` will be calculated to percent '100%'
  38262. boundPercent = linearMap(
  38263. boundValue, dataExtent, percentExtent, true
  38264. );
  38265. }
  38266. // valueWindow[idx] = round(boundValue);
  38267. // percentWindow[idx] = round(boundPercent);
  38268. valueWindow[idx] = boundValue;
  38269. percentWindow[idx] = boundPercent;
  38270. });
  38271. return {
  38272. valueWindow: asc$1(valueWindow),
  38273. percentWindow: asc$1(percentWindow)
  38274. };
  38275. },
  38276. /**
  38277. * Notice: reset should not be called before series.restoreData() called,
  38278. * so it is recommanded to be called in "process stage" but not "model init
  38279. * stage".
  38280. *
  38281. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38282. */
  38283. reset: function (dataZoomModel) {
  38284. if (dataZoomModel !== this._dataZoomModel) {
  38285. return;
  38286. }
  38287. var targetSeries = this.getTargetSeriesModels();
  38288. // Culculate data window and data extent, and record them.
  38289. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  38290. this.hasSeriesStacked = false;
  38291. each$14(targetSeries, function (series) {
  38292. var data = series.getData();
  38293. var dataDim = data.mapDimension(this._dimName);
  38294. if (data.isStacked(dataDim)) {
  38295. this.hasSeriesStacked = true;
  38296. }
  38297. }, this);
  38298. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  38299. this._valueWindow = dataWindow.valueWindow;
  38300. this._percentWindow = dataWindow.percentWindow;
  38301. setMinMaxSpan(this);
  38302. // Update axis setting then.
  38303. setAxisModel(this);
  38304. },
  38305. /**
  38306. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38307. */
  38308. restore: function (dataZoomModel) {
  38309. if (dataZoomModel !== this._dataZoomModel) {
  38310. return;
  38311. }
  38312. this._valueWindow = this._percentWindow = null;
  38313. setAxisModel(this, true);
  38314. },
  38315. /**
  38316. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38317. */
  38318. filterData: function (dataZoomModel, api) {
  38319. if (dataZoomModel !== this._dataZoomModel) {
  38320. return;
  38321. }
  38322. var axisDim = this._dimName;
  38323. var seriesModels = this.getTargetSeriesModels();
  38324. var filterMode = dataZoomModel.get('filterMode');
  38325. var valueWindow = this._valueWindow;
  38326. if (filterMode === 'none') {
  38327. return;
  38328. }
  38329. // FIXME
  38330. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  38331. // with NaN data, NaN will be filtered and stack will be wrong.
  38332. // So we need to force the mode to be set empty.
  38333. // In fect, it is not a big deal that do not support filterMode-'filter'
  38334. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  38335. // selection" some day, which might need "adapt to data extent on the
  38336. // otherAxis", which is disabled by filterMode-'empty'.
  38337. var otherAxisModel = this.getOtherAxisModel();
  38338. if (dataZoomModel.get('$fromToolbox')
  38339. && otherAxisModel
  38340. && otherAxisModel.hasSeriesStacked
  38341. ) {
  38342. filterMode = 'empty';
  38343. }
  38344. // TODO
  38345. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  38346. // Process series data
  38347. each$14(seriesModels, function (seriesModel) {
  38348. var seriesData = seriesModel.getData();
  38349. var dataDims = seriesData.mapDimension(axisDim, true);
  38350. if (filterMode === 'weakFilter') {
  38351. seriesData.filterSelf(function (dataIndex) {
  38352. var leftOut;
  38353. var rightOut;
  38354. var hasValue;
  38355. for (var i = 0; i < dataDims.length; i++) {
  38356. var value = seriesData.get(dataDims[i], dataIndex);
  38357. var thisHasValue = !isNaN(value);
  38358. var thisLeftOut = value < valueWindow[0];
  38359. var thisRightOut = value > valueWindow[1];
  38360. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  38361. return true;
  38362. }
  38363. thisHasValue && (hasValue = true);
  38364. thisLeftOut && (leftOut = true);
  38365. thisRightOut && (rightOut = true);
  38366. }
  38367. // If both left out and right out, do not filter.
  38368. return hasValue && leftOut && rightOut;
  38369. });
  38370. }
  38371. else {
  38372. each$14(dataDims, function (dim) {
  38373. if (filterMode === 'empty') {
  38374. seriesModel.setData(
  38375. seriesData.map(dim, function (value) {
  38376. return !isInWindow(value) ? NaN : value;
  38377. })
  38378. );
  38379. }
  38380. else {
  38381. var range = {};
  38382. range[dim] = valueWindow;
  38383. // console.time('select');
  38384. seriesData.selectRange(range);
  38385. // console.timeEnd('select');
  38386. }
  38387. });
  38388. }
  38389. each$14(dataDims, function (dim) {
  38390. seriesData.setApproximateExtent(valueWindow, dim);
  38391. });
  38392. });
  38393. function isInWindow(value) {
  38394. return value >= valueWindow[0] && value <= valueWindow[1];
  38395. }
  38396. }
  38397. };
  38398. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  38399. var dataExtent = [Infinity, -Infinity];
  38400. each$14(seriesModels, function (seriesModel) {
  38401. var seriesData = seriesModel.getData();
  38402. if (seriesData) {
  38403. each$14(seriesData.mapDimension(axisDim, true), function (dim) {
  38404. var seriesExtent = seriesData.getApproximateExtent(dim);
  38405. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  38406. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  38407. });
  38408. }
  38409. });
  38410. if (dataExtent[1] < dataExtent[0]) {
  38411. dataExtent = [NaN, NaN];
  38412. }
  38413. // It is important to get "consistent" extent when more then one axes is
  38414. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  38415. // when zooming. But it is difficult to know what is "consistent", considering
  38416. // axes have different type or even different meanings (For example, two
  38417. // time axes are used to compare data of the same date in different years).
  38418. // So basically dataZoom just obtains extent by series.data (in category axis
  38419. // extent can be obtained from axis.data).
  38420. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  38421. // consistent.
  38422. fixExtentByAxis(axisProxy, dataExtent);
  38423. return dataExtent;
  38424. }
  38425. function fixExtentByAxis(axisProxy, dataExtent) {
  38426. var axisModel = axisProxy.getAxisModel();
  38427. var min = axisModel.getMin(true);
  38428. // For category axis, if min/max/scale are not set, extent is determined
  38429. // by axis.data by default.
  38430. var isCategoryAxis = axisModel.get('type') === 'category';
  38431. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  38432. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  38433. dataExtent[0] = min;
  38434. }
  38435. else if (isCategoryAxis) {
  38436. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  38437. }
  38438. var max = axisModel.getMax(true);
  38439. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  38440. dataExtent[1] = max;
  38441. }
  38442. else if (isCategoryAxis) {
  38443. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  38444. }
  38445. if (!axisModel.get('scale', true)) {
  38446. dataExtent[0] > 0 && (dataExtent[0] = 0);
  38447. dataExtent[1] < 0 && (dataExtent[1] = 0);
  38448. }
  38449. // For value axis, if min/max/scale are not set, we just use the extent obtained
  38450. // by series data, which may be a little different from the extent calculated by
  38451. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  38452. // little when zooming. So it will not be fixed until some users require it strongly.
  38453. return dataExtent;
  38454. }
  38455. function setAxisModel(axisProxy, isRestore) {
  38456. var axisModel = axisProxy.getAxisModel();
  38457. var percentWindow = axisProxy._percentWindow;
  38458. var valueWindow = axisProxy._valueWindow;
  38459. if (!percentWindow) {
  38460. return;
  38461. }
  38462. // [0, 500]: arbitrary value, guess axis extent.
  38463. var precision = getPixelPrecision(valueWindow, [0, 500]);
  38464. precision = Math.min(precision, 20);
  38465. // isRestore or isFull
  38466. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  38467. axisModel.setRange(
  38468. useOrigin ? null : +valueWindow[0].toFixed(precision),
  38469. useOrigin ? null : +valueWindow[1].toFixed(precision)
  38470. );
  38471. }
  38472. function setMinMaxSpan(axisProxy) {
  38473. var minMaxSpan = axisProxy._minMaxSpan = {};
  38474. var dataZoomModel = axisProxy._dataZoomModel;
  38475. each$14(['min', 'max'], function (minMax) {
  38476. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  38477. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  38478. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  38479. if (valueSpan != null) {
  38480. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  38481. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  38482. if (valueSpan != null) {
  38483. var dataExtent = axisProxy._dataExtent;
  38484. minMaxSpan[minMax + 'Span'] = linearMap(
  38485. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  38486. );
  38487. }
  38488. }
  38489. });
  38490. }
  38491. var each$13 = each$1;
  38492. var eachAxisDim = eachAxisDim$1;
  38493. var DataZoomModel = extendComponentModel({
  38494. type: 'dataZoom',
  38495. dependencies: [
  38496. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  38497. ],
  38498. /**
  38499. * @protected
  38500. */
  38501. defaultOption: {
  38502. zlevel: 0,
  38503. z: 4, // Higher than normal component (z: 2).
  38504. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  38505. xAxisIndex: null, // Default the first horizontal category axis.
  38506. yAxisIndex: null, // Default the first vertical category axis.
  38507. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  38508. // 'filter': data items which are out of window will be removed. This option is
  38509. // applicable when filtering outliers. For each data item, it will be
  38510. // filtered if one of the relevant dimensions is out of the window.
  38511. // 'weakFilter': data items which are out of window will be removed. This option
  38512. // is applicable when filtering outliers. For each data item, it will be
  38513. // filtered only if all of the relevant dimensions are out of the same
  38514. // side of the window.
  38515. // 'empty': data items which are out of window will be set to empty.
  38516. // This option is applicable when user should not neglect
  38517. // that there are some data items out of window.
  38518. // 'none': Do not filter.
  38519. // Taking line chart as an example, line will be broken in
  38520. // the filtered points when filterModel is set to 'empty', but
  38521. // be connected when set to 'filter'.
  38522. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  38523. // default 100. Do not throttle when use null/undefined.
  38524. // If animation === true and animationDurationUpdate > 0,
  38525. // default value is 100, otherwise 20.
  38526. start: 0, // Start percent. 0 ~ 100
  38527. end: 100, // End percent. 0 ~ 100
  38528. startValue: null, // Start value. If startValue specified, start is ignored.
  38529. endValue: null, // End value. If endValue specified, end is ignored.
  38530. minSpan: null, // 0 ~ 100
  38531. maxSpan: null, // 0 ~ 100
  38532. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  38533. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  38534. rangeMode: null // Array, can be 'value' or 'percent'.
  38535. },
  38536. /**
  38537. * @override
  38538. */
  38539. init: function (option, parentModel, ecModel) {
  38540. /**
  38541. * key like x_0, y_1
  38542. * @private
  38543. * @type {Object}
  38544. */
  38545. this._dataIntervalByAxis = {};
  38546. /**
  38547. * @private
  38548. */
  38549. this._dataInfo = {};
  38550. /**
  38551. * key like x_0, y_1
  38552. * @private
  38553. */
  38554. this._axisProxies = {};
  38555. /**
  38556. * @readOnly
  38557. */
  38558. this.textStyleModel;
  38559. /**
  38560. * @private
  38561. */
  38562. this._autoThrottle = true;
  38563. /**
  38564. * 'percent' or 'value'
  38565. * @private
  38566. */
  38567. this._rangePropMode = ['percent', 'percent'];
  38568. var rawOption = retrieveRaw(option);
  38569. this.mergeDefaultAndTheme(option, ecModel);
  38570. this.doInit(rawOption);
  38571. },
  38572. /**
  38573. * @override
  38574. */
  38575. mergeOption: function (newOption) {
  38576. var rawOption = retrieveRaw(newOption);
  38577. //FIX #2591
  38578. merge(this.option, newOption, true);
  38579. this.doInit(rawOption);
  38580. },
  38581. /**
  38582. * @protected
  38583. */
  38584. doInit: function (rawOption) {
  38585. var thisOption = this.option;
  38586. // Disable realtime view update if canvas is not supported.
  38587. if (!env$1.canvasSupported) {
  38588. thisOption.realtime = false;
  38589. }
  38590. this._setDefaultThrottle(rawOption);
  38591. updateRangeUse(this, rawOption);
  38592. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  38593. // start/end has higher priority over startValue/endValue if they
  38594. // both set, but we should make chart.setOption({endValue: 1000})
  38595. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  38596. if (this._rangePropMode[index] === 'value') {
  38597. thisOption[names[0]] = null;
  38598. }
  38599. // Otherwise do nothing and use the merge result.
  38600. }, this);
  38601. this.textStyleModel = this.getModel('textStyle');
  38602. this._resetTarget();
  38603. this._giveAxisProxies();
  38604. },
  38605. /**
  38606. * @private
  38607. */
  38608. _giveAxisProxies: function () {
  38609. var axisProxies = this._axisProxies;
  38610. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  38611. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  38612. // If exists, share axisProxy with other dataZoomModels.
  38613. var axisProxy = axisModel.__dzAxisProxy || (
  38614. // Use the first dataZoomModel as the main model of axisProxy.
  38615. axisModel.__dzAxisProxy = new AxisProxy(
  38616. dimNames.name, axisIndex, this, ecModel
  38617. )
  38618. );
  38619. // FIXME
  38620. // dispose __dzAxisProxy
  38621. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  38622. }, this);
  38623. },
  38624. /**
  38625. * @private
  38626. */
  38627. _resetTarget: function () {
  38628. var thisOption = this.option;
  38629. var autoMode = this._judgeAutoMode();
  38630. eachAxisDim(function (dimNames) {
  38631. var axisIndexName = dimNames.axisIndex;
  38632. thisOption[axisIndexName] = normalizeToArray(
  38633. thisOption[axisIndexName]
  38634. );
  38635. }, this);
  38636. if (autoMode === 'axisIndex') {
  38637. this._autoSetAxisIndex();
  38638. }
  38639. else if (autoMode === 'orient') {
  38640. this._autoSetOrient();
  38641. }
  38642. },
  38643. /**
  38644. * @private
  38645. */
  38646. _judgeAutoMode: function () {
  38647. // Auto set only works for setOption at the first time.
  38648. // The following is user's reponsibility. So using merged
  38649. // option is OK.
  38650. var thisOption = this.option;
  38651. var hasIndexSpecified = false;
  38652. eachAxisDim(function (dimNames) {
  38653. // When user set axisIndex as a empty array, we think that user specify axisIndex
  38654. // but do not want use auto mode. Because empty array may be encountered when
  38655. // some error occured.
  38656. if (thisOption[dimNames.axisIndex] != null) {
  38657. hasIndexSpecified = true;
  38658. }
  38659. }, this);
  38660. var orient = thisOption.orient;
  38661. if (orient == null && hasIndexSpecified) {
  38662. return 'orient';
  38663. }
  38664. else if (!hasIndexSpecified) {
  38665. if (orient == null) {
  38666. thisOption.orient = 'horizontal';
  38667. }
  38668. return 'axisIndex';
  38669. }
  38670. },
  38671. /**
  38672. * @private
  38673. */
  38674. _autoSetAxisIndex: function () {
  38675. var autoAxisIndex = true;
  38676. var orient = this.get('orient', true);
  38677. var thisOption = this.option;
  38678. var dependentModels = this.dependentModels;
  38679. if (autoAxisIndex) {
  38680. // Find axis that parallel to dataZoom as default.
  38681. var dimName = orient === 'vertical' ? 'y' : 'x';
  38682. if (dependentModels[dimName + 'Axis'].length) {
  38683. thisOption[dimName + 'AxisIndex'] = [0];
  38684. autoAxisIndex = false;
  38685. }
  38686. else {
  38687. each$13(dependentModels.singleAxis, function (singleAxisModel) {
  38688. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  38689. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  38690. autoAxisIndex = false;
  38691. }
  38692. });
  38693. }
  38694. }
  38695. if (autoAxisIndex) {
  38696. // Find the first category axis as default. (consider polar)
  38697. eachAxisDim(function (dimNames) {
  38698. if (!autoAxisIndex) {
  38699. return;
  38700. }
  38701. var axisIndices = [];
  38702. var axisModels = this.dependentModels[dimNames.axis];
  38703. if (axisModels.length && !axisIndices.length) {
  38704. for (var i = 0, len = axisModels.length; i < len; i++) {
  38705. if (axisModels[i].get('type') === 'category') {
  38706. axisIndices.push(i);
  38707. }
  38708. }
  38709. }
  38710. thisOption[dimNames.axisIndex] = axisIndices;
  38711. if (axisIndices.length) {
  38712. autoAxisIndex = false;
  38713. }
  38714. }, this);
  38715. }
  38716. if (autoAxisIndex) {
  38717. // FIXME
  38718. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  38719. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  38720. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  38721. // dataZoom component auto adopts series that reference to
  38722. // both xAxis and yAxis which type is 'value'.
  38723. this.ecModel.eachSeries(function (seriesModel) {
  38724. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  38725. eachAxisDim(function (dimNames) {
  38726. var axisIndices = thisOption[dimNames.axisIndex];
  38727. var axisIndex = seriesModel.get(dimNames.axisIndex);
  38728. var axisId = seriesModel.get(dimNames.axisId);
  38729. var axisModel = seriesModel.ecModel.queryComponents({
  38730. mainType: dimNames.axis,
  38731. index: axisIndex,
  38732. id: axisId
  38733. })[0];
  38734. if (__DEV__) {
  38735. if (!axisModel) {
  38736. throw new Error(
  38737. dimNames.axis + ' "' + retrieve(
  38738. axisIndex,
  38739. axisId,
  38740. 0
  38741. ) + '" not found'
  38742. );
  38743. }
  38744. }
  38745. axisIndex = axisModel.componentIndex;
  38746. if (indexOf(axisIndices, axisIndex) < 0) {
  38747. axisIndices.push(axisIndex);
  38748. }
  38749. });
  38750. }
  38751. }, this);
  38752. }
  38753. },
  38754. /**
  38755. * @private
  38756. */
  38757. _autoSetOrient: function () {
  38758. var dim;
  38759. // Find the first axis
  38760. this.eachTargetAxis(function (dimNames) {
  38761. !dim && (dim = dimNames.name);
  38762. }, this);
  38763. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  38764. },
  38765. /**
  38766. * @private
  38767. */
  38768. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  38769. // FIXME
  38770. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  38771. // 例如series.type === scatter时。
  38772. var is = true;
  38773. eachAxisDim(function (dimNames) {
  38774. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  38775. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  38776. if (!axisModel || axisModel.get('type') !== axisType) {
  38777. is = false;
  38778. }
  38779. }, this);
  38780. return is;
  38781. },
  38782. /**
  38783. * @private
  38784. */
  38785. _setDefaultThrottle: function (rawOption) {
  38786. // When first time user set throttle, auto throttle ends.
  38787. if (rawOption.hasOwnProperty('throttle')) {
  38788. this._autoThrottle = false;
  38789. }
  38790. if (this._autoThrottle) {
  38791. var globalOption = this.ecModel.option;
  38792. this.option.throttle =
  38793. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  38794. ? 100 : 20;
  38795. }
  38796. },
  38797. /**
  38798. * @public
  38799. */
  38800. getFirstTargetAxisModel: function () {
  38801. var firstAxisModel;
  38802. eachAxisDim(function (dimNames) {
  38803. if (firstAxisModel == null) {
  38804. var indices = this.get(dimNames.axisIndex);
  38805. if (indices.length) {
  38806. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  38807. }
  38808. }
  38809. }, this);
  38810. return firstAxisModel;
  38811. },
  38812. /**
  38813. * @public
  38814. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  38815. */
  38816. eachTargetAxis: function (callback, context) {
  38817. var ecModel = this.ecModel;
  38818. eachAxisDim(function (dimNames) {
  38819. each$13(
  38820. this.get(dimNames.axisIndex),
  38821. function (axisIndex) {
  38822. callback.call(context, dimNames, axisIndex, this, ecModel);
  38823. },
  38824. this
  38825. );
  38826. }, this);
  38827. },
  38828. /**
  38829. * @param {string} dimName
  38830. * @param {number} axisIndex
  38831. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  38832. */
  38833. getAxisProxy: function (dimName, axisIndex) {
  38834. return this._axisProxies[dimName + '_' + axisIndex];
  38835. },
  38836. /**
  38837. * @param {string} dimName
  38838. * @param {number} axisIndex
  38839. * @return {module:echarts/model/Model} If not found, return null/undefined.
  38840. */
  38841. getAxisModel: function (dimName, axisIndex) {
  38842. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  38843. return axisProxy && axisProxy.getAxisModel();
  38844. },
  38845. /**
  38846. * If not specified, set to undefined.
  38847. *
  38848. * @public
  38849. * @param {Object} opt
  38850. * @param {number} [opt.start]
  38851. * @param {number} [opt.end]
  38852. * @param {number} [opt.startValue]
  38853. * @param {number} [opt.endValue]
  38854. * @param {boolean} [ignoreUpdateRangeUsg=false]
  38855. */
  38856. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  38857. var option = this.option;
  38858. each$13([['start', 'startValue'], ['end', 'endValue']], function (names) {
  38859. // If only one of 'start' and 'startValue' is not null/undefined, the other
  38860. // should be cleared, which enable clear the option.
  38861. // If both of them are not set, keep option with the original value, which
  38862. // enable use only set start but not set end when calling `dispatchAction`.
  38863. // The same as 'end' and 'endValue'.
  38864. if (opt[names[0]] != null || opt[names[1]] != null) {
  38865. option[names[0]] = opt[names[0]];
  38866. option[names[1]] = opt[names[1]];
  38867. }
  38868. }, this);
  38869. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  38870. },
  38871. /**
  38872. * @public
  38873. * @return {Array.<number>} [startPercent, endPercent]
  38874. */
  38875. getPercentRange: function () {
  38876. var axisProxy = this.findRepresentativeAxisProxy();
  38877. if (axisProxy) {
  38878. return axisProxy.getDataPercentWindow();
  38879. }
  38880. },
  38881. /**
  38882. * @public
  38883. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  38884. *
  38885. * @param {string} [axisDimName]
  38886. * @param {number} [axisIndex]
  38887. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  38888. */
  38889. getValueRange: function (axisDimName, axisIndex) {
  38890. if (axisDimName == null && axisIndex == null) {
  38891. var axisProxy = this.findRepresentativeAxisProxy();
  38892. if (axisProxy) {
  38893. return axisProxy.getDataValueWindow();
  38894. }
  38895. }
  38896. else {
  38897. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  38898. }
  38899. },
  38900. /**
  38901. * @public
  38902. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  38903. * corresponding to the axisModel
  38904. * @return {module:echarts/component/dataZoom/AxisProxy}
  38905. */
  38906. findRepresentativeAxisProxy: function (axisModel) {
  38907. if (axisModel) {
  38908. return axisModel.__dzAxisProxy;
  38909. }
  38910. // Find the first hosted axisProxy
  38911. var axisProxies = this._axisProxies;
  38912. for (var key in axisProxies) {
  38913. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  38914. return axisProxies[key];
  38915. }
  38916. }
  38917. // If no hosted axis find not hosted axisProxy.
  38918. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  38919. // and the option.start or option.end settings are different. The percentRange
  38920. // should follow axisProxy.
  38921. // (We encounter this problem in toolbox data zoom.)
  38922. for (var key in axisProxies) {
  38923. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  38924. return axisProxies[key];
  38925. }
  38926. }
  38927. },
  38928. /**
  38929. * @return {Array.<string>}
  38930. */
  38931. getRangePropMode: function () {
  38932. return this._rangePropMode.slice();
  38933. }
  38934. });
  38935. function retrieveRaw(option) {
  38936. var ret = {};
  38937. each$13(
  38938. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  38939. function (name) {
  38940. option.hasOwnProperty(name) && (ret[name] = option[name]);
  38941. }
  38942. );
  38943. return ret;
  38944. }
  38945. function updateRangeUse(dataZoomModel, rawOption) {
  38946. var rangePropMode = dataZoomModel._rangePropMode;
  38947. var rangeModeInOption = dataZoomModel.get('rangeMode');
  38948. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  38949. var percentSpecified = rawOption[names[0]] != null;
  38950. var valueSpecified = rawOption[names[1]] != null;
  38951. if (percentSpecified && !valueSpecified) {
  38952. rangePropMode[index] = 'percent';
  38953. }
  38954. else if (!percentSpecified && valueSpecified) {
  38955. rangePropMode[index] = 'value';
  38956. }
  38957. else if (rangeModeInOption) {
  38958. rangePropMode[index] = rangeModeInOption[index];
  38959. }
  38960. else if (percentSpecified) { // percentSpecified && valueSpecified
  38961. rangePropMode[index] = 'percent';
  38962. }
  38963. // else remain its original setting.
  38964. });
  38965. }
  38966. var DataZoomView = Component$1.extend({
  38967. type: 'dataZoom',
  38968. render: function (dataZoomModel, ecModel, api, payload) {
  38969. this.dataZoomModel = dataZoomModel;
  38970. this.ecModel = ecModel;
  38971. this.api = api;
  38972. },
  38973. /**
  38974. * Find the first target coordinate system.
  38975. *
  38976. * @protected
  38977. * @return {Object} {
  38978. * grid: [
  38979. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  38980. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  38981. * ...
  38982. * ], // cartesians must not be null/undefined.
  38983. * polar: [
  38984. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  38985. * ...
  38986. * ], // polars must not be null/undefined.
  38987. * singleAxis: [
  38988. * {model: coord0, axisModels: [], coordIndex: 0}
  38989. * ]
  38990. */
  38991. getTargetCoordInfo: function () {
  38992. var dataZoomModel = this.dataZoomModel;
  38993. var ecModel = this.ecModel;
  38994. var coordSysLists = {};
  38995. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  38996. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  38997. if (axisModel) {
  38998. var coordModel = axisModel.getCoordSysModel();
  38999. coordModel && save(
  39000. coordModel,
  39001. axisModel,
  39002. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  39003. coordModel.componentIndex
  39004. );
  39005. }
  39006. }, this);
  39007. function save(coordModel, axisModel, store, coordIndex) {
  39008. var item;
  39009. for (var i = 0; i < store.length; i++) {
  39010. if (store[i].model === coordModel) {
  39011. item = store[i];
  39012. break;
  39013. }
  39014. }
  39015. if (!item) {
  39016. store.push(item = {
  39017. model: coordModel, axisModels: [], coordIndex: coordIndex
  39018. });
  39019. }
  39020. item.axisModels.push(axisModel);
  39021. }
  39022. return coordSysLists;
  39023. }
  39024. });
  39025. var SliderZoomModel = DataZoomModel.extend({
  39026. type: 'dataZoom.slider',
  39027. layoutMode: 'box',
  39028. /**
  39029. * @protected
  39030. */
  39031. defaultOption: {
  39032. show: true,
  39033. // ph => placeholder. Using placehoder here because
  39034. // deault value can only be drived in view stage.
  39035. right: 'ph', // Default align to grid rect.
  39036. top: 'ph', // Default align to grid rect.
  39037. width: 'ph', // Default align to grid rect.
  39038. height: 'ph', // Default align to grid rect.
  39039. left: null, // Default align to grid rect.
  39040. bottom: null, // Default align to grid rect.
  39041. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  39042. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  39043. // highest priority, remain for compatibility of
  39044. // previous version, but not recommended any more.
  39045. dataBackground: {
  39046. lineStyle: {
  39047. color: '#2f4554',
  39048. width: 0.5,
  39049. opacity: 0.3
  39050. },
  39051. areaStyle: {
  39052. color: 'rgba(47,69,84,0.3)',
  39053. opacity: 0.3
  39054. }
  39055. },
  39056. borderColor: '#ddd', // border color of the box. For compatibility,
  39057. // if dataBackgroundColor is set, borderColor
  39058. // is ignored.
  39059. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  39060. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  39061. // 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',
  39062. 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',
  39063. // Percent of the slider height
  39064. handleSize: '100%',
  39065. handleStyle: {
  39066. color: '#a7b7cc'
  39067. },
  39068. labelPrecision: null,
  39069. labelFormatter: null,
  39070. showDetail: true,
  39071. showDataShadow: 'auto', // Default auto decision.
  39072. realtime: true,
  39073. zoomLock: false, // Whether disable zoom.
  39074. textStyle: {
  39075. color: '#333'
  39076. }
  39077. }
  39078. });
  39079. /**
  39080. * Calculate slider move result.
  39081. * Usage:
  39082. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  39083. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  39084. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  39085. *
  39086. * @param {number} delta Move length.
  39087. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  39088. * handleEnds will be modified in this method.
  39089. * @param {Array.<number>} extent handleEnds is restricted by extent.
  39090. * extent[0] should less or equals than extent[1].
  39091. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  39092. * where the input minSpan and maxSpan will not work.
  39093. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  39094. * If not set, handle0 and cross handle1. If set as a non-negative
  39095. * number (including `0`), handles will push each other when reaching
  39096. * the minSpan.
  39097. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  39098. * @return {Array.<number>} The input handleEnds.
  39099. */
  39100. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  39101. // Normalize firstly.
  39102. handleEnds[0] = restrict(handleEnds[0], extent);
  39103. handleEnds[1] = restrict(handleEnds[1], extent);
  39104. delta = delta || 0;
  39105. var extentSpan = extent[1] - extent[0];
  39106. // Notice maxSpan and minSpan can be null/undefined.
  39107. if (minSpan != null) {
  39108. minSpan = restrict(minSpan, [0, extentSpan]);
  39109. }
  39110. if (maxSpan != null) {
  39111. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  39112. }
  39113. if (handleIndex === 'all') {
  39114. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  39115. handleIndex = 0;
  39116. }
  39117. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  39118. handleEnds[handleIndex] += delta;
  39119. // Restrict in extent.
  39120. var extentMinSpan = minSpan || 0;
  39121. var realExtent = extent.slice();
  39122. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  39123. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  39124. // Expand span.
  39125. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39126. if (minSpan != null && (
  39127. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  39128. )) {
  39129. // If minSpan exists, 'cross' is forbinden.
  39130. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  39131. }
  39132. // Shrink span.
  39133. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39134. if (maxSpan != null && currDistSign.span > maxSpan) {
  39135. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  39136. }
  39137. return handleEnds;
  39138. };
  39139. function getSpanSign(handleEnds, handleIndex) {
  39140. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  39141. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  39142. // is at left of handleEnds[1] for non-cross case.
  39143. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  39144. }
  39145. function restrict(value, extend) {
  39146. return Math.min(extend[1], Math.max(extend[0], value));
  39147. }
  39148. var Rect$1 = Rect;
  39149. var linearMap$2 = linearMap;
  39150. var asc$2 = asc;
  39151. var bind$3 = bind;
  39152. var each$15 = each$1;
  39153. // Constants
  39154. var DEFAULT_LOCATION_EDGE_GAP = 7;
  39155. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  39156. var DEFAULT_FILLER_SIZE = 30;
  39157. var HORIZONTAL = 'horizontal';
  39158. var VERTICAL = 'vertical';
  39159. var LABEL_GAP = 5;
  39160. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  39161. var SliderZoomView = DataZoomView.extend({
  39162. type: 'dataZoom.slider',
  39163. init: function (ecModel, api) {
  39164. /**
  39165. * @private
  39166. * @type {Object}
  39167. */
  39168. this._displayables = {};
  39169. /**
  39170. * @private
  39171. * @type {string}
  39172. */
  39173. this._orient;
  39174. /**
  39175. * [0, 100]
  39176. * @private
  39177. */
  39178. this._range;
  39179. /**
  39180. * [coord of the first handle, coord of the second handle]
  39181. * @private
  39182. */
  39183. this._handleEnds;
  39184. /**
  39185. * [length, thick]
  39186. * @private
  39187. * @type {Array.<number>}
  39188. */
  39189. this._size;
  39190. /**
  39191. * @private
  39192. * @type {number}
  39193. */
  39194. this._handleWidth;
  39195. /**
  39196. * @private
  39197. * @type {number}
  39198. */
  39199. this._handleHeight;
  39200. /**
  39201. * @private
  39202. */
  39203. this._location;
  39204. /**
  39205. * @private
  39206. */
  39207. this._dragging;
  39208. /**
  39209. * @private
  39210. */
  39211. this._dataShadowInfo;
  39212. this.api = api;
  39213. },
  39214. /**
  39215. * @override
  39216. */
  39217. render: function (dataZoomModel, ecModel, api, payload) {
  39218. SliderZoomView.superApply(this, 'render', arguments);
  39219. createOrUpdate(
  39220. this,
  39221. '_dispatchZoomAction',
  39222. this.dataZoomModel.get('throttle'),
  39223. 'fixRate'
  39224. );
  39225. this._orient = dataZoomModel.get('orient');
  39226. if (this.dataZoomModel.get('show') === false) {
  39227. this.group.removeAll();
  39228. return;
  39229. }
  39230. // Notice: this._resetInterval() should not be executed when payload.type
  39231. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  39232. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  39233. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  39234. this._buildView();
  39235. }
  39236. this._updateView();
  39237. },
  39238. /**
  39239. * @override
  39240. */
  39241. remove: function () {
  39242. SliderZoomView.superApply(this, 'remove', arguments);
  39243. clear(this, '_dispatchZoomAction');
  39244. },
  39245. /**
  39246. * @override
  39247. */
  39248. dispose: function () {
  39249. SliderZoomView.superApply(this, 'dispose', arguments);
  39250. clear(this, '_dispatchZoomAction');
  39251. },
  39252. _buildView: function () {
  39253. var thisGroup = this.group;
  39254. thisGroup.removeAll();
  39255. this._resetLocation();
  39256. this._resetInterval();
  39257. var barGroup = this._displayables.barGroup = new Group();
  39258. this._renderBackground();
  39259. this._renderHandle();
  39260. this._renderDataShadow();
  39261. thisGroup.add(barGroup);
  39262. this._positionGroup();
  39263. },
  39264. /**
  39265. * @private
  39266. */
  39267. _resetLocation: function () {
  39268. var dataZoomModel = this.dataZoomModel;
  39269. var api = this.api;
  39270. // If some of x/y/width/height are not specified,
  39271. // auto-adapt according to target grid.
  39272. var coordRect = this._findCoordRect();
  39273. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  39274. // Default align by coordinate system rect.
  39275. var positionInfo = this._orient === HORIZONTAL
  39276. ? {
  39277. // Why using 'right', because right should be used in vertical,
  39278. // and it is better to be consistent for dealing with position param merge.
  39279. right: ecSize.width - coordRect.x - coordRect.width,
  39280. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  39281. width: coordRect.width,
  39282. height: DEFAULT_FILLER_SIZE
  39283. }
  39284. : { // vertical
  39285. right: DEFAULT_LOCATION_EDGE_GAP,
  39286. top: coordRect.y,
  39287. width: DEFAULT_FILLER_SIZE,
  39288. height: coordRect.height
  39289. };
  39290. // Do not write back to option and replace value 'ph', because
  39291. // the 'ph' value should be recalculated when resize.
  39292. var layoutParams = getLayoutParams(dataZoomModel.option);
  39293. // Replace the placeholder value.
  39294. each$1(['right', 'top', 'width', 'height'], function (name) {
  39295. if (layoutParams[name] === 'ph') {
  39296. layoutParams[name] = positionInfo[name];
  39297. }
  39298. });
  39299. var layoutRect = getLayoutRect(
  39300. layoutParams,
  39301. ecSize,
  39302. dataZoomModel.padding
  39303. );
  39304. this._location = {x: layoutRect.x, y: layoutRect.y};
  39305. this._size = [layoutRect.width, layoutRect.height];
  39306. this._orient === VERTICAL && this._size.reverse();
  39307. },
  39308. /**
  39309. * @private
  39310. */
  39311. _positionGroup: function () {
  39312. var thisGroup = this.group;
  39313. var location = this._location;
  39314. var orient = this._orient;
  39315. // Just use the first axis to determine mapping.
  39316. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  39317. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  39318. var barGroup = this._displayables.barGroup;
  39319. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  39320. // Transform barGroup.
  39321. barGroup.attr(
  39322. (orient === HORIZONTAL && !inverse)
  39323. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  39324. : (orient === HORIZONTAL && inverse)
  39325. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  39326. : (orient === VERTICAL && !inverse)
  39327. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  39328. // Dont use Math.PI, considering shadow direction.
  39329. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  39330. );
  39331. // Position barGroup
  39332. var rect = thisGroup.getBoundingRect([barGroup]);
  39333. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  39334. },
  39335. /**
  39336. * @private
  39337. */
  39338. _getViewExtent: function () {
  39339. return [0, this._size[0]];
  39340. },
  39341. _renderBackground: function () {
  39342. var dataZoomModel = this.dataZoomModel;
  39343. var size = this._size;
  39344. var barGroup = this._displayables.barGroup;
  39345. barGroup.add(new Rect$1({
  39346. silent: true,
  39347. shape: {
  39348. x: 0, y: 0, width: size[0], height: size[1]
  39349. },
  39350. style: {
  39351. fill: dataZoomModel.get('backgroundColor')
  39352. },
  39353. z2: -40
  39354. }));
  39355. // Click panel, over shadow, below handles.
  39356. barGroup.add(new Rect$1({
  39357. shape: {
  39358. x: 0, y: 0, width: size[0], height: size[1]
  39359. },
  39360. style: {
  39361. fill: 'transparent'
  39362. },
  39363. z2: 0,
  39364. onclick: bind(this._onClickPanelClick, this)
  39365. }));
  39366. },
  39367. _renderDataShadow: function () {
  39368. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  39369. if (!info) {
  39370. return;
  39371. }
  39372. var size = this._size;
  39373. var seriesModel = info.series;
  39374. var data = seriesModel.getRawData();
  39375. var otherDim = seriesModel.getShadowDim
  39376. ? seriesModel.getShadowDim() // @see candlestick
  39377. : info.otherDim;
  39378. if (otherDim == null) {
  39379. return;
  39380. }
  39381. var otherDataExtent = data.getDataExtent(otherDim);
  39382. // Nice extent.
  39383. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  39384. otherDataExtent = [
  39385. otherDataExtent[0] - otherOffset,
  39386. otherDataExtent[1] + otherOffset
  39387. ];
  39388. var otherShadowExtent = [0, size[1]];
  39389. var thisShadowExtent = [0, size[0]];
  39390. var areaPoints = [[size[0], 0], [0, 0]];
  39391. var linePoints = [];
  39392. var step = thisShadowExtent[1] / (data.count() - 1);
  39393. var thisCoord = 0;
  39394. // Optimize for large data shadow
  39395. var stride = Math.round(data.count() / size[0]);
  39396. var lastIsEmpty;
  39397. data.each([otherDim], function (value, index) {
  39398. if (stride > 0 && (index % stride)) {
  39399. thisCoord += step;
  39400. return;
  39401. }
  39402. // FIXME
  39403. // Should consider axis.min/axis.max when drawing dataShadow.
  39404. // FIXME
  39405. // 应该使用统一的空判断?还是在list里进行空判断?
  39406. var isEmpty = value == null || isNaN(value) || value === '';
  39407. // See #4235.
  39408. var otherCoord = isEmpty
  39409. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  39410. // Attempt to draw data shadow precisely when there are empty value.
  39411. if (isEmpty && !lastIsEmpty && index) {
  39412. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  39413. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  39414. }
  39415. else if (!isEmpty && lastIsEmpty) {
  39416. areaPoints.push([thisCoord, 0]);
  39417. linePoints.push([thisCoord, 0]);
  39418. }
  39419. areaPoints.push([thisCoord, otherCoord]);
  39420. linePoints.push([thisCoord, otherCoord]);
  39421. thisCoord += step;
  39422. lastIsEmpty = isEmpty;
  39423. });
  39424. var dataZoomModel = this.dataZoomModel;
  39425. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  39426. this._displayables.barGroup.add(new Polygon({
  39427. shape: {points: areaPoints},
  39428. style: defaults(
  39429. {fill: dataZoomModel.get('dataBackgroundColor')},
  39430. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  39431. ),
  39432. silent: true,
  39433. z2: -20
  39434. }));
  39435. this._displayables.barGroup.add(new Polyline({
  39436. shape: {points: linePoints},
  39437. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  39438. silent: true,
  39439. z2: -19
  39440. }));
  39441. },
  39442. _prepareDataShadowInfo: function () {
  39443. var dataZoomModel = this.dataZoomModel;
  39444. var showDataShadow = dataZoomModel.get('showDataShadow');
  39445. if (showDataShadow === false) {
  39446. return;
  39447. }
  39448. // Find a representative series.
  39449. var result;
  39450. var ecModel = this.ecModel;
  39451. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  39452. var seriesModels = dataZoomModel
  39453. .getAxisProxy(dimNames.name, axisIndex)
  39454. .getTargetSeriesModels();
  39455. each$1(seriesModels, function (seriesModel) {
  39456. if (result) {
  39457. return;
  39458. }
  39459. if (showDataShadow !== true && indexOf(
  39460. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  39461. ) < 0
  39462. ) {
  39463. return;
  39464. }
  39465. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  39466. var otherDim = getOtherDim(dimNames.name);
  39467. var otherAxisInverse;
  39468. var coordSys = seriesModel.coordinateSystem;
  39469. if (otherDim != null && coordSys.getOtherAxis) {
  39470. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  39471. }
  39472. otherDim = seriesModel.getData().mapDimension(otherDim);
  39473. result = {
  39474. thisAxis: thisAxis,
  39475. series: seriesModel,
  39476. thisDim: dimNames.name,
  39477. otherDim: otherDim,
  39478. otherAxisInverse: otherAxisInverse
  39479. };
  39480. }, this);
  39481. }, this);
  39482. return result;
  39483. },
  39484. _renderHandle: function () {
  39485. var displaybles = this._displayables;
  39486. var handles = displaybles.handles = [];
  39487. var handleLabels = displaybles.handleLabels = [];
  39488. var barGroup = this._displayables.barGroup;
  39489. var size = this._size;
  39490. var dataZoomModel = this.dataZoomModel;
  39491. barGroup.add(displaybles.filler = new Rect$1({
  39492. draggable: true,
  39493. cursor: getCursor(this._orient),
  39494. drift: bind$3(this._onDragMove, this, 'all'),
  39495. onmousemove: function (e) {
  39496. // Fot mobile devicem, prevent screen slider on the button.
  39497. stop(e.event);
  39498. },
  39499. ondragstart: bind$3(this._showDataInfo, this, true),
  39500. ondragend: bind$3(this._onDragEnd, this),
  39501. onmouseover: bind$3(this._showDataInfo, this, true),
  39502. onmouseout: bind$3(this._showDataInfo, this, false),
  39503. style: {
  39504. fill: dataZoomModel.get('fillerColor'),
  39505. textPosition : 'inside'
  39506. }
  39507. }));
  39508. // Frame border.
  39509. barGroup.add(new Rect$1(subPixelOptimizeRect({
  39510. silent: true,
  39511. shape: {
  39512. x: 0,
  39513. y: 0,
  39514. width: size[0],
  39515. height: size[1]
  39516. },
  39517. style: {
  39518. stroke: dataZoomModel.get('dataBackgroundColor')
  39519. || dataZoomModel.get('borderColor'),
  39520. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  39521. fill: 'rgba(0,0,0,0)'
  39522. }
  39523. })));
  39524. each$15([0, 1], function (handleIndex) {
  39525. var path = createIcon(
  39526. dataZoomModel.get('handleIcon'),
  39527. {
  39528. cursor: getCursor(this._orient),
  39529. draggable: true,
  39530. drift: bind$3(this._onDragMove, this, handleIndex),
  39531. onmousemove: function (e) {
  39532. // Fot mobile devicem, prevent screen slider on the button.
  39533. stop(e.event);
  39534. },
  39535. ondragend: bind$3(this._onDragEnd, this),
  39536. onmouseover: bind$3(this._showDataInfo, this, true),
  39537. onmouseout: bind$3(this._showDataInfo, this, false)
  39538. },
  39539. {x: -1, y: 0, width: 2, height: 2}
  39540. );
  39541. var bRect = path.getBoundingRect();
  39542. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  39543. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  39544. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  39545. var handleColor = dataZoomModel.get('handleColor');
  39546. // Compatitable with previous version
  39547. if (handleColor != null) {
  39548. path.style.fill = handleColor;
  39549. }
  39550. barGroup.add(handles[handleIndex] = path);
  39551. var textStyleModel = dataZoomModel.textStyleModel;
  39552. this.group.add(
  39553. handleLabels[handleIndex] = new Text({
  39554. silent: true,
  39555. invisible: true,
  39556. style: {
  39557. x: 0, y: 0, text: '',
  39558. textVerticalAlign: 'middle',
  39559. textAlign: 'center',
  39560. textFill: textStyleModel.getTextColor(),
  39561. textFont: textStyleModel.getFont()
  39562. },
  39563. z2: 10
  39564. }));
  39565. }, this);
  39566. },
  39567. /**
  39568. * @private
  39569. */
  39570. _resetInterval: function () {
  39571. var range = this._range = this.dataZoomModel.getPercentRange();
  39572. var viewExtent = this._getViewExtent();
  39573. this._handleEnds = [
  39574. linearMap$2(range[0], [0, 100], viewExtent, true),
  39575. linearMap$2(range[1], [0, 100], viewExtent, true)
  39576. ];
  39577. },
  39578. /**
  39579. * @private
  39580. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  39581. * @param {number} delta
  39582. */
  39583. _updateInterval: function (handleIndex, delta) {
  39584. var dataZoomModel = this.dataZoomModel;
  39585. var handleEnds = this._handleEnds;
  39586. var viewExtend = this._getViewExtent();
  39587. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  39588. var percentExtent = [0, 100];
  39589. sliderMove(
  39590. delta,
  39591. handleEnds,
  39592. viewExtend,
  39593. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  39594. minMaxSpan.minSpan != null
  39595. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  39596. minMaxSpan.maxSpan != null
  39597. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  39598. );
  39599. this._range = asc$2([
  39600. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  39601. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  39602. ]);
  39603. },
  39604. /**
  39605. * @private
  39606. */
  39607. _updateView: function (nonRealtime) {
  39608. var displaybles = this._displayables;
  39609. var handleEnds = this._handleEnds;
  39610. var handleInterval = asc$2(handleEnds.slice());
  39611. var size = this._size;
  39612. each$15([0, 1], function (handleIndex) {
  39613. // Handles
  39614. var handle = displaybles.handles[handleIndex];
  39615. var handleHeight = this._handleHeight;
  39616. handle.attr({
  39617. scale: [handleHeight / 2, handleHeight / 2],
  39618. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  39619. });
  39620. }, this);
  39621. // Filler
  39622. displaybles.filler.setShape({
  39623. x: handleInterval[0],
  39624. y: 0,
  39625. width: handleInterval[1] - handleInterval[0],
  39626. height: size[1]
  39627. });
  39628. this._updateDataInfo(nonRealtime);
  39629. },
  39630. /**
  39631. * @private
  39632. */
  39633. _updateDataInfo: function (nonRealtime) {
  39634. var dataZoomModel = this.dataZoomModel;
  39635. var displaybles = this._displayables;
  39636. var handleLabels = displaybles.handleLabels;
  39637. var orient = this._orient;
  39638. var labelTexts = ['', ''];
  39639. // FIXME
  39640. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  39641. if (dataZoomModel.get('showDetail')) {
  39642. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  39643. if (axisProxy) {
  39644. var axis = axisProxy.getAxisModel().axis;
  39645. var range = this._range;
  39646. var dataInterval = nonRealtime
  39647. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  39648. ? axisProxy.calculateDataWindow({
  39649. start: range[0], end: range[1]
  39650. }).valueWindow
  39651. : axisProxy.getDataValueWindow();
  39652. labelTexts = [
  39653. this._formatLabel(dataInterval[0], axis),
  39654. this._formatLabel(dataInterval[1], axis)
  39655. ];
  39656. }
  39657. }
  39658. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  39659. setLabel.call(this, 0);
  39660. setLabel.call(this, 1);
  39661. function setLabel(handleIndex) {
  39662. // Label
  39663. // Text should not transform by barGroup.
  39664. // Ignore handlers transform
  39665. var barTransform = getTransform(
  39666. displaybles.handles[handleIndex].parent, this.group
  39667. );
  39668. var direction = transformDirection(
  39669. handleIndex === 0 ? 'right' : 'left', barTransform
  39670. );
  39671. var offset = this._handleWidth / 2 + LABEL_GAP;
  39672. var textPoint = applyTransform$1(
  39673. [
  39674. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  39675. this._size[1] / 2
  39676. ],
  39677. barTransform
  39678. );
  39679. handleLabels[handleIndex].setStyle({
  39680. x: textPoint[0],
  39681. y: textPoint[1],
  39682. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  39683. textAlign: orient === HORIZONTAL ? direction : 'center',
  39684. text: labelTexts[handleIndex]
  39685. });
  39686. }
  39687. },
  39688. /**
  39689. * @private
  39690. */
  39691. _formatLabel: function (value, axis) {
  39692. var dataZoomModel = this.dataZoomModel;
  39693. var labelFormatter = dataZoomModel.get('labelFormatter');
  39694. var labelPrecision = dataZoomModel.get('labelPrecision');
  39695. if (labelPrecision == null || labelPrecision === 'auto') {
  39696. labelPrecision = axis.getPixelPrecision();
  39697. }
  39698. var valueStr = (value == null || isNaN(value))
  39699. ? ''
  39700. // FIXME Glue code
  39701. : (axis.type === 'category' || axis.type === 'time')
  39702. ? axis.scale.getLabel(Math.round(value))
  39703. // param of toFixed should less then 20.
  39704. : value.toFixed(Math.min(labelPrecision, 20));
  39705. return isFunction$1(labelFormatter)
  39706. ? labelFormatter(value, valueStr)
  39707. : isString(labelFormatter)
  39708. ? labelFormatter.replace('{value}', valueStr)
  39709. : valueStr;
  39710. },
  39711. /**
  39712. * @private
  39713. * @param {boolean} showOrHide true: show, false: hide
  39714. */
  39715. _showDataInfo: function (showOrHide) {
  39716. // Always show when drgging.
  39717. showOrHide = this._dragging || showOrHide;
  39718. var handleLabels = this._displayables.handleLabels;
  39719. handleLabels[0].attr('invisible', !showOrHide);
  39720. handleLabels[1].attr('invisible', !showOrHide);
  39721. },
  39722. _onDragMove: function (handleIndex, dx, dy) {
  39723. this._dragging = true;
  39724. // Transform dx, dy to bar coordination.
  39725. var barTransform = this._displayables.barGroup.getLocalTransform();
  39726. var vertex = applyTransform$1([dx, dy], barTransform, true);
  39727. this._updateInterval(handleIndex, vertex[0]);
  39728. var realtime = this.dataZoomModel.get('realtime');
  39729. this._updateView(!realtime);
  39730. realtime && this._dispatchZoomAction();
  39731. },
  39732. _onDragEnd: function () {
  39733. this._dragging = false;
  39734. this._showDataInfo(false);
  39735. // While in realtime mode and stream mode, dispatch action when
  39736. // drag end will cause the whole view rerender, which is unnecessary.
  39737. var realtime = this.dataZoomModel.get('realtime');
  39738. !realtime && this._dispatchZoomAction();
  39739. },
  39740. _onClickPanelClick: function (e) {
  39741. var size = this._size;
  39742. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  39743. if (localPoint[0] < 0 || localPoint[0] > size[0]
  39744. || localPoint[1] < 0 || localPoint[1] > size[1]
  39745. ) {
  39746. return;
  39747. }
  39748. var handleEnds = this._handleEnds;
  39749. var center = (handleEnds[0] + handleEnds[1]) / 2;
  39750. this._updateInterval('all', localPoint[0] - center);
  39751. this._updateView();
  39752. this._dispatchZoomAction();
  39753. },
  39754. /**
  39755. * This action will be throttled.
  39756. * @private
  39757. */
  39758. _dispatchZoomAction: function () {
  39759. var range = this._range;
  39760. this.api.dispatchAction({
  39761. type: 'dataZoom',
  39762. from: this.uid,
  39763. dataZoomId: this.dataZoomModel.id,
  39764. start: range[0],
  39765. end: range[1]
  39766. });
  39767. },
  39768. /**
  39769. * @private
  39770. */
  39771. _findCoordRect: function () {
  39772. // Find the grid coresponding to the first axis referred by dataZoom.
  39773. var rect;
  39774. each$15(this.getTargetCoordInfo(), function (coordInfoList) {
  39775. if (!rect && coordInfoList.length) {
  39776. var coordSys = coordInfoList[0].model.coordinateSystem;
  39777. rect = coordSys.getRect && coordSys.getRect();
  39778. }
  39779. });
  39780. if (!rect) {
  39781. var width = this.api.getWidth();
  39782. var height = this.api.getHeight();
  39783. rect = {
  39784. x: width * 0.2,
  39785. y: height * 0.2,
  39786. width: width * 0.6,
  39787. height: height * 0.6
  39788. };
  39789. }
  39790. return rect;
  39791. }
  39792. });
  39793. function getOtherDim(thisDim) {
  39794. // FIXME
  39795. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  39796. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  39797. return map$$1[thisDim];
  39798. }
  39799. function getCursor(orient) {
  39800. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  39801. }
  39802. DataZoomModel.extend({
  39803. type: 'dataZoom.inside',
  39804. /**
  39805. * @protected
  39806. */
  39807. defaultOption: {
  39808. disabled: false, // Whether disable this inside zoom.
  39809. zoomLock: false, // Whether disable zoom but only pan.
  39810. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39811. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39812. preventDefaultMouseMove: true
  39813. }
  39814. });
  39815. var ATTR$1 = '\0_ec_interaction_mutex';
  39816. function take(zr, resourceKey, userKey) {
  39817. var store = getStore(zr);
  39818. store[resourceKey] = userKey;
  39819. }
  39820. function release(zr, resourceKey, userKey) {
  39821. var store = getStore(zr);
  39822. var uKey = store[resourceKey];
  39823. if (uKey === userKey) {
  39824. store[resourceKey] = null;
  39825. }
  39826. }
  39827. function isTaken(zr, resourceKey) {
  39828. return !!getStore(zr)[resourceKey];
  39829. }
  39830. function getStore(zr) {
  39831. return zr[ATTR$1] || (zr[ATTR$1] = {});
  39832. }
  39833. /**
  39834. * payload: {
  39835. * type: 'takeGlobalCursor',
  39836. * key: 'dataZoomSelect', or 'brush', or ...,
  39837. * If no userKey, release global cursor.
  39838. * }
  39839. */
  39840. registerAction(
  39841. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  39842. function () {}
  39843. );
  39844. /**
  39845. * @alias module:echarts/component/helper/RoamController
  39846. * @constructor
  39847. * @mixin {module:zrender/mixin/Eventful}
  39848. *
  39849. * @param {module:zrender/zrender~ZRender} zr
  39850. */
  39851. function RoamController(zr) {
  39852. /**
  39853. * @type {Function}
  39854. */
  39855. this.pointerChecker;
  39856. /**
  39857. * @type {module:zrender}
  39858. */
  39859. this._zr = zr;
  39860. /**
  39861. * @type {Object}
  39862. */
  39863. this._opt = {};
  39864. // Avoid two roamController bind the same handler
  39865. var bind$$1 = bind;
  39866. var mousedownHandler = bind$$1(mousedown, this);
  39867. var mousemoveHandler = bind$$1(mousemove, this);
  39868. var mouseupHandler = bind$$1(mouseup, this);
  39869. var mousewheelHandler = bind$$1(mousewheel, this);
  39870. var pinchHandler = bind$$1(pinch, this);
  39871. Eventful.call(this);
  39872. /**
  39873. * @param {Function} pointerChecker
  39874. * input: x, y
  39875. * output: boolean
  39876. */
  39877. this.setPointerChecker = function (pointerChecker) {
  39878. this.pointerChecker = pointerChecker;
  39879. };
  39880. /**
  39881. * Notice: only enable needed types. For example, if 'zoom'
  39882. * is not needed, 'zoom' should not be enabled, otherwise
  39883. * default mousewheel behaviour (scroll page) will be disabled.
  39884. *
  39885. * @param {boolean|string} [controlType=true] Specify the control type,
  39886. * which can be null/undefined or true/false
  39887. * or 'pan/move' or 'zoom'/'scale'
  39888. * @param {Object} [opt]
  39889. * @param {Object} [opt.zoomOnMouseWheel=true]
  39890. * @param {Object} [opt.moveOnMouseMove=true]
  39891. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  39892. */
  39893. this.enable = function (controlType, opt) {
  39894. // Disable previous first
  39895. this.disable();
  39896. this._opt = defaults(clone(opt) || {}, {
  39897. zoomOnMouseWheel: true,
  39898. moveOnMouseMove: true,
  39899. preventDefaultMouseMove: true
  39900. });
  39901. if (controlType == null) {
  39902. controlType = true;
  39903. }
  39904. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  39905. zr.on('mousedown', mousedownHandler);
  39906. zr.on('mousemove', mousemoveHandler);
  39907. zr.on('mouseup', mouseupHandler);
  39908. }
  39909. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  39910. zr.on('mousewheel', mousewheelHandler);
  39911. zr.on('pinch', pinchHandler);
  39912. }
  39913. };
  39914. this.disable = function () {
  39915. zr.off('mousedown', mousedownHandler);
  39916. zr.off('mousemove', mousemoveHandler);
  39917. zr.off('mouseup', mouseupHandler);
  39918. zr.off('mousewheel', mousewheelHandler);
  39919. zr.off('pinch', pinchHandler);
  39920. };
  39921. this.dispose = this.disable;
  39922. this.isDragging = function () {
  39923. return this._dragging;
  39924. };
  39925. this.isPinching = function () {
  39926. return this._pinching;
  39927. };
  39928. }
  39929. mixin(RoamController, Eventful);
  39930. function mousedown(e) {
  39931. if (notLeftMouse(e)
  39932. || (e.target && e.target.draggable)
  39933. ) {
  39934. return;
  39935. }
  39936. var x = e.offsetX;
  39937. var y = e.offsetY;
  39938. // Only check on mosedown, but not mousemove.
  39939. // Mouse can be out of target when mouse moving.
  39940. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  39941. this._x = x;
  39942. this._y = y;
  39943. this._dragging = true;
  39944. }
  39945. }
  39946. function mousemove(e) {
  39947. if (notLeftMouse(e)
  39948. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  39949. || !this._dragging
  39950. || e.gestureEvent === 'pinch'
  39951. || isTaken(this._zr, 'globalPan')
  39952. ) {
  39953. return;
  39954. }
  39955. var x = e.offsetX;
  39956. var y = e.offsetY;
  39957. var oldX = this._x;
  39958. var oldY = this._y;
  39959. var dx = x - oldX;
  39960. var dy = y - oldY;
  39961. this._x = x;
  39962. this._y = y;
  39963. this._opt.preventDefaultMouseMove && stop(e.event);
  39964. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  39965. }
  39966. function mouseup(e) {
  39967. if (!notLeftMouse(e)) {
  39968. this._dragging = false;
  39969. }
  39970. }
  39971. function mousewheel(e) {
  39972. // wheelDelta maybe -0 in chrome mac.
  39973. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  39974. return;
  39975. }
  39976. // Convenience:
  39977. // Mac and VM Windows on Mac: scroll up: zoom out.
  39978. // Windows: scroll up: zoom in.
  39979. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  39980. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  39981. }
  39982. function pinch(e) {
  39983. if (isTaken(this._zr, 'globalPan')) {
  39984. return;
  39985. }
  39986. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  39987. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  39988. }
  39989. function zoom(e, zoomDelta, zoomX, zoomY) {
  39990. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  39991. // When mouse is out of roamController rect,
  39992. // default befavoius should not be be disabled, otherwise
  39993. // page sliding is disabled, contrary to expectation.
  39994. stop(e.event);
  39995. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  39996. }
  39997. }
  39998. function checkKeyBinding(roamController, prop, e) {
  39999. var setting = roamController._opt[prop];
  40000. return setting
  40001. && (!isString(setting) || e.event[setting + 'Key']);
  40002. }
  40003. // Only create one roam controller for each coordinate system.
  40004. // one roam controller might be refered by two inside data zoom
  40005. // components (for example, one for x and one for y). When user
  40006. // pan or zoom, only dispatch one action for those data zoom
  40007. // components.
  40008. var curry$5 = curry;
  40009. var ATTR = '\0_ec_dataZoom_roams';
  40010. /**
  40011. * @public
  40012. * @param {module:echarts/ExtensionAPI} api
  40013. * @param {Object} dataZoomInfo
  40014. * @param {string} dataZoomInfo.coordId
  40015. * @param {Function} dataZoomInfo.containsPoint
  40016. * @param {Array.<string>} dataZoomInfo.allCoordIds
  40017. * @param {string} dataZoomInfo.dataZoomId
  40018. * @param {number} dataZoomInfo.throttleRate
  40019. * @param {Function} dataZoomInfo.panGetRange
  40020. * @param {Function} dataZoomInfo.zoomGetRange
  40021. * @param {boolean} [dataZoomInfo.zoomLock]
  40022. * @param {boolean} [dataZoomInfo.disabled]
  40023. */
  40024. function register$1(api, dataZoomInfo) {
  40025. var store = giveStore(api);
  40026. var theDataZoomId = dataZoomInfo.dataZoomId;
  40027. var theCoordId = dataZoomInfo.coordId;
  40028. // Do clean when a dataZoom changes its target coordnate system.
  40029. // Avoid memory leak, dispose all not-used-registered.
  40030. each$1(store, function (record, coordId) {
  40031. var dataZoomInfos = record.dataZoomInfos;
  40032. if (dataZoomInfos[theDataZoomId]
  40033. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  40034. ) {
  40035. delete dataZoomInfos[theDataZoomId];
  40036. record.count--;
  40037. }
  40038. });
  40039. cleanStore(store);
  40040. var record = store[theCoordId];
  40041. // Create if needed.
  40042. if (!record) {
  40043. record = store[theCoordId] = {
  40044. coordId: theCoordId,
  40045. dataZoomInfos: {},
  40046. count: 0
  40047. };
  40048. record.controller = createController(api, record);
  40049. record.dispatchAction = curry(dispatchAction, api);
  40050. }
  40051. // Update reference of dataZoom.
  40052. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  40053. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  40054. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  40055. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  40056. // Consider resize, area should be always updated.
  40057. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  40058. // Update throttle.
  40059. createOrUpdate(
  40060. record,
  40061. 'dispatchAction',
  40062. dataZoomInfo.throttleRate,
  40063. 'fixRate'
  40064. );
  40065. }
  40066. /**
  40067. * @public
  40068. * @param {module:echarts/ExtensionAPI} api
  40069. * @param {string} dataZoomId
  40070. */
  40071. function unregister$1(api, dataZoomId) {
  40072. var store = giveStore(api);
  40073. each$1(store, function (record) {
  40074. record.controller.dispose();
  40075. var dataZoomInfos = record.dataZoomInfos;
  40076. if (dataZoomInfos[dataZoomId]) {
  40077. delete dataZoomInfos[dataZoomId];
  40078. record.count--;
  40079. }
  40080. });
  40081. cleanStore(store);
  40082. }
  40083. /**
  40084. * @public
  40085. */
  40086. function shouldRecordRange(payload, dataZoomId) {
  40087. if (payload && payload.type === 'dataZoom' && payload.batch) {
  40088. for (var i = 0, len = payload.batch.length; i < len; i++) {
  40089. if (payload.batch[i].dataZoomId === dataZoomId) {
  40090. return false;
  40091. }
  40092. }
  40093. }
  40094. return true;
  40095. }
  40096. /**
  40097. * @public
  40098. */
  40099. function generateCoordId(coordModel) {
  40100. return coordModel.type + '\0_' + coordModel.id;
  40101. }
  40102. /**
  40103. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  40104. * @type {Array.<Object>}
  40105. */
  40106. function giveStore(api) {
  40107. // Mount store on zrender instance, so that we do not
  40108. // need to worry about dispose.
  40109. var zr = api.getZr();
  40110. return zr[ATTR] || (zr[ATTR] = {});
  40111. }
  40112. function createController(api, newRecord) {
  40113. var controller = new RoamController(api.getZr());
  40114. controller.on('pan', curry$5(onPan, newRecord));
  40115. controller.on('zoom', curry$5(onZoom, newRecord));
  40116. return controller;
  40117. }
  40118. function cleanStore(store) {
  40119. each$1(store, function (record, coordId) {
  40120. if (!record.count) {
  40121. record.controller.dispose();
  40122. delete store[coordId];
  40123. }
  40124. });
  40125. }
  40126. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  40127. wrapAndDispatch(record, function (info) {
  40128. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  40129. });
  40130. }
  40131. function onZoom(record, scale, mouseX, mouseY) {
  40132. wrapAndDispatch(record, function (info) {
  40133. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  40134. });
  40135. }
  40136. function wrapAndDispatch(record, getRange) {
  40137. var batch = [];
  40138. each$1(record.dataZoomInfos, function (info) {
  40139. var range = getRange(info);
  40140. !info.disabled && range && batch.push({
  40141. dataZoomId: info.dataZoomId,
  40142. start: range[0],
  40143. end: range[1]
  40144. });
  40145. });
  40146. record.dispatchAction(batch);
  40147. }
  40148. /**
  40149. * This action will be throttled.
  40150. */
  40151. function dispatchAction(api, batch) {
  40152. api.dispatchAction({
  40153. type: 'dataZoom',
  40154. batch: batch
  40155. });
  40156. }
  40157. /**
  40158. * Merge roamController settings when multiple dataZooms share one roamController.
  40159. */
  40160. function mergeControllerParams(dataZoomInfos) {
  40161. var controlType;
  40162. var opt = {};
  40163. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  40164. // as string, it is probably revert to reserved word by compress tool. See #7411.
  40165. var prefix = 'type_';
  40166. var typePriority = {
  40167. 'type_true': 2,
  40168. 'type_move': 1,
  40169. 'type_false': 0,
  40170. 'type_undefined': -1
  40171. };
  40172. each$1(dataZoomInfos, function (dataZoomInfo) {
  40173. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  40174. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  40175. controlType = oneType;
  40176. }
  40177. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  40178. extend(opt, dataZoomInfo.roamControllerOpt);
  40179. });
  40180. return {
  40181. controlType: controlType,
  40182. opt: opt
  40183. };
  40184. }
  40185. var bind$4 = bind;
  40186. var InsideZoomView = DataZoomView.extend({
  40187. type: 'dataZoom.inside',
  40188. /**
  40189. * @override
  40190. */
  40191. init: function (ecModel, api) {
  40192. /**
  40193. * 'throttle' is used in this.dispatchAction, so we save range
  40194. * to avoid missing some 'pan' info.
  40195. * @private
  40196. * @type {Array.<number>}
  40197. */
  40198. this._range;
  40199. },
  40200. /**
  40201. * @override
  40202. */
  40203. render: function (dataZoomModel, ecModel, api, payload) {
  40204. InsideZoomView.superApply(this, 'render', arguments);
  40205. // Notice: origin this._range should be maintained, and should not be re-fetched
  40206. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  40207. // info will be missed because of 'throttle' of this.dispatchAction.
  40208. if (shouldRecordRange(payload, dataZoomModel.id)) {
  40209. this._range = dataZoomModel.getPercentRange();
  40210. }
  40211. // Reset controllers.
  40212. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  40213. var allCoordIds = map(coordInfoList, function (coordInfo) {
  40214. return generateCoordId(coordInfo.model);
  40215. });
  40216. each$1(coordInfoList, function (coordInfo) {
  40217. var coordModel = coordInfo.model;
  40218. var dataZoomOption = dataZoomModel.option;
  40219. register$1(
  40220. api,
  40221. {
  40222. coordId: generateCoordId(coordModel),
  40223. allCoordIds: allCoordIds,
  40224. containsPoint: function (e, x, y) {
  40225. return coordModel.coordinateSystem.containPoint([x, y]);
  40226. },
  40227. dataZoomId: dataZoomModel.id,
  40228. throttleRate: dataZoomModel.get('throttle', true),
  40229. panGetRange: bind$4(this._onPan, this, coordInfo, coordSysName),
  40230. zoomGetRange: bind$4(this._onZoom, this, coordInfo, coordSysName),
  40231. zoomLock: dataZoomOption.zoomLock,
  40232. disabled: dataZoomOption.disabled,
  40233. roamControllerOpt: {
  40234. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  40235. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  40236. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  40237. }
  40238. }
  40239. );
  40240. }, this);
  40241. }, this);
  40242. },
  40243. /**
  40244. * @override
  40245. */
  40246. dispose: function () {
  40247. unregister$1(this.api, this.dataZoomModel.id);
  40248. InsideZoomView.superApply(this, 'dispose', arguments);
  40249. this._range = null;
  40250. },
  40251. /**
  40252. * @private
  40253. */
  40254. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  40255. var range = this._range.slice();
  40256. // Calculate transform by the first axis.
  40257. var axisModel = coordInfo.axisModels[0];
  40258. if (!axisModel) {
  40259. return;
  40260. }
  40261. var directionInfo = getDirectionInfo[coordSysName](
  40262. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  40263. );
  40264. var percentDelta = directionInfo.signal
  40265. * (range[1] - range[0])
  40266. * directionInfo.pixel / directionInfo.pixelLength;
  40267. sliderMove(percentDelta, range, [0, 100], 'all');
  40268. return (this._range = range);
  40269. },
  40270. /**
  40271. * @private
  40272. */
  40273. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  40274. var range = this._range.slice();
  40275. // Calculate transform by the first axis.
  40276. var axisModel = coordInfo.axisModels[0];
  40277. if (!axisModel) {
  40278. return;
  40279. }
  40280. var directionInfo = getDirectionInfo[coordSysName](
  40281. null, [mouseX, mouseY], axisModel, controller, coordInfo
  40282. );
  40283. var percentPoint = (
  40284. directionInfo.signal > 0
  40285. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  40286. : (directionInfo.pixel - directionInfo.pixelStart)
  40287. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  40288. scale = Math.max(1 / scale, 0);
  40289. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  40290. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  40291. // Restrict range.
  40292. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  40293. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  40294. return (this._range = range);
  40295. }
  40296. });
  40297. var getDirectionInfo = {
  40298. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40299. var axis = axisModel.axis;
  40300. var ret = {};
  40301. var rect = coordInfo.model.coordinateSystem.getRect();
  40302. oldPoint = oldPoint || [0, 0];
  40303. if (axis.dim === 'x') {
  40304. ret.pixel = newPoint[0] - oldPoint[0];
  40305. ret.pixelLength = rect.width;
  40306. ret.pixelStart = rect.x;
  40307. ret.signal = axis.inverse ? 1 : -1;
  40308. }
  40309. else { // axis.dim === 'y'
  40310. ret.pixel = newPoint[1] - oldPoint[1];
  40311. ret.pixelLength = rect.height;
  40312. ret.pixelStart = rect.y;
  40313. ret.signal = axis.inverse ? -1 : 1;
  40314. }
  40315. return ret;
  40316. },
  40317. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40318. var axis = axisModel.axis;
  40319. var ret = {};
  40320. var polar = coordInfo.model.coordinateSystem;
  40321. var radiusExtent = polar.getRadiusAxis().getExtent();
  40322. var angleExtent = polar.getAngleAxis().getExtent();
  40323. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  40324. newPoint = polar.pointToCoord(newPoint);
  40325. if (axisModel.mainType === 'radiusAxis') {
  40326. ret.pixel = newPoint[0] - oldPoint[0];
  40327. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  40328. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  40329. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  40330. ret.pixelStart = radiusExtent[0];
  40331. ret.signal = axis.inverse ? 1 : -1;
  40332. }
  40333. else { // 'angleAxis'
  40334. ret.pixel = newPoint[1] - oldPoint[1];
  40335. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  40336. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  40337. ret.pixelLength = angleExtent[1] - angleExtent[0];
  40338. ret.pixelStart = angleExtent[0];
  40339. ret.signal = axis.inverse ? -1 : 1;
  40340. }
  40341. return ret;
  40342. },
  40343. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  40344. var axis = axisModel.axis;
  40345. var rect = coordInfo.model.coordinateSystem.getRect();
  40346. var ret = {};
  40347. oldPoint = oldPoint || [0, 0];
  40348. if (axis.orient === 'horizontal') {
  40349. ret.pixel = newPoint[0] - oldPoint[0];
  40350. ret.pixelLength = rect.width;
  40351. ret.pixelStart = rect.x;
  40352. ret.signal = axis.inverse ? 1 : -1;
  40353. }
  40354. else { // 'vertical'
  40355. ret.pixel = newPoint[1] - oldPoint[1];
  40356. ret.pixelLength = rect.height;
  40357. ret.pixelStart = rect.y;
  40358. ret.signal = axis.inverse ? -1 : 1;
  40359. }
  40360. return ret;
  40361. }
  40362. };
  40363. registerProcessor({
  40364. getTargetSeries: function (ecModel) {
  40365. var seriesModelMap = createHashMap();
  40366. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40367. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40368. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  40369. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  40370. seriesModelMap.set(seriesModel.uid, seriesModel);
  40371. });
  40372. });
  40373. });
  40374. return seriesModelMap;
  40375. },
  40376. isOverallFilter: true,
  40377. // Consider appendData, where filter should be performed. Because data process is
  40378. // in block mode currently, it is not need to worry about that the overallProgress
  40379. // execute every frame.
  40380. overallReset: function (ecModel, api) {
  40381. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40382. // We calculate window and reset axis here but not in model
  40383. // init stage and not after action dispatch handler, because
  40384. // reset should be called after seriesData.restoreData.
  40385. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40386. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  40387. });
  40388. // Caution: data zoom filtering is order sensitive when using
  40389. // percent range and no min/max/scale set on axis.
  40390. // For example, we have dataZoom definition:
  40391. // [
  40392. // {xAxisIndex: 0, start: 30, end: 70},
  40393. // {yAxisIndex: 0, start: 20, end: 80}
  40394. // ]
  40395. // In this case, [20, 80] of y-dataZoom should be based on data
  40396. // that have filtered by x-dataZoom using range of [30, 70],
  40397. // but should not be based on full raw data. Thus sliding
  40398. // x-dataZoom will change both ranges of xAxis and yAxis,
  40399. // while sliding y-dataZoom will only change the range of yAxis.
  40400. // So we should filter x-axis after reset x-axis immediately,
  40401. // and then reset y-axis and filter y-axis.
  40402. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  40403. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  40404. });
  40405. });
  40406. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  40407. // Fullfill all of the range props so that user
  40408. // is able to get them from chart.getOption().
  40409. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  40410. var percentRange = axisProxy.getDataPercentWindow();
  40411. var valueRange = axisProxy.getDataValueWindow();
  40412. dataZoomModel.setRawRange({
  40413. start: percentRange[0],
  40414. end: percentRange[1],
  40415. startValue: valueRange[0],
  40416. endValue: valueRange[1]
  40417. }, true);
  40418. });
  40419. }
  40420. });
  40421. registerAction('dataZoom', function (payload, ecModel) {
  40422. var linkedNodesFinder = createLinkedNodesFinder(
  40423. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  40424. eachAxisDim$1,
  40425. function (model, dimNames) {
  40426. return model.get(dimNames.axisIndex);
  40427. }
  40428. );
  40429. var effectedModels = [];
  40430. ecModel.eachComponent(
  40431. {mainType: 'dataZoom', query: payload},
  40432. function (model, index) {
  40433. effectedModels.push.apply(
  40434. effectedModels, linkedNodesFinder(model).nodes
  40435. );
  40436. }
  40437. );
  40438. each$1(effectedModels, function (dataZoomModel, index) {
  40439. dataZoomModel.setRawRange({
  40440. start: payload.start,
  40441. end: payload.end,
  40442. startValue: payload.startValue,
  40443. endValue: payload.endValue
  40444. });
  40445. });
  40446. });
  40447. /**
  40448. * DataZoom component entry
  40449. */
  40450. var features = {};
  40451. function register$2(name, ctor) {
  40452. features[name] = ctor;
  40453. }
  40454. function get$1(name) {
  40455. return features[name];
  40456. }
  40457. var ToolboxModel = extendComponentModel({
  40458. type: 'toolbox',
  40459. layoutMode: {
  40460. type: 'box',
  40461. ignoreSize: true
  40462. },
  40463. mergeDefaultAndTheme: function (option) {
  40464. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  40465. each$1(this.option.feature, function (featureOpt, featureName) {
  40466. var Feature = get$1(featureName);
  40467. Feature && merge(featureOpt, Feature.defaultOption);
  40468. });
  40469. },
  40470. defaultOption: {
  40471. show: true,
  40472. z: 6,
  40473. zlevel: 0,
  40474. orient: 'horizontal',
  40475. left: 'right',
  40476. top: 'top',
  40477. // right
  40478. // bottom
  40479. backgroundColor: 'transparent',
  40480. borderColor: '#ccc',
  40481. borderRadius: 0,
  40482. borderWidth: 0,
  40483. padding: 5,
  40484. itemSize: 15,
  40485. itemGap: 8,
  40486. showTitle: true,
  40487. iconStyle: {
  40488. borderColor: '#666',
  40489. color: 'none'
  40490. },
  40491. emphasis: {
  40492. iconStyle: {
  40493. borderColor: '#3E98C5'
  40494. }
  40495. }
  40496. // textStyle: {},
  40497. // feature
  40498. }
  40499. });
  40500. extendComponentView({
  40501. type: 'toolbox',
  40502. render: function (toolboxModel, ecModel, api, payload) {
  40503. var group = this.group;
  40504. group.removeAll();
  40505. if (!toolboxModel.get('show')) {
  40506. return;
  40507. }
  40508. var itemSize = +toolboxModel.get('itemSize');
  40509. var featureOpts = toolboxModel.get('feature') || {};
  40510. var features = this._features || (this._features = {});
  40511. var featureNames = [];
  40512. each$1(featureOpts, function (opt, name) {
  40513. featureNames.push(name);
  40514. });
  40515. (new DataDiffer(this._featureNames || [], featureNames))
  40516. .add(processFeature)
  40517. .update(processFeature)
  40518. .remove(curry(processFeature, null))
  40519. .execute();
  40520. // Keep for diff.
  40521. this._featureNames = featureNames;
  40522. function processFeature(newIndex, oldIndex) {
  40523. var featureName = featureNames[newIndex];
  40524. var oldName = featureNames[oldIndex];
  40525. var featureOpt = featureOpts[featureName];
  40526. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  40527. var feature;
  40528. if (featureName && !oldName) { // Create
  40529. if (isUserFeatureName(featureName)) {
  40530. feature = {
  40531. model: featureModel,
  40532. onclick: featureModel.option.onclick,
  40533. featureName: featureName
  40534. };
  40535. }
  40536. else {
  40537. var Feature = get$1(featureName);
  40538. if (!Feature) {
  40539. return;
  40540. }
  40541. feature = new Feature(featureModel, ecModel, api);
  40542. }
  40543. features[featureName] = feature;
  40544. }
  40545. else {
  40546. feature = features[oldName];
  40547. // If feature does not exsit.
  40548. if (!feature) {
  40549. return;
  40550. }
  40551. feature.model = featureModel;
  40552. feature.ecModel = ecModel;
  40553. feature.api = api;
  40554. }
  40555. if (!featureName && oldName) {
  40556. feature.dispose && feature.dispose(ecModel, api);
  40557. return;
  40558. }
  40559. if (!featureModel.get('show') || feature.unusable) {
  40560. feature.remove && feature.remove(ecModel, api);
  40561. return;
  40562. }
  40563. createIconPaths(featureModel, feature, featureName);
  40564. featureModel.setIconStatus = function (iconName, status) {
  40565. var option = this.option;
  40566. var iconPaths = this.iconPaths;
  40567. option.iconStatus = option.iconStatus || {};
  40568. option.iconStatus[iconName] = status;
  40569. // FIXME
  40570. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  40571. };
  40572. if (feature.render) {
  40573. feature.render(featureModel, ecModel, api, payload);
  40574. }
  40575. }
  40576. function createIconPaths(featureModel, feature, featureName) {
  40577. var iconStyleModel = featureModel.getModel('iconStyle');
  40578. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  40579. // If one feature has mutiple icon. they are orginaized as
  40580. // {
  40581. // icon: {
  40582. // foo: '',
  40583. // bar: ''
  40584. // },
  40585. // title: {
  40586. // foo: '',
  40587. // bar: ''
  40588. // }
  40589. // }
  40590. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  40591. var titles = featureModel.get('title') || {};
  40592. if (typeof icons === 'string') {
  40593. var icon = icons;
  40594. var title = titles;
  40595. icons = {};
  40596. titles = {};
  40597. icons[featureName] = icon;
  40598. titles[featureName] = title;
  40599. }
  40600. var iconPaths = featureModel.iconPaths = {};
  40601. each$1(icons, function (iconStr, iconName) {
  40602. var path = createIcon(
  40603. iconStr,
  40604. {},
  40605. {
  40606. x: -itemSize / 2,
  40607. y: -itemSize / 2,
  40608. width: itemSize,
  40609. height: itemSize
  40610. }
  40611. );
  40612. path.setStyle(iconStyleModel.getItemStyle());
  40613. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  40614. setHoverStyle(path);
  40615. if (toolboxModel.get('showTitle')) {
  40616. path.__title = titles[iconName];
  40617. path.on('mouseover', function () {
  40618. // Should not reuse above hoverStyle, which might be modified.
  40619. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  40620. path.setStyle({
  40621. text: titles[iconName],
  40622. textPosition: hoverStyle.textPosition || 'bottom',
  40623. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  40624. textAlign: hoverStyle.textAlign || 'center'
  40625. });
  40626. })
  40627. .on('mouseout', function () {
  40628. path.setStyle({
  40629. textFill: null
  40630. });
  40631. });
  40632. }
  40633. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  40634. group.add(path);
  40635. path.on('click', bind(
  40636. feature.onclick, feature, ecModel, api, iconName
  40637. ));
  40638. iconPaths[iconName] = path;
  40639. });
  40640. }
  40641. layout$2(group, toolboxModel, api);
  40642. // Render background after group is layout
  40643. // FIXME
  40644. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  40645. // Adjust icon title positions to avoid them out of screen
  40646. group.eachChild(function (icon) {
  40647. var titleText = icon.__title;
  40648. var hoverStyle = icon.hoverStyle;
  40649. // May be background element
  40650. if (hoverStyle && titleText) {
  40651. var rect = getBoundingRect(
  40652. titleText, makeFont(hoverStyle)
  40653. );
  40654. var offsetX = icon.position[0] + group.position[0];
  40655. var offsetY = icon.position[1] + group.position[1] + itemSize;
  40656. var needPutOnTop = false;
  40657. if (offsetY + rect.height > api.getHeight()) {
  40658. hoverStyle.textPosition = 'top';
  40659. needPutOnTop = true;
  40660. }
  40661. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  40662. if (offsetX + rect.width / 2 > api.getWidth()) {
  40663. hoverStyle.textPosition = ['100%', topOffset];
  40664. hoverStyle.textAlign = 'right';
  40665. }
  40666. else if (offsetX - rect.width / 2 < 0) {
  40667. hoverStyle.textPosition = [0, topOffset];
  40668. hoverStyle.textAlign = 'left';
  40669. }
  40670. }
  40671. });
  40672. },
  40673. updateView: function (toolboxModel, ecModel, api, payload) {
  40674. each$1(this._features, function (feature) {
  40675. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  40676. });
  40677. },
  40678. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  40679. // zrUtil.each(this._features, function (feature) {
  40680. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  40681. // });
  40682. // },
  40683. remove: function (ecModel, api) {
  40684. each$1(this._features, function (feature) {
  40685. feature.remove && feature.remove(ecModel, api);
  40686. });
  40687. this.group.removeAll();
  40688. },
  40689. dispose: function (ecModel, api) {
  40690. each$1(this._features, function (feature) {
  40691. feature.dispose && feature.dispose(ecModel, api);
  40692. });
  40693. }
  40694. });
  40695. function isUserFeatureName(featureName) {
  40696. return featureName.indexOf('my') === 0;
  40697. }
  40698. var saveAsImageLang = lang.toolbox.saveAsImage;
  40699. function SaveAsImage(model) {
  40700. this.model = model;
  40701. }
  40702. SaveAsImage.defaultOption = {
  40703. show: true,
  40704. 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',
  40705. title: saveAsImageLang.title,
  40706. type: 'png',
  40707. // Default use option.backgroundColor
  40708. // backgroundColor: '#fff',
  40709. name: '',
  40710. excludeComponents: ['toolbox'],
  40711. pixelRatio: 1,
  40712. lang: saveAsImageLang.lang.slice()
  40713. };
  40714. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  40715. var proto$2 = SaveAsImage.prototype;
  40716. proto$2.onclick = function (ecModel, api) {
  40717. var model = this.model;
  40718. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  40719. var $a = document.createElement('a');
  40720. var type = model.get('type', true) || 'png';
  40721. $a.download = title + '.' + type;
  40722. $a.target = '_blank';
  40723. var url = api.getConnectedDataURL({
  40724. type: type,
  40725. backgroundColor: model.get('backgroundColor', true)
  40726. || ecModel.get('backgroundColor') || '#fff',
  40727. excludeComponents: model.get('excludeComponents'),
  40728. pixelRatio: model.get('pixelRatio')
  40729. });
  40730. $a.href = url;
  40731. // Chrome and Firefox
  40732. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  40733. var evt = new MouseEvent('click', {
  40734. view: window,
  40735. bubbles: true,
  40736. cancelable: false
  40737. });
  40738. $a.dispatchEvent(evt);
  40739. }
  40740. // IE
  40741. else {
  40742. if (window.navigator.msSaveOrOpenBlob) {
  40743. var bstr = atob(url.split(',')[1]);
  40744. var n = bstr.length;
  40745. var u8arr = new Uint8Array(n);
  40746. while(n--) {
  40747. u8arr[n] = bstr.charCodeAt(n);
  40748. }
  40749. var blob = new Blob([u8arr]);
  40750. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  40751. }
  40752. else {
  40753. var lang$$1 = model.get('lang');
  40754. var html = '' +
  40755. '<body style="margin:0;">' +
  40756. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  40757. '</body>';
  40758. var tab = window.open();
  40759. tab.document.write(html);
  40760. }
  40761. }
  40762. };
  40763. register$2(
  40764. 'saveAsImage', SaveAsImage
  40765. );
  40766. var magicTypeLang = lang.toolbox.magicType;
  40767. function MagicType(model) {
  40768. this.model = model;
  40769. }
  40770. MagicType.defaultOption = {
  40771. show: true,
  40772. type: [],
  40773. // Icon group
  40774. icon: {
  40775. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  40776. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  40777. 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
  40778. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  40779. },
  40780. // `line`, `bar`, `stack`, `tiled`
  40781. title: clone(magicTypeLang.title),
  40782. option: {},
  40783. seriesIndex: {}
  40784. };
  40785. var proto$3 = MagicType.prototype;
  40786. proto$3.getIcons = function () {
  40787. var model = this.model;
  40788. var availableIcons = model.get('icon');
  40789. var icons = {};
  40790. each$1(model.get('type'), function (type) {
  40791. if (availableIcons[type]) {
  40792. icons[type] = availableIcons[type];
  40793. }
  40794. });
  40795. return icons;
  40796. };
  40797. var seriesOptGenreator = {
  40798. 'line': function (seriesType, seriesId, seriesModel, model) {
  40799. if (seriesType === 'bar') {
  40800. return merge({
  40801. id: seriesId,
  40802. type: 'line',
  40803. // Preserve data related option
  40804. data: seriesModel.get('data'),
  40805. stack: seriesModel.get('stack'),
  40806. markPoint: seriesModel.get('markPoint'),
  40807. markLine: seriesModel.get('markLine')
  40808. }, model.get('option.line') || {}, true);
  40809. }
  40810. },
  40811. 'bar': function (seriesType, seriesId, seriesModel, model) {
  40812. if (seriesType === 'line') {
  40813. return merge({
  40814. id: seriesId,
  40815. type: 'bar',
  40816. // Preserve data related option
  40817. data: seriesModel.get('data'),
  40818. stack: seriesModel.get('stack'),
  40819. markPoint: seriesModel.get('markPoint'),
  40820. markLine: seriesModel.get('markLine')
  40821. }, model.get('option.bar') || {}, true);
  40822. }
  40823. },
  40824. 'stack': function (seriesType, seriesId, seriesModel, model) {
  40825. if (seriesType === 'line' || seriesType === 'bar') {
  40826. return merge({
  40827. id: seriesId,
  40828. stack: '__ec_magicType_stack__'
  40829. }, model.get('option.stack') || {}, true);
  40830. }
  40831. },
  40832. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  40833. if (seriesType === 'line' || seriesType === 'bar') {
  40834. return merge({
  40835. id: seriesId,
  40836. stack: ''
  40837. }, model.get('option.tiled') || {}, true);
  40838. }
  40839. }
  40840. };
  40841. var radioTypes = [
  40842. ['line', 'bar'],
  40843. ['stack', 'tiled']
  40844. ];
  40845. proto$3.onclick = function (ecModel, api, type) {
  40846. var model = this.model;
  40847. var seriesIndex = model.get('seriesIndex.' + type);
  40848. // Not supported magicType
  40849. if (!seriesOptGenreator[type]) {
  40850. return;
  40851. }
  40852. var newOption = {
  40853. series: []
  40854. };
  40855. var generateNewSeriesTypes = function (seriesModel) {
  40856. var seriesType = seriesModel.subType;
  40857. var seriesId = seriesModel.id;
  40858. var newSeriesOpt = seriesOptGenreator[type](
  40859. seriesType, seriesId, seriesModel, model
  40860. );
  40861. if (newSeriesOpt) {
  40862. // PENDING If merge original option?
  40863. defaults(newSeriesOpt, seriesModel.option);
  40864. newOption.series.push(newSeriesOpt);
  40865. }
  40866. // Modify boundaryGap
  40867. var coordSys = seriesModel.coordinateSystem;
  40868. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  40869. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  40870. if (categoryAxis) {
  40871. var axisDim = categoryAxis.dim;
  40872. var axisType = axisDim + 'Axis';
  40873. var axisModel = ecModel.queryComponents({
  40874. mainType: axisType,
  40875. index: seriesModel.get(name + 'Index'),
  40876. id: seriesModel.get(name + 'Id')
  40877. })[0];
  40878. var axisIndex = axisModel.componentIndex;
  40879. newOption[axisType] = newOption[axisType] || [];
  40880. for (var i = 0; i <= axisIndex; i++) {
  40881. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  40882. }
  40883. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  40884. }
  40885. }
  40886. };
  40887. each$1(radioTypes, function (radio) {
  40888. if (indexOf(radio, type) >= 0) {
  40889. each$1(radio, function (item) {
  40890. model.setIconStatus(item, 'normal');
  40891. });
  40892. }
  40893. });
  40894. model.setIconStatus(type, 'emphasis');
  40895. ecModel.eachComponent(
  40896. {
  40897. mainType: 'series',
  40898. query: seriesIndex == null ? null : {
  40899. seriesIndex: seriesIndex
  40900. }
  40901. }, generateNewSeriesTypes
  40902. );
  40903. api.dispatchAction({
  40904. type: 'changeMagicType',
  40905. currentType: type,
  40906. newOption: newOption
  40907. });
  40908. };
  40909. registerAction({
  40910. type: 'changeMagicType',
  40911. event: 'magicTypeChanged',
  40912. update: 'prepareAndUpdate'
  40913. }, function (payload, ecModel) {
  40914. ecModel.mergeOption(payload.newOption);
  40915. });
  40916. register$2('magicType', MagicType);
  40917. var dataViewLang = lang.toolbox.dataView;
  40918. var BLOCK_SPLITER = new Array(60).join('-');
  40919. var ITEM_SPLITER = '\t';
  40920. /**
  40921. * Group series into two types
  40922. * 1. on category axis, like line, bar
  40923. * 2. others, like scatter, pie
  40924. * @param {module:echarts/model/Global} ecModel
  40925. * @return {Object}
  40926. * @inner
  40927. */
  40928. function groupSeries(ecModel) {
  40929. var seriesGroupByCategoryAxis = {};
  40930. var otherSeries = [];
  40931. var meta = [];
  40932. ecModel.eachRawSeries(function (seriesModel) {
  40933. var coordSys = seriesModel.coordinateSystem;
  40934. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  40935. var baseAxis = coordSys.getBaseAxis();
  40936. if (baseAxis.type === 'category') {
  40937. var key = baseAxis.dim + '_' + baseAxis.index;
  40938. if (!seriesGroupByCategoryAxis[key]) {
  40939. seriesGroupByCategoryAxis[key] = {
  40940. categoryAxis: baseAxis,
  40941. valueAxis: coordSys.getOtherAxis(baseAxis),
  40942. series: []
  40943. };
  40944. meta.push({
  40945. axisDim: baseAxis.dim,
  40946. axisIndex: baseAxis.index
  40947. });
  40948. }
  40949. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  40950. }
  40951. else {
  40952. otherSeries.push(seriesModel);
  40953. }
  40954. }
  40955. else {
  40956. otherSeries.push(seriesModel);
  40957. }
  40958. });
  40959. return {
  40960. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  40961. other: otherSeries,
  40962. meta: meta
  40963. };
  40964. }
  40965. /**
  40966. * Assemble content of series on cateogory axis
  40967. * @param {Array.<module:echarts/model/Series>} series
  40968. * @return {string}
  40969. * @inner
  40970. */
  40971. function assembleSeriesWithCategoryAxis(series) {
  40972. var tables = [];
  40973. each$1(series, function (group, key) {
  40974. var categoryAxis = group.categoryAxis;
  40975. var valueAxis = group.valueAxis;
  40976. var valueAxisDim = valueAxis.dim;
  40977. var headers = [' '].concat(map(group.series, function (series) {
  40978. return series.name;
  40979. }));
  40980. var columns = [categoryAxis.model.getCategories()];
  40981. each$1(group.series, function (series) {
  40982. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  40983. return val;
  40984. }));
  40985. });
  40986. // Assemble table content
  40987. var lines = [headers.join(ITEM_SPLITER)];
  40988. for (var i = 0; i < columns[0].length; i++) {
  40989. var items = [];
  40990. for (var j = 0; j < columns.length; j++) {
  40991. items.push(columns[j][i]);
  40992. }
  40993. lines.push(items.join(ITEM_SPLITER));
  40994. }
  40995. tables.push(lines.join('\n'));
  40996. });
  40997. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  40998. }
  40999. /**
  41000. * Assemble content of other series
  41001. * @param {Array.<module:echarts/model/Series>} series
  41002. * @return {string}
  41003. * @inner
  41004. */
  41005. function assembleOtherSeries(series) {
  41006. return map(series, function (series) {
  41007. var data = series.getRawData();
  41008. var lines = [series.name];
  41009. var vals = [];
  41010. data.each(data.dimensions, function () {
  41011. var argLen = arguments.length;
  41012. var dataIndex = arguments[argLen - 1];
  41013. var name = data.getName(dataIndex);
  41014. for (var i = 0; i < argLen - 1; i++) {
  41015. vals[i] = arguments[i];
  41016. }
  41017. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  41018. });
  41019. return lines.join('\n');
  41020. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  41021. }
  41022. /**
  41023. * @param {module:echarts/model/Global}
  41024. * @return {Object}
  41025. * @inner
  41026. */
  41027. function getContentFromModel(ecModel) {
  41028. var result = groupSeries(ecModel);
  41029. return {
  41030. value: filter([
  41031. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  41032. assembleOtherSeries(result.other)
  41033. ], function (str) {
  41034. return str.replace(/[\n\t\s]/g, '');
  41035. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  41036. meta: result.meta
  41037. };
  41038. }
  41039. function trim$1(str) {
  41040. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  41041. }
  41042. /**
  41043. * If a block is tsv format
  41044. */
  41045. function isTSVFormat(block) {
  41046. // Simple method to find out if a block is tsv format
  41047. var firstLine = block.slice(0, block.indexOf('\n'));
  41048. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  41049. return true;
  41050. }
  41051. }
  41052. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  41053. /**
  41054. * @param {string} tsv
  41055. * @return {Object}
  41056. */
  41057. function parseTSVContents(tsv) {
  41058. var tsvLines = tsv.split(/\n+/g);
  41059. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  41060. var categories = [];
  41061. var series = map(headers, function (header) {
  41062. return {
  41063. name: header,
  41064. data: []
  41065. };
  41066. });
  41067. for (var i = 0; i < tsvLines.length; i++) {
  41068. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  41069. categories.push(items.shift());
  41070. for (var j = 0; j < items.length; j++) {
  41071. series[j] && (series[j].data[i] = items[j]);
  41072. }
  41073. }
  41074. return {
  41075. series: series,
  41076. categories: categories
  41077. };
  41078. }
  41079. /**
  41080. * @param {string} str
  41081. * @return {Array.<Object>}
  41082. * @inner
  41083. */
  41084. function parseListContents(str) {
  41085. var lines = str.split(/\n+/g);
  41086. var seriesName = trim$1(lines.shift());
  41087. var data = [];
  41088. for (var i = 0; i < lines.length; i++) {
  41089. var items = trim$1(lines[i]).split(itemSplitRegex);
  41090. var name = '';
  41091. var value;
  41092. var hasName = false;
  41093. if (isNaN(items[0])) { // First item is name
  41094. hasName = true;
  41095. name = items[0];
  41096. items = items.slice(1);
  41097. data[i] = {
  41098. name: name,
  41099. value: []
  41100. };
  41101. value = data[i].value;
  41102. }
  41103. else {
  41104. value = data[i] = [];
  41105. }
  41106. for (var j = 0; j < items.length; j++) {
  41107. value.push(+items[j]);
  41108. }
  41109. if (value.length === 1) {
  41110. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  41111. }
  41112. }
  41113. return {
  41114. name: seriesName,
  41115. data: data
  41116. };
  41117. }
  41118. /**
  41119. * @param {string} str
  41120. * @param {Array.<Object>} blockMetaList
  41121. * @return {Object}
  41122. * @inner
  41123. */
  41124. function parseContents(str, blockMetaList) {
  41125. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  41126. var newOption = {
  41127. series: []
  41128. };
  41129. each$1(blocks, function (block, idx) {
  41130. if (isTSVFormat(block)) {
  41131. var result = parseTSVContents(block);
  41132. var blockMeta = blockMetaList[idx];
  41133. var axisKey = blockMeta.axisDim + 'Axis';
  41134. if (blockMeta) {
  41135. newOption[axisKey] = newOption[axisKey] || [];
  41136. newOption[axisKey][blockMeta.axisIndex] = {
  41137. data: result.categories
  41138. };
  41139. newOption.series = newOption.series.concat(result.series);
  41140. }
  41141. }
  41142. else {
  41143. var result = parseListContents(block);
  41144. newOption.series.push(result);
  41145. }
  41146. });
  41147. return newOption;
  41148. }
  41149. /**
  41150. * @alias {module:echarts/component/toolbox/feature/DataView}
  41151. * @constructor
  41152. * @param {module:echarts/model/Model} model
  41153. */
  41154. function DataView(model) {
  41155. this._dom = null;
  41156. this.model = model;
  41157. }
  41158. DataView.defaultOption = {
  41159. show: true,
  41160. readOnly: false,
  41161. optionToContent: null,
  41162. contentToOption: null,
  41163. 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',
  41164. title: clone(dataViewLang.title),
  41165. lang: clone(dataViewLang.lang),
  41166. backgroundColor: '#fff',
  41167. textColor: '#000',
  41168. textareaColor: '#fff',
  41169. textareaBorderColor: '#333',
  41170. buttonColor: '#c23531',
  41171. buttonTextColor: '#fff'
  41172. };
  41173. DataView.prototype.onclick = function (ecModel, api) {
  41174. var container = api.getDom();
  41175. var model = this.model;
  41176. if (this._dom) {
  41177. container.removeChild(this._dom);
  41178. }
  41179. var root = document.createElement('div');
  41180. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  41181. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  41182. // Create elements
  41183. var header = document.createElement('h4');
  41184. var lang$$1 = model.get('lang') || [];
  41185. header.innerHTML = lang$$1[0] || model.get('title');
  41186. header.style.cssText = 'margin: 10px 20px;';
  41187. header.style.color = model.get('textColor');
  41188. var viewMain = document.createElement('div');
  41189. var textarea = document.createElement('textarea');
  41190. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  41191. var optionToContent = model.get('optionToContent');
  41192. var contentToOption = model.get('contentToOption');
  41193. var result = getContentFromModel(ecModel);
  41194. if (typeof optionToContent === 'function') {
  41195. var htmlOrDom = optionToContent(api.getOption());
  41196. if (typeof htmlOrDom === 'string') {
  41197. viewMain.innerHTML = htmlOrDom;
  41198. }
  41199. else if (isDom(htmlOrDom)) {
  41200. viewMain.appendChild(htmlOrDom);
  41201. }
  41202. }
  41203. else {
  41204. // Use default textarea
  41205. viewMain.appendChild(textarea);
  41206. textarea.readOnly = model.get('readOnly');
  41207. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  41208. textarea.style.color = model.get('textColor');
  41209. textarea.style.borderColor = model.get('textareaBorderColor');
  41210. textarea.style.backgroundColor = model.get('textareaColor');
  41211. textarea.value = result.value;
  41212. }
  41213. var blockMetaList = result.meta;
  41214. var buttonContainer = document.createElement('div');
  41215. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  41216. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  41217. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  41218. var closeButton = document.createElement('div');
  41219. var refreshButton = document.createElement('div');
  41220. buttonStyle += ';background-color:' + model.get('buttonColor');
  41221. buttonStyle += ';color:' + model.get('buttonTextColor');
  41222. var self = this;
  41223. function close() {
  41224. container.removeChild(root);
  41225. self._dom = null;
  41226. }
  41227. addEventListener(closeButton, 'click', close);
  41228. addEventListener(refreshButton, 'click', function () {
  41229. var newOption;
  41230. try {
  41231. if (typeof contentToOption === 'function') {
  41232. newOption = contentToOption(viewMain, api.getOption());
  41233. }
  41234. else {
  41235. newOption = parseContents(textarea.value, blockMetaList);
  41236. }
  41237. }
  41238. catch (e) {
  41239. close();
  41240. throw new Error('Data view format error ' + e);
  41241. }
  41242. if (newOption) {
  41243. api.dispatchAction({
  41244. type: 'changeDataView',
  41245. newOption: newOption
  41246. });
  41247. }
  41248. close();
  41249. });
  41250. closeButton.innerHTML = lang$$1[1];
  41251. refreshButton.innerHTML = lang$$1[2];
  41252. refreshButton.style.cssText = buttonStyle;
  41253. closeButton.style.cssText = buttonStyle;
  41254. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  41255. buttonContainer.appendChild(closeButton);
  41256. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  41257. addEventListener(textarea, 'keydown', function (e) {
  41258. if ((e.keyCode || e.which) === 9) {
  41259. // get caret position/selection
  41260. var val = this.value;
  41261. var start = this.selectionStart;
  41262. var end = this.selectionEnd;
  41263. // set textarea value to: text before caret + tab + text after caret
  41264. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  41265. // put caret at right position again
  41266. this.selectionStart = this.selectionEnd = start + 1;
  41267. // prevent the focus lose
  41268. stop(e);
  41269. }
  41270. });
  41271. root.appendChild(header);
  41272. root.appendChild(viewMain);
  41273. root.appendChild(buttonContainer);
  41274. viewMain.style.height = (container.clientHeight - 80) + 'px';
  41275. container.appendChild(root);
  41276. this._dom = root;
  41277. };
  41278. DataView.prototype.remove = function (ecModel, api) {
  41279. this._dom && api.getDom().removeChild(this._dom);
  41280. };
  41281. DataView.prototype.dispose = function (ecModel, api) {
  41282. this.remove(ecModel, api);
  41283. };
  41284. /**
  41285. * @inner
  41286. */
  41287. function tryMergeDataOption(newData, originalData) {
  41288. return map(newData, function (newVal, idx) {
  41289. var original = originalData && originalData[idx];
  41290. if (isObject$1(original) && !isArray(original)) {
  41291. if (isObject$1(newVal) && !isArray(newVal)) {
  41292. newVal = newVal.value;
  41293. }
  41294. // Original data has option
  41295. return defaults({
  41296. value: newVal
  41297. }, original);
  41298. }
  41299. else {
  41300. return newVal;
  41301. }
  41302. });
  41303. }
  41304. register$2('dataView', DataView);
  41305. registerAction({
  41306. type: 'changeDataView',
  41307. event: 'dataViewChanged',
  41308. update: 'prepareAndUpdate'
  41309. }, function (payload, ecModel) {
  41310. var newSeriesOptList = [];
  41311. each$1(payload.newOption.series, function (seriesOpt) {
  41312. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  41313. if (!seriesModel) {
  41314. // New created series
  41315. // Geuss the series type
  41316. newSeriesOptList.push(extend({
  41317. // Default is scatter
  41318. type: 'scatter'
  41319. }, seriesOpt));
  41320. }
  41321. else {
  41322. var originalData = seriesModel.get('data');
  41323. newSeriesOptList.push({
  41324. name: seriesOpt.name,
  41325. data: tryMergeDataOption(seriesOpt.data, originalData)
  41326. });
  41327. }
  41328. });
  41329. ecModel.mergeOption(defaults({
  41330. series: newSeriesOptList
  41331. }, payload.newOption));
  41332. });
  41333. var curry$6 = curry;
  41334. var each$17 = each$1;
  41335. var map$2 = map;
  41336. var mathMin$4 = Math.min;
  41337. var mathMax$4 = Math.max;
  41338. var mathPow$2 = Math.pow;
  41339. var COVER_Z = 10000;
  41340. var UNSELECT_THRESHOLD = 6;
  41341. var MIN_RESIZE_LINE_WIDTH = 6;
  41342. var MUTEX_RESOURCE_KEY = 'globalPan';
  41343. var DIRECTION_MAP = {
  41344. w: [0, 0],
  41345. e: [0, 1],
  41346. n: [1, 0],
  41347. s: [1, 1]
  41348. };
  41349. var CURSOR_MAP = {
  41350. w: 'ew',
  41351. e: 'ew',
  41352. n: 'ns',
  41353. s: 'ns',
  41354. ne: 'nesw',
  41355. sw: 'nesw',
  41356. nw: 'nwse',
  41357. se: 'nwse'
  41358. };
  41359. var DEFAULT_BRUSH_OPT = {
  41360. brushStyle: {
  41361. lineWidth: 2,
  41362. stroke: 'rgba(0,0,0,0.3)',
  41363. fill: 'rgba(0,0,0,0.1)'
  41364. },
  41365. transformable: true,
  41366. brushMode: 'single',
  41367. removeOnClick: false
  41368. };
  41369. var baseUID = 0;
  41370. /**
  41371. * @alias module:echarts/component/helper/BrushController
  41372. * @constructor
  41373. * @mixin {module:zrender/mixin/Eventful}
  41374. * @event module:echarts/component/helper/BrushController#brush
  41375. * params:
  41376. * areas: Array.<Array>, coord relates to container group,
  41377. * If no container specified, to global.
  41378. * opt {
  41379. * isEnd: boolean,
  41380. * removeOnClick: boolean
  41381. * }
  41382. *
  41383. * @param {module:zrender/zrender~ZRender} zr
  41384. */
  41385. function BrushController(zr) {
  41386. if (__DEV__) {
  41387. assert$1(zr);
  41388. }
  41389. Eventful.call(this);
  41390. /**
  41391. * @type {module:zrender/zrender~ZRender}
  41392. * @private
  41393. */
  41394. this._zr = zr;
  41395. /**
  41396. * @type {module:zrender/container/Group}
  41397. * @readOnly
  41398. */
  41399. this.group = new Group();
  41400. /**
  41401. * Only for drawing (after enabledBrush).
  41402. * 'line', 'rect', 'polygon' or false
  41403. * If passing false/null/undefined, disable brush.
  41404. * If passing 'auto', determined by panel.defaultBrushType
  41405. * @private
  41406. * @type {string}
  41407. */
  41408. this._brushType;
  41409. /**
  41410. * Only for drawing (after enabledBrush).
  41411. *
  41412. * @private
  41413. * @type {Object}
  41414. */
  41415. this._brushOption;
  41416. /**
  41417. * @private
  41418. * @type {Object}
  41419. */
  41420. this._panels;
  41421. /**
  41422. * @private
  41423. * @type {Array.<nubmer>}
  41424. */
  41425. this._track = [];
  41426. /**
  41427. * @private
  41428. * @type {boolean}
  41429. */
  41430. this._dragging;
  41431. /**
  41432. * @private
  41433. * @type {Array}
  41434. */
  41435. this._covers = [];
  41436. /**
  41437. * @private
  41438. * @type {moudule:zrender/container/Group}
  41439. */
  41440. this._creatingCover;
  41441. /**
  41442. * `true` means global panel
  41443. * @private
  41444. * @type {module:zrender/container/Group|boolean}
  41445. */
  41446. this._creatingPanel;
  41447. /**
  41448. * @private
  41449. * @type {boolean}
  41450. */
  41451. this._enableGlobalPan;
  41452. /**
  41453. * @private
  41454. * @type {boolean}
  41455. */
  41456. if (__DEV__) {
  41457. this._mounted;
  41458. }
  41459. /**
  41460. * @private
  41461. * @type {string}
  41462. */
  41463. this._uid = 'brushController_' + baseUID++;
  41464. /**
  41465. * @private
  41466. * @type {Object}
  41467. */
  41468. this._handlers = {};
  41469. each$17(mouseHandlers, function (handler, eventName) {
  41470. this._handlers[eventName] = bind(handler, this);
  41471. }, this);
  41472. }
  41473. BrushController.prototype = {
  41474. constructor: BrushController,
  41475. /**
  41476. * If set to null/undefined/false, select disabled.
  41477. * @param {Object} brushOption
  41478. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  41479. * If passing false/null/undefined, disable brush.
  41480. * If passing 'auto', determined by panel.defaultBrushType.
  41481. * ('auto' can not be used in global panel)
  41482. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  41483. * @param {boolean} [brushOption.transformable=true]
  41484. * @param {boolean} [brushOption.removeOnClick=false]
  41485. * @param {Object} [brushOption.brushStyle]
  41486. * @param {number} [brushOption.brushStyle.width]
  41487. * @param {number} [brushOption.brushStyle.lineWidth]
  41488. * @param {string} [brushOption.brushStyle.stroke]
  41489. * @param {string} [brushOption.brushStyle.fill]
  41490. * @param {number} [brushOption.z]
  41491. */
  41492. enableBrush: function (brushOption) {
  41493. if (__DEV__) {
  41494. assert$1(this._mounted);
  41495. }
  41496. this._brushType && doDisableBrush(this);
  41497. brushOption.brushType && doEnableBrush(this, brushOption);
  41498. return this;
  41499. },
  41500. /**
  41501. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  41502. * Each items: {
  41503. * panelId, // mandatory.
  41504. * clipPath, // mandatory. function.
  41505. * isTargetByCursor, // mandatory. function.
  41506. * defaultBrushType, // optional, only used when brushType is 'auto'.
  41507. * getLinearBrushOtherExtent, // optional. function.
  41508. * }
  41509. */
  41510. setPanels: function (panelOpts) {
  41511. if (panelOpts && panelOpts.length) {
  41512. var panels = this._panels = {};
  41513. each$1(panelOpts, function (panelOpts) {
  41514. panels[panelOpts.panelId] = clone(panelOpts);
  41515. });
  41516. }
  41517. else {
  41518. this._panels = null;
  41519. }
  41520. return this;
  41521. },
  41522. /**
  41523. * @param {Object} [opt]
  41524. * @return {boolean} [opt.enableGlobalPan=false]
  41525. */
  41526. mount: function (opt) {
  41527. opt = opt || {};
  41528. if (__DEV__) {
  41529. this._mounted = true; // should be at first.
  41530. }
  41531. this._enableGlobalPan = opt.enableGlobalPan;
  41532. var thisGroup = this.group;
  41533. this._zr.add(thisGroup);
  41534. thisGroup.attr({
  41535. position: opt.position || [0, 0],
  41536. rotation: opt.rotation || 0,
  41537. scale: opt.scale || [1, 1]
  41538. });
  41539. this._transform = thisGroup.getLocalTransform();
  41540. return this;
  41541. },
  41542. eachCover: function (cb, context) {
  41543. each$17(this._covers, cb, context);
  41544. },
  41545. /**
  41546. * Update covers.
  41547. * @param {Array.<Object>} brushOptionList Like:
  41548. * [
  41549. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  41550. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  41551. * ...
  41552. * ]
  41553. * `brushType` is required in each cover info. (can not be 'auto')
  41554. * `id` is not mandatory.
  41555. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  41556. * If brushOptionList is null/undefined, all covers removed.
  41557. */
  41558. updateCovers: function (brushOptionList) {
  41559. if (__DEV__) {
  41560. assert$1(this._mounted);
  41561. }
  41562. brushOptionList = map(brushOptionList, function (brushOption) {
  41563. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  41564. });
  41565. var tmpIdPrefix = '\0-brush-index-';
  41566. var oldCovers = this._covers;
  41567. var newCovers = this._covers = [];
  41568. var controller = this;
  41569. var creatingCover = this._creatingCover;
  41570. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  41571. .add(addOrUpdate)
  41572. .update(addOrUpdate)
  41573. .remove(remove)
  41574. .execute();
  41575. return this;
  41576. function getKey(brushOption, index) {
  41577. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  41578. + '-' + brushOption.brushType;
  41579. }
  41580. function oldGetKey(cover, index) {
  41581. return getKey(cover.__brushOption, index);
  41582. }
  41583. function addOrUpdate(newIndex, oldIndex) {
  41584. var newBrushOption = brushOptionList[newIndex];
  41585. // Consider setOption in event listener of brushSelect,
  41586. // where updating cover when creating should be forbiden.
  41587. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  41588. newCovers[newIndex] = oldCovers[oldIndex];
  41589. }
  41590. else {
  41591. var cover = newCovers[newIndex] = oldIndex != null
  41592. ? (
  41593. oldCovers[oldIndex].__brushOption = newBrushOption,
  41594. oldCovers[oldIndex]
  41595. )
  41596. : endCreating(controller, createCover(controller, newBrushOption));
  41597. updateCoverAfterCreation(controller, cover);
  41598. }
  41599. }
  41600. function remove(oldIndex) {
  41601. if (oldCovers[oldIndex] !== creatingCover) {
  41602. controller.group.remove(oldCovers[oldIndex]);
  41603. }
  41604. }
  41605. },
  41606. unmount: function () {
  41607. if (__DEV__) {
  41608. if (!this._mounted) {
  41609. return;
  41610. }
  41611. }
  41612. this.enableBrush(false);
  41613. // container may 'removeAll' outside.
  41614. clearCovers(this);
  41615. this._zr.remove(this.group);
  41616. if (__DEV__) {
  41617. this._mounted = false; // should be at last.
  41618. }
  41619. return this;
  41620. },
  41621. dispose: function () {
  41622. this.unmount();
  41623. this.off();
  41624. }
  41625. };
  41626. mixin(BrushController, Eventful);
  41627. function doEnableBrush(controller, brushOption) {
  41628. var zr = controller._zr;
  41629. // Consider roam, which takes globalPan too.
  41630. if (!controller._enableGlobalPan) {
  41631. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  41632. }
  41633. each$17(controller._handlers, function (handler, eventName) {
  41634. zr.on(eventName, handler);
  41635. });
  41636. controller._brushType = brushOption.brushType;
  41637. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  41638. }
  41639. function doDisableBrush(controller) {
  41640. var zr = controller._zr;
  41641. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  41642. each$17(controller._handlers, function (handler, eventName) {
  41643. zr.off(eventName, handler);
  41644. });
  41645. controller._brushType = controller._brushOption = null;
  41646. }
  41647. function createCover(controller, brushOption) {
  41648. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  41649. cover.__brushOption = brushOption;
  41650. updateZ$1(cover, brushOption);
  41651. controller.group.add(cover);
  41652. return cover;
  41653. }
  41654. function endCreating(controller, creatingCover) {
  41655. var coverRenderer = getCoverRenderer(creatingCover);
  41656. if (coverRenderer.endCreating) {
  41657. coverRenderer.endCreating(controller, creatingCover);
  41658. updateZ$1(creatingCover, creatingCover.__brushOption);
  41659. }
  41660. return creatingCover;
  41661. }
  41662. function updateCoverShape(controller, cover) {
  41663. var brushOption = cover.__brushOption;
  41664. getCoverRenderer(cover).updateCoverShape(
  41665. controller, cover, brushOption.range, brushOption
  41666. );
  41667. }
  41668. function updateZ$1(cover, brushOption) {
  41669. var z = brushOption.z;
  41670. z == null && (z = COVER_Z);
  41671. cover.traverse(function (el) {
  41672. el.z = z;
  41673. el.z2 = z; // Consider in given container.
  41674. });
  41675. }
  41676. function updateCoverAfterCreation(controller, cover) {
  41677. getCoverRenderer(cover).updateCommon(controller, cover);
  41678. updateCoverShape(controller, cover);
  41679. }
  41680. function getCoverRenderer(cover) {
  41681. return coverRenderers[cover.__brushOption.brushType];
  41682. }
  41683. // return target panel or `true` (means global panel)
  41684. function getPanelByPoint(controller, e, localCursorPoint) {
  41685. var panels = controller._panels;
  41686. if (!panels) {
  41687. return true; // Global panel
  41688. }
  41689. var panel;
  41690. var transform = controller._transform;
  41691. each$17(panels, function (pn) {
  41692. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  41693. });
  41694. return panel;
  41695. }
  41696. // Return a panel or true
  41697. function getPanelByCover(controller, cover) {
  41698. var panels = controller._panels;
  41699. if (!panels) {
  41700. return true; // Global panel
  41701. }
  41702. var panelId = cover.__brushOption.panelId;
  41703. // User may give cover without coord sys info,
  41704. // which is then treated as global panel.
  41705. return panelId != null ? panels[panelId] : true;
  41706. }
  41707. function clearCovers(controller) {
  41708. var covers = controller._covers;
  41709. var originalLength = covers.length;
  41710. each$17(covers, function (cover) {
  41711. controller.group.remove(cover);
  41712. }, controller);
  41713. covers.length = 0;
  41714. return !!originalLength;
  41715. }
  41716. function trigger(controller, opt) {
  41717. var areas = map$2(controller._covers, function (cover) {
  41718. var brushOption = cover.__brushOption;
  41719. var range = clone(brushOption.range);
  41720. return {
  41721. brushType: brushOption.brushType,
  41722. panelId: brushOption.panelId,
  41723. range: range
  41724. };
  41725. });
  41726. controller.trigger('brush', areas, {
  41727. isEnd: !!opt.isEnd,
  41728. removeOnClick: !!opt.removeOnClick
  41729. });
  41730. }
  41731. function shouldShowCover(controller) {
  41732. var track = controller._track;
  41733. if (!track.length) {
  41734. return false;
  41735. }
  41736. var p2 = track[track.length - 1];
  41737. var p1 = track[0];
  41738. var dx = p2[0] - p1[0];
  41739. var dy = p2[1] - p1[1];
  41740. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  41741. return dist > UNSELECT_THRESHOLD;
  41742. }
  41743. function getTrackEnds(track) {
  41744. var tail = track.length - 1;
  41745. tail < 0 && (tail = 0);
  41746. return [track[0], track[tail]];
  41747. }
  41748. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  41749. var cover = new Group();
  41750. cover.add(new Rect({
  41751. name: 'main',
  41752. style: makeStyle(brushOption),
  41753. silent: true,
  41754. draggable: true,
  41755. cursor: 'move',
  41756. drift: curry$6(doDrift, controller, cover, 'nswe'),
  41757. ondragend: curry$6(trigger, controller, {isEnd: true})
  41758. }));
  41759. each$17(
  41760. edgeNames,
  41761. function (name) {
  41762. cover.add(new Rect({
  41763. name: name,
  41764. style: {opacity: 0},
  41765. draggable: true,
  41766. silent: true,
  41767. invisible: true,
  41768. drift: curry$6(doDrift, controller, cover, name),
  41769. ondragend: curry$6(trigger, controller, {isEnd: true})
  41770. }));
  41771. }
  41772. );
  41773. return cover;
  41774. }
  41775. function updateBaseRect(controller, cover, localRange, brushOption) {
  41776. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  41777. var handleSize = mathMax$4(lineWidth, MIN_RESIZE_LINE_WIDTH);
  41778. var x = localRange[0][0];
  41779. var y = localRange[1][0];
  41780. var xa = x - lineWidth / 2;
  41781. var ya = y - lineWidth / 2;
  41782. var x2 = localRange[0][1];
  41783. var y2 = localRange[1][1];
  41784. var x2a = x2 - handleSize + lineWidth / 2;
  41785. var y2a = y2 - handleSize + lineWidth / 2;
  41786. var width = x2 - x;
  41787. var height = y2 - y;
  41788. var widtha = width + lineWidth;
  41789. var heighta = height + lineWidth;
  41790. updateRectShape(controller, cover, 'main', x, y, width, height);
  41791. if (brushOption.transformable) {
  41792. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  41793. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  41794. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  41795. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  41796. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  41797. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  41798. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  41799. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  41800. }
  41801. }
  41802. function updateCommon(controller, cover) {
  41803. var brushOption = cover.__brushOption;
  41804. var transformable = brushOption.transformable;
  41805. var mainEl = cover.childAt(0);
  41806. mainEl.useStyle(makeStyle(brushOption));
  41807. mainEl.attr({
  41808. silent: !transformable,
  41809. cursor: transformable ? 'move' : 'default'
  41810. });
  41811. each$17(
  41812. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  41813. function (name) {
  41814. var el = cover.childOfName(name);
  41815. var globalDir = getGlobalDirection(controller, name);
  41816. el && el.attr({
  41817. silent: !transformable,
  41818. invisible: !transformable,
  41819. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  41820. });
  41821. }
  41822. );
  41823. }
  41824. function updateRectShape(controller, cover, name, x, y, w, h) {
  41825. var el = cover.childOfName(name);
  41826. el && el.setShape(pointsToRect(
  41827. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  41828. ));
  41829. }
  41830. function makeStyle(brushOption) {
  41831. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  41832. }
  41833. function formatRectRange(x, y, x2, y2) {
  41834. var min = [mathMin$4(x, x2), mathMin$4(y, y2)];
  41835. var max = [mathMax$4(x, x2), mathMax$4(y, y2)];
  41836. return [
  41837. [min[0], max[0]], // x range
  41838. [min[1], max[1]] // y range
  41839. ];
  41840. }
  41841. function getTransform$1(controller) {
  41842. return getTransform(controller.group);
  41843. }
  41844. function getGlobalDirection(controller, localDirection) {
  41845. if (localDirection.length > 1) {
  41846. localDirection = localDirection.split('');
  41847. var globalDir = [
  41848. getGlobalDirection(controller, localDirection[0]),
  41849. getGlobalDirection(controller, localDirection[1])
  41850. ];
  41851. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  41852. return globalDir.join('');
  41853. }
  41854. else {
  41855. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  41856. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  41857. var globalDir = transformDirection(
  41858. map$$1[localDirection], getTransform$1(controller)
  41859. );
  41860. return inverseMap[globalDir];
  41861. }
  41862. }
  41863. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  41864. var brushOption = cover.__brushOption;
  41865. var rectRange = toRectRange(brushOption.range);
  41866. var localDelta = toLocalDelta(controller, dx, dy);
  41867. each$17(name.split(''), function (namePart) {
  41868. var ind = DIRECTION_MAP[namePart];
  41869. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  41870. });
  41871. brushOption.range = fromRectRange(formatRectRange(
  41872. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  41873. ));
  41874. updateCoverAfterCreation(controller, cover);
  41875. trigger(controller, {isEnd: false});
  41876. }
  41877. function driftPolygon(controller, cover, dx, dy, e) {
  41878. var range = cover.__brushOption.range;
  41879. var localDelta = toLocalDelta(controller, dx, dy);
  41880. each$17(range, function (point) {
  41881. point[0] += localDelta[0];
  41882. point[1] += localDelta[1];
  41883. });
  41884. updateCoverAfterCreation(controller, cover);
  41885. trigger(controller, {isEnd: false});
  41886. }
  41887. function toLocalDelta(controller, dx, dy) {
  41888. var thisGroup = controller.group;
  41889. var localD = thisGroup.transformCoordToLocal(dx, dy);
  41890. var localZero = thisGroup.transformCoordToLocal(0, 0);
  41891. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  41892. }
  41893. function clipByPanel(controller, cover, data) {
  41894. var panel = getPanelByCover(controller, cover);
  41895. return (panel && panel !== true)
  41896. ? panel.clipPath(data, controller._transform)
  41897. : clone(data);
  41898. }
  41899. function pointsToRect(points) {
  41900. var xmin = mathMin$4(points[0][0], points[1][0]);
  41901. var ymin = mathMin$4(points[0][1], points[1][1]);
  41902. var xmax = mathMax$4(points[0][0], points[1][0]);
  41903. var ymax = mathMax$4(points[0][1], points[1][1]);
  41904. return {
  41905. x: xmin,
  41906. y: ymin,
  41907. width: xmax - xmin,
  41908. height: ymax - ymin
  41909. };
  41910. }
  41911. function resetCursor(controller, e, localCursorPoint) {
  41912. // Check active
  41913. if (!controller._brushType) {
  41914. return;
  41915. }
  41916. var zr = controller._zr;
  41917. var covers = controller._covers;
  41918. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  41919. // Check whether in covers.
  41920. if (!controller._dragging) {
  41921. for (var i = 0; i < covers.length; i++) {
  41922. var brushOption = covers[i].__brushOption;
  41923. if (currPanel
  41924. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  41925. && coverRenderers[brushOption.brushType].contain(
  41926. covers[i], localCursorPoint[0], localCursorPoint[1]
  41927. )
  41928. ) {
  41929. // Use cursor style set on cover.
  41930. return;
  41931. }
  41932. }
  41933. }
  41934. currPanel && zr.setCursorStyle('crosshair');
  41935. }
  41936. function preventDefault(e) {
  41937. var rawE = e.event;
  41938. rawE.preventDefault && rawE.preventDefault();
  41939. }
  41940. function mainShapeContain(cover, x, y) {
  41941. return cover.childOfName('main').contain(x, y);
  41942. }
  41943. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  41944. var creatingCover = controller._creatingCover;
  41945. var panel = controller._creatingPanel;
  41946. var thisBrushOption = controller._brushOption;
  41947. var eventParams;
  41948. controller._track.push(localCursorPoint.slice());
  41949. if (shouldShowCover(controller) || creatingCover) {
  41950. if (panel && !creatingCover) {
  41951. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  41952. var brushOption = clone(thisBrushOption);
  41953. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  41954. brushOption.panelId = panel === true ? null : panel.panelId;
  41955. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  41956. controller._covers.push(creatingCover);
  41957. }
  41958. if (creatingCover) {
  41959. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  41960. var coverBrushOption = creatingCover.__brushOption;
  41961. coverBrushOption.range = coverRenderer.getCreatingRange(
  41962. clipByPanel(controller, creatingCover, controller._track)
  41963. );
  41964. if (isEnd) {
  41965. endCreating(controller, creatingCover);
  41966. coverRenderer.updateCommon(controller, creatingCover);
  41967. }
  41968. updateCoverShape(controller, creatingCover);
  41969. eventParams = {isEnd: isEnd};
  41970. }
  41971. }
  41972. else if (
  41973. isEnd
  41974. && thisBrushOption.brushMode === 'single'
  41975. && thisBrushOption.removeOnClick
  41976. ) {
  41977. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  41978. // But a single click do not clear covers, because user may have casual
  41979. // clicks (for example, click on other component and do not expect covers
  41980. // disappear).
  41981. // Only some cover removed, trigger action, but not every click trigger action.
  41982. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  41983. eventParams = {isEnd: isEnd, removeOnClick: true};
  41984. }
  41985. }
  41986. return eventParams;
  41987. }
  41988. function determineBrushType(brushType, panel) {
  41989. if (brushType === 'auto') {
  41990. if (__DEV__) {
  41991. assert$1(
  41992. panel && panel.defaultBrushType,
  41993. 'MUST have defaultBrushType when brushType is "atuo"'
  41994. );
  41995. }
  41996. return panel.defaultBrushType;
  41997. }
  41998. return brushType;
  41999. }
  42000. var mouseHandlers = {
  42001. mousedown: function (e) {
  42002. if (this._dragging) {
  42003. // In case some browser do not support globalOut,
  42004. // and release mose out side the browser.
  42005. handleDragEnd.call(this, e);
  42006. }
  42007. else if (!e.target || !e.target.draggable) {
  42008. preventDefault(e);
  42009. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42010. this._creatingCover = null;
  42011. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  42012. if (panel) {
  42013. this._dragging = true;
  42014. this._track = [localCursorPoint.slice()];
  42015. }
  42016. }
  42017. },
  42018. mousemove: function (e) {
  42019. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42020. resetCursor(this, e, localCursorPoint);
  42021. if (this._dragging) {
  42022. preventDefault(e);
  42023. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  42024. eventParams && trigger(this, eventParams);
  42025. }
  42026. },
  42027. mouseup: handleDragEnd //,
  42028. // FIXME
  42029. // in tooltip, globalout should not be triggered.
  42030. // globalout: handleDragEnd
  42031. };
  42032. function handleDragEnd(e) {
  42033. if (this._dragging) {
  42034. preventDefault(e);
  42035. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42036. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  42037. this._dragging = false;
  42038. this._track = [];
  42039. this._creatingCover = null;
  42040. // trigger event shoule be at final, after procedure will be nested.
  42041. eventParams && trigger(this, eventParams);
  42042. }
  42043. }
  42044. /**
  42045. * key: brushType
  42046. * @type {Object}
  42047. */
  42048. var coverRenderers = {
  42049. lineX: getLineRenderer(0),
  42050. lineY: getLineRenderer(1),
  42051. rect: {
  42052. createCover: function (controller, brushOption) {
  42053. return createBaseRectCover(
  42054. curry$6(
  42055. driftRect,
  42056. function (range) {
  42057. return range;
  42058. },
  42059. function (range) {
  42060. return range;
  42061. }
  42062. ),
  42063. controller,
  42064. brushOption,
  42065. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  42066. );
  42067. },
  42068. getCreatingRange: function (localTrack) {
  42069. var ends = getTrackEnds(localTrack);
  42070. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  42071. },
  42072. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42073. updateBaseRect(controller, cover, localRange, brushOption);
  42074. },
  42075. updateCommon: updateCommon,
  42076. contain: mainShapeContain
  42077. },
  42078. polygon: {
  42079. createCover: function (controller, brushOption) {
  42080. var cover = new Group();
  42081. // Do not use graphic.Polygon because graphic.Polyline do not close the
  42082. // border of the shape when drawing, which is a better experience for user.
  42083. cover.add(new Polyline({
  42084. name: 'main',
  42085. style: makeStyle(brushOption),
  42086. silent: true
  42087. }));
  42088. return cover;
  42089. },
  42090. getCreatingRange: function (localTrack) {
  42091. return localTrack;
  42092. },
  42093. endCreating: function (controller, cover) {
  42094. cover.remove(cover.childAt(0));
  42095. // Use graphic.Polygon close the shape.
  42096. cover.add(new Polygon({
  42097. name: 'main',
  42098. draggable: true,
  42099. drift: curry$6(driftPolygon, controller, cover),
  42100. ondragend: curry$6(trigger, controller, {isEnd: true})
  42101. }));
  42102. },
  42103. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42104. cover.childAt(0).setShape({
  42105. points: clipByPanel(controller, cover, localRange)
  42106. });
  42107. },
  42108. updateCommon: updateCommon,
  42109. contain: mainShapeContain
  42110. }
  42111. };
  42112. function getLineRenderer(xyIndex) {
  42113. return {
  42114. createCover: function (controller, brushOption) {
  42115. return createBaseRectCover(
  42116. curry$6(
  42117. driftRect,
  42118. function (range) {
  42119. var rectRange = [range, [0, 100]];
  42120. xyIndex && rectRange.reverse();
  42121. return rectRange;
  42122. },
  42123. function (rectRange) {
  42124. return rectRange[xyIndex];
  42125. }
  42126. ),
  42127. controller,
  42128. brushOption,
  42129. [['w', 'e'], ['n', 's']][xyIndex]
  42130. );
  42131. },
  42132. getCreatingRange: function (localTrack) {
  42133. var ends = getTrackEnds(localTrack);
  42134. var min = mathMin$4(ends[0][xyIndex], ends[1][xyIndex]);
  42135. var max = mathMax$4(ends[0][xyIndex], ends[1][xyIndex]);
  42136. return [min, max];
  42137. },
  42138. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42139. var otherExtent;
  42140. // If brushWidth not specified, fit the panel.
  42141. var panel = getPanelByCover(controller, cover);
  42142. if (panel !== true && panel.getLinearBrushOtherExtent) {
  42143. otherExtent = panel.getLinearBrushOtherExtent(
  42144. xyIndex, controller._transform
  42145. );
  42146. }
  42147. else {
  42148. var zr = controller._zr;
  42149. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  42150. }
  42151. var rectRange = [localRange, otherExtent];
  42152. xyIndex && rectRange.reverse();
  42153. updateBaseRect(controller, cover, rectRange, brushOption);
  42154. },
  42155. updateCommon: updateCommon,
  42156. contain: mainShapeContain
  42157. };
  42158. }
  42159. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  42160. /**
  42161. * Avoid that: mouse click on a elements that is over geo or graph,
  42162. * but roam is triggered.
  42163. */
  42164. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42165. var model = api.getComponentByElement(e.topTarget);
  42166. // If model is axisModel, it works only if it is injected with coordinateSystem.
  42167. var coordSys = model && model.coordinateSystem;
  42168. return model
  42169. && model !== targetCoordSysModel
  42170. && !IRRELEVANT_EXCLUDES[model.mainType]
  42171. && (coordSys && coordSys.model !== targetCoordSysModel);
  42172. }
  42173. function makeRectPanelClipPath(rect) {
  42174. rect = normalizeRect(rect);
  42175. return function (localPoints, transform) {
  42176. return clipPointsByRect(localPoints, rect);
  42177. };
  42178. }
  42179. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  42180. rect = normalizeRect(rect);
  42181. return function (xyIndex) {
  42182. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  42183. var brushWidth = idx ? rect.width : rect.height;
  42184. var base = idx ? rect.x : rect.y;
  42185. return [base, base + (brushWidth || 0)];
  42186. };
  42187. }
  42188. function makeRectIsTargetByCursor(rect, api, targetModel) {
  42189. rect = normalizeRect(rect);
  42190. return function (e, localCursorPoint, transform) {
  42191. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  42192. && !onIrrelevantElement(e, api, targetModel);
  42193. };
  42194. }
  42195. // Consider width/height is negative.
  42196. function normalizeRect(rect) {
  42197. return BoundingRect.create(rect);
  42198. }
  42199. var each$18 = each$1;
  42200. var indexOf$2 = indexOf;
  42201. var curry$7 = curry;
  42202. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  42203. // FIXME
  42204. // how to genarialize to more coordinate systems.
  42205. var INCLUDE_FINDER_MAIN_TYPES = [
  42206. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  42207. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  42208. ];
  42209. /**
  42210. * [option in constructor]:
  42211. * {
  42212. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42213. * }
  42214. *
  42215. *
  42216. * [targetInfo]:
  42217. *
  42218. * There can be multiple axes in a single targetInfo. Consider the case
  42219. * of `grid` component, a targetInfo represents a grid which contains one or more
  42220. * cartesian and one or more axes. And consider the case of parallel system,
  42221. * which has multiple axes in a coordinate system.
  42222. * Can be {
  42223. * panelId: ...,
  42224. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  42225. * coordSyses: all cartesians.
  42226. * gridModel: <grid component>
  42227. * xAxes: correspond to coordSyses on index
  42228. * yAxes: correspond to coordSyses on index
  42229. * }
  42230. * or {
  42231. * panelId: ...,
  42232. * coordSys: <geo coord sys>
  42233. * coordSyses: [<geo coord sys>]
  42234. * geoModel: <geo component>
  42235. * }
  42236. *
  42237. *
  42238. * [panelOpt]:
  42239. *
  42240. * Make from targetInfo. Input to BrushController.
  42241. * {
  42242. * panelId: ...,
  42243. * rect: ...
  42244. * }
  42245. *
  42246. *
  42247. * [area]:
  42248. *
  42249. * Generated by BrushController or user input.
  42250. * {
  42251. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  42252. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  42253. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42254. * range: pixel range.
  42255. * coordRange: representitive coord range (the first one of coordRanges).
  42256. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  42257. * }
  42258. */
  42259. /**
  42260. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  42261. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  42262. * @param {module:echarts/model/Global} ecModel
  42263. * @param {Object} [opt]
  42264. * @param {Array.<string>} [opt.include] include coordinate system types.
  42265. */
  42266. function BrushTargetManager(option, ecModel, opt) {
  42267. /**
  42268. * @private
  42269. * @type {Array.<Object>}
  42270. */
  42271. var targetInfoList = this._targetInfoList = [];
  42272. var info = {};
  42273. var foundCpts = parseFinder$1(ecModel, option);
  42274. each$18(targetInfoBuilders, function (builder, type) {
  42275. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  42276. builder(foundCpts, targetInfoList, info);
  42277. }
  42278. });
  42279. }
  42280. var proto$5 = BrushTargetManager.prototype;
  42281. proto$5.setOutputRanges = function (areas, ecModel) {
  42282. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  42283. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  42284. // area.coordRange is the first of area.coordRanges
  42285. if (!area.coordRange) {
  42286. area.coordRange = coordRange;
  42287. // In 'category' axis, coord to pixel is not reversible, so we can not
  42288. // rebuild range by coordRange accrately, which may bring trouble when
  42289. // brushing only one item. So we use __rangeOffset to rebuilding range
  42290. // by coordRange. And this it only used in brush component so it is no
  42291. // need to be adapted to coordRanges.
  42292. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  42293. area.__rangeOffset = {
  42294. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  42295. xyMinMax: result.xyMinMax
  42296. };
  42297. }
  42298. });
  42299. };
  42300. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  42301. each$18(areas, function (area) {
  42302. var targetInfo = this.findTargetInfo(area, ecModel);
  42303. if (targetInfo && targetInfo !== true) {
  42304. each$1(
  42305. targetInfo.coordSyses,
  42306. function (coordSys) {
  42307. var result = coordConvert[area.brushType](1, coordSys, area.range);
  42308. cb(area, result.values, coordSys, ecModel);
  42309. }
  42310. );
  42311. }
  42312. }, this);
  42313. };
  42314. proto$5.setInputRanges = function (areas, ecModel) {
  42315. each$18(areas, function (area) {
  42316. var targetInfo = this.findTargetInfo(area, ecModel);
  42317. if (__DEV__) {
  42318. assert$1(
  42319. !targetInfo || targetInfo === true || area.coordRange,
  42320. 'coordRange must be specified when coord index specified.'
  42321. );
  42322. assert$1(
  42323. !targetInfo || targetInfo !== true || area.range,
  42324. 'range must be specified in global brush.'
  42325. );
  42326. }
  42327. area.range = area.range || [];
  42328. // convert coordRange to global range and set panelId.
  42329. if (targetInfo && targetInfo !== true) {
  42330. area.panelId = targetInfo.panelId;
  42331. // (1) area.range shoule always be calculate from coordRange but does
  42332. // not keep its original value, for the sake of the dataZoom scenario,
  42333. // where area.coordRange remains unchanged but area.range may be changed.
  42334. // (2) Only support converting one coordRange to pixel range in brush
  42335. // component. So do not consider `coordRanges`.
  42336. // (3) About __rangeOffset, see comment above.
  42337. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  42338. var rangeOffset = area.__rangeOffset;
  42339. area.range = rangeOffset
  42340. ? diffProcessor[area.brushType](
  42341. result.values,
  42342. rangeOffset.offset,
  42343. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  42344. )
  42345. : result.values;
  42346. }
  42347. }, this);
  42348. };
  42349. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  42350. return map(this._targetInfoList, function (targetInfo) {
  42351. var rect = targetInfo.getPanelRect();
  42352. return {
  42353. panelId: targetInfo.panelId,
  42354. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  42355. clipPath: makeRectPanelClipPath(rect),
  42356. isTargetByCursor: makeRectIsTargetByCursor(
  42357. rect, api, targetInfo.coordSysModel
  42358. ),
  42359. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  42360. };
  42361. });
  42362. };
  42363. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  42364. // Check whether area is bound in coord, and series do not belong to that coord.
  42365. // If do not do this check, some brush (like lineX) will controll all axes.
  42366. var targetInfo = this.findTargetInfo(area, ecModel);
  42367. return targetInfo === true || (
  42368. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  42369. );
  42370. };
  42371. /**
  42372. * If return Object, a coord found.
  42373. * If reutrn true, global found.
  42374. * Otherwise nothing found.
  42375. *
  42376. * @param {Object} area
  42377. * @param {Array} targetInfoList
  42378. * @return {Object|boolean}
  42379. */
  42380. proto$5.findTargetInfo = function (area, ecModel) {
  42381. var targetInfoList = this._targetInfoList;
  42382. var foundCpts = parseFinder$1(ecModel, area);
  42383. for (var i = 0; i < targetInfoList.length; i++) {
  42384. var targetInfo = targetInfoList[i];
  42385. var areaPanelId = area.panelId;
  42386. if (areaPanelId) {
  42387. if (targetInfo.panelId === areaPanelId) {
  42388. return targetInfo;
  42389. }
  42390. }
  42391. else {
  42392. for (var i = 0; i < targetInfoMatchers.length; i++) {
  42393. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  42394. return targetInfo;
  42395. }
  42396. }
  42397. }
  42398. }
  42399. return true;
  42400. };
  42401. function formatMinMax(minMax) {
  42402. minMax[0] > minMax[1] && minMax.reverse();
  42403. return minMax;
  42404. }
  42405. function parseFinder$1(ecModel, option) {
  42406. return parseFinder(
  42407. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  42408. );
  42409. }
  42410. var targetInfoBuilders = {
  42411. grid: function (foundCpts, targetInfoList) {
  42412. var xAxisModels = foundCpts.xAxisModels;
  42413. var yAxisModels = foundCpts.yAxisModels;
  42414. var gridModels = foundCpts.gridModels;
  42415. // Remove duplicated.
  42416. var gridModelMap = createHashMap();
  42417. var xAxesHas = {};
  42418. var yAxesHas = {};
  42419. if (!xAxisModels && !yAxisModels && !gridModels) {
  42420. return;
  42421. }
  42422. each$18(xAxisModels, function (axisModel) {
  42423. var gridModel = axisModel.axis.grid.model;
  42424. gridModelMap.set(gridModel.id, gridModel);
  42425. xAxesHas[gridModel.id] = true;
  42426. });
  42427. each$18(yAxisModels, function (axisModel) {
  42428. var gridModel = axisModel.axis.grid.model;
  42429. gridModelMap.set(gridModel.id, gridModel);
  42430. yAxesHas[gridModel.id] = true;
  42431. });
  42432. each$18(gridModels, function (gridModel) {
  42433. gridModelMap.set(gridModel.id, gridModel);
  42434. xAxesHas[gridModel.id] = true;
  42435. yAxesHas[gridModel.id] = true;
  42436. });
  42437. gridModelMap.each(function (gridModel) {
  42438. var grid = gridModel.coordinateSystem;
  42439. var cartesians = [];
  42440. each$18(grid.getCartesians(), function (cartesian, index) {
  42441. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  42442. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  42443. ) {
  42444. cartesians.push(cartesian);
  42445. }
  42446. });
  42447. targetInfoList.push({
  42448. panelId: 'grid--' + gridModel.id,
  42449. gridModel: gridModel,
  42450. coordSysModel: gridModel,
  42451. // Use the first one as the representitive coordSys.
  42452. coordSys: cartesians[0],
  42453. coordSyses: cartesians,
  42454. getPanelRect: panelRectBuilder.grid,
  42455. xAxisDeclared: xAxesHas[gridModel.id],
  42456. yAxisDeclared: yAxesHas[gridModel.id]
  42457. });
  42458. });
  42459. },
  42460. geo: function (foundCpts, targetInfoList) {
  42461. each$18(foundCpts.geoModels, function (geoModel) {
  42462. var coordSys = geoModel.coordinateSystem;
  42463. targetInfoList.push({
  42464. panelId: 'geo--' + geoModel.id,
  42465. geoModel: geoModel,
  42466. coordSysModel: geoModel,
  42467. coordSys: coordSys,
  42468. coordSyses: [coordSys],
  42469. getPanelRect: panelRectBuilder.geo
  42470. });
  42471. });
  42472. }
  42473. };
  42474. var targetInfoMatchers = [
  42475. // grid
  42476. function (foundCpts, targetInfo) {
  42477. var xAxisModel = foundCpts.xAxisModel;
  42478. var yAxisModel = foundCpts.yAxisModel;
  42479. var gridModel = foundCpts.gridModel;
  42480. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  42481. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  42482. return gridModel && gridModel === targetInfo.gridModel;
  42483. },
  42484. // geo
  42485. function (foundCpts, targetInfo) {
  42486. var geoModel = foundCpts.geoModel;
  42487. return geoModel && geoModel === targetInfo.geoModel;
  42488. }
  42489. ];
  42490. var panelRectBuilder = {
  42491. grid: function () {
  42492. // grid is not Transformable.
  42493. return this.coordSys.grid.getRect().clone();
  42494. },
  42495. geo: function () {
  42496. var coordSys = this.coordSys;
  42497. var rect = coordSys.getBoundingRect().clone();
  42498. // geo roam and zoom transform
  42499. rect.applyTransform(getTransform(coordSys));
  42500. return rect;
  42501. }
  42502. };
  42503. var coordConvert = {
  42504. lineX: curry$7(axisConvert, 0),
  42505. lineY: curry$7(axisConvert, 1),
  42506. rect: function (to, coordSys, rangeOrCoordRange) {
  42507. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  42508. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  42509. var values = [
  42510. formatMinMax([xminymin[0], xmaxymax[0]]),
  42511. formatMinMax([xminymin[1], xmaxymax[1]])
  42512. ];
  42513. return {values: values, xyMinMax: values};
  42514. },
  42515. polygon: function (to, coordSys, rangeOrCoordRange) {
  42516. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  42517. var values = map(rangeOrCoordRange, function (item) {
  42518. var p = coordSys[COORD_CONVERTS[to]](item);
  42519. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  42520. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  42521. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  42522. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  42523. return p;
  42524. });
  42525. return {values: values, xyMinMax: xyMinMax};
  42526. }
  42527. };
  42528. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  42529. if (__DEV__) {
  42530. assert$1(
  42531. coordSys.type === 'cartesian2d',
  42532. 'lineX/lineY brush is available only in cartesian2d.'
  42533. );
  42534. }
  42535. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  42536. var values = formatMinMax(map([0, 1], function (i) {
  42537. return to
  42538. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  42539. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  42540. }));
  42541. var xyMinMax = [];
  42542. xyMinMax[axisNameIndex] = values;
  42543. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  42544. return {values: values, xyMinMax: xyMinMax};
  42545. }
  42546. var diffProcessor = {
  42547. lineX: curry$7(axisDiffProcessor, 0),
  42548. lineY: curry$7(axisDiffProcessor, 1),
  42549. rect: function (values, refer, scales) {
  42550. return [
  42551. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  42552. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  42553. ];
  42554. },
  42555. polygon: function (values, refer, scales) {
  42556. return map(values, function (item, idx) {
  42557. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  42558. });
  42559. }
  42560. };
  42561. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  42562. return [
  42563. values[0] - scales[axisNameIndex] * refer[0],
  42564. values[1] - scales[axisNameIndex] * refer[1]
  42565. ];
  42566. }
  42567. // We have to process scale caused by dataZoom manually,
  42568. // although it might be not accurate.
  42569. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  42570. var sizeCurr = getSize(xyMinMaxCurr);
  42571. var sizeOrigin = getSize(xyMinMaxOrigin);
  42572. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  42573. isNaN(scales[0]) && (scales[0] = 1);
  42574. isNaN(scales[1]) && (scales[1] = 1);
  42575. return scales;
  42576. }
  42577. function getSize(xyMinMax) {
  42578. return xyMinMax
  42579. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  42580. : [NaN, NaN];
  42581. }
  42582. var each$19 = each$1;
  42583. var ATTR$2 = '\0_ec_hist_store';
  42584. /**
  42585. * @param {module:echarts/model/Global} ecModel
  42586. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  42587. */
  42588. function push(ecModel, newSnapshot) {
  42589. var store = giveStore$1(ecModel);
  42590. // If previous dataZoom can not be found,
  42591. // complete an range with current range.
  42592. each$19(newSnapshot, function (batchItem, dataZoomId) {
  42593. var i = store.length - 1;
  42594. for (; i >= 0; i--) {
  42595. var snapshot = store[i];
  42596. if (snapshot[dataZoomId]) {
  42597. break;
  42598. }
  42599. }
  42600. if (i < 0) {
  42601. // No origin range set, create one by current range.
  42602. var dataZoomModel = ecModel.queryComponents(
  42603. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  42604. )[0];
  42605. if (dataZoomModel) {
  42606. var percentRange = dataZoomModel.getPercentRange();
  42607. store[0][dataZoomId] = {
  42608. dataZoomId: dataZoomId,
  42609. start: percentRange[0],
  42610. end: percentRange[1]
  42611. };
  42612. }
  42613. }
  42614. });
  42615. store.push(newSnapshot);
  42616. }
  42617. /**
  42618. * @param {module:echarts/model/Global} ecModel
  42619. * @return {Object} snapshot
  42620. */
  42621. function pop(ecModel) {
  42622. var store = giveStore$1(ecModel);
  42623. var head = store[store.length - 1];
  42624. store.length > 1 && store.pop();
  42625. // Find top for all dataZoom.
  42626. var snapshot = {};
  42627. each$19(head, function (batchItem, dataZoomId) {
  42628. for (var i = store.length - 1; i >= 0; i--) {
  42629. var batchItem = store[i][dataZoomId];
  42630. if (batchItem) {
  42631. snapshot[dataZoomId] = batchItem;
  42632. break;
  42633. }
  42634. }
  42635. });
  42636. return snapshot;
  42637. }
  42638. /**
  42639. * @param {module:echarts/model/Global} ecModel
  42640. */
  42641. function clear$1(ecModel) {
  42642. ecModel[ATTR$2] = null;
  42643. }
  42644. /**
  42645. * @param {module:echarts/model/Global} ecModel
  42646. * @return {number} records. always >= 1.
  42647. */
  42648. function count(ecModel) {
  42649. return giveStore$1(ecModel).length;
  42650. }
  42651. /**
  42652. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  42653. * History length of each dataZoom may be different.
  42654. * this._history[0] is used to store origin range.
  42655. * @type {Array.<Object>}
  42656. */
  42657. function giveStore$1(ecModel) {
  42658. var store = ecModel[ATTR$2];
  42659. if (!store) {
  42660. store = ecModel[ATTR$2] = [{}];
  42661. }
  42662. return store;
  42663. }
  42664. DataZoomModel.extend({
  42665. type: 'dataZoom.select'
  42666. });
  42667. DataZoomView.extend({
  42668. type: 'dataZoom.select'
  42669. });
  42670. /**
  42671. * DataZoom component entry
  42672. */
  42673. // Use dataZoomSelect
  42674. var dataZoomLang = lang.toolbox.dataZoom;
  42675. var each$16 = each$1;
  42676. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  42677. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  42678. function DataZoom(model, ecModel, api) {
  42679. /**
  42680. * @private
  42681. * @type {module:echarts/component/helper/BrushController}
  42682. */
  42683. (this._brushController = new BrushController(api.getZr()))
  42684. .on('brush', bind(this._onBrush, this))
  42685. .mount();
  42686. /**
  42687. * @private
  42688. * @type {boolean}
  42689. */
  42690. this._isZoomActive;
  42691. }
  42692. DataZoom.defaultOption = {
  42693. show: true,
  42694. // Icon group
  42695. icon: {
  42696. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  42697. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  42698. },
  42699. // `zoom`, `back`
  42700. title: clone(dataZoomLang.title)
  42701. };
  42702. var proto$4 = DataZoom.prototype;
  42703. proto$4.render = function (featureModel, ecModel, api, payload) {
  42704. this.model = featureModel;
  42705. this.ecModel = ecModel;
  42706. this.api = api;
  42707. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  42708. updateBackBtnStatus(featureModel, ecModel);
  42709. };
  42710. proto$4.onclick = function (ecModel, api, type) {
  42711. handlers[type].call(this);
  42712. };
  42713. proto$4.remove = function (ecModel, api) {
  42714. this._brushController.unmount();
  42715. };
  42716. proto$4.dispose = function (ecModel, api) {
  42717. this._brushController.dispose();
  42718. };
  42719. /**
  42720. * @private
  42721. */
  42722. var handlers = {
  42723. zoom: function () {
  42724. var nextActive = !this._isZoomActive;
  42725. this.api.dispatchAction({
  42726. type: 'takeGlobalCursor',
  42727. key: 'dataZoomSelect',
  42728. dataZoomSelectActive: nextActive
  42729. });
  42730. },
  42731. back: function () {
  42732. this._dispatchZoomAction(pop(this.ecModel));
  42733. }
  42734. };
  42735. /**
  42736. * @private
  42737. */
  42738. proto$4._onBrush = function (areas, opt) {
  42739. if (!opt.isEnd || !areas.length) {
  42740. return;
  42741. }
  42742. var snapshot = {};
  42743. var ecModel = this.ecModel;
  42744. this._brushController.updateCovers([]); // remove cover
  42745. var brushTargetManager = new BrushTargetManager(
  42746. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  42747. );
  42748. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  42749. if (coordSys.type !== 'cartesian2d') {
  42750. return;
  42751. }
  42752. var brushType = area.brushType;
  42753. if (brushType === 'rect') {
  42754. setBatch('x', coordSys, coordRange[0]);
  42755. setBatch('y', coordSys, coordRange[1]);
  42756. }
  42757. else {
  42758. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  42759. }
  42760. });
  42761. push(ecModel, snapshot);
  42762. this._dispatchZoomAction(snapshot);
  42763. function setBatch(dimName, coordSys, minMax) {
  42764. var axis = coordSys.getAxis(dimName);
  42765. var axisModel = axis.model;
  42766. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  42767. // Restrict range.
  42768. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  42769. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  42770. minMax = sliderMove(
  42771. 0, minMax.slice(), axis.scale.getExtent(), 0,
  42772. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  42773. );
  42774. }
  42775. dataZoomModel && (snapshot[dataZoomModel.id] = {
  42776. dataZoomId: dataZoomModel.id,
  42777. startValue: minMax[0],
  42778. endValue: minMax[1]
  42779. });
  42780. }
  42781. function findDataZoom(dimName, axisModel, ecModel) {
  42782. var found;
  42783. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  42784. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  42785. has && (found = dzModel);
  42786. });
  42787. return found;
  42788. }
  42789. };
  42790. /**
  42791. * @private
  42792. */
  42793. proto$4._dispatchZoomAction = function (snapshot) {
  42794. var batch = [];
  42795. // Convert from hash map to array.
  42796. each$16(snapshot, function (batchItem, dataZoomId) {
  42797. batch.push(clone(batchItem));
  42798. });
  42799. batch.length && this.api.dispatchAction({
  42800. type: 'dataZoom',
  42801. from: this.uid,
  42802. batch: batch
  42803. });
  42804. };
  42805. function retrieveAxisSetting(option) {
  42806. var setting = {};
  42807. // Compatible with previous setting: null => all axis, false => no axis.
  42808. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  42809. setting[name] = option[name];
  42810. setting[name] == null && (setting[name] = 'all');
  42811. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  42812. });
  42813. return setting;
  42814. }
  42815. function updateBackBtnStatus(featureModel, ecModel) {
  42816. featureModel.setIconStatus(
  42817. 'back',
  42818. count(ecModel) > 1 ? 'emphasis' : 'normal'
  42819. );
  42820. }
  42821. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  42822. var zoomActive = view._isZoomActive;
  42823. if (payload && payload.type === 'takeGlobalCursor') {
  42824. zoomActive = payload.key === 'dataZoomSelect'
  42825. ? payload.dataZoomSelectActive : false;
  42826. }
  42827. view._isZoomActive = zoomActive;
  42828. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  42829. var brushTargetManager = new BrushTargetManager(
  42830. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  42831. );
  42832. view._brushController
  42833. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  42834. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  42835. ? 'lineX'
  42836. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  42837. ? 'lineY'
  42838. : 'rect';
  42839. }))
  42840. .enableBrush(
  42841. zoomActive
  42842. ? {
  42843. brushType: 'auto',
  42844. brushStyle: {
  42845. // FIXME user customized?
  42846. lineWidth: 0,
  42847. fill: 'rgba(0,0,0,0.2)'
  42848. }
  42849. }
  42850. : false
  42851. );
  42852. }
  42853. register$2('dataZoom', DataZoom);
  42854. // Create special dataZoom option for select
  42855. registerPreprocessor(function (option) {
  42856. if (!option) {
  42857. return;
  42858. }
  42859. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  42860. if (!isArray(dataZoomOpts)) {
  42861. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  42862. }
  42863. var toolboxOpt = option.toolbox;
  42864. if (toolboxOpt) {
  42865. // Assume there is only one toolbox
  42866. if (isArray(toolboxOpt)) {
  42867. toolboxOpt = toolboxOpt[0];
  42868. }
  42869. if (toolboxOpt && toolboxOpt.feature) {
  42870. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  42871. addForAxis('xAxis', dataZoomOpt);
  42872. addForAxis('yAxis', dataZoomOpt);
  42873. }
  42874. }
  42875. function addForAxis(axisName, dataZoomOpt) {
  42876. if (!dataZoomOpt) {
  42877. return;
  42878. }
  42879. // Try not to modify model, because it is not merged yet.
  42880. var axisIndicesName = axisName + 'Index';
  42881. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  42882. if (givenAxisIndices != null
  42883. && givenAxisIndices != 'all'
  42884. && !isArray(givenAxisIndices)
  42885. ) {
  42886. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  42887. }
  42888. forEachComponent(axisName, function (axisOpt, axisIndex) {
  42889. if (givenAxisIndices != null
  42890. && givenAxisIndices != 'all'
  42891. && indexOf(givenAxisIndices, axisIndex) === -1
  42892. ) {
  42893. return;
  42894. }
  42895. var newOpt = {
  42896. type: 'select',
  42897. $fromToolbox: true,
  42898. // Id for merge mapping.
  42899. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  42900. };
  42901. // FIXME
  42902. // Only support one axis now.
  42903. newOpt[axisIndicesName] = axisIndex;
  42904. dataZoomOpts.push(newOpt);
  42905. });
  42906. }
  42907. function forEachComponent(mainType, cb) {
  42908. var opts = option[mainType];
  42909. if (!isArray(opts)) {
  42910. opts = opts ? [opts] : [];
  42911. }
  42912. each$16(opts, cb);
  42913. }
  42914. });
  42915. var restoreLang = lang.toolbox.restore;
  42916. function Restore(model) {
  42917. this.model = model;
  42918. }
  42919. Restore.defaultOption = {
  42920. show: true,
  42921. 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',
  42922. title: restoreLang.title
  42923. };
  42924. var proto$6 = Restore.prototype;
  42925. proto$6.onclick = function (ecModel, api, type) {
  42926. clear$1(ecModel);
  42927. api.dispatchAction({
  42928. type: 'restore',
  42929. from: this.uid
  42930. });
  42931. };
  42932. register$2('restore', Restore);
  42933. registerAction(
  42934. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  42935. function (payload, ecModel) {
  42936. ecModel.resetOption('recreate');
  42937. }
  42938. );
  42939. var urn = 'urn:schemas-microsoft-com:vml';
  42940. var win = typeof window === 'undefined' ? null : window;
  42941. var vmlInited = false;
  42942. var doc = win && win.document;
  42943. function createNode(tagName) {
  42944. return doCreateNode(tagName);
  42945. }
  42946. // Avoid assign to an exported variable, for transforming to cjs.
  42947. var doCreateNode;
  42948. if (doc && !env$1.canvasSupported) {
  42949. try {
  42950. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  42951. doCreateNode = function (tagName) {
  42952. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  42953. };
  42954. }
  42955. catch (e) {
  42956. doCreateNode = function (tagName) {
  42957. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  42958. };
  42959. }
  42960. }
  42961. // From raphael
  42962. function initVML() {
  42963. if (vmlInited || !doc) {
  42964. return;
  42965. }
  42966. vmlInited = true;
  42967. var styleSheets = doc.styleSheets;
  42968. if (styleSheets.length < 31) {
  42969. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  42970. }
  42971. else {
  42972. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  42973. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  42974. }
  42975. }
  42976. // http://www.w3.org/TR/NOTE-VML
  42977. // TODO Use proxy like svg instead of overwrite brush methods
  42978. var CMD$3 = PathProxy.CMD;
  42979. var round$2 = Math.round;
  42980. var sqrt = Math.sqrt;
  42981. var abs$1 = Math.abs;
  42982. var cos = Math.cos;
  42983. var sin = Math.sin;
  42984. var mathMax$5 = Math.max;
  42985. if (!env$1.canvasSupported) {
  42986. var comma = ',';
  42987. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  42988. var Z = 21600;
  42989. var Z2 = Z / 2;
  42990. var ZLEVEL_BASE = 100000;
  42991. var Z_BASE = 1000;
  42992. var initRootElStyle = function (el) {
  42993. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  42994. el.coordsize = Z + ',' + Z;
  42995. el.coordorigin = '0,0';
  42996. };
  42997. var encodeHtmlAttribute = function (s) {
  42998. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  42999. };
  43000. var rgb2Str = function (r, g, b) {
  43001. return 'rgb(' + [r, g, b].join(',') + ')';
  43002. };
  43003. var append = function (parent, child) {
  43004. if (child && parent && child.parentNode !== parent) {
  43005. parent.appendChild(child);
  43006. }
  43007. };
  43008. var remove = function (parent, child) {
  43009. if (child && parent && child.parentNode === parent) {
  43010. parent.removeChild(child);
  43011. }
  43012. };
  43013. var getZIndex = function (zlevel, z, z2) {
  43014. // z 的取值范围为 [0, 1000]
  43015. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  43016. };
  43017. var parsePercent$3 = function (value, maxValue) {
  43018. if (typeof value === 'string') {
  43019. if (value.lastIndexOf('%') >= 0) {
  43020. return parseFloat(value) / 100 * maxValue;
  43021. }
  43022. return parseFloat(value);
  43023. }
  43024. return value;
  43025. };
  43026. /***************************************************
  43027. * PATH
  43028. **************************************************/
  43029. var setColorAndOpacity = function (el, color, opacity) {
  43030. var colorArr = parse(color);
  43031. opacity = +opacity;
  43032. if (isNaN(opacity)) {
  43033. opacity = 1;
  43034. }
  43035. if (colorArr) {
  43036. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  43037. el.opacity = opacity * colorArr[3];
  43038. }
  43039. };
  43040. var getColorAndAlpha = function (color) {
  43041. var colorArr = parse(color);
  43042. return [
  43043. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  43044. colorArr[3]
  43045. ];
  43046. };
  43047. var updateFillNode = function (el, style, zrEl) {
  43048. // TODO pattern
  43049. var fill = style.fill;
  43050. if (fill != null) {
  43051. // Modified from excanvas
  43052. if (fill instanceof Gradient) {
  43053. var gradientType;
  43054. var angle = 0;
  43055. var focus = [0, 0];
  43056. // additional offset
  43057. var shift = 0;
  43058. // scale factor for offset
  43059. var expansion = 1;
  43060. var rect = zrEl.getBoundingRect();
  43061. var rectWidth = rect.width;
  43062. var rectHeight = rect.height;
  43063. if (fill.type === 'linear') {
  43064. gradientType = 'gradient';
  43065. var transform = zrEl.transform;
  43066. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43067. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  43068. if (transform) {
  43069. applyTransform(p0, p0, transform);
  43070. applyTransform(p1, p1, transform);
  43071. }
  43072. var dx = p1[0] - p0[0];
  43073. var dy = p1[1] - p0[1];
  43074. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  43075. // The angle should be a non-negative number.
  43076. if (angle < 0) {
  43077. angle += 360;
  43078. }
  43079. // Very small angles produce an unexpected result because they are
  43080. // converted to a scientific notation string.
  43081. if (angle < 1e-6) {
  43082. angle = 0;
  43083. }
  43084. }
  43085. else {
  43086. gradientType = 'gradientradial';
  43087. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43088. var transform = zrEl.transform;
  43089. var scale$$1 = zrEl.scale;
  43090. var width = rectWidth;
  43091. var height = rectHeight;
  43092. focus = [
  43093. // Percent in bounding rect
  43094. (p0[0] - rect.x) / width,
  43095. (p0[1] - rect.y) / height
  43096. ];
  43097. if (transform) {
  43098. applyTransform(p0, p0, transform);
  43099. }
  43100. width /= scale$$1[0] * Z;
  43101. height /= scale$$1[1] * Z;
  43102. var dimension = mathMax$5(width, height);
  43103. shift = 2 * 0 / dimension;
  43104. expansion = 2 * fill.r / dimension - shift;
  43105. }
  43106. // We need to sort the color stops in ascending order by offset,
  43107. // otherwise IE won't interpret it correctly.
  43108. var stops = fill.colorStops.slice();
  43109. stops.sort(function(cs1, cs2) {
  43110. return cs1.offset - cs2.offset;
  43111. });
  43112. var length$$1 = stops.length;
  43113. // Color and alpha list of first and last stop
  43114. var colorAndAlphaList = [];
  43115. var colors = [];
  43116. for (var i = 0; i < length$$1; i++) {
  43117. var stop = stops[i];
  43118. var colorAndAlpha = getColorAndAlpha(stop.color);
  43119. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  43120. if (i === 0 || i === length$$1 - 1) {
  43121. colorAndAlphaList.push(colorAndAlpha);
  43122. }
  43123. }
  43124. if (length$$1 >= 2) {
  43125. var color1 = colorAndAlphaList[0][0];
  43126. var color2 = colorAndAlphaList[1][0];
  43127. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  43128. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  43129. el.type = gradientType;
  43130. el.method = 'none';
  43131. el.focus = '100%';
  43132. el.angle = angle;
  43133. el.color = color1;
  43134. el.color2 = color2;
  43135. el.colors = colors.join(',');
  43136. // When colors attribute is used, the meanings of opacity and o:opacity2
  43137. // are reversed.
  43138. el.opacity = opacity2;
  43139. // FIXME g_o_:opacity ?
  43140. el.opacity2 = opacity1;
  43141. }
  43142. if (gradientType === 'radial') {
  43143. el.focusposition = focus.join(',');
  43144. }
  43145. }
  43146. else {
  43147. // FIXME Change from Gradient fill to color fill
  43148. setColorAndOpacity(el, fill, style.opacity);
  43149. }
  43150. }
  43151. };
  43152. var updateStrokeNode = function (el, style) {
  43153. // if (style.lineJoin != null) {
  43154. // el.joinstyle = style.lineJoin;
  43155. // }
  43156. // if (style.miterLimit != null) {
  43157. // el.miterlimit = style.miterLimit * Z;
  43158. // }
  43159. // if (style.lineCap != null) {
  43160. // el.endcap = style.lineCap;
  43161. // }
  43162. if (style.lineDash != null) {
  43163. el.dashstyle = style.lineDash.join(' ');
  43164. }
  43165. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  43166. setColorAndOpacity(el, style.stroke, style.opacity);
  43167. }
  43168. };
  43169. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  43170. var isFill = type == 'fill';
  43171. var el = vmlEl.getElementsByTagName(type)[0];
  43172. // Stroke must have lineWidth
  43173. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  43174. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  43175. // FIXME Remove before updating, or set `colors` will throw error
  43176. if (style[type] instanceof Gradient) {
  43177. remove(vmlEl, el);
  43178. }
  43179. if (!el) {
  43180. el = createNode(type);
  43181. }
  43182. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  43183. append(vmlEl, el);
  43184. }
  43185. else {
  43186. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  43187. remove(vmlEl, el);
  43188. }
  43189. };
  43190. var points$1 = [[], [], []];
  43191. var pathDataToString = function (path, m) {
  43192. var M = CMD$3.M;
  43193. var C = CMD$3.C;
  43194. var L = CMD$3.L;
  43195. var A = CMD$3.A;
  43196. var Q = CMD$3.Q;
  43197. var str = [];
  43198. var nPoint;
  43199. var cmdStr;
  43200. var cmd;
  43201. var i;
  43202. var xi;
  43203. var yi;
  43204. var data = path.data;
  43205. var dataLength = path.len();
  43206. for (i = 0; i < dataLength;) {
  43207. cmd = data[i++];
  43208. cmdStr = '';
  43209. nPoint = 0;
  43210. switch (cmd) {
  43211. case M:
  43212. cmdStr = ' m ';
  43213. nPoint = 1;
  43214. xi = data[i++];
  43215. yi = data[i++];
  43216. points$1[0][0] = xi;
  43217. points$1[0][1] = yi;
  43218. break;
  43219. case L:
  43220. cmdStr = ' l ';
  43221. nPoint = 1;
  43222. xi = data[i++];
  43223. yi = data[i++];
  43224. points$1[0][0] = xi;
  43225. points$1[0][1] = yi;
  43226. break;
  43227. case Q:
  43228. case C:
  43229. cmdStr = ' c ';
  43230. nPoint = 3;
  43231. var x1 = data[i++];
  43232. var y1 = data[i++];
  43233. var x2 = data[i++];
  43234. var y2 = data[i++];
  43235. var x3;
  43236. var y3;
  43237. if (cmd === Q) {
  43238. // Convert quadratic to cubic using degree elevation
  43239. x3 = x2;
  43240. y3 = y2;
  43241. x2 = (x2 + 2 * x1) / 3;
  43242. y2 = (y2 + 2 * y1) / 3;
  43243. x1 = (xi + 2 * x1) / 3;
  43244. y1 = (yi + 2 * y1) / 3;
  43245. }
  43246. else {
  43247. x3 = data[i++];
  43248. y3 = data[i++];
  43249. }
  43250. points$1[0][0] = x1;
  43251. points$1[0][1] = y1;
  43252. points$1[1][0] = x2;
  43253. points$1[1][1] = y2;
  43254. points$1[2][0] = x3;
  43255. points$1[2][1] = y3;
  43256. xi = x3;
  43257. yi = y3;
  43258. break;
  43259. case A:
  43260. var x = 0;
  43261. var y = 0;
  43262. var sx = 1;
  43263. var sy = 1;
  43264. var angle = 0;
  43265. if (m) {
  43266. // Extract SRT from matrix
  43267. x = m[4];
  43268. y = m[5];
  43269. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  43270. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  43271. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  43272. }
  43273. var cx = data[i++];
  43274. var cy = data[i++];
  43275. var rx = data[i++];
  43276. var ry = data[i++];
  43277. var startAngle = data[i++] + angle;
  43278. var endAngle = data[i++] + startAngle + angle;
  43279. // FIXME
  43280. // var psi = data[i++];
  43281. i++;
  43282. var clockwise = data[i++];
  43283. var x0 = cx + cos(startAngle) * rx;
  43284. var y0 = cy + sin(startAngle) * ry;
  43285. var x1 = cx + cos(endAngle) * rx;
  43286. var y1 = cy + sin(endAngle) * ry;
  43287. var type = clockwise ? ' wa ' : ' at ';
  43288. if (Math.abs(x0 - x1) < 1e-4) {
  43289. // IE won't render arches drawn counter clockwise if x0 == x1.
  43290. if (Math.abs(endAngle - startAngle) > 1e-2) {
  43291. // Offset x0 by 1/80 of a pixel. Use something
  43292. // that can be represented in binary
  43293. if (clockwise) {
  43294. x0 += 270 / Z;
  43295. }
  43296. }
  43297. else {
  43298. // Avoid case draw full circle
  43299. if (Math.abs(y0 - cy) < 1e-4) {
  43300. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  43301. y1 -= 270 / Z;
  43302. }
  43303. else {
  43304. y1 += 270 / Z;
  43305. }
  43306. }
  43307. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  43308. x1 += 270 / Z;
  43309. }
  43310. else {
  43311. x1 -= 270 / Z;
  43312. }
  43313. }
  43314. }
  43315. str.push(
  43316. type,
  43317. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  43318. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  43319. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  43320. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  43321. round$2((x0 * sx + x) * Z - Z2), comma,
  43322. round$2((y0 * sy + y) * Z - Z2), comma,
  43323. round$2((x1 * sx + x) * Z - Z2), comma,
  43324. round$2((y1 * sy + y) * Z - Z2)
  43325. );
  43326. xi = x1;
  43327. yi = y1;
  43328. break;
  43329. case CMD$3.R:
  43330. var p0 = points$1[0];
  43331. var p1 = points$1[1];
  43332. // x0, y0
  43333. p0[0] = data[i++];
  43334. p0[1] = data[i++];
  43335. // x1, y1
  43336. p1[0] = p0[0] + data[i++];
  43337. p1[1] = p0[1] + data[i++];
  43338. if (m) {
  43339. applyTransform(p0, p0, m);
  43340. applyTransform(p1, p1, m);
  43341. }
  43342. p0[0] = round$2(p0[0] * Z - Z2);
  43343. p1[0] = round$2(p1[0] * Z - Z2);
  43344. p0[1] = round$2(p0[1] * Z - Z2);
  43345. p1[1] = round$2(p1[1] * Z - Z2);
  43346. str.push(
  43347. // x0, y0
  43348. ' m ', p0[0], comma, p0[1],
  43349. // x1, y0
  43350. ' l ', p1[0], comma, p0[1],
  43351. // x1, y1
  43352. ' l ', p1[0], comma, p1[1],
  43353. // x0, y1
  43354. ' l ', p0[0], comma, p1[1]
  43355. );
  43356. break;
  43357. case CMD$3.Z:
  43358. // FIXME Update xi, yi
  43359. str.push(' x ');
  43360. }
  43361. if (nPoint > 0) {
  43362. str.push(cmdStr);
  43363. for (var k = 0; k < nPoint; k++) {
  43364. var p = points$1[k];
  43365. m && applyTransform(p, p, m);
  43366. // 不 round 会非常慢
  43367. str.push(
  43368. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  43369. k < nPoint - 1 ? comma : ''
  43370. );
  43371. }
  43372. }
  43373. }
  43374. return str.join('');
  43375. };
  43376. // Rewrite the original path method
  43377. Path.prototype.brushVML = function (vmlRoot) {
  43378. var style = this.style;
  43379. var vmlEl = this._vmlEl;
  43380. if (!vmlEl) {
  43381. vmlEl = createNode('shape');
  43382. initRootElStyle(vmlEl);
  43383. this._vmlEl = vmlEl;
  43384. }
  43385. updateFillAndStroke(vmlEl, 'fill', style, this);
  43386. updateFillAndStroke(vmlEl, 'stroke', style, this);
  43387. var m = this.transform;
  43388. var needTransform = m != null;
  43389. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  43390. if (strokeEl) {
  43391. var lineWidth = style.lineWidth;
  43392. // Get the line scale.
  43393. // Determinant of this.m_ means how much the area is enlarged by the
  43394. // transformation. So its square root can be used as a scale factor
  43395. // for width.
  43396. if (needTransform && !style.strokeNoScale) {
  43397. var det = m[0] * m[3] - m[1] * m[2];
  43398. lineWidth *= sqrt(abs$1(det));
  43399. }
  43400. strokeEl.weight = lineWidth + 'px';
  43401. }
  43402. var path = this.path || (this.path = new PathProxy());
  43403. if (this.__dirtyPath) {
  43404. path.beginPath();
  43405. this.buildPath(path, this.shape);
  43406. path.toStatic();
  43407. this.__dirtyPath = false;
  43408. }
  43409. vmlEl.path = pathDataToString(path, this.transform);
  43410. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43411. // Append to root
  43412. append(vmlRoot, vmlEl);
  43413. // Text
  43414. if (style.text != null) {
  43415. this.drawRectText(vmlRoot, this.getBoundingRect());
  43416. }
  43417. else {
  43418. this.removeRectText(vmlRoot);
  43419. }
  43420. };
  43421. Path.prototype.onRemove = function (vmlRoot) {
  43422. remove(vmlRoot, this._vmlEl);
  43423. this.removeRectText(vmlRoot);
  43424. };
  43425. Path.prototype.onAdd = function (vmlRoot) {
  43426. append(vmlRoot, this._vmlEl);
  43427. this.appendRectText(vmlRoot);
  43428. };
  43429. /***************************************************
  43430. * IMAGE
  43431. **************************************************/
  43432. var isImage = function (img) {
  43433. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  43434. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  43435. // return img instanceof Image;
  43436. };
  43437. // Rewrite the original path method
  43438. ZImage.prototype.brushVML = function (vmlRoot) {
  43439. var style = this.style;
  43440. var image = style.image;
  43441. // Image original width, height
  43442. var ow;
  43443. var oh;
  43444. if (isImage(image)) {
  43445. var src = image.src;
  43446. if (src === this._imageSrc) {
  43447. ow = this._imageWidth;
  43448. oh = this._imageHeight;
  43449. }
  43450. else {
  43451. var imageRuntimeStyle = image.runtimeStyle;
  43452. var oldRuntimeWidth = imageRuntimeStyle.width;
  43453. var oldRuntimeHeight = imageRuntimeStyle.height;
  43454. imageRuntimeStyle.width = 'auto';
  43455. imageRuntimeStyle.height = 'auto';
  43456. // get the original size
  43457. ow = image.width;
  43458. oh = image.height;
  43459. // and remove overides
  43460. imageRuntimeStyle.width = oldRuntimeWidth;
  43461. imageRuntimeStyle.height = oldRuntimeHeight;
  43462. // Caching image original width, height and src
  43463. this._imageSrc = src;
  43464. this._imageWidth = ow;
  43465. this._imageHeight = oh;
  43466. }
  43467. image = src;
  43468. }
  43469. else {
  43470. if (image === this._imageSrc) {
  43471. ow = this._imageWidth;
  43472. oh = this._imageHeight;
  43473. }
  43474. }
  43475. if (!image) {
  43476. return;
  43477. }
  43478. var x = style.x || 0;
  43479. var y = style.y || 0;
  43480. var dw = style.width;
  43481. var dh = style.height;
  43482. var sw = style.sWidth;
  43483. var sh = style.sHeight;
  43484. var sx = style.sx || 0;
  43485. var sy = style.sy || 0;
  43486. var hasCrop = sw && sh;
  43487. var vmlEl = this._vmlEl;
  43488. if (!vmlEl) {
  43489. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  43490. // vmlEl = vmlCore.createNode('group');
  43491. vmlEl = doc.createElement('div');
  43492. initRootElStyle(vmlEl);
  43493. this._vmlEl = vmlEl;
  43494. }
  43495. var vmlElStyle = vmlEl.style;
  43496. var hasRotation = false;
  43497. var m;
  43498. var scaleX = 1;
  43499. var scaleY = 1;
  43500. if (this.transform) {
  43501. m = this.transform;
  43502. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  43503. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  43504. hasRotation = m[1] || m[2];
  43505. }
  43506. if (hasRotation) {
  43507. // If filters are necessary (rotation exists), create them
  43508. // filters are bog-slow, so only create them if abbsolutely necessary
  43509. // The following check doesn't account for skews (which don't exist
  43510. // in the canvas spec (yet) anyway.
  43511. // From excanvas
  43512. var p0 = [x, y];
  43513. var p1 = [x + dw, y];
  43514. var p2 = [x, y + dh];
  43515. var p3 = [x + dw, y + dh];
  43516. applyTransform(p0, p0, m);
  43517. applyTransform(p1, p1, m);
  43518. applyTransform(p2, p2, m);
  43519. applyTransform(p3, p3, m);
  43520. var maxX = mathMax$5(p0[0], p1[0], p2[0], p3[0]);
  43521. var maxY = mathMax$5(p0[1], p1[1], p2[1], p3[1]);
  43522. var transformFilter = [];
  43523. transformFilter.push('M11=', m[0] / scaleX, comma,
  43524. 'M12=', m[2] / scaleY, comma,
  43525. 'M21=', m[1] / scaleX, comma,
  43526. 'M22=', m[3] / scaleY, comma,
  43527. 'Dx=', round$2(x * scaleX + m[4]), comma,
  43528. 'Dy=', round$2(y * scaleY + m[5]));
  43529. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  43530. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  43531. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  43532. + transformFilter.join('') + ', SizingMethod=clip)';
  43533. }
  43534. else {
  43535. if (m) {
  43536. x = x * scaleX + m[4];
  43537. y = y * scaleY + m[5];
  43538. }
  43539. vmlElStyle.filter = '';
  43540. vmlElStyle.left = round$2(x) + 'px';
  43541. vmlElStyle.top = round$2(y) + 'px';
  43542. }
  43543. var imageEl = this._imageEl;
  43544. var cropEl = this._cropEl;
  43545. if (!imageEl) {
  43546. imageEl = doc.createElement('div');
  43547. this._imageEl = imageEl;
  43548. }
  43549. var imageELStyle = imageEl.style;
  43550. if (hasCrop) {
  43551. // Needs know image original width and height
  43552. if (! (ow && oh)) {
  43553. var tmpImage = new Image();
  43554. var self = this;
  43555. tmpImage.onload = function () {
  43556. tmpImage.onload = null;
  43557. ow = tmpImage.width;
  43558. oh = tmpImage.height;
  43559. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  43560. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  43561. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  43562. // Caching image original width, height and src
  43563. self._imageWidth = ow;
  43564. self._imageHeight = oh;
  43565. self._imageSrc = image;
  43566. };
  43567. tmpImage.src = image;
  43568. }
  43569. else {
  43570. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  43571. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  43572. }
  43573. if (! cropEl) {
  43574. cropEl = doc.createElement('div');
  43575. cropEl.style.overflow = 'hidden';
  43576. this._cropEl = cropEl;
  43577. }
  43578. var cropElStyle = cropEl.style;
  43579. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  43580. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  43581. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  43582. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  43583. if (! cropEl.parentNode) {
  43584. vmlEl.appendChild(cropEl);
  43585. }
  43586. if (imageEl.parentNode != cropEl) {
  43587. cropEl.appendChild(imageEl);
  43588. }
  43589. }
  43590. else {
  43591. imageELStyle.width = round$2(scaleX * dw) + 'px';
  43592. imageELStyle.height = round$2(scaleY * dh) + 'px';
  43593. vmlEl.appendChild(imageEl);
  43594. if (cropEl && cropEl.parentNode) {
  43595. vmlEl.removeChild(cropEl);
  43596. this._cropEl = null;
  43597. }
  43598. }
  43599. var filterStr = '';
  43600. var alpha = style.opacity;
  43601. if (alpha < 1) {
  43602. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  43603. }
  43604. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  43605. imageELStyle.filter = filterStr;
  43606. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43607. // Append to root
  43608. append(vmlRoot, vmlEl);
  43609. // Text
  43610. if (style.text != null) {
  43611. this.drawRectText(vmlRoot, this.getBoundingRect());
  43612. }
  43613. };
  43614. ZImage.prototype.onRemove = function (vmlRoot) {
  43615. remove(vmlRoot, this._vmlEl);
  43616. this._vmlEl = null;
  43617. this._cropEl = null;
  43618. this._imageEl = null;
  43619. this.removeRectText(vmlRoot);
  43620. };
  43621. ZImage.prototype.onAdd = function (vmlRoot) {
  43622. append(vmlRoot, this._vmlEl);
  43623. this.appendRectText(vmlRoot);
  43624. };
  43625. /***************************************************
  43626. * TEXT
  43627. **************************************************/
  43628. var DEFAULT_STYLE_NORMAL = 'normal';
  43629. var fontStyleCache = {};
  43630. var fontStyleCacheCount = 0;
  43631. var MAX_FONT_CACHE_SIZE = 100;
  43632. var fontEl = document.createElement('div');
  43633. var getFontStyle = function (fontString) {
  43634. var fontStyle = fontStyleCache[fontString];
  43635. if (!fontStyle) {
  43636. // Clear cache
  43637. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  43638. fontStyleCacheCount = 0;
  43639. fontStyleCache = {};
  43640. }
  43641. var style = fontEl.style;
  43642. var fontFamily;
  43643. try {
  43644. style.font = fontString;
  43645. fontFamily = style.fontFamily.split(',')[0];
  43646. }
  43647. catch (e) {
  43648. }
  43649. fontStyle = {
  43650. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  43651. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  43652. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  43653. size: parseFloat(style.fontSize || 12) | 0,
  43654. family: fontFamily || 'Microsoft YaHei'
  43655. };
  43656. fontStyleCache[fontString] = fontStyle;
  43657. fontStyleCacheCount++;
  43658. }
  43659. return fontStyle;
  43660. };
  43661. var textMeasureEl;
  43662. // Overwrite measure text method
  43663. $override$1('measureText', function (text, textFont) {
  43664. var doc$$1 = doc;
  43665. if (!textMeasureEl) {
  43666. textMeasureEl = doc$$1.createElement('div');
  43667. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  43668. + 'padding:0;margin:0;border:none;white-space:pre;';
  43669. doc.body.appendChild(textMeasureEl);
  43670. }
  43671. try {
  43672. textMeasureEl.style.font = textFont;
  43673. } catch (ex) {
  43674. // Ignore failures to set to invalid font.
  43675. }
  43676. textMeasureEl.innerHTML = '';
  43677. // Don't use innerHTML or innerText because they allow markup/whitespace.
  43678. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  43679. return {
  43680. width: textMeasureEl.offsetWidth
  43681. };
  43682. });
  43683. var tmpRect$2 = new BoundingRect();
  43684. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  43685. var style = this.style;
  43686. // Optimize, avoid normalize every time.
  43687. this.__dirty && normalizeTextStyle(style, true);
  43688. var text = style.text;
  43689. // Convert to string
  43690. text != null && (text += '');
  43691. if (!text) {
  43692. return;
  43693. }
  43694. // Convert rich text to plain text. Rich text is not supported in
  43695. // IE8-, but tags in rich text template will be removed.
  43696. if (style.rich) {
  43697. var contentBlock = parseRichText(text, style);
  43698. text = [];
  43699. for (var i = 0; i < contentBlock.lines.length; i++) {
  43700. var tokens = contentBlock.lines[i].tokens;
  43701. var textLine = [];
  43702. for (var j = 0; j < tokens.length; j++) {
  43703. textLine.push(tokens[j].text);
  43704. }
  43705. text.push(textLine.join(''));
  43706. }
  43707. text = text.join('\n');
  43708. }
  43709. var x;
  43710. var y;
  43711. var align = style.textAlign;
  43712. var verticalAlign = style.textVerticalAlign;
  43713. var fontStyle = getFontStyle(style.font);
  43714. // FIXME encodeHtmlAttribute ?
  43715. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  43716. + fontStyle.size + 'px "' + fontStyle.family + '"';
  43717. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  43718. // Transform rect to view space
  43719. var m = this.transform;
  43720. // Ignore transform for text in other element
  43721. if (m && !fromTextEl) {
  43722. tmpRect$2.copy(rect);
  43723. tmpRect$2.applyTransform(m);
  43724. rect = tmpRect$2;
  43725. }
  43726. if (!fromTextEl) {
  43727. var textPosition = style.textPosition;
  43728. var distance$$1 = style.textDistance;
  43729. // Text position represented by coord
  43730. if (textPosition instanceof Array) {
  43731. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  43732. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  43733. align = align || 'left';
  43734. }
  43735. else {
  43736. var res = adjustTextPositionOnRect(
  43737. textPosition, rect, distance$$1
  43738. );
  43739. x = res.x;
  43740. y = res.y;
  43741. // Default align and baseline when has textPosition
  43742. align = align || res.textAlign;
  43743. verticalAlign = verticalAlign || res.textVerticalAlign;
  43744. }
  43745. }
  43746. else {
  43747. x = rect.x;
  43748. y = rect.y;
  43749. }
  43750. x = adjustTextX(x, textRect.width, align);
  43751. y = adjustTextY(y, textRect.height, verticalAlign);
  43752. // Force baseline 'middle'
  43753. y += textRect.height / 2;
  43754. // var fontSize = fontStyle.size;
  43755. // 1.75 is an arbitrary number, as there is no info about the text baseline
  43756. // switch (baseline) {
  43757. // case 'hanging':
  43758. // case 'top':
  43759. // y += fontSize / 1.75;
  43760. // break;
  43761. // case 'middle':
  43762. // break;
  43763. // default:
  43764. // // case null:
  43765. // // case 'alphabetic':
  43766. // // case 'ideographic':
  43767. // // case 'bottom':
  43768. // y -= fontSize / 2.25;
  43769. // break;
  43770. // }
  43771. // switch (align) {
  43772. // case 'left':
  43773. // break;
  43774. // case 'center':
  43775. // x -= textRect.width / 2;
  43776. // break;
  43777. // case 'right':
  43778. // x -= textRect.width;
  43779. // break;
  43780. // case 'end':
  43781. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  43782. // break;
  43783. // case 'start':
  43784. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  43785. // break;
  43786. // default:
  43787. // align = 'left';
  43788. // }
  43789. var createNode$$1 = createNode;
  43790. var textVmlEl = this._textVmlEl;
  43791. var pathEl;
  43792. var textPathEl;
  43793. var skewEl;
  43794. if (!textVmlEl) {
  43795. textVmlEl = createNode$$1('line');
  43796. pathEl = createNode$$1('path');
  43797. textPathEl = createNode$$1('textpath');
  43798. skewEl = createNode$$1('skew');
  43799. // FIXME Why here is not cammel case
  43800. // Align 'center' seems wrong
  43801. textPathEl.style['v-text-align'] = 'left';
  43802. initRootElStyle(textVmlEl);
  43803. pathEl.textpathok = true;
  43804. textPathEl.on = true;
  43805. textVmlEl.from = '0 0';
  43806. textVmlEl.to = '1000 0.05';
  43807. append(textVmlEl, skewEl);
  43808. append(textVmlEl, pathEl);
  43809. append(textVmlEl, textPathEl);
  43810. this._textVmlEl = textVmlEl;
  43811. }
  43812. else {
  43813. // 这里是在前面 appendChild 保证顺序的前提下
  43814. skewEl = textVmlEl.firstChild;
  43815. pathEl = skewEl.nextSibling;
  43816. textPathEl = pathEl.nextSibling;
  43817. }
  43818. var coords = [x, y];
  43819. var textVmlElStyle = textVmlEl.style;
  43820. // Ignore transform for text in other element
  43821. if (m && fromTextEl) {
  43822. applyTransform(coords, coords, m);
  43823. skewEl.on = true;
  43824. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  43825. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  43826. // Text position
  43827. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  43828. // Left top point as origin
  43829. skewEl.origin = '0 0';
  43830. textVmlElStyle.left = '0px';
  43831. textVmlElStyle.top = '0px';
  43832. }
  43833. else {
  43834. skewEl.on = false;
  43835. textVmlElStyle.left = round$2(x) + 'px';
  43836. textVmlElStyle.top = round$2(y) + 'px';
  43837. }
  43838. textPathEl.string = encodeHtmlAttribute(text);
  43839. // TODO
  43840. try {
  43841. textPathEl.style.font = font;
  43842. }
  43843. // Error font format
  43844. catch (e) {}
  43845. updateFillAndStroke(textVmlEl, 'fill', {
  43846. fill: style.textFill,
  43847. opacity: style.opacity
  43848. }, this);
  43849. updateFillAndStroke(textVmlEl, 'stroke', {
  43850. stroke: style.textStroke,
  43851. opacity: style.opacity,
  43852. lineDash: style.lineDash
  43853. }, this);
  43854. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  43855. // Attached to root
  43856. append(vmlRoot, textVmlEl);
  43857. };
  43858. var removeRectText = function (vmlRoot) {
  43859. remove(vmlRoot, this._textVmlEl);
  43860. this._textVmlEl = null;
  43861. };
  43862. var appendRectText = function (vmlRoot) {
  43863. append(vmlRoot, this._textVmlEl);
  43864. };
  43865. var list = [RectText, Displayable, ZImage, Path, Text];
  43866. // In case Displayable has been mixed in RectText
  43867. for (var i$1 = 0; i$1 < list.length; i$1++) {
  43868. var proto$7 = list[i$1].prototype;
  43869. proto$7.drawRectText = drawRectText;
  43870. proto$7.removeRectText = removeRectText;
  43871. proto$7.appendRectText = appendRectText;
  43872. }
  43873. Text.prototype.brushVML = function (vmlRoot) {
  43874. var style = this.style;
  43875. if (style.text != null) {
  43876. this.drawRectText(vmlRoot, {
  43877. x: style.x || 0, y: style.y || 0,
  43878. width: 0, height: 0
  43879. }, this.getBoundingRect(), true);
  43880. }
  43881. else {
  43882. this.removeRectText(vmlRoot);
  43883. }
  43884. };
  43885. Text.prototype.onRemove = function (vmlRoot) {
  43886. this.removeRectText(vmlRoot);
  43887. };
  43888. Text.prototype.onAdd = function (vmlRoot) {
  43889. this.appendRectText(vmlRoot);
  43890. };
  43891. }
  43892. /**
  43893. * VML Painter.
  43894. *
  43895. * @module zrender/vml/Painter
  43896. */
  43897. function parseInt10$1(val) {
  43898. return parseInt(val, 10);
  43899. }
  43900. /**
  43901. * @alias module:zrender/vml/Painter
  43902. */
  43903. function VMLPainter(root, storage) {
  43904. initVML();
  43905. this.root = root;
  43906. this.storage = storage;
  43907. var vmlViewport = document.createElement('div');
  43908. var vmlRoot = document.createElement('div');
  43909. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  43910. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  43911. root.appendChild(vmlViewport);
  43912. this._vmlRoot = vmlRoot;
  43913. this._vmlViewport = vmlViewport;
  43914. this.resize();
  43915. // Modify storage
  43916. var oldDelFromStorage = storage.delFromStorage;
  43917. var oldAddToStorage = storage.addToStorage;
  43918. storage.delFromStorage = function (el) {
  43919. oldDelFromStorage.call(storage, el);
  43920. if (el) {
  43921. el.onRemove && el.onRemove(vmlRoot);
  43922. }
  43923. };
  43924. storage.addToStorage = function (el) {
  43925. // Displayable already has a vml node
  43926. el.onAdd && el.onAdd(vmlRoot);
  43927. oldAddToStorage.call(storage, el);
  43928. };
  43929. this._firstPaint = true;
  43930. }
  43931. VMLPainter.prototype = {
  43932. constructor: VMLPainter,
  43933. getType: function () {
  43934. return 'vml';
  43935. },
  43936. /**
  43937. * @return {HTMLDivElement}
  43938. */
  43939. getViewportRoot: function () {
  43940. return this._vmlViewport;
  43941. },
  43942. getViewportRootOffset: function () {
  43943. var viewportRoot = this.getViewportRoot();
  43944. if (viewportRoot) {
  43945. return {
  43946. offsetLeft: viewportRoot.offsetLeft || 0,
  43947. offsetTop: viewportRoot.offsetTop || 0
  43948. };
  43949. }
  43950. },
  43951. /**
  43952. * 刷新
  43953. */
  43954. refresh: function () {
  43955. var list = this.storage.getDisplayList(true, true);
  43956. this._paintList(list);
  43957. },
  43958. _paintList: function (list) {
  43959. var vmlRoot = this._vmlRoot;
  43960. for (var i = 0; i < list.length; i++) {
  43961. var el = list[i];
  43962. if (el.invisible || el.ignore) {
  43963. if (!el.__alreadyNotVisible) {
  43964. el.onRemove(vmlRoot);
  43965. }
  43966. // Set as already invisible
  43967. el.__alreadyNotVisible = true;
  43968. }
  43969. else {
  43970. if (el.__alreadyNotVisible) {
  43971. el.onAdd(vmlRoot);
  43972. }
  43973. el.__alreadyNotVisible = false;
  43974. if (el.__dirty) {
  43975. el.beforeBrush && el.beforeBrush();
  43976. (el.brushVML || el.brush).call(el, vmlRoot);
  43977. el.afterBrush && el.afterBrush();
  43978. }
  43979. }
  43980. el.__dirty = false;
  43981. }
  43982. if (this._firstPaint) {
  43983. // Detached from document at first time
  43984. // to avoid page refreshing too many times
  43985. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  43986. this._vmlViewport.appendChild(vmlRoot);
  43987. this._firstPaint = false;
  43988. }
  43989. },
  43990. resize: function (width, height) {
  43991. var width = width == null ? this._getWidth() : width;
  43992. var height = height == null ? this._getHeight() : height;
  43993. if (this._width != width || this._height != height) {
  43994. this._width = width;
  43995. this._height = height;
  43996. var vmlViewportStyle = this._vmlViewport.style;
  43997. vmlViewportStyle.width = width + 'px';
  43998. vmlViewportStyle.height = height + 'px';
  43999. }
  44000. },
  44001. dispose: function () {
  44002. this.root.innerHTML = '';
  44003. this._vmlRoot =
  44004. this._vmlViewport =
  44005. this.storage = null;
  44006. },
  44007. getWidth: function () {
  44008. return this._width;
  44009. },
  44010. getHeight: function () {
  44011. return this._height;
  44012. },
  44013. clear: function () {
  44014. if (this._vmlViewport) {
  44015. this.root.removeChild(this._vmlViewport);
  44016. }
  44017. },
  44018. _getWidth: function () {
  44019. var root = this.root;
  44020. var stl = root.currentStyle;
  44021. return ((root.clientWidth || parseInt10$1(stl.width))
  44022. - parseInt10$1(stl.paddingLeft)
  44023. - parseInt10$1(stl.paddingRight)) | 0;
  44024. },
  44025. _getHeight: function () {
  44026. var root = this.root;
  44027. var stl = root.currentStyle;
  44028. return ((root.clientHeight || parseInt10$1(stl.height))
  44029. - parseInt10$1(stl.paddingTop)
  44030. - parseInt10$1(stl.paddingBottom)) | 0;
  44031. }
  44032. };
  44033. // Not supported methods
  44034. function createMethodNotSupport(method) {
  44035. return function () {
  44036. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  44037. };
  44038. }
  44039. // Unsupported methods
  44040. each$1([
  44041. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  44042. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  44043. ], function (name) {
  44044. VMLPainter.prototype[name] = createMethodNotSupport(name);
  44045. });
  44046. registerPainter('vml', VMLPainter);
  44047. var svgURI = 'http://www.w3.org/2000/svg';
  44048. function createElement(name) {
  44049. return document.createElementNS(svgURI, name);
  44050. }
  44051. // TODO
  44052. // 1. shadow
  44053. // 2. Image: sx, sy, sw, sh
  44054. var CMD$4 = PathProxy.CMD;
  44055. var arrayJoin = Array.prototype.join;
  44056. var NONE = 'none';
  44057. var mathRound = Math.round;
  44058. var mathSin$3 = Math.sin;
  44059. var mathCos$3 = Math.cos;
  44060. var PI$3 = Math.PI;
  44061. var PI2$5 = Math.PI * 2;
  44062. var degree = 180 / PI$3;
  44063. var EPSILON$4 = 1e-4;
  44064. function round4(val) {
  44065. return mathRound(val * 1e4) / 1e4;
  44066. }
  44067. function isAroundZero$1(val) {
  44068. return val < EPSILON$4 && val > -EPSILON$4;
  44069. }
  44070. function pathHasFill(style, isText) {
  44071. var fill = isText ? style.textFill : style.fill;
  44072. return fill != null && fill !== NONE;
  44073. }
  44074. function pathHasStroke(style, isText) {
  44075. var stroke = isText ? style.textStroke : style.stroke;
  44076. return stroke != null && stroke !== NONE;
  44077. }
  44078. function setTransform(svgEl, m) {
  44079. if (m) {
  44080. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  44081. }
  44082. }
  44083. function attr(el, key, val) {
  44084. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  44085. // Don't set attribute for gradient, since it need new dom nodes
  44086. el.setAttribute(key, val);
  44087. }
  44088. }
  44089. function attrXLink(el, key, val) {
  44090. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  44091. }
  44092. function bindStyle(svgEl, style, isText) {
  44093. if (pathHasFill(style, isText)) {
  44094. var fill = isText ? style.textFill : style.fill;
  44095. fill = fill === 'transparent' ? NONE : fill;
  44096. /**
  44097. * FIXME:
  44098. * This is a temporary fix for Chrome's clipping bug
  44099. * that happens when a clip-path is referring another one.
  44100. * This fix should be used before Chrome's bug is fixed.
  44101. * For an element that has clip-path, and fill is none,
  44102. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  44103. * Otherwise, it will show black fill color.
  44104. * 0.002 is used because this won't work for alpha values smaller
  44105. * than 0.002.
  44106. *
  44107. * See
  44108. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  44109. * for more information.
  44110. */
  44111. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  44112. fill = 'rgba(0, 0, 0, 0.002)';
  44113. }
  44114. attr(svgEl, 'fill', fill);
  44115. attr(svgEl, 'fill-opacity', style.opacity);
  44116. }
  44117. else {
  44118. attr(svgEl, 'fill', NONE);
  44119. }
  44120. if (pathHasStroke(style, isText)) {
  44121. var stroke = isText ? style.textStroke : style.stroke;
  44122. stroke = stroke === 'transparent' ? NONE : stroke;
  44123. attr(svgEl, 'stroke', stroke);
  44124. var strokeWidth = isText
  44125. ? style.textStrokeWidth
  44126. : style.lineWidth;
  44127. var strokeScale = !isText && style.strokeNoScale
  44128. ? style.host.getLineScale()
  44129. : 1;
  44130. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  44131. // stroke then fill for text; fill then stroke for others
  44132. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  44133. attr(svgEl, 'stroke-opacity', style.opacity);
  44134. var lineDash = style.lineDash;
  44135. if (lineDash) {
  44136. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  44137. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  44138. }
  44139. else {
  44140. attr(svgEl, 'stroke-dasharray', '');
  44141. }
  44142. // PENDING
  44143. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  44144. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  44145. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  44146. }
  44147. else {
  44148. attr(svgEl, 'stroke', NONE);
  44149. }
  44150. }
  44151. /***************************************************
  44152. * PATH
  44153. **************************************************/
  44154. function pathDataToString$1(path) {
  44155. var str = [];
  44156. var data = path.data;
  44157. var dataLength = path.len();
  44158. for (var i = 0; i < dataLength;) {
  44159. var cmd = data[i++];
  44160. var cmdStr = '';
  44161. var nData = 0;
  44162. switch (cmd) {
  44163. case CMD$4.M:
  44164. cmdStr = 'M';
  44165. nData = 2;
  44166. break;
  44167. case CMD$4.L:
  44168. cmdStr = 'L';
  44169. nData = 2;
  44170. break;
  44171. case CMD$4.Q:
  44172. cmdStr = 'Q';
  44173. nData = 4;
  44174. break;
  44175. case CMD$4.C:
  44176. cmdStr = 'C';
  44177. nData = 6;
  44178. break;
  44179. case CMD$4.A:
  44180. var cx = data[i++];
  44181. var cy = data[i++];
  44182. var rx = data[i++];
  44183. var ry = data[i++];
  44184. var theta = data[i++];
  44185. var dTheta = data[i++];
  44186. var psi = data[i++];
  44187. var clockwise = data[i++];
  44188. var dThetaPositive = Math.abs(dTheta);
  44189. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  44190. && !isAroundZero$1(dThetaPositive);
  44191. var large = false;
  44192. if (dThetaPositive >= PI2$5) {
  44193. large = true;
  44194. }
  44195. else if (isAroundZero$1(dThetaPositive)) {
  44196. large = false;
  44197. }
  44198. else {
  44199. large = (dTheta > -PI$3 && dTheta < 0 || dTheta > PI$3)
  44200. === !!clockwise;
  44201. }
  44202. var x0 = round4(cx + rx * mathCos$3(theta));
  44203. var y0 = round4(cy + ry * mathSin$3(theta));
  44204. // It will not draw if start point and end point are exactly the same
  44205. // We need to shift the end point with a small value
  44206. // FIXME A better way to draw circle ?
  44207. if (isCircle) {
  44208. if (clockwise) {
  44209. dTheta = PI2$5 - 1e-4;
  44210. }
  44211. else {
  44212. dTheta = -PI2$5 + 1e-4;
  44213. }
  44214. large = true;
  44215. if (i === 9) {
  44216. // Move to (x0, y0) only when CMD.A comes at the
  44217. // first position of a shape.
  44218. // For instance, when drawing a ring, CMD.A comes
  44219. // after CMD.M, so it's unnecessary to move to
  44220. // (x0, y0).
  44221. str.push('M', x0, y0);
  44222. }
  44223. }
  44224. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  44225. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  44226. // FIXME Ellipse
  44227. str.push('A', round4(rx), round4(ry),
  44228. mathRound(psi * degree), +large, +clockwise, x, y);
  44229. break;
  44230. case CMD$4.Z:
  44231. cmdStr = 'Z';
  44232. break;
  44233. case CMD$4.R:
  44234. var x = round4(data[i++]);
  44235. var y = round4(data[i++]);
  44236. var w = round4(data[i++]);
  44237. var h = round4(data[i++]);
  44238. str.push(
  44239. 'M', x, y,
  44240. 'L', x + w, y,
  44241. 'L', x + w, y + h,
  44242. 'L', x, y + h,
  44243. 'L', x, y
  44244. );
  44245. break;
  44246. }
  44247. cmdStr && str.push(cmdStr);
  44248. for (var j = 0; j < nData; j++) {
  44249. // PENDING With scale
  44250. str.push(round4(data[i++]));
  44251. }
  44252. }
  44253. return str.join(' ');
  44254. }
  44255. var svgPath = {};
  44256. svgPath.brush = function (el) {
  44257. var style = el.style;
  44258. var svgEl = el.__svgEl;
  44259. if (!svgEl) {
  44260. svgEl = createElement('path');
  44261. el.__svgEl = svgEl;
  44262. }
  44263. if (!el.path) {
  44264. el.createPathProxy();
  44265. }
  44266. var path = el.path;
  44267. if (el.__dirtyPath) {
  44268. path.beginPath();
  44269. el.buildPath(path, el.shape);
  44270. el.__dirtyPath = false;
  44271. var pathStr = pathDataToString$1(path);
  44272. if (pathStr.indexOf('NaN') < 0) {
  44273. // Ignore illegal path, which may happen such in out-of-range
  44274. // data in Calendar series.
  44275. attr(svgEl, 'd', pathStr);
  44276. }
  44277. }
  44278. bindStyle(svgEl, style);
  44279. setTransform(svgEl, el.transform);
  44280. if (style.text != null) {
  44281. svgTextDrawRectText(el, el.getBoundingRect());
  44282. }
  44283. };
  44284. /***************************************************
  44285. * IMAGE
  44286. **************************************************/
  44287. var svgImage = {};
  44288. svgImage.brush = function (el) {
  44289. var style = el.style;
  44290. var image = style.image;
  44291. if (image instanceof HTMLImageElement) {
  44292. var src = image.src;
  44293. image = src;
  44294. }
  44295. if (! image) {
  44296. return;
  44297. }
  44298. var x = style.x || 0;
  44299. var y = style.y || 0;
  44300. var dw = style.width;
  44301. var dh = style.height;
  44302. var svgEl = el.__svgEl;
  44303. if (! svgEl) {
  44304. svgEl = createElement('image');
  44305. el.__svgEl = svgEl;
  44306. }
  44307. if (image !== el.__imageSrc) {
  44308. attrXLink(svgEl, 'href', image);
  44309. // Caching image src
  44310. el.__imageSrc = image;
  44311. }
  44312. attr(svgEl, 'width', dw);
  44313. attr(svgEl, 'height', dh);
  44314. attr(svgEl, 'x', x);
  44315. attr(svgEl, 'y', y);
  44316. setTransform(svgEl, el.transform);
  44317. if (style.text != null) {
  44318. svgTextDrawRectText(el, el.getBoundingRect());
  44319. }
  44320. };
  44321. /***************************************************
  44322. * TEXT
  44323. **************************************************/
  44324. var svgText = {};
  44325. var tmpRect$3 = new BoundingRect();
  44326. var svgTextDrawRectText = function (el, rect, textRect) {
  44327. var style = el.style;
  44328. el.__dirty && normalizeTextStyle(style, true);
  44329. var text = style.text;
  44330. // Convert to string
  44331. if (text == null) {
  44332. // Draw no text only when text is set to null, but not ''
  44333. return;
  44334. }
  44335. else {
  44336. text += '';
  44337. }
  44338. var textSvgEl = el.__textSvgEl;
  44339. if (! textSvgEl) {
  44340. textSvgEl = createElement('text');
  44341. el.__textSvgEl = textSvgEl;
  44342. }
  44343. bindStyle(textSvgEl, style, true);
  44344. if (el instanceof Text || el.style.transformText) {
  44345. // Transform text with element
  44346. setTransform(textSvgEl, el.transform);
  44347. }
  44348. else {
  44349. if (el.transform) {
  44350. tmpRect$3.copy(rect);
  44351. tmpRect$3.applyTransform(el.transform);
  44352. rect = tmpRect$3;
  44353. }
  44354. else {
  44355. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  44356. rect.x = pos[0];
  44357. rect.y = pos[1];
  44358. }
  44359. }
  44360. var x;
  44361. var y;
  44362. var textPosition = style.textPosition;
  44363. var distance = style.textDistance;
  44364. var align = style.textAlign || 'left';
  44365. if (typeof style.fontSize === 'number') {
  44366. style.fontSize += 'px';
  44367. }
  44368. var font = style.font
  44369. || [
  44370. style.fontStyle || '',
  44371. style.fontWeight || '',
  44372. style.fontSize || '',
  44373. style.fontFamily || ''
  44374. ].join(' ')
  44375. || DEFAULT_FONT;
  44376. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  44377. textRect = getBoundingRect(text, font, align,
  44378. verticalAlign);
  44379. var lineHeight = textRect.lineHeight;
  44380. // Text position represented by coord
  44381. if (textPosition instanceof Array) {
  44382. x = rect.x + textPosition[0];
  44383. y = rect.y + textPosition[1];
  44384. }
  44385. else {
  44386. var newPos = adjustTextPositionOnRect(
  44387. textPosition, rect, distance
  44388. );
  44389. x = newPos.x;
  44390. y = newPos.y;
  44391. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  44392. align = newPos.textAlign;
  44393. }
  44394. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  44395. if (font) {
  44396. textSvgEl.style.font = font;
  44397. }
  44398. var textPadding = style.textPadding;
  44399. // Make baseline top
  44400. attr(textSvgEl, 'x', x);
  44401. attr(textSvgEl, 'y', y);
  44402. var textLines = text.split('\n');
  44403. var nTextLines = textLines.length;
  44404. var textAnchor = align;
  44405. // PENDING
  44406. if (textAnchor === 'left') {
  44407. textAnchor = 'start';
  44408. textPadding && (x += textPadding[3]);
  44409. }
  44410. else if (textAnchor === 'right') {
  44411. textAnchor = 'end';
  44412. textPadding && (x -= textPadding[1]);
  44413. }
  44414. else if (textAnchor === 'center') {
  44415. textAnchor = 'middle';
  44416. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  44417. }
  44418. var dy = 0;
  44419. if (verticalAlign === 'baseline') {
  44420. dy = -textRect.height + lineHeight;
  44421. textPadding && (dy -= textPadding[2]);
  44422. }
  44423. else if (verticalAlign === 'middle') {
  44424. dy = (-textRect.height + lineHeight) / 2;
  44425. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  44426. }
  44427. else {
  44428. textPadding && (dy += textPadding[0]);
  44429. }
  44430. // Font may affect position of each tspan elements
  44431. if (el.__text !== text || el.__textFont !== font) {
  44432. var tspanList = el.__tspanList || [];
  44433. el.__tspanList = tspanList;
  44434. for (var i = 0; i < nTextLines; i++) {
  44435. // Using cached tspan elements
  44436. var tspan = tspanList[i];
  44437. if (! tspan) {
  44438. tspan = tspanList[i] = createElement('tspan');
  44439. textSvgEl.appendChild(tspan);
  44440. attr(tspan, 'alignment-baseline', verticalAlign);
  44441. attr(tspan, 'text-anchor', textAnchor);
  44442. }
  44443. else {
  44444. tspan.innerHTML = '';
  44445. }
  44446. attr(tspan, 'x', x);
  44447. attr(tspan, 'y', y + i * lineHeight + dy);
  44448. tspan.appendChild(document.createTextNode(textLines[i]));
  44449. }
  44450. // Remove unsed tspan elements
  44451. for (; i < tspanList.length; i++) {
  44452. textSvgEl.removeChild(tspanList[i]);
  44453. }
  44454. tspanList.length = nTextLines;
  44455. el.__text = text;
  44456. el.__textFont = font;
  44457. }
  44458. else if (el.__tspanList.length) {
  44459. // Update span x and y
  44460. var len = el.__tspanList.length;
  44461. for (var i = 0; i < len; ++i) {
  44462. var tspan = el.__tspanList[i];
  44463. if (tspan) {
  44464. attr(tspan, 'x', x);
  44465. attr(tspan, 'y', y + i * lineHeight + dy);
  44466. }
  44467. }
  44468. }
  44469. };
  44470. function getVerticalAlignForSvg(verticalAlign) {
  44471. if (verticalAlign === 'middle') {
  44472. return 'middle';
  44473. }
  44474. else if (verticalAlign === 'bottom') {
  44475. return 'baseline';
  44476. }
  44477. else {
  44478. return 'hanging';
  44479. }
  44480. }
  44481. svgText.drawRectText = svgTextDrawRectText;
  44482. svgText.brush = function (el) {
  44483. var style = el.style;
  44484. if (style.text != null) {
  44485. // 强制设置 textPosition
  44486. style.textPosition = [0, 0];
  44487. svgTextDrawRectText(el, {
  44488. x: style.x || 0, y: style.y || 0,
  44489. width: 0, height: 0
  44490. }, el.getBoundingRect());
  44491. }
  44492. };
  44493. // Myers' Diff Algorithm
  44494. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  44495. function Diff() {}
  44496. Diff.prototype = {
  44497. diff: function (oldArr, newArr, equals) {
  44498. if (!equals) {
  44499. equals = function (a, b) {
  44500. return a === b;
  44501. };
  44502. }
  44503. this.equals = equals;
  44504. var self = this;
  44505. oldArr = oldArr.slice();
  44506. newArr = newArr.slice();
  44507. // Allow subclasses to massage the input prior to running
  44508. var newLen = newArr.length;
  44509. var oldLen = oldArr.length;
  44510. var editLength = 1;
  44511. var maxEditLength = newLen + oldLen;
  44512. var bestPath = [{ newPos: -1, components: [] }];
  44513. // Seed editLength = 0, i.e. the content starts with the same values
  44514. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  44515. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  44516. var indices = [];
  44517. for (var i = 0; i < newArr.length; i++) {
  44518. indices.push(i);
  44519. }
  44520. // Identity per the equality and tokenizer
  44521. return [{
  44522. indices: indices, count: newArr.length
  44523. }];
  44524. }
  44525. // Main worker method. checks all permutations of a given edit length for acceptance.
  44526. function execEditLength() {
  44527. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  44528. var basePath;
  44529. var addPath = bestPath[diagonalPath - 1];
  44530. var removePath = bestPath[diagonalPath + 1];
  44531. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  44532. if (addPath) {
  44533. // No one else is going to attempt to use this value, clear it
  44534. bestPath[diagonalPath - 1] = undefined;
  44535. }
  44536. var canAdd = addPath && addPath.newPos + 1 < newLen;
  44537. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  44538. if (!canAdd && !canRemove) {
  44539. // If this path is a terminal then prune
  44540. bestPath[diagonalPath] = undefined;
  44541. continue;
  44542. }
  44543. // Select the diagonal that we want to branch from. We select the prior
  44544. // path whose position in the new string is the farthest from the origin
  44545. // and does not pass the bounds of the diff graph
  44546. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  44547. basePath = clonePath(removePath);
  44548. self.pushComponent(basePath.components, undefined, true);
  44549. }
  44550. else {
  44551. basePath = addPath; // No need to clone, we've pulled it from the list
  44552. basePath.newPos++;
  44553. self.pushComponent(basePath.components, true, undefined);
  44554. }
  44555. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  44556. // If we have hit the end of both strings, then we are done
  44557. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  44558. return buildValues(self, basePath.components, newArr, oldArr);
  44559. }
  44560. else {
  44561. // Otherwise track this path as a potential candidate and continue.
  44562. bestPath[diagonalPath] = basePath;
  44563. }
  44564. }
  44565. editLength++;
  44566. }
  44567. while (editLength <= maxEditLength) {
  44568. var ret = execEditLength();
  44569. if (ret) {
  44570. return ret;
  44571. }
  44572. }
  44573. },
  44574. pushComponent: function (components, added, removed) {
  44575. var last = components[components.length - 1];
  44576. if (last && last.added === added && last.removed === removed) {
  44577. // We need to clone here as the component clone operation is just
  44578. // as shallow array clone
  44579. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  44580. }
  44581. else {
  44582. components.push({count: 1, added: added, removed: removed });
  44583. }
  44584. },
  44585. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  44586. var newLen = newArr.length;
  44587. var oldLen = oldArr.length;
  44588. var newPos = basePath.newPos;
  44589. var oldPos = newPos - diagonalPath;
  44590. var commonCount = 0;
  44591. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  44592. newPos++;
  44593. oldPos++;
  44594. commonCount++;
  44595. }
  44596. if (commonCount) {
  44597. basePath.components.push({count: commonCount});
  44598. }
  44599. basePath.newPos = newPos;
  44600. return oldPos;
  44601. },
  44602. tokenize: function (value) {
  44603. return value.slice();
  44604. },
  44605. join: function (value) {
  44606. return value.slice();
  44607. }
  44608. };
  44609. function buildValues(diff, components, newArr, oldArr) {
  44610. var componentPos = 0;
  44611. var componentLen = components.length;
  44612. var newPos = 0;
  44613. var oldPos = 0;
  44614. for (; componentPos < componentLen; componentPos++) {
  44615. var component = components[componentPos];
  44616. if (!component.removed) {
  44617. var indices = [];
  44618. for (var i = newPos; i < newPos + component.count; i++) {
  44619. indices.push(i);
  44620. }
  44621. component.indices = indices;
  44622. newPos += component.count;
  44623. // Common case
  44624. if (!component.added) {
  44625. oldPos += component.count;
  44626. }
  44627. }
  44628. else {
  44629. var indices = [];
  44630. for (var i = oldPos; i < oldPos + component.count; i++) {
  44631. indices.push(i);
  44632. }
  44633. component.indices = indices;
  44634. oldPos += component.count;
  44635. }
  44636. }
  44637. return components;
  44638. }
  44639. function clonePath(path) {
  44640. return { newPos: path.newPos, components: path.components.slice(0) };
  44641. }
  44642. var arrayDiff = new Diff();
  44643. var arrayDiff$1 = function (oldArr, newArr, callback) {
  44644. return arrayDiff.diff(oldArr, newArr, callback);
  44645. };
  44646. /**
  44647. * @file Manages elements that can be defined in <defs> in SVG,
  44648. * e.g., gradients, clip path, etc.
  44649. * @author Zhang Wenli
  44650. */
  44651. var MARK_UNUSED = '0';
  44652. var MARK_USED = '1';
  44653. /**
  44654. * Manages elements that can be defined in <defs> in SVG,
  44655. * e.g., gradients, clip path, etc.
  44656. *
  44657. * @class
  44658. * @param {number} zrId zrender instance id
  44659. * @param {SVGElement} svgRoot root of SVG document
  44660. * @param {string|string[]} tagNames possible tag names
  44661. * @param {string} markLabel label name to make if the element
  44662. * is used
  44663. */
  44664. function Definable(
  44665. zrId,
  44666. svgRoot,
  44667. tagNames,
  44668. markLabel,
  44669. domName
  44670. ) {
  44671. this._zrId = zrId;
  44672. this._svgRoot = svgRoot;
  44673. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  44674. this._markLabel = markLabel;
  44675. this._domName = domName || '_dom';
  44676. this.nextId = 0;
  44677. }
  44678. Definable.prototype.createElement = createElement;
  44679. /**
  44680. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  44681. *
  44682. * @param {boolean} isForceCreating if need to create when not exists
  44683. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  44684. * exist and isForceCreating is false
  44685. */
  44686. Definable.prototype.getDefs = function (isForceCreating) {
  44687. var svgRoot = this._svgRoot;
  44688. var defs = this._svgRoot.getElementsByTagName('defs');
  44689. if (defs.length === 0) {
  44690. // Not exist
  44691. if (isForceCreating) {
  44692. defs = svgRoot.insertBefore(
  44693. this.createElement('defs'), // Create new tag
  44694. svgRoot.firstChild // Insert in the front of svg
  44695. );
  44696. if (!defs.contains) {
  44697. // IE doesn't support contains method
  44698. defs.contains = function (el) {
  44699. var children = defs.children;
  44700. if (!children) {
  44701. return false;
  44702. }
  44703. for (var i = children.length - 1; i >= 0; --i) {
  44704. if (children[i] === el) {
  44705. return true;
  44706. }
  44707. }
  44708. return false;
  44709. };
  44710. }
  44711. return defs;
  44712. }
  44713. else {
  44714. return null;
  44715. }
  44716. }
  44717. else {
  44718. return defs[0];
  44719. }
  44720. };
  44721. /**
  44722. * Update DOM element if necessary.
  44723. *
  44724. * @param {Object|string} element style element. e.g., for gradient,
  44725. * it may be '#ccc' or {type: 'linear', ...}
  44726. * @param {Function|undefined} onUpdate update callback
  44727. */
  44728. Definable.prototype.update = function (element, onUpdate) {
  44729. if (!element) {
  44730. return;
  44731. }
  44732. var defs = this.getDefs(false);
  44733. if (element[this._domName] && defs.contains(element[this._domName])) {
  44734. // Update DOM
  44735. if (typeof onUpdate === 'function') {
  44736. onUpdate(element);
  44737. }
  44738. }
  44739. else {
  44740. // No previous dom, create new
  44741. var dom = this.add(element);
  44742. if (dom) {
  44743. element[this._domName] = dom;
  44744. }
  44745. }
  44746. };
  44747. /**
  44748. * Add gradient dom to defs
  44749. *
  44750. * @param {SVGElement} dom DOM to be added to <defs>
  44751. */
  44752. Definable.prototype.addDom = function (dom) {
  44753. var defs = this.getDefs(true);
  44754. defs.appendChild(dom);
  44755. };
  44756. /**
  44757. * Remove DOM of a given element.
  44758. *
  44759. * @param {SVGElement} element element to remove dom
  44760. */
  44761. Definable.prototype.removeDom = function (element) {
  44762. var defs = this.getDefs(false);
  44763. if (defs && element[this._domName]) {
  44764. defs.removeChild(element[this._domName]);
  44765. element[this._domName] = null;
  44766. }
  44767. };
  44768. /**
  44769. * Get DOMs of this element.
  44770. *
  44771. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  44772. */
  44773. Definable.prototype.getDoms = function () {
  44774. var defs = this.getDefs(false);
  44775. if (!defs) {
  44776. // No dom when defs is not defined
  44777. return [];
  44778. }
  44779. var doms = [];
  44780. each$1(this._tagNames, function (tagName) {
  44781. var tags = defs.getElementsByTagName(tagName);
  44782. // Note that tags is HTMLCollection, which is array-like
  44783. // rather than real array.
  44784. // So `doms.concat(tags)` add tags as one object.
  44785. doms = doms.concat([].slice.call(tags));
  44786. });
  44787. return doms;
  44788. };
  44789. /**
  44790. * Mark DOMs to be unused before painting, and clear unused ones at the end
  44791. * of the painting.
  44792. */
  44793. Definable.prototype.markAllUnused = function () {
  44794. var doms = this.getDoms();
  44795. var that = this;
  44796. each$1(doms, function (dom) {
  44797. dom[that._markLabel] = MARK_UNUSED;
  44798. });
  44799. };
  44800. /**
  44801. * Mark a single DOM to be used.
  44802. *
  44803. * @param {SVGElement} dom DOM to mark
  44804. */
  44805. Definable.prototype.markUsed = function (dom) {
  44806. if (dom) {
  44807. dom[this._markLabel] = MARK_USED;
  44808. }
  44809. };
  44810. /**
  44811. * Remove unused DOMs defined in <defs>
  44812. */
  44813. Definable.prototype.removeUnused = function () {
  44814. var defs = this.getDefs(false);
  44815. if (!defs) {
  44816. // Nothing to remove
  44817. return;
  44818. }
  44819. var doms = this.getDoms();
  44820. var that = this;
  44821. each$1(doms, function (dom) {
  44822. if (dom[that._markLabel] !== MARK_USED) {
  44823. // Remove gradient
  44824. defs.removeChild(dom);
  44825. }
  44826. });
  44827. };
  44828. /**
  44829. * Get SVG proxy.
  44830. *
  44831. * @param {Displayable} displayable displayable element
  44832. * @return {Path|Image|Text} svg proxy of given element
  44833. */
  44834. Definable.prototype.getSvgProxy = function (displayable) {
  44835. if (displayable instanceof Path) {
  44836. return svgPath;
  44837. }
  44838. else if (displayable instanceof ZImage) {
  44839. return svgImage;
  44840. }
  44841. else if (displayable instanceof Text) {
  44842. return svgText;
  44843. }
  44844. else {
  44845. return svgPath;
  44846. }
  44847. };
  44848. /**
  44849. * Get text SVG element.
  44850. *
  44851. * @param {Displayable} displayable displayable element
  44852. * @return {SVGElement} SVG element of text
  44853. */
  44854. Definable.prototype.getTextSvgElement = function (displayable) {
  44855. return displayable.__textSvgEl;
  44856. };
  44857. /**
  44858. * Get SVG element.
  44859. *
  44860. * @param {Displayable} displayable displayable element
  44861. * @return {SVGElement} SVG element
  44862. */
  44863. Definable.prototype.getSvgElement = function (displayable) {
  44864. return displayable.__svgEl;
  44865. };
  44866. /**
  44867. * @file Manages SVG gradient elements.
  44868. * @author Zhang Wenli
  44869. */
  44870. /**
  44871. * Manages SVG gradient elements.
  44872. *
  44873. * @class
  44874. * @extends Definable
  44875. * @param {number} zrId zrender instance id
  44876. * @param {SVGElement} svgRoot root of SVG document
  44877. */
  44878. function GradientManager(zrId, svgRoot) {
  44879. Definable.call(
  44880. this,
  44881. zrId,
  44882. svgRoot,
  44883. ['linearGradient', 'radialGradient'],
  44884. '__gradient_in_use__'
  44885. );
  44886. }
  44887. inherits(GradientManager, Definable);
  44888. /**
  44889. * Create new gradient DOM for fill or stroke if not exist,
  44890. * but will not update gradient if exists.
  44891. *
  44892. * @param {SvgElement} svgElement SVG element to paint
  44893. * @param {Displayable} displayable zrender displayable element
  44894. */
  44895. GradientManager.prototype.addWithoutUpdate = function (
  44896. svgElement,
  44897. displayable
  44898. ) {
  44899. if (displayable && displayable.style) {
  44900. var that = this;
  44901. each$1(['fill', 'stroke'], function (fillOrStroke) {
  44902. if (displayable.style[fillOrStroke]
  44903. && (displayable.style[fillOrStroke].type === 'linear'
  44904. || displayable.style[fillOrStroke].type === 'radial')
  44905. ) {
  44906. var gradient = displayable.style[fillOrStroke];
  44907. var defs = that.getDefs(true);
  44908. // Create dom in <defs> if not exists
  44909. var dom;
  44910. if (gradient._dom) {
  44911. // Gradient exists
  44912. dom = gradient._dom;
  44913. if (!defs.contains(gradient._dom)) {
  44914. // _dom is no longer in defs, recreate
  44915. that.addDom(dom);
  44916. }
  44917. }
  44918. else {
  44919. // New dom
  44920. dom = that.add(gradient);
  44921. }
  44922. that.markUsed(displayable);
  44923. var id = dom.getAttribute('id');
  44924. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  44925. }
  44926. });
  44927. }
  44928. };
  44929. /**
  44930. * Add a new gradient tag in <defs>
  44931. *
  44932. * @param {Gradient} gradient zr gradient instance
  44933. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  44934. * created DOM
  44935. */
  44936. GradientManager.prototype.add = function (gradient) {
  44937. var dom;
  44938. if (gradient.type === 'linear') {
  44939. dom = this.createElement('linearGradient');
  44940. }
  44941. else if (gradient.type === 'radial') {
  44942. dom = this.createElement('radialGradient');
  44943. }
  44944. else {
  44945. zrLog('Illegal gradient type.');
  44946. return null;
  44947. }
  44948. // Set dom id with gradient id, since each gradient instance
  44949. // will have no more than one dom element.
  44950. // id may exists before for those dirty elements, in which case
  44951. // id should remain the same, and other attributes should be
  44952. // updated.
  44953. gradient.id = gradient.id || this.nextId++;
  44954. dom.setAttribute('id', 'zr' + this._zrId
  44955. + '-gradient-' + gradient.id);
  44956. this.updateDom(gradient, dom);
  44957. this.addDom(dom);
  44958. return dom;
  44959. };
  44960. /**
  44961. * Update gradient.
  44962. *
  44963. * @param {Gradient} gradient zr gradient instance
  44964. */
  44965. GradientManager.prototype.update = function (gradient) {
  44966. var that = this;
  44967. Definable.prototype.update.call(this, gradient, function () {
  44968. var type = gradient.type;
  44969. var tagName = gradient._dom.tagName;
  44970. if (type === 'linear' && tagName === 'linearGradient'
  44971. || type === 'radial' && tagName === 'radialGradient'
  44972. ) {
  44973. // Gradient type is not changed, update gradient
  44974. that.updateDom(gradient, gradient._dom);
  44975. }
  44976. else {
  44977. // Remove and re-create if type is changed
  44978. that.removeDom(gradient);
  44979. that.add(gradient);
  44980. }
  44981. });
  44982. };
  44983. /**
  44984. * Update gradient dom
  44985. *
  44986. * @param {Gradient} gradient zr gradient instance
  44987. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  44988. * DOM to update
  44989. */
  44990. GradientManager.prototype.updateDom = function (gradient, dom) {
  44991. if (gradient.type === 'linear') {
  44992. dom.setAttribute('x1', gradient.x);
  44993. dom.setAttribute('y1', gradient.y);
  44994. dom.setAttribute('x2', gradient.x2);
  44995. dom.setAttribute('y2', gradient.y2);
  44996. }
  44997. else if (gradient.type === 'radial') {
  44998. dom.setAttribute('cx', gradient.x);
  44999. dom.setAttribute('cy', gradient.y);
  45000. dom.setAttribute('r', gradient.r);
  45001. }
  45002. else {
  45003. zrLog('Illegal gradient type.');
  45004. return;
  45005. }
  45006. if (gradient.global) {
  45007. // x1, x2, y1, y2 in range of 0 to canvas width or height
  45008. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  45009. }
  45010. else {
  45011. // x1, x2, y1, y2 in range of 0 to 1
  45012. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  45013. }
  45014. // Remove color stops if exists
  45015. dom.innerHTML = '';
  45016. // Add color stops
  45017. var colors = gradient.colorStops;
  45018. for (var i = 0, len = colors.length; i < len; ++i) {
  45019. var stop = this.createElement('stop');
  45020. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  45021. stop.setAttribute('stop-color', colors[i].color);
  45022. dom.appendChild(stop);
  45023. }
  45024. // Store dom element in gradient, to avoid creating multiple
  45025. // dom instances for the same gradient element
  45026. gradient._dom = dom;
  45027. };
  45028. /**
  45029. * Mark a single gradient to be used
  45030. *
  45031. * @param {Displayable} displayable displayable element
  45032. */
  45033. GradientManager.prototype.markUsed = function (displayable) {
  45034. if (displayable.style) {
  45035. var gradient = displayable.style.fill;
  45036. if (gradient && gradient._dom) {
  45037. Definable.prototype.markUsed.call(this, gradient._dom);
  45038. }
  45039. gradient = displayable.style.stroke;
  45040. if (gradient && gradient._dom) {
  45041. Definable.prototype.markUsed.call(this, gradient._dom);
  45042. }
  45043. }
  45044. };
  45045. /**
  45046. * @file Manages SVG clipPath elements.
  45047. * @author Zhang Wenli
  45048. */
  45049. /**
  45050. * Manages SVG clipPath elements.
  45051. *
  45052. * @class
  45053. * @extends Definable
  45054. * @param {number} zrId zrender instance id
  45055. * @param {SVGElement} svgRoot root of SVG document
  45056. */
  45057. function ClippathManager(zrId, svgRoot) {
  45058. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  45059. }
  45060. inherits(ClippathManager, Definable);
  45061. /**
  45062. * Update clipPath.
  45063. *
  45064. * @param {Displayable} displayable displayable element
  45065. */
  45066. ClippathManager.prototype.update = function (displayable) {
  45067. var svgEl = this.getSvgElement(displayable);
  45068. if (svgEl) {
  45069. this.updateDom(svgEl, displayable.__clipPaths, false);
  45070. }
  45071. var textEl = this.getTextSvgElement(displayable);
  45072. if (textEl) {
  45073. // Make another clipPath for text, since it's transform
  45074. // matrix is not the same with svgElement
  45075. this.updateDom(textEl, displayable.__clipPaths, true);
  45076. }
  45077. this.markUsed(displayable);
  45078. };
  45079. /**
  45080. * Create an SVGElement of displayable and create a <clipPath> of its
  45081. * clipPath
  45082. *
  45083. * @param {Displayable} parentEl parent element
  45084. * @param {ClipPath[]} clipPaths clipPaths of parent element
  45085. * @param {boolean} isText if parent element is Text
  45086. */
  45087. ClippathManager.prototype.updateDom = function (
  45088. parentEl,
  45089. clipPaths,
  45090. isText
  45091. ) {
  45092. if (clipPaths && clipPaths.length > 0) {
  45093. // Has clipPath, create <clipPath> with the first clipPath
  45094. var defs = this.getDefs(true);
  45095. var clipPath = clipPaths[0];
  45096. var clipPathEl;
  45097. var id;
  45098. var dom = isText ? '_textDom' : '_dom';
  45099. if (clipPath[dom]) {
  45100. // Use a dom that is already in <defs>
  45101. id = clipPath[dom].getAttribute('id');
  45102. clipPathEl = clipPath[dom];
  45103. // Use a dom that is already in <defs>
  45104. if (!defs.contains(clipPathEl)) {
  45105. // This happens when set old clipPath that has
  45106. // been previously removed
  45107. defs.appendChild(clipPathEl);
  45108. }
  45109. }
  45110. else {
  45111. // New <clipPath>
  45112. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  45113. ++this.nextId;
  45114. clipPathEl = this.createElement('clipPath');
  45115. clipPathEl.setAttribute('id', id);
  45116. defs.appendChild(clipPathEl);
  45117. clipPath[dom] = clipPathEl;
  45118. }
  45119. // Build path and add to <clipPath>
  45120. var svgProxy = this.getSvgProxy(clipPath);
  45121. if (clipPath.transform
  45122. && clipPath.parent.invTransform
  45123. && !isText
  45124. ) {
  45125. /**
  45126. * If a clipPath has a parent with transform, the transform
  45127. * of parent should not be considered when setting transform
  45128. * of clipPath. So we need to transform back from parent's
  45129. * transform, which is done by multiplying parent's inverse
  45130. * transform.
  45131. */
  45132. // Store old transform
  45133. var transform = Array.prototype.slice.call(
  45134. clipPath.transform
  45135. );
  45136. // Transform back from parent, and brush path
  45137. mul$1(
  45138. clipPath.transform,
  45139. clipPath.parent.invTransform,
  45140. clipPath.transform
  45141. );
  45142. svgProxy.brush(clipPath);
  45143. // Set back transform of clipPath
  45144. clipPath.transform = transform;
  45145. }
  45146. else {
  45147. svgProxy.brush(clipPath);
  45148. }
  45149. var pathEl = this.getSvgElement(clipPath);
  45150. clipPathEl.innerHTML = '';
  45151. /**
  45152. * Use `cloneNode()` here to appendChild to multiple parents,
  45153. * which may happend when Text and other shapes are using the same
  45154. * clipPath. Since Text will create an extra clipPath DOM due to
  45155. * different transform rules.
  45156. */
  45157. clipPathEl.appendChild(pathEl.cloneNode());
  45158. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  45159. if (clipPaths.length > 1) {
  45160. // Make the other clipPaths recursively
  45161. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  45162. }
  45163. }
  45164. else {
  45165. // No clipPath
  45166. if (parentEl) {
  45167. parentEl.setAttribute('clip-path', 'none');
  45168. }
  45169. }
  45170. };
  45171. /**
  45172. * Mark a single clipPath to be used
  45173. *
  45174. * @param {Displayable} displayable displayable element
  45175. */
  45176. ClippathManager.prototype.markUsed = function (displayable) {
  45177. var that = this;
  45178. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  45179. each$1(displayable.__clipPaths, function (clipPath) {
  45180. if (clipPath._dom) {
  45181. Definable.prototype.markUsed.call(that, clipPath._dom);
  45182. }
  45183. if (clipPath._textDom) {
  45184. Definable.prototype.markUsed.call(that, clipPath._textDom);
  45185. }
  45186. });
  45187. }
  45188. };
  45189. /**
  45190. * @file Manages SVG shadow elements.
  45191. * @author Zhang Wenli
  45192. */
  45193. /**
  45194. * Manages SVG shadow elements.
  45195. *
  45196. * @class
  45197. * @extends Definable
  45198. * @param {number} zrId zrender instance id
  45199. * @param {SVGElement} svgRoot root of SVG document
  45200. */
  45201. function ShadowManager(zrId, svgRoot) {
  45202. Definable.call(
  45203. this,
  45204. zrId,
  45205. svgRoot,
  45206. ['filter'],
  45207. '__filter_in_use__',
  45208. '_shadowDom'
  45209. );
  45210. }
  45211. inherits(ShadowManager, Definable);
  45212. /**
  45213. * Create new shadow DOM for fill or stroke if not exist,
  45214. * but will not update shadow if exists.
  45215. *
  45216. * @param {SvgElement} svgElement SVG element to paint
  45217. * @param {Displayable} displayable zrender displayable element
  45218. */
  45219. ShadowManager.prototype.addWithoutUpdate = function (
  45220. svgElement,
  45221. displayable
  45222. ) {
  45223. if (displayable && hasShadow(displayable.style)) {
  45224. var style = displayable.style;
  45225. // Create dom in <defs> if not exists
  45226. var dom;
  45227. if (style._shadowDom) {
  45228. // Gradient exists
  45229. dom = style._shadowDom;
  45230. var defs = this.getDefs(true);
  45231. if (!defs.contains(style._shadowDom)) {
  45232. // _shadowDom is no longer in defs, recreate
  45233. this.addDom(dom);
  45234. }
  45235. }
  45236. else {
  45237. // New dom
  45238. dom = this.add(displayable);
  45239. }
  45240. this.markUsed(displayable);
  45241. var id = dom.getAttribute('id');
  45242. svgElement.style.filter = 'url(#' + id + ')';
  45243. }
  45244. };
  45245. /**
  45246. * Add a new shadow tag in <defs>
  45247. *
  45248. * @param {Displayable} displayable zrender displayable element
  45249. * @return {SVGFilterElement} created DOM
  45250. */
  45251. ShadowManager.prototype.add = function (displayable) {
  45252. var dom = this.createElement('filter');
  45253. var style = displayable.style;
  45254. // Set dom id with shadow id, since each shadow instance
  45255. // will have no more than one dom element.
  45256. // id may exists before for those dirty elements, in which case
  45257. // id should remain the same, and other attributes should be
  45258. // updated.
  45259. style._shadowDomId = style._shadowDomId || this.nextId++;
  45260. dom.setAttribute('id', 'zr' + this._zrId
  45261. + '-shadow-' + style._shadowDomId);
  45262. this.updateDom(displayable, dom);
  45263. this.addDom(dom);
  45264. return dom;
  45265. };
  45266. /**
  45267. * Update shadow.
  45268. *
  45269. * @param {Displayable} displayable zrender displayable element
  45270. */
  45271. ShadowManager.prototype.update = function (svgElement, displayable) {
  45272. var style = displayable.style;
  45273. if (hasShadow(style)) {
  45274. var that = this;
  45275. Definable.prototype.update.call(this, displayable, function (style) {
  45276. that.updateDom(displayable, style._shadowDom);
  45277. });
  45278. }
  45279. else {
  45280. // Remove shadow
  45281. this.remove(svgElement, style);
  45282. }
  45283. };
  45284. /**
  45285. * Remove DOM and clear parent filter
  45286. */
  45287. ShadowManager.prototype.remove = function (svgElement, style) {
  45288. if (style._shadowDomId != null) {
  45289. this.removeDom(style);
  45290. svgElement.style.filter = '';
  45291. }
  45292. };
  45293. /**
  45294. * Update shadow dom
  45295. *
  45296. * @param {Displayable} displayable zrender displayable element
  45297. * @param {SVGFilterElement} dom DOM to update
  45298. */
  45299. ShadowManager.prototype.updateDom = function (displayable, dom) {
  45300. var domChild = dom.getElementsByTagName('feDropShadow');
  45301. if (domChild.length === 0) {
  45302. domChild = this.createElement('feDropShadow');
  45303. }
  45304. else {
  45305. domChild = domChild[0];
  45306. }
  45307. var style = displayable.style;
  45308. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  45309. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  45310. // TODO: textBoxShadowBlur is not supported yet
  45311. var offsetX, offsetY, blur, color;
  45312. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  45313. offsetX = style.shadowOffsetX || 0;
  45314. offsetY = style.shadowOffsetY || 0;
  45315. blur = style.shadowBlur;
  45316. color = style.shadowColor;
  45317. }
  45318. else if (style.textShadowBlur) {
  45319. offsetX = style.textShadowOffsetX || 0;
  45320. offsetY = style.textShadowOffsetY || 0;
  45321. blur = style.textShadowBlur;
  45322. color = style.textShadowColor;
  45323. }
  45324. else {
  45325. // Remove shadow
  45326. this.removeDom(dom, style);
  45327. return;
  45328. }
  45329. domChild.setAttribute('dx', offsetX / scaleX);
  45330. domChild.setAttribute('dy', offsetY / scaleY);
  45331. domChild.setAttribute('flood-color', color);
  45332. // Divide by two here so that it looks the same as in canvas
  45333. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  45334. var stdDx = blur / 2 / scaleX;
  45335. var stdDy = blur / 2 / scaleY;
  45336. var stdDeviation = stdDx + ' ' + stdDy;
  45337. domChild.setAttribute('stdDeviation', stdDeviation);
  45338. // Fix filter clipping problem
  45339. dom.setAttribute('x', '-100%');
  45340. dom.setAttribute('y', '-100%');
  45341. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  45342. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  45343. dom.appendChild(domChild);
  45344. // Store dom element in shadow, to avoid creating multiple
  45345. // dom instances for the same shadow element
  45346. style._shadowDom = dom;
  45347. };
  45348. /**
  45349. * Mark a single shadow to be used
  45350. *
  45351. * @param {Displayable} displayable displayable element
  45352. */
  45353. ShadowManager.prototype.markUsed = function (displayable) {
  45354. var style = displayable.style;
  45355. if (style && style._shadowDom) {
  45356. Definable.prototype.markUsed.call(this, style._shadowDom);
  45357. }
  45358. };
  45359. function hasShadow(style) {
  45360. // TODO: textBoxShadowBlur is not supported yet
  45361. return style
  45362. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  45363. || style.textShadowBlur || style.textShadowOffsetX
  45364. || style.textShadowOffsetY);
  45365. }
  45366. /**
  45367. * SVG Painter
  45368. * @module zrender/svg/Painter
  45369. */
  45370. function parseInt10$2(val) {
  45371. return parseInt(val, 10);
  45372. }
  45373. function getSvgProxy(el) {
  45374. if (el instanceof Path) {
  45375. return svgPath;
  45376. }
  45377. else if (el instanceof ZImage) {
  45378. return svgImage;
  45379. }
  45380. else if (el instanceof Text) {
  45381. return svgText;
  45382. }
  45383. else {
  45384. return svgPath;
  45385. }
  45386. }
  45387. function checkParentAvailable(parent, child) {
  45388. return child && parent && child.parentNode !== parent;
  45389. }
  45390. function insertAfter(parent, child, prevSibling) {
  45391. if (checkParentAvailable(parent, child) && prevSibling) {
  45392. var nextSibling = prevSibling.nextSibling;
  45393. nextSibling ? parent.insertBefore(child, nextSibling)
  45394. : parent.appendChild(child);
  45395. }
  45396. }
  45397. function prepend(parent, child) {
  45398. if (checkParentAvailable(parent, child)) {
  45399. var firstChild = parent.firstChild;
  45400. firstChild ? parent.insertBefore(child, firstChild)
  45401. : parent.appendChild(child);
  45402. }
  45403. }
  45404. function remove$1(parent, child) {
  45405. if (child && parent && child.parentNode === parent) {
  45406. parent.removeChild(child);
  45407. }
  45408. }
  45409. function getTextSvgElement(displayable) {
  45410. return displayable.__textSvgEl;
  45411. }
  45412. function getSvgElement(displayable) {
  45413. return displayable.__svgEl;
  45414. }
  45415. /**
  45416. * @alias module:zrender/svg/Painter
  45417. * @constructor
  45418. * @param {HTMLElement} root 绘图容器
  45419. * @param {module:zrender/Storage} storage
  45420. * @param {Object} opts
  45421. */
  45422. var SVGPainter = function (root, storage, opts, zrId) {
  45423. this.root = root;
  45424. this.storage = storage;
  45425. this._opts = opts = extend({}, opts || {});
  45426. var svgRoot = createElement('svg');
  45427. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  45428. svgRoot.setAttribute('version', '1.1');
  45429. svgRoot.setAttribute('baseProfile', 'full');
  45430. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  45431. this.gradientManager = new GradientManager(zrId, svgRoot);
  45432. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  45433. this.shadowManager = new ShadowManager(zrId, svgRoot);
  45434. var viewport = document.createElement('div');
  45435. viewport.style.cssText = 'overflow:hidden;position:relative';
  45436. this._svgRoot = svgRoot;
  45437. this._viewport = viewport;
  45438. root.appendChild(viewport);
  45439. viewport.appendChild(svgRoot);
  45440. this.resize(opts.width, opts.height);
  45441. this._visibleList = [];
  45442. };
  45443. SVGPainter.prototype = {
  45444. constructor: SVGPainter,
  45445. getType: function () {
  45446. return 'svg';
  45447. },
  45448. getViewportRoot: function () {
  45449. return this._viewport;
  45450. },
  45451. getViewportRootOffset: function () {
  45452. var viewportRoot = this.getViewportRoot();
  45453. if (viewportRoot) {
  45454. return {
  45455. offsetLeft: viewportRoot.offsetLeft || 0,
  45456. offsetTop: viewportRoot.offsetTop || 0
  45457. };
  45458. }
  45459. },
  45460. refresh: function () {
  45461. var list = this.storage.getDisplayList(true);
  45462. this._paintList(list);
  45463. },
  45464. _paintList: function (list) {
  45465. this.gradientManager.markAllUnused();
  45466. this.clipPathManager.markAllUnused();
  45467. this.shadowManager.markAllUnused();
  45468. var svgRoot = this._svgRoot;
  45469. var visibleList = this._visibleList;
  45470. var listLen = list.length;
  45471. var newVisibleList = [];
  45472. var i;
  45473. for (i = 0; i < listLen; i++) {
  45474. var displayable = list[i];
  45475. var svgProxy = getSvgProxy(displayable);
  45476. var svgElement = getSvgElement(displayable)
  45477. || getTextSvgElement(displayable);
  45478. if (!displayable.invisible) {
  45479. if (displayable.__dirty) {
  45480. svgProxy && svgProxy.brush(displayable);
  45481. // Update clipPath
  45482. this.clipPathManager.update(displayable);
  45483. // Update gradient and shadow
  45484. if (displayable.style) {
  45485. this.gradientManager
  45486. .update(displayable.style.fill);
  45487. this.gradientManager
  45488. .update(displayable.style.stroke);
  45489. this.shadowManager
  45490. .update(svgElement, displayable);
  45491. }
  45492. displayable.__dirty = false;
  45493. }
  45494. newVisibleList.push(displayable);
  45495. }
  45496. }
  45497. var diff = arrayDiff$1(visibleList, newVisibleList);
  45498. var prevSvgElement;
  45499. // First do remove, in case element moved to the head and do remove
  45500. // after add
  45501. for (i = 0; i < diff.length; i++) {
  45502. var item = diff[i];
  45503. if (item.removed) {
  45504. for (var k = 0; k < item.count; k++) {
  45505. var displayable = visibleList[item.indices[k]];
  45506. var svgElement = getSvgElement(displayable);
  45507. var textSvgElement = getTextSvgElement(displayable);
  45508. remove$1(svgRoot, svgElement);
  45509. remove$1(svgRoot, textSvgElement);
  45510. }
  45511. }
  45512. }
  45513. for (i = 0; i < diff.length; i++) {
  45514. var item = diff[i];
  45515. if (item.added) {
  45516. for (var k = 0; k < item.count; k++) {
  45517. var displayable = newVisibleList[item.indices[k]];
  45518. var svgElement = getSvgElement(displayable);
  45519. var textSvgElement = getTextSvgElement(displayable);
  45520. prevSvgElement
  45521. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  45522. : prepend(svgRoot, svgElement);
  45523. if (svgElement) {
  45524. insertAfter(svgRoot, textSvgElement, svgElement);
  45525. }
  45526. else if (prevSvgElement) {
  45527. insertAfter(
  45528. svgRoot, textSvgElement, prevSvgElement
  45529. );
  45530. }
  45531. else {
  45532. prepend(svgRoot, textSvgElement);
  45533. }
  45534. // Insert text
  45535. insertAfter(svgRoot, textSvgElement, svgElement);
  45536. prevSvgElement = textSvgElement || svgElement
  45537. || prevSvgElement;
  45538. this.gradientManager
  45539. .addWithoutUpdate(svgElement, displayable);
  45540. this.shadowManager
  45541. .addWithoutUpdate(prevSvgElement, displayable);
  45542. this.clipPathManager.markUsed(displayable);
  45543. }
  45544. }
  45545. else if (!item.removed) {
  45546. for (var k = 0; k < item.count; k++) {
  45547. var displayable = newVisibleList[item.indices[k]];
  45548. prevSvgElement
  45549. = svgElement
  45550. = getTextSvgElement(displayable)
  45551. || getSvgElement(displayable)
  45552. || prevSvgElement;
  45553. this.gradientManager.markUsed(displayable);
  45554. this.gradientManager
  45555. .addWithoutUpdate(svgElement, displayable);
  45556. this.shadowManager.markUsed(displayable);
  45557. this.shadowManager
  45558. .addWithoutUpdate(svgElement, displayable);
  45559. this.clipPathManager.markUsed(displayable);
  45560. }
  45561. }
  45562. }
  45563. this.gradientManager.removeUnused();
  45564. this.clipPathManager.removeUnused();
  45565. this.shadowManager.removeUnused();
  45566. this._visibleList = newVisibleList;
  45567. },
  45568. _getDefs: function (isForceCreating) {
  45569. var svgRoot = this._svgRoot;
  45570. var defs = this._svgRoot.getElementsByTagName('defs');
  45571. if (defs.length === 0) {
  45572. // Not exist
  45573. if (isForceCreating) {
  45574. var defs = svgRoot.insertBefore(
  45575. createElement('defs'), // Create new tag
  45576. svgRoot.firstChild // Insert in the front of svg
  45577. );
  45578. if (!defs.contains) {
  45579. // IE doesn't support contains method
  45580. defs.contains = function (el) {
  45581. var children = defs.children;
  45582. if (!children) {
  45583. return false;
  45584. }
  45585. for (var i = children.length - 1; i >= 0; --i) {
  45586. if (children[i] === el) {
  45587. return true;
  45588. }
  45589. }
  45590. return false;
  45591. };
  45592. }
  45593. return defs;
  45594. }
  45595. else {
  45596. return null;
  45597. }
  45598. }
  45599. else {
  45600. return defs[0];
  45601. }
  45602. },
  45603. resize: function (width, height) {
  45604. var viewport = this._viewport;
  45605. // FIXME Why ?
  45606. viewport.style.display = 'none';
  45607. // Save input w/h
  45608. var opts = this._opts;
  45609. width != null && (opts.width = width);
  45610. height != null && (opts.height = height);
  45611. width = this._getSize(0);
  45612. height = this._getSize(1);
  45613. viewport.style.display = '';
  45614. if (this._width !== width || this._height !== height) {
  45615. this._width = width;
  45616. this._height = height;
  45617. var viewportStyle = viewport.style;
  45618. viewportStyle.width = width + 'px';
  45619. viewportStyle.height = height + 'px';
  45620. var svgRoot = this._svgRoot;
  45621. // Set width by 'svgRoot.width = width' is invalid
  45622. svgRoot.setAttribute('width', width);
  45623. svgRoot.setAttribute('height', height);
  45624. }
  45625. },
  45626. /**
  45627. * 获取绘图区域宽度
  45628. */
  45629. getWidth: function () {
  45630. return this._width;
  45631. },
  45632. /**
  45633. * 获取绘图区域高度
  45634. */
  45635. getHeight: function () {
  45636. return this._height;
  45637. },
  45638. _getSize: function (whIdx) {
  45639. var opts = this._opts;
  45640. var wh = ['width', 'height'][whIdx];
  45641. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  45642. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  45643. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  45644. if (opts[wh] != null && opts[wh] !== 'auto') {
  45645. return parseFloat(opts[wh]);
  45646. }
  45647. var root = this.root;
  45648. // IE8 does not support getComputedStyle, but it use VML.
  45649. var stl = document.defaultView.getComputedStyle(root);
  45650. return (
  45651. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  45652. - (parseInt10$2(stl[plt]) || 0)
  45653. - (parseInt10$2(stl[prb]) || 0)
  45654. ) | 0;
  45655. },
  45656. dispose: function () {
  45657. this.root.innerHTML = '';
  45658. this._svgRoot
  45659. = this._viewport
  45660. = this.storage
  45661. = null;
  45662. },
  45663. clear: function () {
  45664. if (this._viewport) {
  45665. this.root.removeChild(this._viewport);
  45666. }
  45667. },
  45668. pathToSvg: function () {
  45669. this.refresh();
  45670. var html = this._svgRoot.outerHTML;
  45671. return 'data:img/svg+xml;utf-8,' + unescape(html);
  45672. }
  45673. };
  45674. // Not supported methods
  45675. function createMethodNotSupport$1(method) {
  45676. return function () {
  45677. zrLog('In SVG mode painter not support method "' + method + '"');
  45678. };
  45679. }
  45680. // Unsuppoted methods
  45681. each$1([
  45682. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  45683. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  45684. 'toDataURL', 'pathToImage'
  45685. ], function (name) {
  45686. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  45687. });
  45688. registerPainter('svg', SVGPainter);
  45689. exports.version = version;
  45690. exports.dependencies = dependencies;
  45691. exports.PRIORITY = PRIORITY;
  45692. exports.init = init;
  45693. exports.connect = connect;
  45694. exports.disConnect = disConnect;
  45695. exports.disconnect = disconnect;
  45696. exports.dispose = dispose;
  45697. exports.getInstanceByDom = getInstanceByDom;
  45698. exports.getInstanceById = getInstanceById;
  45699. exports.registerTheme = registerTheme;
  45700. exports.registerPreprocessor = registerPreprocessor;
  45701. exports.registerProcessor = registerProcessor;
  45702. exports.registerPostUpdate = registerPostUpdate;
  45703. exports.registerAction = registerAction;
  45704. exports.registerCoordinateSystem = registerCoordinateSystem;
  45705. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  45706. exports.registerLayout = registerLayout;
  45707. exports.registerVisual = registerVisual;
  45708. exports.registerLoading = registerLoading;
  45709. exports.extendComponentModel = extendComponentModel;
  45710. exports.extendComponentView = extendComponentView;
  45711. exports.extendSeriesModel = extendSeriesModel;
  45712. exports.extendChartView = extendChartView;
  45713. exports.setCanvasCreator = setCanvasCreator;
  45714. exports.registerMap = registerMap;
  45715. exports.getMap = getMap;
  45716. exports.dataTool = dataTool;
  45717. exports.zrender = zrender;
  45718. exports.graphic = graphic;
  45719. exports.number = number;
  45720. exports.format = format;
  45721. exports.throttle = throttle;
  45722. exports.helper = helper;
  45723. exports.matrix = matrix;
  45724. exports.vector = vector;
  45725. exports.color = color;
  45726. exports.parseGeoJSON = parseGeoJSON;
  45727. exports.parseGeoJson = parseGeoJson;
  45728. exports.util = ecUtil;
  45729. exports.List = List;
  45730. exports.Model = Model;
  45731. exports.Axis = Axis;
  45732. exports.env = env$1;
  45733. })));